kcg.py 21 KB

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