kcg.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. if log.no_epics and log.epics_reachable:
  203. logging.error("Epics installation not found. Logfiles will not contain information that is to be "
  204. "obtained via epics.")
  205. if not log.epics_reachable:
  206. logging.error("Epics PVs could not be accessed. Check Internet connection and Epics PV provider. Logfiles will not contain"
  207. "information that is to be obtained via epics.")
  208. def doMenu(self):
  209. """
  210. Create and show the menu and it's entries
  211. :return: -
  212. """
  213. self.menu = self.menuBar()
  214. self.fileMenu = self.menu.addMenu("&"+tr("Button", "File"))
  215. self.saveConfigAction = self.fileMenu.addAction(tr("Button", "Save Board Configuration"), self.saveConfig)
  216. self.saveConfigAction = self.fileMenu.addAction(tr("Button", "Load Board Configuration"), self.loadConfig)
  217. self.settingsAction = self.fileMenu.addAction(tr("Button", "Settings"), self.showSettings, "Ctrl+P")
  218. self.configAction = self.fileMenu.addAction(tr("Button", "Rerun Configuration Wizard"), self.rerunConfig)
  219. self.quitAction = self.fileMenu.addAction(QtGui.QIcon(config.install_path + "icons/exit.png"), tr("Button", "Quit"), self.close, "Ctrl+Q")
  220. self.menu.setCornerWidget(self.cw.pagesWidget.leftright)
  221. # ----------[ Page specific Menu Entries ]-------------
  222. self.multiMenu = self.menu.addMenu("&"+tr("Button", "Windows"))
  223. MenuItems.addMenuItem(_MultiView_Name_, self.multiMenu)
  224. self.plotAction = self.multiMenu.addAction(QtGui.QIcon(config.install_path + config.newPlotLiveIcon), tr("Button", "New Plot"), self.cw.mainMultiWidget.leftBar.add_plot)
  225. self.addWindowMenuEntries()
  226. if not available_boards.multi_board:
  227. self.acquireMenu = self.menu.addMenu("&"+tr("Button", "Acquire"))
  228. MenuItems.addMenuItem(_MultiView_Name_, self.acquireMenu)
  229. self.startAcquisitionAction = self.acquireMenu.addAction(QtGui.QIcon(config.install_path + config.startIcon),
  230. tr("Button", "Start Acquisition"), lambda: bif.bk_acquire(available_boards[0]))
  231. self.startAcquisitionAction.setObjectName("start_acquisition_action")
  232. MenuItems.addMenuItem("continuous_read_{}".format(available_boards[0]), self.startAcquisitionAction)
  233. MenuItems.addMenuItem("acquireTrigger_{}".format(available_boards[0]), self.startAcquisitionAction)
  234. # -----[ disable Menu Items for MultiView as it is not the startup page ]-------------
  235. # this could be avoided if menu is created before the multipage widget
  236. MenuItems.setEnabled(_MultiView_Name_, False)
  237. self.help = self.menu.addMenu("&"+tr("Button", "Help"))
  238. import webbrowser
  239. self.help.addAction(tr("Button", "Open Manual"), lambda: webbrowser.open(config.install_path + "Documentation/build/html/index.html"))
  240. self.help.addAction(tr("Button", "About"), self.showAbout)
  241. def saveConfig(self, board_id):
  242. """
  243. Save the current configuration to a configuration file
  244. :param board_id: the board to save the configuration for
  245. """
  246. filenameDialog = QtGui.QFileDialog(self, tr("Heading", "Save Configuration"), '', 'KAPTURE Configuration File (*.kcf)')
  247. filenameDialog.setDefaultSuffix("kcf")
  248. filenameDialog.setAcceptMode(filenameDialog.AcceptSave)
  249. filenameDialog.exec_()
  250. filename = filenameDialog.selectedFiles()
  251. if filename[0]:
  252. if not board.get_board_config(board_id).save_config(filename[0]):
  253. QtGui.QMessageBox.critical(self, tr("Heading", "Error Saving Config"), tr("Dialog", "There was an error saving to a config file."))
  254. else:
  255. QtGui.QMessageBox.critical(self, tr("Heading", "Error Saving Config"), tr("Dialog", "There was an error saving to a config file."))
  256. def loadConfig(self, board_id):
  257. """
  258. Load the configuration for the given board from a file
  259. :param board_id: the board to read the configuration for
  260. """
  261. filename = QtGui.QFileDialog.getOpenFileName(self, 'Open Configuration', '', 'KAPTURE Configuration File (*.kcf)')
  262. if not filename:
  263. return
  264. if board.get_board_config(board_id).load_config(filename):
  265. bif.bk_write_values(board_id, defaults=False)
  266. else:
  267. 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."))
  268. def rerunConfig(self):
  269. """
  270. Rerun the initial configuration wizard
  271. """
  272. self.setupConfig = initialconfig.ConfigSetup(restart=True)
  273. self.setupConfig.setWindowModality(QtCore.Qt.ApplicationModal)
  274. def restart():
  275. import subprocess
  276. import sys
  277. import os
  278. try:
  279. subprocess.Popen(['kcg'])
  280. except OSError as exception:
  281. try:
  282. path = config.install_path[:-4]+'kcg'
  283. subprocess.Popen([sys.executable, path])
  284. except:
  285. print('ERROR: could not restart aplication:')
  286. print(' %s' % str(exception))
  287. else:
  288. QtGui.qApp.quit()
  289. else:
  290. QtGui.qApp.quit()
  291. self.setupConfig.success_signal.connect(restart)
  292. self.setupConfig.show()
  293. def showAbout(self):
  294. """
  295. Show the about window.
  296. :return: -
  297. """
  298. version = open(config.install_path+"VERSION").read()
  299. about = QtGui.QDialog(self)
  300. about.setWindowTitle("KCG - About")
  301. about_label = QtGui.QLabel(tr("About", "KAPTURE Control Gui\n"
  302. "KCG is a graphical control interface to the KAPTURE board\n\n"
  303. "Author: Patrick Schreiber\n\n"
  304. "Version:\n")+version)
  305. about_label.setAlignment(QtCore.Qt.AlignCenter)
  306. header_label = QtGui.QLabel(tr("About", "KCG"))
  307. header_label.setStyleSheet("font-size: 25pt; text-align: center;")
  308. header_label.setAlignment(QtCore.Qt.AlignCenter)
  309. footer_label = QtGui.QLabel(tr("About", "\nKAPTURE - Karlsruhe Pulse-Taking and Ultrafast Readout Electronics"))
  310. footer_label.setStyleSheet("font-size: 7pt;")
  311. footer_label.setAlignment(QtCore.Qt.AlignRight)
  312. about_layout = QtGui.QHBoxLayout()
  313. about_text_layout = QtGui.QVBoxLayout()
  314. about.setLayout(about_layout)
  315. # pxm = QtGui.QPixmap(config.guiIcon)
  316. # icon_layout = QtGui.QVBoxLayout()
  317. # icon_label = QtGui.QLabel("")
  318. # icon_label.setPixmap(pxm.scaled(QtCore.QSize(128, 128), QtCore.Qt.KeepAspectRatio))
  319. # icon_label.setFixedSize(130, 130)
  320. # icon_layout.addWidget(icon_label)
  321. # icon_layout.addStretch(1)
  322. # about_layout.addLayout(icon_layout)
  323. about_layout.addLayout(about_text_layout)
  324. about_text_layout.addWidget(header_label)
  325. about_text_layout.addWidget(about_label)
  326. about_text_layout.addWidget(footer_label)
  327. about.setFixedSize(400, 230)
  328. about.setStyleSheet("background-color: darkgrey;")
  329. about.exec_()
  330. def addWindowMenuEntries(self):
  331. """
  332. Adds Window Menu entries for custom widgets
  333. :return: -
  334. """
  335. for f in kcgw.get_registered_widgets():
  336. self.multiMenu.addAction(*f[:3]) # TODO: icon - ???
  337. def showSettings(self):
  338. """
  339. Create and show settings window
  340. :return: -
  341. """
  342. if self.settings: # use preopened window
  343. self.settings.show()
  344. self.settings.raise_()
  345. self.settings.activateWindow()
  346. else:
  347. self.settings = Settings(self.storage)
  348. self.settings.changed.connect(self.updateSettings)
  349. def updateSettings(self, changedsettings):
  350. """
  351. Update settings in storage if settings were changed in the settings window.
  352. :param changedsettings: list of settings that have been changed
  353. :return: -
  354. """
  355. for setting in changedsettings:
  356. if setting == 'language':
  357. lang = getattr(self.storage, setting)
  358. self.update_configuration_file({'language':'"'+str(lang)+'"'})
  359. QtGui.QMessageBox.information(self, "Change Language", "Language change takes effect after Gui restart", 1)
  360. if setting == 'advanced_control':
  361. self.showAdvancedControl(getattr(self.storage, setting))
  362. for bid in available_boards.board_ids:
  363. try:
  364. if bif.bk_get_config(bid, setting) != None:
  365. bif.bk_update_config(bid, setting, getattr(self.storage, setting))
  366. except board.NoSuchKeyError:
  367. pass
  368. def showAdvancedControl(self, value):
  369. """
  370. Enable or disable advanced table control view (Tables for registers)
  371. :param value: (bool) True to show and False to hide advanced view
  372. :return: -
  373. """
  374. if value:
  375. if self.cw.tableWidget.isHidden():
  376. self.cw.pagesWidget.addPage(self.cw.tableWidget, 'Bits Table', set_to_first=False)
  377. self.cw.tableWidget.show()
  378. else:
  379. if not self.cw.tableWidget.isHidden():
  380. self.cw.pagesWidget.removePage(self.cw.tableWidget)
  381. self.cw.tableWidget.hide()
  382. def after_start_status_handler(self):
  383. """
  384. Method to check for boards and perform a status_readout after the gui is fully started
  385. :return:
  386. """
  387. for bid in available_boards.board_ids: # there is always at least a dummy board
  388. bif.bk_check_for_board(bid)
  389. bif.bk_status_readout()
  390. def populate_storage(self):
  391. """
  392. Initially fills storage with predefined settings and configuration values
  393. :return: -
  394. """
  395. self.storage.header = config.save_header
  396. self.storage.subdirname = config.subdirectory_name
  397. self.storage.save_location = config.save_location
  398. self.storage.language = config.language
  399. self.storage.advanced_control = False
  400. def update_header(val):
  401. '''Update header'''
  402. self.storage.header = val
  403. if self.settings:
  404. self.settings.headerTick.setChecked(val)
  405. 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)
  406. def update_configuration_file(self, new_conf):
  407. """
  408. Update variablevalues in config file
  409. NOTE: this doesn't use standard ConfigParser as that would delete comments
  410. :param new_conf: Dictionary with variable, value pair
  411. :return:
  412. """
  413. import re
  414. # filename = "config.py"
  415. filename = os.path.expanduser("~")+"/.kcg/config.cfg"
  416. RE = '(('+'|'.join(new_conf.keys())+')\s*=)[^\r\n]*?(\r?\n|\r)'
  417. pat = re.compile(RE)
  418. def jojo(mat,dic = new_conf ):
  419. return dic[mat.group(2)].join(mat.group(1,3))
  420. with open(filename,'rb') as f:
  421. content = f.read()
  422. with open(filename,'wb') as f:
  423. f.write(pat.sub(jojo,content))
  424. def closeEvent(self, ev):
  425. """
  426. Handles closing of the GUI - this function is called by pyqt upon a close event.
  427. Asks if user really wants to close the gui
  428. :param ev: event
  429. :return: -
  430. """
  431. extra = ""
  432. for b in available_boards:
  433. if board.get_board_status(b).wait:
  434. extra += '\n'+tr('Dialog', 'Waiting on external trigger is still enabled.')
  435. if board.get_board_status(b).continuous_read:
  436. extra += '\n'+tr('Dialog', 'Continuous read is still enabled.')
  437. if extra:
  438. break
  439. cl = None
  440. if extra:
  441. cl = QtGui.QMessageBox.critical(self, tr("Heading", "Close KCG"),
  442. tr("Dialog", "Close KCG?")+extra,
  443. QtGui.QMessageBox.No | QtGui.QMessageBox.Yes,
  444. QtGui.QMessageBox.No)
  445. if not cl or cl == QtGui.QMessageBox.Yes:
  446. cl = QtGui.QMessageBox.question(self, tr("Heading", "Close KCG"),
  447. tr("Dialog", "Close KCG?\nYou will loose the state of open plots etc."),
  448. QtGui.QMessageBox.No | QtGui.QMessageBox.Yes,
  449. QtGui.QMessageBox.No)
  450. if cl == QtGui.QMessageBox.Yes:
  451. if self.settings:
  452. self.settings.close()
  453. ev.accept()
  454. else:
  455. ev.ignore()