Debian Codegraph @

wxgeometrie/GUI/fenetre_principale.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 ##--------------------------------------##
4 # WxGeometrie #
5 # fenetre principale #
6 ##--------------------------------------##
7 # WxGeometrie
8 # Dynamic geometry, graph plotter, and more for french mathematic teachers.
9 # Copyright (C) 2005-2013 Nicolas Pourcelot
10 #
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
15 #
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with this program; if not, write to the Free Software
23 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
24
25 import sys, os, _thread, traceback
26
27 from PyQt5.QtGui import QIcon, QColor, QPalette, QTextCursor
28 from PyQt5.QtWidgets import QApplication, QMainWindow, QPlainTextEdit, QLabel,\
29 QWidget, QMessageBox, QVBoxLayout
30 from PyQt5.QtCore import QSize, Qt, pyqtSignal
31
32 from ..pylib import print_error, path2, debug, warning
33 from ..API.console import Console
34 from ..API.sauvegarde import FichierSession
35 from ..API.parametres import sauvegarder_module
36 from .ligne_commande import LigneCommande
37 from .gestion_session import GestionnaireSession
38 from .onglets import Onglets
39 from .. import param
40 NOMPROG = param.NOMPROG
41
42
43 class PyOnDemandOutputWindow(QPlainTextEdit):
44 def __init__(self, title):
45 QPlainTextEdit.__init__(self)
46 self.setWindowTitle(title)
47 self.setReadOnly(True) # assuming QPlainTextEdit
48 self.hide()
49 self.resize(QSize(450, 300))
50
51 def write(self, s):
52 self.show()
53 self.moveCursor(QTextCursor.End)
54 self.insertPlainText(s) # again assuming QPlainTextEdit
55
56 def close(self):
57 try:
58 QPlainTextEdit.close(self)
59 except RuntimeError:
60 # Erreur à la fermeture du programme, quand on ferme toutes les sorties car l'objet Qt n'existe déjà plus.
61 pass
62
63 class FenetrePrincipale(QMainWindow):
64
65 def __init__(self, app, fichier_log=None):
66 QMainWindow.__init__(self, None)
67 self.setWindowTitle(NOMPROG)
68 self.setStyleSheet(".QWidget {background:white}")
69 # palette = QPalette()
70 # white = QColor(Qt.white)
71 # palette.setColor(QPalette.Window, white)
72 # palette.setColor(QPalette.AlternateBase, white)
73 # self.setPalette(palette)
74
75 self.application = app # pour acceder a l'application en interne
76 # Pour que toutes les fenêtres puissent simplement retrouver la
77 # fenêtre principale:
78 app.fenetre_principale = self
79
80
81 # À créer avant les onglets
82 self.fenetre_sortie = PyOnDemandOutputWindow(title="%s - messages."
83 % NOMPROG)
84 self.fenetre_sortie.setWindowIcon(
85 QIcon(path2("%/wxgeometrie/images/icone_log.svg")))
86 self.fichier_log = fichier_log
87
88 self.setWindowIcon(QIcon(path2("%/wxgeometrie/images/icone.svg")))
89 self.barre = self.statusBar()
90 self.barre_dte = QLabel(self)
91 # self.barre_dte.setText(
92 self.barre.addPermanentWidget(self.barre_dte)
93
94
95
96 self.message(" Bienvenue !", 1)
97 self.message(NOMPROG + " version " + param.version)
98
99 #Ligne de commande de débogage
100 self.ligne_commande = LigneCommande(self, 300, action=self.executer_commande,
101 afficher_bouton=False, legende='Ligne de commande :')
102 self.ligne_commande.setVisible(param.ligne_commande)
103
104 # Creation des onglets et de leur contenu
105 self.onglets = Onglets(self)
106
107 self.mainWidget=QWidget(self) # dummy widget to contain the
108 # layout manager
109 self.setCentralWidget(self.mainWidget)
110 self.mainLayout = QVBoxLayout(self.mainWidget)
111 self.mainLayout.setSpacing(0)
112 self.mainLayout.addWidget(self.ligne_commande, 0)
113 self.mainLayout.addWidget(self.onglets)
114
115 self.setMinimumSize(*param.dimensions_fenetre)
116
117 self.console = Console(self)
118
119 self.setAcceptDrops(True)
120 self.setFocus()
121
122 # closing == True si l'application est en train d'être fermée
123 self.closing = False
124
125 self.gestion = GestionnaireSession(self.onglets)
126
127
128 def dragEnterEvent(self, event):
129 if event.mimeData().hasUrls():
130 if any(url.path().endswith('.geo') or url.path().endswith('.geoz')
131 for url in event.mimeData().urls()):
132 event.accept()
133 else:
134 event.ignore()
135 else:
136 event.ignore()
137
138 def dropEvent(self, event):
139 assert event.mimeData().hasUrls()
140 for url in event.mimeData().urls():
141 if url.path().endswith('.geo') or url.path().endswith('.geoz'):
142 self.onglets.ouvrir(url.toLocalFile())
143
144 def afficher_ligne_commande(self, afficher=None):
145 "Afficher ou non la ligne de commande."
146 if afficher is not None:
147 if isinstance(afficher, bool):
148 param.ligne_commande = afficher
149 else:
150 param.ligne_commande = not param.ligne_commande
151 self.ligne_commande.setVisible(param.ligne_commande)
152 if param.ligne_commande:
153 self.ligne_commande.setFocus()
154 return param.ligne_commande
155
156
157 def mode_debug(self, debug=None):
158 "Passer en mode déboguage."
159 if debug is not None:
160 if isinstance(debug, bool):
161 param.debug = debug
162 else:
163 param.debug = not param.debug
164 if not param.debug:
165 self.fenetre_sortie.close()
166 return param.debug
167
168
169 def message(self, texte, lieu=0):
170 if lieu == 0:
171 self.barre.showMessage(texte)
172 else:
173 assert lieu == 1
174 self.barre_dte.setText(texte)
175
176
177 def titre(self, texte=None):
178 titre = NOMPROG
179 if texte:
180 titre += ' - ' + texte
181 self.setWindowTitle(titre)
182
183
184 def executer_commande(self, commande, **kw):
185 try:
186 self.console.executer(commande)
187 self.message("Commande interne exécutée.")
188 self.ligne_commande.clear()
189 except Exception:
190 self.message("Commande incorrecte.")
191 if param.debug:
192 raise
193
194 def plein_ecran(self):
195 "Bascule en mode plein écran <-> mode normal."
196 self.setWindowState(self.windowState()^Qt.WindowFullScreen)
197
198 def show(self):
199 QMainWindow.show(self)
200 # Si la liste des onglets n'est pas vide, on indique que l'onglet
201 # affiché est devenu onglet actif (on invoque manuellement
202 # l'action .evt_changer() qui est associée à chaque changement d'onglet).
203 # NOTA: à effectuer **après** QMainWindow.show() !
204 # Sinon, par exemple, le champ de saisie de la calculatrice ne peut
205 # récupérer le focus à cette occasion.
206 if self.onglets.onglet_actuel is not None:
207 self.onglets.evt_changer(self.onglets.currentIndex())
208
209 def closeEvent(self, event):
210 self.activateWindow()
211 self.showNormal()
212 self.raise_()
213 self.closing = True
214 if not param.fermeture_instantanee: # pour des tests rapides
215 try:
216 if param.confirmer_quitter and not param._restart:
217 panel = self.onglets.onglet_actuel
218 test = hasattr(panel, 'canvas') and hasattr(panel.canvas, 'setUpdatesEnabled')
219 if test:
220 panel.canvas.setUpdatesEnabled(False)
221 reponse = QMessageBox.question(self, 'Quitter %s ?' %NOMPROG,
222 'Voulez-vous quitter %s ?' %NOMPROG,
223 QMessageBox.Yes | QMessageBox.No,
224 QMessageBox.Yes)
225 if test:
226 panel.canvas.setUpdatesEnabled(True)
227 if reponse != QMessageBox.Yes:
228 self.closing = False
229 event.ignore()
230 return
231
232 self.gestion.fermer()
233
234 # for onglet in self.onglets:
235 # try:
236 # if isinstance(onglet, Panel_API_graphique):
237 # if param.historique_log:
238 # onglet.log.archiver()
239 # onglet.fermer_feuilles()
240 # except:
241 # #print_error()
242 # debug(u"Fermeture incorrecte de l'onglet : ", uu(str(onglet)))
243 # raise
244
245 except Exception:
246 try:
247 print_error()
248 QMessageBox.warning(self, "Erreur lors de la fermeture du programme", traceback.format_exc())
249 except UnicodeError:
250 QMessageBox.warning(self, "Erreur lors de la fermeture du programme", "Impossible d'afficher l'erreur.")
251 sys.stdout = sys.__stdout__
252 sys.stderr = sys.__stderr__
253 if hasattr(self, "fenetre_sortie"):
254 self.fenetre_sortie.close()
255 print("On ferme !")
256
257
258 def restart(self):
259 param._restart = True
260 self.close()