]> SALOME platform Git repositories - samples/pylight.git/blobdiff - src/PYLIGHTGUI/PYLIGHTGUI.py
Salome HOME
Copyright update 2020
[samples/pylight.git] / src / PYLIGHTGUI / PYLIGHTGUI.py
index 29d5024f110bbba5ffa83c8b90f52cddbaac2659..1ea21577fa63a6894515d953f36abd6986fce138 100644 (file)
-#  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2009-2020  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, or (at your option) any later version.
 #
-#  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.
 #
-#  This library is distributed in the hope that 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
 #
-#  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
 #
-#  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 
-#  Author : Roman NIKOLAEV Open CASCADE S.A.S. (roman.nikolaev@opencascade.com)
+#  Author : Roman NIKOLAEV, Open CASCADE S.A.S. (roman.nikolaev@opencascade.com)
 #  Date   : 13/04/2009
-
+#
 import traceback
 from SalomePyQt import *
 import PYLIGHT_DataModel
-from PyQt4.QtGui import *
-from PyQt4.QtCore import *
+from qtsalome import *
 import libSALOME_Swig
 
 import os
+import os.path as osp
 import libSalomePy
 import vtk
 
 # Get SALOME PyQt interface
-sgPyQt=SalomePyQt()
+sgPyQt = SalomePyQt()
 # Get SALOME Swig interface
 sg = libSALOME_Swig.SALOMEGUI_Swig()
 
-# Create DataModel
-DM = PYLIGHT_DataModel.PYLIGHT_DataModel()
+################################################
+# GUI context class
+# Used to store actions, menus, toolbars, etc...
+################################################
+
+# data model
+__data_model__ = None
+
+class GUIcontext:
+
+    # constructor
+    def __init__( self ):
+        global __data_model__
+        # Load File action
+        sgPyQt.createAction(dict_actions["loadfile"], "Load text File", "Load text file")
+        # Save File action
+        sgPyQt.createAction(dict_actions["savefile"], "Save text File", "Save text file")
+        # Insert Line action
+        sgPyQt.createAction(dict_actions["insertLine"], "Insert Line", "Insert new text line")
+        # Insert new line action
+        sgPyQt.createAction(dict_actions["insertLine"], "Insert Line", "Insert new line")
+        # Edit selected line action
+        sgPyQt.createAction(dict_actions["editLine"], "Edit Line", "Edit selected line")
+        # Remove selected line action
+        sgPyQt.createAction(dict_actions["removeLine"], "Remove Lines", "Remove selected lines")
+        # Clear paragraph
+        sgPyQt.createAction(dict_actions["clearParagraph"], "Clear Paragraph", "Clear selected paragraph")
+        # Clear all paragraphs
+        sgPyQt.createAction(dict_actions["clearAll"], "Clear All", "Clear all paragraphs")
+        # Display line
+        sgPyQt.createAction(dict_actions["displayLine"], "Display Line", "Display selected line")
+        # Erase line
+        sgPyQt.createAction(dict_actions["eraseLine"], "Erase Line", "Erase selected line")
+        # Separator
+        separator = sgPyQt.createSeparator()
+
+        # Get Menu 'File'
+        menuFile = sgPyQt.createMenu( "File", -1, -1 )
+        # Add actions in the menu 'File'
+        sgPyQt.createMenu( separator,                menuFile, -1, 10)
+        sgPyQt.createMenu( dict_actions["loadfile"], menuFile, 10 );
+        sgPyQt.createMenu( dict_actions["savefile"], menuFile, 10 );
+        sgPyQt.createMenu( separator,                menuFile, -1, 10)
+        # Create 'PyLight' menu 
+        menuPyLight = sgPyQt.createMenu( "PyLight", -1, -1, 50)
+        # Add actions in the menu 'PyLight'
+        sgPyQt.createMenu( dict_actions["insertLine"],  menuPyLight, 10 );
+        sgPyQt.createMenu( dict_actions["editLine"],    menuPyLight, 10 );
+        sgPyQt.createMenu( dict_actions["removeLine"],  menuPyLight, 10 );
+        sgPyQt.createMenu( separator,                   menuPyLight, -1, 10);
+        sgPyQt.createMenu( dict_actions["clearAll"],    menuPyLight, 10 );
+        sgPyQt.createMenu( separator,                   menuPyLight, -1, 10);
+        sgPyQt.createMenu( dict_actions["displayLine"], menuPyLight, 10 );
+        sgPyQt.createMenu( dict_actions["eraseLine"],   menuPyLight, 10 );
+
+        # Create DataModel
+        if __data_model__ is None:
+            __data_model__ = PYLIGHT_DataModel.PYLIGHT_DataModel()
+            pass
+            
+        pass # def __init__( self )
+
+    pass # class GUIcontext
+
+################################################
+# Global variables and functions
+################################################
+
+# verbosity level
+__verbose__ = None
+
+###
+# Get verbose level
+###
+def verbose():
+    global __verbose__
+    if __verbose__ is None:
+        try:
+            __verbose__ = int( os.getenv( 'SALOME_VERBOSE', 0 ) )
+        except:
+            __verbose__ = 0
+            pass
+        pass
+    return __verbose__
+
+################################################
 
 # Create actions and menus
 def initialize():
-    
-    print "PYLIGHTGUI::initialize()"
-    # Load File action
-    sgPyQt.createAction(dict_actions["loadfile"], "Load text File", "Load text file")
-    # Save File action
-    sgPyQt.createAction(dict_actions["savefile"], "Save text File", "Save text file")
-    # Insert Line action
-    sgPyQt.createAction(dict_actions["insertLine"], "Insert Line", "Insert new text line")
-    # Separator
-    separator = sgPyQt.createSeparator()
-    # Get Menu 'File'
-    menuFile = sgPyQt.createMenu( "File", -1, -1 )
-    # Add actions in the menu 'File'
-    sgPyQt.createMenu( separator ,menuFile, -1, 10)
-    sgPyQt.createMenu( dict_actions["loadfile"],  menuFile, 10 );
-    sgPyQt.createMenu( dict_actions["savefile"],  menuFile, 10 );
-    sgPyQt.createMenu( separator ,menuFile, -1, 10)
-    
-    # Insert new line action
-    sgPyQt.createAction(dict_actions["insertLine"], "Insert Line", "Insert new line")
-    # Edit selected line action
-    sgPyQt.createAction(dict_actions["editLine"], "Edit Line", "Edit selected line")
-    # Remove selected line action
-    sgPyQt.createAction(dict_actions["removeLine"], "Remove Lines", "Remove selected lines")
-    # Clear all paragraphs
-    sgPyQt.createAction(dict_actions["clearAll"], "Clear All", "Clear all paragraphs")
-    # Display line
-    sgPyQt.createAction(dict_actions["displayLine"], "Display Line", "Display selected line")
-    # Erase line
-    sgPyQt.createAction(dict_actions["eraseLine"], "Erase Line", "Erase selected line")
-    
-    # Create 'PyLight' menu 
-    menuPyLight = sgPyQt.createMenu( "PyLight",-1,-1,50)
-    # Add actions in the menu 'PyLight'
-    sgPyQt.createMenu( dict_actions["insertLine"],  menuPyLight, 10 );
-    sgPyQt.createMenu( dict_actions["editLine"],  menuPyLight, 10 );
-    sgPyQt.createMenu( dict_actions["removeLine"],  menuPyLight, 10 );
-    sgPyQt.createMenu( separator, menuPyLight, -1, 10);
-    sgPyQt.createMenu( dict_actions["clearAll"],  menuPyLight, 10 );
-    sgPyQt.createMenu( separator, menuPyLight, -1, 10);
-    sgPyQt.createMenu( dict_actions["displayLine"],  menuPyLight, 10 );
-    sgPyQt.createMenu( dict_actions["eraseLine"],  menuPyLight, 10 );
-    
+    GUIcontext()
+    if verbose(): print("PYLIGHTGUI::initialize()")
     return
 
+# called when module is activated
+# returns True if activating is successfull and False otherwise
+def activate():
+    if verbose() : print("PYLIGHTGUI.activate()")
+    return True
+
+# called when module is deactivated
+def deactivate():
+    if verbose() : print("PYLIGHTGUI.deactivate()")
+    pass
 
 # Process GUI action
 def OnGUIEvent(commandID):
-    print "PYLIGHTGUI::OnGUIEvent : commandID =",commandID
-    if dict_command.has_key( commandID ):
+    if verbose() : print("PYLIGHTGUI::OnGUIEvent : commandID = %d" % commandID)
+    if commandID in dict_command:
         try:
             dict_command[commandID]()
         except:
             traceback.print_exc()
     else:
-       print "The command is not implemented: ",commandID
+       if verbose() : print("The command is not implemented: %d" % commandID)
     pass
 
 # Customize popup menu
 def createPopupMenu(popup, context):
+    global __data_model__
+    if verbose() : print("PYLIGHTGUI.createPopupMenu(): context = %s" % context)
 
-
-    
     if context != 'ObjectBrowser':
         return
     
     selcount = sg.SelectedCount()
     if selcount == 1:
         entry = sg.getSelected( 0 )
-        obj = DM.getObject(entry)
+        obj = __data_model__.getObject(entry)
         if obj is not None:
             if obj.getText() != "\n":
-                #Line is selected
+                # Line is selected
                 popup.addAction(sgPyQt.action(dict_actions["editLine"]))
                 popup.addAction(sgPyQt.action(dict_actions["removeLine"]))
                 popup.addSeparator()
                 popup.addAction(sgPyQt.action(dict_actions["displayLine"]))
                 popup.addAction(sgPyQt.action(dict_actions["displayLine"]))
                 popup.addAction(sgPyQt.action(dict_actions["eraseLine"]))
-
-                                                
+                pass
             else:
-                #Paragraph is selected
+                # Paragraph is selected
                 popup.addAction(sgPyQt.action(dict_actions["insertLine"]))
                 popup.addAction(sgPyQt.action(dict_actions["clearParagraph"]))
+                pass
+            pass
         else:
-            onlyLines = True            
+            onlyLines = True
+            pass
+        pass # if selcount == 1
     pass
 
 # For saving data in the study
-def saveFiles(prefix):
-    print "PYLIGHTGUI::saveFile()"
-    postfix = "PYLIGHT.txt"
-    filename = prefix+postfix
-    DM.saveFile(QString(filename))
-    return postfix
+def saveFiles(directory, url):
+    global __data_model__
+    if verbose(): print("PYLIGHTGUI::saveFile()")
+    filename = osp.join(directory, osp.splitext(osp.basename(url))[0]) + "_PYLIGHT.txt"
+    __data_model__.saveFile(filename)
+    return osp.basename(filename)
 
 # For restore data from the study
-def openFiles(filelist):
-    print "PYLIGHTGUI::openFile()"
-    filename =  filelist[0]
-    filename.append(filelist[1])
-    DM.loadFile(filename)
+def openFiles(filelist, url):
+    global __data_model__
+    if verbose(): print("PYLIGHTGUI::openFile()")
+    filename = os.path.join(*filelist)
+    __data_model__.loadFile(filename)
     return True
 
 # Loading a text file
 def loadfile():
+    global __data_model__
     aFilter = "Text files (*.txt)"
     filename = QFileDialog.getOpenFileName(sgPyQt.getDesktop(), "Open text file", "", aFilter, "Choose a text file to open")
-    if filename.isEmpty():
+
+    if isinstance(filename,tuple) and len(filename) >=2:
+       filename = filename[0]
+
+    if len(filename) == 0:
         return
     
     if os.access(str(filename),os.R_OK):
-        DM.loadFile(filename)
+        __data_model__.loadFile(filename)
     else:
         QMessageBox.warning(sgPyQt.getDesktop(),
                             "Error!",
-                            QString("Can not read file:\n%1").arg(filename))
+                            "Can not read file:\n%s"%(filename))
         pass
-    sg.updateObjBrowser(True)
+    sg.updateObjBrowser()
     pass
 
 # Saving a text file
 def savefile():
+    global __data_model__
     aFilter = "Text files (*.txt)"
     filename = QFileDialog.getSaveFileName(sgPyQt.getDesktop(),"Save text file", "", aFilter, "Choose a text file to save")
-    if filename.contains(".txt") == 0:
-        filename.append(".txt")
+
+    if isinstance(filename,tuple) and len(filename) >=2:
+        filename = filename[0]
+
+    if filename.endswith(".txt") == 0:
+        filename+=".txt"
         pass
+
     fn = filename
-    print filename
     # Get directory name and check access
-    if os.access(str(fn.left(fn.lastIndexOf("/"))), os.W_OK):
-        DM.saveFile(filename)
+    if os.access(str(fn[:fn.rindex(osp.sep)]), os.W_OK):
+        __data_model__.saveFile(filename)
     else:
         QMessageBox.warning(sgPyQt.getDesktop(),
                             "Error!",
-                            QString("Can not save file:\n%1").arg(filename))
+                            "Can not save file:\n%s"%(filename))
         pass
     pass
 
@@ -188,6 +252,7 @@ def insertLine():
     '''
     Insert new line in the selected paragraph.
     '''
+    global __data_model__
     #Get result
     res = QInputDialog.getText(sgPyQt.getDesktop(),
                                "Add new line",
@@ -200,20 +265,20 @@ def insertLine():
     # Nb selected objects
     selcount = sg.SelectedCount()
     # Nb object in the Data Model
-    paragrCount = len(DM.getParagraphs())
+    paragrCount = len(__data_model__.getParagraphs())
 
     # Create first paragraph
     if paragrCount == 0:
-        DM.createObject()
+        __data_model__.createObject()
         # If line not empty create first line
         if text != "\n":
-            DM.createObject(text,DM.getParagraphs()[0])
-        sg.updateObjBrowser(True)
+            __data_model__.createObject(text,__data_model__.getParagraphs()[0])
+        sg.updateObjBrowser()
         return
     # Create paragraph
     if text == "\n":
-        DM.createObject()
-        sg.updateObjBrowser(True)
+        __data_model__.createObject()
+        sg.updateObjBrowser()
         return
     else:
         if selcount == 0:
@@ -223,12 +288,12 @@ def insertLine():
             return
         if selcount == 1:
             entry = sg.getSelected( 0 )
-            obj = DM.getObject(entry)
+            obj = __data_model__.getObject(entry)
             if obj is not None:
                 # Create line
                 if(obj.getText() == "\n"):
-                    DM.createObject(text,entry)
-                    sg.updateObjBrowser(True);
+                    __data_model__.createObject(text,entry)
+                    sg.updateObjBrowser();
                     return
                 else:
                     QMessageBox.warning(sgPyQt.getDesktop(),
@@ -243,10 +308,11 @@ def insertLine():
         
 # Edit selected line
 def editLine():
+    global __data_model__
     if sg.SelectedCount() == 1:
         entry = sg.getSelected( 0 )
-        obj = DM.getObject(entry)
-        if(obj.getText() != "\n"):
+        obj = __data_model__.getObject(entry)
+        if(obj is not None and obj.getText() != "\n"):
             #Get text line
             res = QInputDialog.getText(sgPyQt.getDesktop(),
                                        "Edit line",
@@ -266,18 +332,22 @@ def editLine():
         QMessageBox.information(sgPyQt.getDesktop(),
                                 'Info',
                                 'Please, select one line!')
-    sg.updateObjBrowser(True);
+    sg.updateObjBrowser();
     pass
 
 # Remove selected lines
 def removeLine():
+    global __data_model__
     selcount = sg.SelectedCount()
     onlyLines = True
     lines = []
     while selcount != 0:
         entry = sg.getSelected( selcount - 1)
         #Check what only lines selected
-        if DM.getObject(entry).getText() == "\n":
+        obj = __data_model__.getObject(entry)
+        if obj is None:
+            continue
+        if obj.getText() == "\n":
             onlyLines = False
             break
         lines.append(entry)
@@ -293,17 +363,18 @@ def removeLine():
                 renderer.RemoveActor(actor)
                 pass
             pass
-        DM.removeObjects(lines)
-        sg.updateObjBrowser(True)
+        __data_model__.removeObjects(lines)
+        sg.updateObjBrowser()
         pass
     pass
 
 # Remove all lines from all paragraphs
 def clearAll():
-    paragraphs = DM.getParagraphs()
+    global __data_model__
+    paragraphs = __data_model__.getParagraphs()
     for paragr in paragraphs:
         lines = sgPyQt.getChildren(paragr)
-        DM.removeObjects(lines)
+        __data_model__.removeObjects(lines)
         renderer=libSalomePy.getRenderer()
         for l in lines:
             actor = getActor(l)
@@ -311,15 +382,22 @@ def clearAll():
                 renderer.RemoveActor(actor)
                 pass
             pass
-    sg.updateObjBrowser(True)
+    sg.updateObjBrowser()
     pass
 
 # Display the selected line
 def displayLine():
+    global __data_model__
     if sg.SelectedCount() != 1:
         return
     entry = sg.getSelected(0)
-    text = DM.getObject(entry).getText()
+    obj = ctx.DM.getObject(entry)
+    if obj is None:
+        QMessageBox.information(sgPyQt.getDesktop(),
+                                'Info',
+                                'Please, select line!')
+        return
+    text = obj.getText()
     if text == "\n":
         return
     renderer=libSalomePy.getRenderer()
@@ -334,24 +412,32 @@ def displayLine():
     txtPr = vtk.vtkTextProperty()
     txtPr.SetFontSize(30)
     actor.SetTextProperty(txtPr)
-    for act in  dict_actors.values():
+    for act in  list(dict_actors.values()):
         renderer.RemoveActor(act)
     renderer.AddActor(actor)
     pass
 
 # Clear remove all lines under selected paragraph
 def clearParagraph():
+    global __data_model__
     lines = sgPyQt.getChildren(sg.getSelected(0))
-    DM.removeObjects(lines)
-    sg.updateObjBrowser(True)
+    __data_model__.removeObjects(lines)
+    sg.updateObjBrowser()
     pass
 
 # Erase the selected line
 def eraseLine():
+    global __data_model__
     if sg.SelectedCount() != 1:
         return
     entry = sg.getSelected(0)
-    text = DM.getObject(entry).getText()
+    obj = __data_model__.getObject(entry)
+    if obj is None:
+        QMessageBox.information(sgPyQt.getDesktop(),
+                                'Info',
+                                'Please, select line!')
+        return
+    text = obj.getText()
     if text == "\n":
         return
     renderer=libSalomePy.getRenderer()
@@ -363,9 +449,8 @@ def eraseLine():
 
 # Return vtkActor by entry
 def getActor(entry):
-    if isinstance(entry,QString):
-        entry = entry.toLatin1().data()
-    if dict_actors.has_key(entry):
+    entry = str(entry)
+    if entry in dict_actors:
         return dict_actors[entry]
     return None