Salome HOME
Pour Adao
[tools/eficas.git] / InterfaceQT4 / browser.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2007-2013   EDF R&D
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20
21 import string,re
22 import types,sys,os
23 import traceback
24 import typeNode
25 from PyQt4 import *
26 from PyQt4.QtGui  import *
27 from PyQt4.QtCore import *
28 from Extensions.i18n import tr
29 from monChoixCommande import MonChoixCommande
30
31 class JDCTree( QTreeWidget ):
32     def __init__( self, jdc_item, QWParent):        
33         #if hasattr(QWParent,'widgetTree') : 
34         if QWParent.widgetTree !=None  :
35            QTreeWidget.__init__(self, QWParent.widgetTree ) 
36            QWParent.verticalLayout_2.addWidget(self)
37            self.headerItem().setText(0,  "Commande   ")
38            self.headerItem().setText(1, "Concept/Valeur")
39            self.setColumnWidth(0,200)
40            self.setExpandsOnDoubleClick(False)
41            self.setSelectionMode(3)
42         else :
43            QTreeWidget.__init__(self, None ) 
44         self.item          = jdc_item
45         self.tree          = self        
46         self.editor        = QWParent
47         self.appliEficas   = self.editor.appliEficas
48         self.childrenComplete=[]
49         self.childrenIssusDesBlocs=[]
50         self.racine=self.item.itemNode(self,self.item)
51  
52         self.itemCourrant=None
53
54         self.connect(self, SIGNAL("itemClicked ( QTreeWidgetItem * ,int) "), self.handleOnItem)
55         #self.connect(self, SIGNAL("itemDoubleClicked ( QTreeWidgetItem * ,int) "), self.handleDoubleClickedOnItem)
56
57         #PNPNPN verifier dans quel cas on se trouve : affiche l arbre ou la commande
58         self.node_selected=self.racine
59         self.expandItem(self.racine)
60         if self.racine.children !=[] :  self.racine.children[0].affichePanneau()
61         else : self.racine.affichePanneau()
62
63
64     def contextMenuEvent(self,event) :
65         print "contextMenuEvent"
66         coord=event.globalPos()
67         item= self.currentItem()
68         self.handleContextMenu(item,coord)
69
70     def handleContextMenu(self,item,coord):
71         """
72         Private slot to show the context menu of the listview.
73         
74         @param itm the selected listview item (QListWidgetItem)
75         @param coord the position of the mouse pointer (QPoint)
76         Attention : existeMenu permet de savoir si un menu est associe a cet item
77         """
78         print "handleContextMenu"
79         if item == None : return
80         if item.existeMenu == 0 : return
81         if item.menu == None:
82            item.createPopUpMenu()
83         if item.menu != None:
84            if item.item.get_nom() == "DISTRIBUTION" and item.item.isvalid() :
85               item.Graphe.setEnabled(1)
86            item.menu.exec_(coord)            
87             
88
89     def handleOnItem(self,item,int):
90         if (len(self.selectedIndexes())!=2): return
91         self.itemCourrant=item
92         self.handleDoubleClickedOnItem(item,int)
93         #try :
94         if 1:
95            fr = item.item.get_fr()
96            if self.editor: self.editor.labelCommentaire.setText(unicode(fr))
97         #except:
98         else :
99             pass
100
101     def handleDoubleClickedOnItem(self,item,int):
102         print "je passe dans handleDoubleClickedOnItem"
103         #if item.fenetre == None :
104         #   while not (hasattr (item,'getPanel2')) : item=item.treeParent 
105         #   item.affichePanneau()
106         #   self.expandItem(item)
107         #else:
108         #   item.fenetre.rendVisible()
109         itemParent=item
110         while not (hasattr (itemParent,'getPanel2')) : itemParent=item.treeParent 
111         itemParent.affichePanneau()
112         if itemParent!=item:
113            item.fenetre.rendVisible()
114
115     def choisitPremier(self,name):
116         self.editor.layoutJDCCHOIX.removeWidget(self.racine.fenetre)
117         self.racine.fenetre.close()
118         new_node=self.racine.append_brother(name,'after')
119  
120 # type de noeud
121 COMMENT     = "COMMENTAIRE"
122 PARAMETERS  = "PARAMETRE"
123  
124 class JDCNode(QTreeWidgetItem):
125     def __init__( self, treeParent, item):
126         #print "creation d'un noeud : ", item, " ",item.nom,"", treeParent
127         self.item        = item
128         self.vraiParent  = treeParent
129         self.treeParent  = treeParent
130         self.tree        = self.treeParent.tree
131         self.editor      = self.treeParent.editor
132         self.appliEficas = treeParent.appliEficas
133         self.treeParent.childrenIssusDesBlocs=[]
134         self.childrenComplete=[]
135                         
136         from InterfaceQT4 import compocomm
137         from InterfaceQT4 import compoparam
138         if   (isinstance(self.item,compocomm.COMMTreeItem)) : name=tr("Commentaire")
139         elif (isinstance(self.item,compoparam.PARAMTreeItem)) : name=self.appliEficas.trUtf8(str(item.GetLabelText()[0]))
140         else:   name  = self.appliEficas.trUtf8(str(tr( item.nom))+" :")
141         value = self.appliEficas.trUtf8(str( item.GetText() ) )
142
143         mesColonnes=QStringList()
144         mesColonnes <<  name << value
145
146         ajoutAuParentduNoeud=0
147         from InterfaceQT4 import compobloc
148         while (isinstance(self.treeParent,compobloc.Node)) :
149               self.treeParent=self.treeParent.treeParent
150               ajoutAuParentduNoeud=1
151         if ajoutAuParentduNoeud :
152            treeParent.childrenComplete.append(self)
153            self.treeParent.childrenIssusDesBlocs.append(self)
154         while (isinstance(self.treeParent,compobloc.Node)) : self.treeParent=self.treeParent.treeParent
155
156         if isinstance(self,compobloc.Node) : 
157            QTreeWidgetItem.__init__(self,None,mesColonnes)
158         else :
159            QTreeWidgetItem.__init__(self,self.treeParent,mesColonnes)
160            self.treeParent.childrenComplete.append(self)
161
162         self.setToolTip(0,QString(self.item.get_fr()))
163         self.setToolTip(1,QString(self.item.get_fr()))
164
165         repIcon=QString(self.appliEficas.repIcon)
166         monIcone = QIcon(repIcon+"/" +self.item.GetIconName() + ".png")
167         self.setIcon(0,monIcone)
168
169         self.children = []
170         self.build_children()
171         self.menu=None
172         self.existeMenu=1
173
174         self.item.connect("valid",self.onValid,())
175         self.item.connect("supp" ,self.onSupp,())
176         self.item.connect("add"  ,self.onAdd,())
177         self.state=""
178         self.fenetre=None
179         try :
180           if self.item.getObject().isBLOC() : self.setExpanded(True) 
181         except :
182           pass
183
184
185     def build_children(self,posInsertion=10000):
186         """ Construit la liste des enfants de self """
187         """ Se charge de remettre les noeuds Expanded dans le meme etat """
188         #print "*********** build_children ",self.item, self.item.GetLabelText()
189         
190         listeExpanded=[]
191         for item in self.childrenComplete :
192             #try :
193             #  print "              je detruis ",  item.item.GetLabelText() ," parent : ", item.treeParent.item.GetLabelText()
194             #except :
195             #  print "mot clef fact"
196             if item.isExpanded():
197                if self.childrenComplete.index(item) < posInsertion :
198                   listeExpanded.append(self.childrenComplete.index(item))
199                else :
200                   listeExpanded.append( self.childrenComplete.index(item) +1)
201             self.detruit_les_noeuds_issus_de_blocs(item)
202             parent=item.treeParent
203             parent.removeChild(item)
204
205         self.children = []
206         self.childrenComplete = []
207         sublist = self.item._GetSubList()
208         ind=0
209         for item in sublist :
210             nouvelItem=item.itemNode(self,item)
211             self.children.append(nouvelItem)
212             #print "         J ajoute ", nouvelItem ,nouvelItem.item.GetLabelText(),"dans" ,self.item.GetLabelText()
213             if ind in listeExpanded : nouvelItem.setExpanded(1)
214             ind=ind+1
215         #print "*********** fin build_children ",self.item, self.item.GetLabelText()
216         
217     def chercheNoeudCorrespondant(self,objSimp):
218         sublist = self.item._GetSubList()
219         for node in self.childrenComplete:
220             if node.item.object==objSimp : return node
221         return None
222
223     def affichePanneau(self) :
224         if self.item.isactif():
225             panel=self.getPanel2()
226         else:
227             from monInactifPanel import PanelInactif
228             panel = PanelInactif(self,self.editor)
229         if hasattr(self,'fenetre') and self.fenetre: 
230            self.fenetre.close()
231         self.fenetre=panel
232         if self.editor.fenetreCentraleAffichee != None : 
233            self.editor.fenetreCentraleAffichee.close()
234         self.editor.fenetreCentraleAffichee=panel
235         if self.editor.widgetTree !=None  : index=1
236         else : index=0
237         self.editor.widgetCentraleLayout.addWidget(self.fenetre)
238
239         if self.editor.first :
240            self.editor.splitter.setSizes((400,1400,400))
241            if not(isinstance(self.fenetre,MonChoixCommande)): self.editor.first=False
242         self.tree.expandItem(self)
243         self.select()
244           
245
246     def createPopUpMenu(self):
247         #implemente dans les noeuds derives si necessaire
248         self.existeMenu = 0
249
250     def commentIt(self):
251         """
252         Cette methode a pour but de commentariser la commande pointee par self
253         """
254         # On traite par une exception le cas ou l'utilisateur final cherche a désactiver
255         # (commentariser) un commentaire.
256         try :
257             pos=self.treeParent.children.index(self)
258             commande_comment = self.item.get_objet_commentarise()
259             # On signale a l editeur du panel (le JDCDisplay) une modification
260             self.editor.init_modif()
261             self.treeParent.build_children()
262             self.treeParent.children[pos].select()
263             self.treeParent.children[pos].affichePanneau()
264         except Exception,e:
265             traceback.print_exc()
266             QMessageBox.critical( self.editor, "TOO BAD",str(e))
267         
268     def unCommentIt(self):
269         """
270         Realise la decommentarisation de self
271         """
272         try :
273             pos=self.treeParent.children.index(self)
274             commande,nom = self.item.uncomment()
275             self.editor.init_modif()
276             self.treeParent.build_children()
277             self.treeParent.children[pos].select()
278             self.treeParent.children[pos].affichePanneau()
279         except Exception,e:
280             QMessageBox.critical( self.editor, "Erreur !",str(e))
281         
282     def addComment( self, after=True ):
283         """
284         Ajoute un commentaire a l'interieur du JDC :
285         """
286         self.editor.init_modif()
287         if after:
288             pos = 'after'
289         else:
290             pos = 'before'
291         return self.append_brother( COMMENT, pos )
292                 
293     def addParameters( self, after=True ):
294         """
295         Ajoute un parametre a l'interieur du JDC :
296         """
297         self.editor.init_modif()
298         if after:
299             pos = 'after'
300         else:
301             pos = 'before'
302         return self.append_brother( PARAMETERS, pos )
303     
304     
305     def select( self ):
306         """
307         Rend le noeud courant (self) selectionne et deselectionne
308         tous les autres
309         """        
310         for item in self.tree.selectedItems() :
311             item.setSelected(0)
312         self.setSelected( True )    
313         self.setExpanded( True )    
314         self.tree.setCurrentItem( self )    
315         self.tree.node_selected= self
316                                
317     #------------------------------------------------------------------
318     # Methodes de creation et destruction de noeuds
319     # Certaines de ces methodes peuvent etre appelees depuis l'externe
320     #------------------------------------------------------------------
321     def append_brother(self,name,pos='after'):
322         """
323         Permet d'ajouter un objet frere a l'objet associe au noeud self
324         par defaut on l'ajoute immediatement apres 
325         Methode externe
326         """
327         #print "*********** append_brother ", self.item.GetLabelText()
328         self.editor.init_modif()
329         index = self.treeParent.children.index(self)
330         if pos == 'before':
331             index = index
332         elif pos == 'after':
333             index = index +1
334         else:
335             print unicode(pos), tr("  n'est pas un index valide pour append_brother")
336             return 0
337         return self.treeParent.append_child(name,pos=index)
338
339     def append_child(self,name,pos=None):
340         """
341            Methode pour ajouter un objet fils a l'objet associe au noeud self.
342            On peut l'ajouter en debut de liste (pos='first'), en fin (pos='last')
343            ou en position intermediaire.
344            Si pos vaut None, on le place a la position du catalogue.
345         """
346         #print "************** append_child ",self.item.GetLabelText()
347         self.editor.init_modif()
348         if pos == 'first':
349             index = 0
350         elif pos == 'last':
351             index = len(self.children)
352         elif type(pos) == types.IntType :
353             # position fixee
354             index = pos
355         elif type(pos) == types.InstanceType:
356             # pos est un item. Il faut inserer name apres pos
357             index = self.item.get_index(pos) +1
358         elif type(name) == types.InstanceType:
359             index = self.item.get_index_child(name.nom)
360         else:
361             index = self.item.get_index_child(name)
362         obj=self.item.additem(name,index) #CS_pbruno emet le signal 'add'
363         if obj is None:obj=0
364         if obj == 0:return 0
365         ## PNPNPN : cas de Map nouvelle version 
366         #if 1 :
367         try :
368           #print "1er Try"
369           old_obj = self.item.object.get_child(name.nom,restreint = 'oui')
370           child=old_obj[-1]
371           child.affichePanneau() 
372         #else :
373         except:
374           # Souci pour gerer les copies des AFFE d'une commande à l autre
375           try :
376              child=self.children[index]
377              child.affichePanneau() 
378           except :
379              child=self.children[index]
380              pass
381         return child
382
383     def deplace(self):
384         self.editor.init_modif()
385         index = self.treeParent.children.index(self) - 1 
386         if index < 0 : index =0
387         ret=self.treeParent.item.deplaceEntite(self.item.getObject())
388
389     def delete(self):
390         """ 
391             Methode externe pour la destruction de l'objet associe au noeud
392         """
393         self.editor.init_modif()
394         index = self.vraiParent.children.index(self) - 1 
395         if index < 0 : index =0
396         recalcule=0
397         if self.item.nom == "VARIABLE" :
398            recalcule=1
399            jdc=self.item.jdc
400         ret=self.vraiParent.item.suppitem(self.item)
401         self.treeParent.build_children()
402         if self.treeParent.childrenComplete : toselect=self.treeParent.childrenComplete[index]
403         else: toselect=self.treeParent
404         if recalcule : jdc.recalcule_etat_correlation()
405         from InterfaceQT4 import compojdc
406         # cas ou on detruit dans l arbre sans affichage
407         if isinstance(self.treeParent,compojdc.Node) : 
408            toselect.affichePanneau()
409         else :
410            if self.treeParent.fenetre== None : return
411            print "J appelle reaffiche de browser apres delete"
412            self.treeParent.fenetre.reaffiche(toselect)
413
414     def deleteMultiple(self,liste=()):
415         """ 
416             Methode externe pour la destruction d une liste de noeud
417         """
418         from InterfaceQT4 import compojdc 
419         self.editor.init_modif()
420         index=9999
421         recalcule=0
422         jdc=self.treeParent
423         parentPosition=jdc
424         while not(isinstance(jdc,compojdc.Node)):
425               jdc=jdc.treeParent
426         for noeud in liste :
427             if not( isinstance(noeud.treeParent, compojdc.Node)): continue
428             if noeud.item.nom == "VARIABLE" : recalcule=1
429             if noeud.treeParent.children.index(noeud) < index : index=noeud.treeParent.children.index(noeud)
430         if index < 0 : index =0
431
432         # Cas ou on détruit dans une ETape
433         if index == 9999 : 
434               parentPosition=self.treeParent
435               while not(isinstance(parentPosition, compojdc.Node)):
436                  index=parentPosition.treeParent.children.index(parentPosition)
437                  parentPosition=parentPosition.treeParent
438
439         for noeud in liste:
440             noeud.treeParent.item.suppitem(noeud.item)
441
442         jdc.build_children()
443         if recalcule : jdc.recalcule_etat_correlation()
444         try    : toselect=parentPosition.children[index]
445         except : toselect=jdc
446         toselect.select()
447         toselect.affichePanneau()
448 #        
449 #    #------------------------------------------------------------------
450     def onValid(self):        
451
452         #print "onValid pour ", self.item.nom
453         if hasattr(self,'fenetre') and self.fenetre: 
454            self.fenetre.setValide()
455         if self.item.nom == "VARIABLE" and self.item.isvalid():
456            self.item.jdc.recalcule_etat_correlation()
457         if hasattr(self.item,'forceRecalcul'):
458            self.forceRecalculChildren(self.item.forceRecalcul)
459         self.editor.init_modif()
460         
461         self.update_node_valid()
462         self.update_node_label()
463         self.update_node_texte()
464
465     def onAdd(self,object):
466         #print "onAdd pour ", self.item.nom
467         self.editor.init_modif()
468         self.update_nodes()
469         print "dans onAdd" ,self.item 
470         # PN -- non necessaire si item=jdc
471         if hasattr(self.item,'jdc'): self.item.jdc.aReafficher=True
472  
473     def onSupp(self,object):
474         #print "onSupp pour ", self.item.nom
475         self.editor.init_modif()
476         self.update_nodes()
477         # PN -- non necessaire si item=jdc
478         if hasattr(self.item,'jdc'): self.item.jdc.aReafficher=True
479          
480     def detruit_les_noeuds_issus_de_blocs(self,bloc):
481         from InterfaceQT4 import compobloc
482         if (isinstance(bloc,compobloc.Node)) :
483            for node in bloc.childrenComplete :
484                self.detruit_les_noeuds_issus_de_blocs(node)
485                parent=node.treeParent
486                #print "je detruit " , node.item.GetLabelText()
487                parent.removeChild(node)
488
489     def update_node_valid(self):
490         """Cette methode remet a jour la validite du noeud (icone)
491            Elle appelle isvalid
492         """
493         repIcon=QString(self.appliEficas.repIcon)
494         monIcone = QIcon(repIcon+"/" +self.item.GetIconName() + ".png")
495         self.setIcon(0,monIcone)
496
497
498     def update_node_label(self):
499         """ Met a jour le label du noeud """
500         #print "NODE update_node_label", self.item.GetLabelText()
501         labeltext,fonte,couleur = self.item.GetLabelText()
502         # PNPN a reflechir
503         #self.setText(0, labeltext)        
504     
505     
506     def update_node_label_in_blue(self):
507         if hasattr(self.appliEficas,'noeudColore'):
508            self.appliEficas.noeudColore.setTextColor( 0,Qt.black)
509            self.appliEficas.noeudColore.update_node_label()
510         self.setTextColor( 0,Qt.blue )
511         labeltext,fonte,couleur = self.item.GetLabelText()
512         self.setText(0, labeltext)        
513         self.appliEficas.noeudColore=self
514
515     def update_plusieurs_node_label_in_blue(self,liste):
516         if hasattr(self.appliEficas,'listeNoeudsColores'):
517            for noeud in self.appliEficas.listeNoeudsColores:
518                noeud.setTextColor( 0,Qt.black)
519                noeud.update_node_label()
520         self.appliEficas.listeNoeudsColores=[]
521         for noeud in liste :
522             noeud.setTextColor( 0,Qt.blue )
523             labeltext,fonte,couleur = noeud.item.GetLabelText()
524             noeud.setText(0, labeltext)        
525             self.appliEficas.listeNoeudsColores.append(noeud)
526
527     def update_node_texte_in_black(self):
528         """ Met a jour les noms des SD et valeurs des mots-cles """
529         self.setTextColor( 1,Qt.black )
530         value = self.item.GetText()
531         self.setText(1, value)
532
533     def update_node_texte(self):
534         """ Met a jour les noms des SD et valeurs des mots-cles """
535         value = self.item.GetText()
536         self.setText(1, value)
537
538     def update_node_texte_in_blue(self):
539         self.setTextColor( 1,Qt.blue )
540         value = self.item.GetText()
541         self.setText(1, value)
542
543     def update_nodes(self):
544         #print 'NODE update_nodes', self.item.GetLabelText()
545         self.build_children()
546
547     def update_valid(self) :
548         """Cette methode a pour but de mettre a jour la validite du noeud
549            et de propager la demande de mise a jour a son parent
550         """
551         #print "NODE update_valid", self.item.GetLabelText()
552         self.update_node_valid()
553         try :
554           self.treeParent.update_valid()
555         except:
556           pass
557             
558     def update_texte(self):
559         """ Met a jour les noms des SD et valeurs des mots-cles """
560         #print "NODE update_texte", self.item.GetLabelText()
561         self.update_node_texte()
562         if self.isExpanded() :
563             for child in self.children:
564                 if child.isHidden() == false : child.update_texte()
565
566
567     def forceRecalculChildren(self,niveau):
568         if self.state=='recalcule' : 
569            self.state=""
570            return
571         self.state='recalcule'
572         if hasattr(self.item,'object'):
573            self.item.object.state="modified"
574         for child in self.children:
575            if niveau > 0 : child.forceRecalculChildren(niveau - 1)
576               
577         
578
579     def doPaste(self,node_selected,pos='after'):
580         """
581             Déclenche la copie de l'objet item avec pour cible
582             l'objet passé en argument : node_selected
583         """
584         #print 'je passe dans doPaste'
585         objet_a_copier = self.item.get_copie_objet()
586         child=node_selected.doPasteCommande(objet_a_copier,pos)
587         return child
588
589     def doPasteCommande(self,objet_a_copier,pos='after'):
590         """
591           Réalise la copie de l'objet passé en argument qui est nécessairement
592           une commande
593         """
594         child=None
595         try :
596           child = self.append_brother(objet_a_copier,pos)
597         except :
598            pass
599         return child
600
601     def doPastePremier(self,objet_a_copier):
602         """
603            Réalise la copie de l'objet passé en argument (objet_a_copier)
604         """
605         objet = objet_a_copier.item.get_copie_objet()
606         child = self.append_child(objet,pos='first')
607         return child
608
609     def setPlie(self):
610         self.plie=True
611         self.setPlieChildren()
612
613     def setPlieChildren(self):
614         self.appartientAUnNoeudPlie=True
615         for item in self.children :
616             item.setPlieChildren()
617             
618
619     def setDeplie(self):
620         self.plie=False
621         self.setDeplieChildren()
622
623     def setDeplieChildren(self):
624         self.appartientAUnNoeudPlie=False
625         for item in self.children :
626             item.setDeplieChildren()
627             
628
629