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 #, create_new_group_object, change_group_obect_to_id
  14. from backend.board import available_boards
  15. from backend import board
  16. from multipage import MultiPage
  17. import bitsTable as bt
  18. import log
  19. # ---------[ Widgets IMPORTANT!!! ]------------------
  20. # this enables widgets. If this is not imported (even though it is not directly used) no widgets will be available
  21. from ..widgets import *
  22. # from widgets import * # copy in case the above line gets removed by ide
  23. # ---------[ IMPORTANT ]---------------------
  24. tr = kcgw.tr
  25. from .. import config
  26. import time
  27. import getpass
  28. # config.curr_id = create_new_group_object()
  29. # Elements.setFlags({'autoremove': True, 'warn': True, 'exception_on_deleted': False})
  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))
  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 # 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. self.pageIndicator = QtGui.QLabel()
  147. self.statusbar.addPermanentWidget(self.pageIndicator)
  148. self.cw = CentralWidget(self)
  149. self.doMenu()
  150. self.setCentralWidget(self.cw)
  151. self.initUI()
  152. self.finalizeInit()
  153. self.after_start_status_handler()
  154. self.setContentsMargins(0, -10, 0, 0)
  155. def initUI(self):
  156. """
  157. Initialize ui
  158. :return: -
  159. """
  160. self.setWindowTitle("KCG - Kapture Control Gui")
  161. self.setWindowIcon(QtGui.QIcon(config.install_path + config.guiIcon))
  162. # self.statusbar.showMessage(board.status.status_text) # TODO: imporant status message for which board? all?
  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. # with open('/tmp/darkorange.stylesheet') as f:
  187. # styleSheet = f.read()
  188. self.setStyleSheet(styleSheet)
  189. # evaluate config file regarding advanced_control
  190. self.showAdvancedControl(config.show_advanced_control)
  191. self.storage.advanced_control = config.show_advanced_control
  192. if not os.path.isdir(storage.storage.save_location + '/' + storage.storage.subdirname):
  193. os.makedirs(storage.storage.save_location + '/' + storage.storage.subdirname)
  194. self.measurementLogger = log.MeasurementLogger() # storage.storage.save_location + '/' + storage.storage.subdirname
  195. # + "/Measurement.log")
  196. log.logger = self.measurementLogger
  197. logStrings = []
  198. functionAndParameter = []
  199. for par in self.measurementLogger.predefined_parameters: # get strings and functions in seperate lists
  200. logStrings.append(par[0])
  201. functionAndParameter.append(par[1])
  202. for e in config.default_log_entries: # for every entry:
  203. if e in logStrings:
  204. self.measurementLogger.register_parameter(e, functionAndParameter[logStrings.index(e)][0], functionAndParameter[logStrings.index(e)][1])
  205. # self.measurementLogger.register_dumper(board.config.dump) # TODO: register dumper for all boards
  206. if log.no_epics and log.epics_reachable:
  207. logging.info("Epics installation not found. Logfiles will not contain information that is to be "
  208. "obtained via epics.")
  209. if not log.epics_reachable:
  210. logging.info("Epics PVs could not be accessed. Check Internet connection and Epics PV provider. Logfiles will not contain"
  211. "information that is to be obtained via epics.")
  212. def doMenu(self):
  213. """
  214. Create and show the menu and it's entries
  215. :return: -
  216. """
  217. self.menu = self.menuBar()
  218. self.fileMenu = self.menu.addMenu("&"+tr("Button", "File"))
  219. self.saveConfigAction = self.fileMenu.addAction(tr("Button", "Save Board Configuration"), self.saveConfig)
  220. self.saveConfigAction = self.fileMenu.addAction(tr("Button", "Load Board Configuration"), self.loadConfig)
  221. self.settingsAction = self.fileMenu.addAction(tr("Button", "Settings"), self.showSettings, "Ctrl+P")
  222. self.quitAction = self.fileMenu.addAction(QtGui.QIcon(config.install_path + "icons/exit.png"), tr("Button", "Quit"), self.close, "Ctrl+Q")
  223. self.menu.setCornerWidget(self.cw.pagesWidget.leftright)
  224. # ----------[ Page specific Menu Entries ]-------------
  225. self.multiMenu = self.menu.addMenu("&"+tr("Button", "Windows"))
  226. MenuItems.addMenuItem(_MultiView_Name_, self.multiMenu)
  227. self.plotAction = self.multiMenu.addAction(QtGui.QIcon(config.install_path + config.newPlotLiveIcon), tr("Button", "New Plot"), self.cw.mainMultiWidget.leftBar.add_plot)
  228. self.addWindowMenuEntries()
  229. if not available_boards.multi_board:
  230. self.acquireMenu = self.menu.addMenu("&"+tr("Button", "Acquire"))
  231. MenuItems.addMenuItem(_MultiView_Name_, self.acquireMenu)
  232. self.startAcquisitionAction = self.acquireMenu.addAction(QtGui.QIcon(config.install_path + config.startIcon),
  233. tr("Button", "Start Acquisition"), lambda: bif.bk_acquire(available_boards[0]))
  234. self.startAcquisitionAction.setObjectName("start_acquisition_action")
  235. MenuItems.addMenuItem("continuous_read_{}".format(available_boards[0]), self.startAcquisitionAction)
  236. MenuItems.addMenuItem("acquireTrigger_{}".format(available_boards[0]), self.startAcquisitionAction)
  237. # -----[ disable Menu Items for MultiView as it is not the startup page ]-------------
  238. # this could be avoided if menu is created before the multipage widget
  239. MenuItems.setEnabled(_MultiView_Name_, False)
  240. # self.changeBoard = self.menu.addMenu("&"+tr("Button", "Change Board"))
  241. # self.changeBoard.addAction(tr("Button", "Board 1"), lambda: self.change_board(0))
  242. # self.changeBoard.addAction(tr("Button", "Board 2"), lambda: self.change_board(1))
  243. self.help = self.menu.addMenu("&"+tr("Button", "Help"))
  244. import webbrowser
  245. self.help.addAction(tr("Button", "Open Manual"), lambda: webbrowser.open(config.install_path + "Documentation/build/html/index.html"))
  246. self.help.addAction(tr("Button", "About"), self.showAbout)
  247. # def change_board(self, id):
  248. # board.change_board_config_to_id(id)
  249. # board.config.board_identifier = "first" ### SET IDENTIFIER HIER
  250. # change_group_obect_to_id(id)
  251. def saveConfig(self, board_id):
  252. filenameDialog = QtGui.QFileDialog(self, tr("Heading", "Save Configuration"), '', 'KAPTURE Configuration File (*.kcf)')
  253. filenameDialog.setDefaultSuffix("kcf")
  254. filenameDialog.setAcceptMode(filenameDialog.AcceptSave)
  255. filenameDialog.exec_()
  256. filename = filenameDialog.selectedFiles()
  257. if filename[0]:
  258. if not board.get_board_config(board_id).save_config(filename[0]):
  259. QtGui.QMessageBox.critical(self, tr("Heading", "Error Saving Config"), tr("Dialog", "There was an error saving to a config file."))
  260. else:
  261. QtGui.QMessageBox.critical(self, tr("Heading", "Error Saving Config"), tr("Dialog", "There was an error saving to a config file."))
  262. def loadConfig(self, board_id):
  263. filename = QtGui.QFileDialog.getOpenFileName(self, 'Open Configuration', '', 'KAPTURE Configuration File (*.kcf)')
  264. if not filename:
  265. return
  266. if board.get_board_config(board_id).load_config(filename):
  267. bif.bk_write_values(board_id, defaults=False)
  268. else:
  269. 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."))
  270. def showAbout(self):
  271. """
  272. Show the about window.
  273. :return: -
  274. """
  275. version = open(config.install_path+"VERSION").read()
  276. about = QtGui.QDialog(self) # TODO: read about text externally? read version externally?
  277. about.setWindowTitle("KCG - About")
  278. about_label = QtGui.QLabel(tr("About", "KAPTURE Control Gui\n"
  279. "KCG is a graphical control interface to the KAPTURE board\n\n"
  280. "Author: Patrick Schreiber\n\n"
  281. "Version:\n")+version)
  282. about_label.setAlignment(QtCore.Qt.AlignCenter)
  283. header_label = QtGui.QLabel(tr("About", "KCG"))
  284. header_label.setStyleSheet("font-size: 25pt; text-align: center;")
  285. header_label.setAlignment(QtCore.Qt.AlignCenter)
  286. footer_label = QtGui.QLabel(tr("About", "\nKAPTURE - Karlsruhe Pulse-Taking and Ultrafast Readout Electronics"))
  287. footer_label.setStyleSheet("font-size: 7pt;")
  288. footer_label.setAlignment(QtCore.Qt.AlignRight)
  289. about_layout = QtGui.QHBoxLayout()
  290. about_text_layout = QtGui.QVBoxLayout()
  291. about.setLayout(about_layout)
  292. # pxm = QtGui.QPixmap(config.guiIcon)
  293. # icon_layout = QtGui.QVBoxLayout()
  294. # icon_label = QtGui.QLabel("")
  295. # icon_label.setPixmap(pxm.scaled(QtCore.QSize(128, 128), QtCore.Qt.KeepAspectRatio))
  296. # icon_label.setFixedSize(130, 130)
  297. # icon_layout.addWidget(icon_label)
  298. # icon_layout.addStretch(1)
  299. # about_layout.addLayout(icon_layout)
  300. about_layout.addLayout(about_text_layout)
  301. about_text_layout.addWidget(header_label)
  302. about_text_layout.addWidget(about_label)
  303. about_text_layout.addWidget(footer_label)
  304. about.setFixedSize(400, 230)
  305. about.setStyleSheet("background-color: darkgrey;")
  306. about.exec_()
  307. def addWindowMenuEntries(self):
  308. """
  309. Adds Window Menu entries for custom widgets
  310. :return: -
  311. """
  312. for f in kcgw.get_registered_widgets():
  313. self.multiMenu.addAction(*f[:3]) # TODO: icon - ???
  314. def showSettings(self):
  315. """
  316. Create and show settings window
  317. :return: -
  318. """
  319. if self.settings: # use preopened window
  320. self.settings.show()
  321. self.settings.raise_()
  322. self.settings.activateWindow()
  323. else:
  324. self.settings = Settings(self.storage)
  325. self.settings.changed.connect(self.updateSettings)
  326. def updateSettings(self, changedsettings):
  327. """
  328. Update settings in storage if settings were changed in the settings window.
  329. :param changedsettings: list of settings that have been changed
  330. :return: -
  331. """
  332. for setting in changedsettings:
  333. if setting == 'language':
  334. lang = getattr(self.storage, setting)
  335. self.update_configuration_file({'language':'"'+str(lang)+'"'})
  336. QtGui.QMessageBox.information(self, "Change Language", "Language change takes effect after Gui restart", 1)
  337. if setting == 'advanced_control':
  338. self.showAdvancedControl(getattr(self.storage, setting))
  339. if bif.bk_get_config(setting) != None:
  340. bif.bk_update_config(setting, getattr(self.storage, setting))
  341. def showAdvancedControl(self, value):
  342. """
  343. Enable or disable advanced table control view (Tables for registers)
  344. :param value: (bool) True to show and False to hide advanced view
  345. :return: -
  346. """
  347. if value:
  348. if self.cw.tableWidget.isHidden():
  349. self.cw.pagesWidget.addPage(self.cw.tableWidget, 'Bits Table', set_to_first=False)
  350. self.cw.tableWidget.show()
  351. else:
  352. if not self.cw.tableWidget.isHidden():
  353. self.cw.pagesWidget.removePage(self.cw.tableWidget)
  354. self.cw.tableWidget.hide()
  355. def after_start_status_handler(self):
  356. bif.bk_status_readout()
  357. def populate_storage(self):
  358. """
  359. Initially fills storage with predefined settings and configuration values
  360. :return: -
  361. """
  362. self.storage.header = config.save_header
  363. self.storage.subdirname = config.subdirectory_name
  364. self.storage.save_location = config.save_location
  365. self.storage.language = config.language
  366. self.storage.advanced_control = False
  367. def update_header(val):
  368. self.storage.header = val
  369. if self.settings:
  370. self.settings.headerTick.setChecked(val)
  371. 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)
  372. def update_configuration_file(self, new_conf):
  373. """
  374. Update variablevalues in config file
  375. NOTE: this doesn't use standard ConfigParser as that would delete comments
  376. :param new_conf: Dictionary with variable, value pair
  377. :return:
  378. """
  379. import re
  380. # filename = "config.py"
  381. filename = os.path.expanduser("~")+"/.kcg/config.cfg"
  382. RE = '(('+'|'.join(new_conf.keys())+')\s*=)[^\r\n]*?(\r?\n|\r)'
  383. pat = re.compile(RE)
  384. def jojo(mat,dic = new_conf ):
  385. return dic[mat.group(2)].join(mat.group(1,3))
  386. with open(filename,'rb') as f:
  387. content = f.read()
  388. with open(filename,'wb') as f:
  389. f.write(pat.sub(jojo,content))
  390. def closeEvent(self, ev):
  391. """
  392. Handles closing of the GUI - this function is called by pyqt upon a close event.
  393. Asks if user really wants to close the gui
  394. :param ev: event
  395. :return: -
  396. """
  397. extra = ""
  398. for b in available_boards:
  399. if board.get_board_status(b).wait:
  400. extra += '\n'+tr('Dialog', 'Waiting on external trigger is still enabled.')
  401. if board.get_board_status(b).continuous_read:
  402. extra += '\n'+tr('Dialog', 'Continuous read is still enabled.')
  403. if extra:
  404. break
  405. cl = None
  406. if extra:
  407. cl = QtGui.QMessageBox.critical(self, tr("Heading", "Close KCG"),
  408. tr("Dialog", "Close KCG?")+extra,
  409. QtGui.QMessageBox.No | QtGui.QMessageBox.Yes,
  410. QtGui.QMessageBox.No)
  411. if not cl or cl == QtGui.QMessageBox.Yes:
  412. cl = QtGui.QMessageBox.question(self, tr("Heading", "Close KCG"),
  413. tr("Dialog", "Close KCG?\nYou will loose the state of open plots etc."),
  414. QtGui.QMessageBox.No | QtGui.QMessageBox.Yes,
  415. QtGui.QMessageBox.No)
  416. if cl == QtGui.QMessageBox.Yes:
  417. if self.settings:
  418. self.settings.close()
  419. # board.config.save_config("backup.kcf")
  420. ev.accept()
  421. else:
  422. ev.ignore()