kcg.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. from PyQt4 import QtGui, QtCore
  2. import os
  3. import logging
  4. # --------[ Backend ]---------
  5. from . import backendinterface as bif
  6. # --------[ Essentials ]---------
  7. from . import storage
  8. from .settings import Settings
  9. # --------[ Necessary Widgets ]------
  10. from . import kcgwidget as kcgw
  11. from .ControlWidget import ControlWidget
  12. from .MultiWidget import MultiWidget
  13. from .groupedelements import MenuItems, Elements
  14. from .backend.board import available_boards
  15. from .backend import board
  16. from .backend.CalibrationHandle import theCalibration
  17. from .MultiPage import MultiPage
  18. from .globals import glob as global_objects
  19. from . import bitsTable as bt
  20. from . import log
  21. from ..widgets.ConfigSetup import ConfigSetup
  22. # ---------[ Widgets IMPORTANT!!! ]------------------
  23. # this enables widgets. If this is not imported (even though it is not directly used) no widgets will be available
  24. from ..widgets import *
  25. # from widgets import * # copy in case the above line gets removed by ide
  26. # ---------[ IMPORTANT ]---------------------
  27. tr = kcgw.tr
  28. from .. import config
  29. import time
  30. import getpass
  31. def readconfig(parent):
  32. """
  33. Reads the config and evalues certain variables
  34. Also: Validates config to check if all necessary values are there
  35. :param parent: parent for popup windows
  36. :return: -
  37. """
  38. nec_conf = ['acquireSettingsIcon', 'bunches_per_turn', 'default_log_entries', 'default_save_location', 'default_subdirectory_name',
  39. 'force_ask', 'guiIcon', 'language', 'logCommentIcon', 'working_channels',
  40. 'logIcon', 'newPlotDataIcon', 'newPlotLiveIcon', 'save_header', 'show_advanced_control', 'singleReadIcon', 'startIcon',
  41. 'stopIcon', 'style', 'tRev', 'timingIcon']
  42. missing_conf = []
  43. for c in nec_conf:
  44. if c not in dir(config):
  45. missing_conf.append(c)
  46. if missing_conf:
  47. class ConfigError(Exception):
  48. pass
  49. raise ConfigError('The Following variables are missing in config.py: "' + '", "'.join(missing_conf)+'"')
  50. if config.language != "en_GB":
  51. kcgw.translator.load(os.path.join(config.install_path,'lang',config.language))
  52. else:
  53. global tr
  54. kcgw.tr = lambda _, x: x
  55. tr = lambda _, x: x
  56. dateG = "{d}.{m}.{y}"
  57. dateGd = "{d}_{m}_{y}"
  58. dateA = "{m}-{d}-{y}"
  59. times = "{H}_{M}"
  60. timel = "{H}_{M}_{S}"
  61. session = ""
  62. if "{ask}" in config.default_subdirectory_name:
  63. status = False
  64. while not status:
  65. text, status = QtGui.QInputDialog.getText(parent, tr("Heading", "Subdirectory"),
  66. tr("Dialog", "Enter a name for the Subdirectory\n"
  67. "in which data will be saved:\n"
  68. "NOTE: You are being asked because it "
  69. "was set this way in the config file."))
  70. if not status and not config.force_ask:
  71. config.default_subdirectory_name = "{user}_{dateGd}-{timel}"
  72. break
  73. else:
  74. config.subdirectory_name = text.replace(" ", "_")
  75. return
  76. if "{sessionname}" in config.default_subdirectory_name:
  77. status = False
  78. while not status:
  79. text, status = QtGui.QInputDialog.getText(parent, tr("Heading", "Sessionname"),
  80. tr("Dialog", "Enter Sessionname\n"
  81. "NOTE: You are being asked because it "
  82. "was set this way in the config file.:"))
  83. if not status and not config.force_ask:
  84. config.default_subdirectory_name = "{user}_{dateGd}-{timel}"
  85. break
  86. else:
  87. session = text.replace(" ", "_")
  88. config.default_subdirectory_name = config.default_subdirectory_name.format(
  89. dateG=dateG, dateGd=dateGd, dateA=dateA, times=times, timel=timel,
  90. d=time.strftime("%d"), m=time.strftime("%m"), y=time.strftime("%y"),
  91. H=time.strftime("%H"), M=time.strftime("%M"), S=time.strftime("%S"),
  92. timestamp=time.localtime(), user=getpass.getuser(), sessionname=session
  93. )
  94. config.subdirectory_name = config.default_subdirectory_name.format(
  95. d=time.strftime("%d"), m=time.strftime("%m"), y=time.strftime("%y"),
  96. H=time.strftime("%H"), M=time.strftime("%M"), S=time.strftime("%S"),
  97. timestamp=time.localtime(), user=getpass.getuser()
  98. )
  99. if config.default_save_location == "pwd":
  100. import os
  101. config.save_location = os.getcwd()
  102. else:
  103. config.save_location = config.default_save_location
  104. _MultiView_Name_ = "MultiView"
  105. class CentralWidget(kcgw.KCGWidgets):
  106. """
  107. Central Widget for the KCG gui main window
  108. """
  109. def __init__(self, parent=None):
  110. super(CentralWidget, self).__init__(parent=parent)
  111. # -------[ Create empty Groups to avoid warnings ]---------
  112. MenuItems.createEmptyGroup('Setup/Control')
  113. MenuItems.createEmptyGroup('Bits Table')
  114. # -------[ END ]---------------
  115. self.layout = QtGui.QHBoxLayout()
  116. self.setLayout(self.layout)
  117. self.pagesWidget = MultiPage(self)
  118. self.layout.addWidget(self.pagesWidget)
  119. self.mainControlWidget = ControlWidget()
  120. self.pagesWidget.addPage(self.mainControlWidget, "Setup/Control")
  121. self.mainMultiWidget = MultiWidget()
  122. self.pagesWidget.addPage(self.mainMultiWidget, "MultiView")
  123. # self.tableWidget = bt.AdvancedBoardInterface(parent=self)
  124. self.tableWidget = bt.AdvanceControlView()
  125. self.tableWidget.hide()
  126. # .d8888b. 888 8888888888
  127. # d88P Y88b888 888 888
  128. # 888 888888 888 888
  129. # 888 888 888 888
  130. # 888 88888888 888 888
  131. # 888 888888 888 888
  132. # Y88b d88PY88b. .d88P 888
  133. # "Y8888P88 "Y88888P" 8888888
  134. class Gui(QtGui.QMainWindow):
  135. """
  136. Main Window of the KCG gui
  137. """
  138. def __init__(self):
  139. super(Gui, self).__init__()
  140. self.createEmptyGroups()
  141. # -------[ Check for boards and create corresponding objects ]------
  142. for board_id in available_boards:
  143. board.create_new_board_config(board_id)
  144. # board.get_board_config(board_id).observe(None, lambda x: bif.update_header(board_id), 'header') # Set update_header as function to call when header config is changed
  145. for board_id in available_boards:
  146. bif.initStatus(board.get_board_status(board_id)) # fill status storage with correct variables
  147. readconfig(self)
  148. # ----------[ Set Variables and create objects ]-----------------
  149. # self.storage = storage.Storage()
  150. self.storage = storage.storage
  151. # storage.storage = self.storage
  152. self.settings = None # (this holds the settings window) Only create Window when used
  153. self.statusbar = self.statusBar()
  154. # kcgw.statusbar = self.statusbar # set status bar to kcgw to easily access from other sources
  155. global_objects.set_global('statusbar', self.statusbar)
  156. self.pageIndicator = QtGui.QLabel()
  157. self.statusbar.addPermanentWidget(self.pageIndicator)
  158. self.cw = CentralWidget(self)
  159. self.doMenu()
  160. self.setCentralWidget(self.cw)
  161. self.initUI()
  162. self.finalizeInit()
  163. self.after_start_status_handler()
  164. self.setContentsMargins(0, -10, 0, 0)
  165. def initUI(self):
  166. """
  167. Initialize ui
  168. :return: -
  169. """
  170. self.setWindowTitle("KCG - Kapture Control Gui")
  171. self.setWindowIcon(QtGui.QIcon(config.icon_path(config.guiIcon)))
  172. # QtGui.QApplication.setStyle("Oxygen") # Make it look less blown up in Gnome for example
  173. def createEmptyGroups(self):
  174. """
  175. This creates empty groups with the GroupedObjects class in groupedelements module.
  176. This has to be done to avoid warnings when groups are enabled or disabled before creation.
  177. :return: -
  178. """
  179. for board_id in available_boards:
  180. Elements.createEmptyGroup("acquire_{}".format(board_id))
  181. Elements.createEmptyGroup("timing_{}".format(board_id))
  182. Elements.createEmptyGroup("no_board_{}".format(board_id))
  183. Elements.createEmptyGroup("continuous_read_{}".format(board_id))
  184. def finalizeInit(self):
  185. """
  186. Final things done at initialisation
  187. :return: -
  188. """
  189. self.populate_storage()
  190. with open(config.style_path("style.css")) as f:
  191. styleSheet = f.read()
  192. if config.style == 'blue':
  193. with open(config.style_path('blue.css')) as f:
  194. styleSheet += f.read()
  195. self.setStyleSheet(styleSheet)
  196. # evaluate config file regarding advanced_control
  197. self.showAdvancedControl(config.show_advanced_control)
  198. self.storage.advanced_control = config.show_advanced_control
  199. bif._bif_update_working_dir()
  200. self.measurementLogger = log.MeasurementLogger()
  201. log.logger = self.measurementLogger
  202. logStrings = []
  203. functionAndParameter = []
  204. for par in self.measurementLogger.predefined_parameters: # get strings and functions in seperate lists
  205. logStrings.append(par[0])
  206. functionAndParameter.append(par[1])
  207. for e in config.default_log_entries: # for every entry:
  208. if e in logStrings:
  209. self.measurementLogger.register_parameter(e, functionAndParameter[logStrings.index(e)][0], functionAndParameter[logStrings.index(e)][1])
  210. # activate Epics if defined
  211. if config.use_epics:
  212. from ..widgets import EpicsWidget
  213. EpicsWidget.epicsConfig = EpicsWidget.EpicsConfig()
  214. # open default CalibrationFile
  215. theCalibration.openFile(config.config_path("calibration.hdf"))
  216. def doMenu(self):
  217. """
  218. Create and show the menu and it's entries
  219. :return: -
  220. """
  221. self.menu = self.menuBar()
  222. self.fileMenu = self.menu.addMenu("&"+tr("Button", "File"))
  223. self.saveConfigAction = self.fileMenu.addAction(tr("Button", "Save Board Configuration"), self.saveConfig)
  224. self.saveConfigAction = self.fileMenu.addAction(tr("Button", "Load Board Configuration"), self.loadConfig)
  225. self.settingsAction = self.fileMenu.addAction(tr("Button", "Settings"), self.showSettings, "Ctrl+P")
  226. self.configAction = self.fileMenu.addAction(tr("Button", "Rerun Configuration Wizard"), self.rerunConfig)
  227. self.quitAction = self.fileMenu.addAction(QtGui.QIcon(config.icon_path("exit.png")), tr("Button", "Quit"), self.close, "Ctrl+Q")
  228. self.menu.setCornerWidget(self.cw.pagesWidget.leftright)
  229. # ----------[ Page specific Menu Entries ]-------------
  230. self.multiMenu = self.menu.addMenu("&"+tr("Button", "Windows"))
  231. MenuItems.addMenuItem(_MultiView_Name_, self.multiMenu)
  232. self.plotAction = self.multiMenu.addAction(QtGui.QIcon(config.icon_path(config.newPlotLiveIcon)), tr("Button", "New Plot"), self.cw.mainMultiWidget.leftBar.add_plot)
  233. self.addWindowMenuEntries()
  234. if not available_boards.multi_board:
  235. self.acquireMenu = self.menu.addMenu("&"+tr("Button", "Acquire"))
  236. MenuItems.addMenuItem(_MultiView_Name_, self.acquireMenu)
  237. self.startAcquisitionAction = self.acquireMenu.addAction(QtGui.QIcon(config.icon_path(config.startIcon)),
  238. tr("Button", "Start Acquisition"), lambda: bif.bk_acquire(available_boards[0]))
  239. self.startAcquisitionAction.setObjectName("start_acquisition_action")
  240. MenuItems.addMenuItem("continuous_read_{}".format(available_boards[0]), self.startAcquisitionAction)
  241. MenuItems.addMenuItem("acquireTrigger_{}".format(available_boards[0]), self.startAcquisitionAction)
  242. # -----[ disable Menu Items for MultiView as it is not the startup page ]-------------
  243. # this could be avoided if menu is created before the multipage widget
  244. MenuItems.setEnabled(_MultiView_Name_, False)
  245. self.help = self.menu.addMenu("&"+tr("Button", "Help"))
  246. import webbrowser
  247. self.help.addAction(tr("Button", "Open Manual"), lambda: webbrowser.open(os.path.join(config.install_path, "Documentation","build","html","index.html")))
  248. self.help.addAction(tr("Button", "About"), self.showAbout)
  249. def _show_board_chooser(self):
  250. selected_boards = []
  251. if len(available_boards.board_ids) == 1:
  252. return [available_boards.board_ids[0]]
  253. chooser = QtGui.QDialog(self)
  254. chooser.setWindowTitle("KCG - Choose Boards")
  255. chooser_layout = QtGui.QVBoxLayout()
  256. chooser.setLayout(chooser_layout)
  257. chooser_layout.addWidget(QtGui.QLabel("Choose Boards"))
  258. boards = {}
  259. for bid in available_boards.board_ids:
  260. boards[bid] = QtGui.QCheckBox(str(bid), chooser)
  261. chooser_layout.addWidget(boards[bid])
  262. button = QtGui.QPushButton("OK", chooser)
  263. def ok():
  264. for bi, box in list(boards.items()):
  265. if box.isChecked():
  266. selected_boards.append(bi)
  267. chooser.close()
  268. button.clicked.connect(ok)
  269. chooser_layout.addWidget(button)
  270. chooser.exec_()
  271. return selected_boards
  272. def saveConfig(self, board_id=None):
  273. """
  274. Save the current configuration to a configuration file
  275. :param board_id: the board to save the configuration for
  276. """
  277. filenameDialog = QtGui.QFileDialog(self, tr("Heading", "Save Configuration"), '', 'KAPTURE Configuration File (*.kcf)')
  278. filenameDialog.setDefaultSuffix("kcf")
  279. filenameDialog.setAcceptMode(filenameDialog.AcceptSave)
  280. filenameDialog.exec_()
  281. filename = filenameDialog.selectedFiles()
  282. if not filename:
  283. return
  284. if board_id is None:
  285. board_id = self._show_board_chooser()
  286. elif not isinstance(board_id, list):
  287. board_id = [board_id]
  288. fname = filename[0].split(".")
  289. for bid in board_id:
  290. if len(board_id) == 1:
  291. fname_board = filename[0]
  292. else:
  293. fname_board = ".".join(map(str, fname[:-1]))+"_"+str(bid)+"."+fname[-1]
  294. if not board.get_board_config(bid).save_config(fname_board):
  295. QtGui.QMessageBox.critical(self, tr("Heading", "Error Saving Config"), tr("Dialog", "There was an error saving to a config file."))
  296. def loadConfig(self, board_id=None):
  297. """
  298. Load the configuration for the given board from a file
  299. :param board_id: the board to read the configuration for
  300. """
  301. filename = QtGui.QFileDialog.getOpenFileName(self, 'Open Configuration', '', 'KAPTURE Configuration File (*.kcf)')
  302. if not filename:
  303. return
  304. if board_id is None:
  305. board_id = self._show_board_chooser()
  306. elif not isinstance(board_id, list):
  307. board_id = [board_id]
  308. for bid in board_id:
  309. if board.get_board_config(bid).load_config(filename):
  310. bif.bk_write_values(bid, defaults=False)
  311. else:
  312. QtGui.QMessageBox.critical(self, tr("Heading", "Error Loading Config"), tr("Dialog", "There was an error loading the config file, make sure it is valid and try again."))
  313. def rerunConfig(self):
  314. """
  315. Rerun the initial configuration wizard
  316. """
  317. self.setupConfig = ConfigSetup(restart=True)
  318. self.setupConfig.setWindowModality(QtCore.Qt.ApplicationModal)
  319. def restart():
  320. import subprocess
  321. import sys
  322. import os
  323. try:
  324. subprocess.Popen(['kcg'])
  325. except OSError as exception:
  326. try:
  327. path = config.install_path[:-4]+'kcg'
  328. subprocess.Popen([sys.executable, path])
  329. except:
  330. print('ERROR: could not restart aplication:')
  331. print((' %s' % str(exception)))
  332. else:
  333. QtGui.qApp.quit()
  334. else:
  335. QtGui.qApp.quit()
  336. self.setupConfig.success_signal.connect(restart)
  337. self.setupConfig.show()
  338. def showAbout(self):
  339. """
  340. Show the about window.
  341. :return: -
  342. """
  343. version = open(os.path.join(config.install_path,"VERSION")).read()
  344. about = QtGui.QDialog(self)
  345. about.setWindowTitle("KCG - About")
  346. about_label = QtGui.QLabel(tr("About", "KAPTURE Control Gui\n"
  347. "KCG is a graphical control interface to the KAPTURE board\n\n"
  348. "Author: Patrick Schreiber\n\n"
  349. "Version:\n")+version)
  350. about_label.setAlignment(QtCore.Qt.AlignCenter)
  351. header_label = QtGui.QLabel(tr("About", "KCG"))
  352. header_label.setStyleSheet("font-size: 25pt; text-align: center;")
  353. header_label.setAlignment(QtCore.Qt.AlignCenter)
  354. footer_label = QtGui.QLabel(tr("About", "\nKAPTURE - Karlsruhe Pulse-Taking and Ultrafast Readout Electronics"))
  355. footer_label.setStyleSheet("font-size: 7pt;")
  356. footer_label.setAlignment(QtCore.Qt.AlignRight)
  357. about_layout = QtGui.QHBoxLayout()
  358. about_text_layout = QtGui.QVBoxLayout()
  359. about.setLayout(about_layout)
  360. # pxm = QtGui.QPixmap(config.guiIcon)
  361. # icon_layout = QtGui.QVBoxLayout()
  362. # icon_label = QtGui.QLabel("")
  363. # icon_label.setPixmap(pxm.scaled(QtCore.QSize(128, 128), QtCore.Qt.KeepAspectRatio))
  364. # icon_label.setFixedSize(130, 130)
  365. # icon_layout.addWidget(icon_label)
  366. # icon_layout.addStretch(1)
  367. # about_layout.addLayout(icon_layout)
  368. about_layout.addLayout(about_text_layout)
  369. about_text_layout.addWidget(header_label)
  370. about_text_layout.addWidget(about_label)
  371. about_text_layout.addWidget(footer_label)
  372. about.setFixedSize(400, 230)
  373. about.setStyleSheet("background-color: darkgrey;")
  374. about.exec_()
  375. def addWindowMenuEntries(self):
  376. """
  377. Adds Window Menu entries for custom widgets
  378. :return: -
  379. """
  380. for f in kcgw.get_registered_widgets():
  381. self.multiMenu.addAction(*f[:3]) # TODO: icon - ???
  382. def showSettings(self):
  383. """
  384. Create and show settings window
  385. :return: -
  386. """
  387. if self.settings: # use preopened window
  388. self.settings.show()
  389. self.settings.raise_()
  390. self.settings.activateWindow()
  391. else:
  392. self.settings = Settings(self.storage)
  393. self.settings.changed.connect(self.updateSettings)
  394. def updateSettings(self, changedsettings):
  395. """
  396. Update settings in storage if settings were changed in the settings window.
  397. :param changedsettings: list of settings that have been changed
  398. :return: -
  399. """
  400. for setting in changedsettings:
  401. if setting == 'language':
  402. lang = getattr(self.storage, setting)
  403. self.update_configuration_file({'language':'"'+str(lang)+'"'})
  404. QtGui.QMessageBox.information(self, "Change Language", "Language change takes effect after Gui restart", 1)
  405. if setting == 'advanced_control':
  406. self.showAdvancedControl(getattr(self.storage, setting))
  407. for bid in available_boards.board_ids:
  408. try:
  409. if bif.bk_get_config(bid, setting) != None:
  410. bif.bk_update_config(bid, setting, getattr(self.storage, setting))
  411. except board.NoSuchKeyError:
  412. pass
  413. def showAdvancedControl(self, value):
  414. """
  415. Enable or disable advanced table control view (Tables for registers)
  416. :param value: (bool) True to show and False to hide advanced view
  417. :return: -
  418. """
  419. if value:
  420. if self.cw.tableWidget.isHidden():
  421. self.cw.pagesWidget.addPage(self.cw.tableWidget, 'Bits Table', set_to_first=False)
  422. self.cw.tableWidget.show()
  423. else:
  424. if not self.cw.tableWidget.isHidden():
  425. self.cw.pagesWidget.removePage(self.cw.tableWidget)
  426. self.cw.tableWidget.hide()
  427. def after_start_status_handler(self):
  428. """
  429. Method to check for boards and perform a status_readout after the gui is fully started
  430. :return:
  431. """
  432. for bid in available_boards.board_ids: # there is always at least a dummy board
  433. bif.bk_check_for_board(bid)
  434. bif.bk_status_readout()
  435. def populate_storage(self):
  436. """
  437. Initially fills storage with predefined settings and configuration values
  438. :return: -
  439. """
  440. self.storage.header = config.save_header
  441. self.storage.subdirname = config.subdirectory_name
  442. self.storage.save_location = config.save_location
  443. self.storage.language = config.language
  444. self.storage.advanced_control = False
  445. def update_header(val):
  446. '''Update header'''
  447. self.storage.header = val
  448. if self.settings:
  449. self.settings.headerTick.setChecked(val)
  450. board.get_board_config(available_boards[0]).observe(self.storage.header, update_header, 'header') # TODO: header at one place for all boards? (here it uses the first board)
  451. def update_configuration_file(self, new_conf):
  452. """
  453. Update variablevalues in config file
  454. NOTE: this doesn't use standard ConfigParser as that would delete comments
  455. :param new_conf: Dictionary with variable, value pair
  456. :return:
  457. """
  458. import re
  459. # filename = "config.py"
  460. filename = config.config_path("config.cfg")
  461. RE = '(('+'|'.join(list(new_conf.keys()))+')\s*=)[^\r\n]*?(\r?\n|\r)'
  462. pat = re.compile(RE)
  463. def jojo(mat,dic = new_conf ):
  464. return dic[mat.group(2)].join(mat.group(1,3))
  465. with open(filename,'rb') as f:
  466. content = f.read()
  467. with open(filename,'wb') as f:
  468. f.write(pat.sub(jojo,content))
  469. def closeEvent(self, ev):
  470. """
  471. Handles closing of the GUI - this function is called by pyqt upon a close event.
  472. Asks if user really wants to close the gui
  473. :param ev: event
  474. :return: -
  475. """
  476. extra = ""
  477. for b in available_boards:
  478. if board.get_board_status(b).wait_on_trigger:
  479. extra += '\n'+tr('Dialog', 'Waiting on external trigger is still enabled.')
  480. if board.get_board_status(b).continuous_read:
  481. extra += '\n'+tr('Dialog', 'Continuous read is still enabled.')
  482. if extra:
  483. break
  484. cl = None
  485. if extra:
  486. cl = QtGui.QMessageBox.critical(self, tr("Heading", "Close KCG"),
  487. tr("Dialog", "Close KCG?")+extra,
  488. QtGui.QMessageBox.No | QtGui.QMessageBox.Yes,
  489. QtGui.QMessageBox.No)
  490. if not cl or cl == QtGui.QMessageBox.Yes:
  491. cl = QtGui.QMessageBox.question(self, tr("Heading", "Close KCG"),
  492. tr("Dialog", "Close KCG?\nYou will loose the state of open plots etc."),
  493. QtGui.QMessageBox.No | QtGui.QMessageBox.Yes,
  494. QtGui.QMessageBox.No)
  495. if cl == QtGui.QMessageBox.Yes:
  496. if self.settings:
  497. self.settings.close()
  498. ev.accept()
  499. else:
  500. ev.ignore()