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