initial commit

This commit is contained in:
2022-01-10 13:15:41 +01:00
commit e2ad99fe36
12 changed files with 22793 additions and 0 deletions

0
__init__py Normal file
View File

1004
base.py Normal file

File diff suppressed because it is too large Load Diff

40
enumkind.py Normal file
View File

@@ -0,0 +1,40 @@
""" Enumerated types for bdbase
"""
from enum import IntEnum
class DAQState(IntEnum):
BS = 10
CA = 20
BS_STOP = 30
CA_STOP = 40
BS_PAUSE = 50
CA_PAUSE = 60
class Facility(IntEnum):
""" Defines mode of application
"""
PSI = 0
SwissFEL = 1
SLS = 2
class MsgSeverity(IntEnum):
""" For use with message logger
"""
FATAL = 1
ERROR = 2
WARN = 3
WARNING = 3 # WARNING is an alias
INFO = 4
DEBUG = 5
class UserMode(IntEnum):
""" Defines mode of application
"""
OPERATION = 1
EXPERT = 2
SIMULATION = 3

1211
guiframe.py Normal file

File diff suppressed because it is too large Load Diff

726
hdf5filemenu.py Normal file
View File

@@ -0,0 +1,726 @@
import inspect
import os
from qtpy.QtCore import (PYQT_VERSION_STR, QFile, QFileInfo, QIODevice,
QSettings, Qt)
from qtpy.QtGui import QFont, QIcon
from qtpy.QtWidgets import (QAction, QApplication, QFileDialog, QFrame,
QGroupBox, QHBoxLayout, QLabel, QLineEdit,
QMenuBar, QMessageBox, QPushButton, QVBoxLayout,
QWidget)
from pyqtacc.bdbase.enumkind import MsgSeverity
_version = "1.0.0"
_pymodule = os.path.basename(__file__)
_appname, _appext = _pymodule.split(".")
def _line():
"""Macro to return the current line number.
The current line number within the file is used when
reporting messages to the message logging window.
Returns:
int: Current line number.
"""
return inspect.currentframe().f_back.f_lineno
class HDF5File(QGroupBox):
def __init__(self, parent):
super(HDF5File, self).__init__(parent)
self.parent = parent
self.show_message = self.parent.show_log_message
self.updateStatus = self.parent.updateStatus
self.createAction = self.parent.create_action
self.filename = None
self.save_filename = None
self.common_path = None
self.recent_files = []
self.max_no_files = 9
self.show_common_path_flag = False
self.file_dir = "."
self.qsettings = QSettings()
self.loadInitialFile()
def show_common_path_only(self, yes=False):
self.show_common_path_only = yes
def saveToFileProcedure(self):
f = QFile(self.save_filename)
if f.open(QIODevice.WriteOnly):
f.write(self.fByteArray)
f.close()
return True
else:
return False
def fileSave(self):
if self.save_filename:
if self.saveToFileProcedure():
self.updateStatus("Saved file {0}".format(self.save_filename))
self.show_message(MsgSeverity.INFO, _pymodule,
_line(),
"Saved file='{0}'".format(self.save_filename))
else:
'''
self.updateStatus("Unable to save file {0}".
format(self.save_filename))
self.show_message(MsgSeverity.INFO, _pymodule, _line(),
"Unable to save file='{0}'".
format(self.save_filename))
'''
return False
else:
self.updateStatus(
"Unable to save as no filename was given")
self.show_message(MsgSeverity.WARN, _pymodule,
_line(),
"Unable to save as no filename was given")
return False
if self.save_filename:
self.showSaveFile()
def fileSaveAs(self):
#print("save file", fname) # True or False
'''
if not fname:
action = self.sender()
if isinstance(action, QAction):
fname = str(action.data())
print("from self.sender:")
print("fname", fname)
'''
_dir = (os.path.dirname(self.save_filename)
if self.save_filename is not None else self.file_dir)
'''
if fname is None:
_dir = self.file_dir
elif not fname:
_dir = self.file_dir
_dir = (os.path.dirname(self.filename)
if self.filename is not None else self.file_dir)
else:
_dir = os.path.dirname(fname)
'''
# if fname is not None else self.file_dir)
#print('fname', fname)
#print ("_dir", _dir, "//", self.file_dir)
_fname = QFileDialog.getSaveFileName(self, "Save File", _dir, (
"HDF5 files (*.hdf *.h5 *.hdf5 *.he5)"))
print(_fname)
print(os.path.basename(_fname[0]))
if _fname == "('', '')":
return False
else:
fname = _fname[0]
if fname:
if "." not in os.path.basename(fname):
fname += ".h5"
##self.addRecentSaveFile(fname)
self.save_filename = fname
print("fileSaveAs, filename ", self.save_filename)
self.fileSave()
return True
return False
def showSaveFile(self):
self.loaded_file_widget.setObjectName("hdf")
self.style().unpolish(self.loaded_file_widget)
self.style().polish(self.loaded_file_widget)
self.loaded_file_widget.setText(self.save_filename)
############### end save fns #######
def fileOpen(self):
_dir = (os.path.dirname(self.filename)
if self.filename is not None else self.file_dir)
fname, ffilter = QFileDialog.getOpenFileName(
self, "Select/Open File", str(_dir), (
"HDF5 files (*.hdf *.h5 *.hdf5 *.he5)"))
if fname:
self.loadFile(fname)
def loadInitialFile(self):
self.recent_files = []
if self.qsettings.value("H5RecentFiles"):
mylist = self.qsettings.value("H5RecentFiles")
print("==============================")
print(mylist)
print("=================================")
self.recent_files = str(mylist).split(',') # mylist
print(self.recent_files)
#exit()
if self.qsettings.value("H5LastLoadedFile"):
fname = str(self.qsettings.value("H5LastLoadedFile"))
if fname and QFile.exists(fname):
print ("loadInitialFile=========================>", fname)
self.filename = fname
def loadFile(self, fname):
print("load file=>", fname)
if not fname:
action = self.sender()
if isinstance(action, QAction):
fname = str(action.data())
print("from self.sender:")
print(fname)
if fname:
self.filename = None
if fname is None:
message = "Failed to read file='{0}'".format(fname)
self.show_message(
MsgSeverity.WARN, _pymodule, _line(), message)
self.updateStatus(message)
return
else:
self.addRecentFile(fname)
self.filename = fname
self.parent.h5_filename = fname
_filename_wgt_str = fname #os.path.basename(fname)
if self.show_common_path_flag:
_start = str(fname).rfind(str(self.common_path))
print("common path in loadFile ============>", self.common_path)
print("start", _start)
if _start == 0:
_filename_wgt_str = str(fname).replace(self.common_path, "")
if _filename_wgt_str:
if _filename_wgt_str.count("/") > 1:
_filename_wgt_str = ".../" + _filename_wgt_str
else:
_filename_wgt_str = fname
if self.loadFromFileProcedure():
message = "Loaded {0}".format(os.path.basename(fname))
message2 = "Loaded file='{0}'".format((fname))
self.show_message(
MsgSeverity.INFO, _pymodule, _line(), message2)
#self.loadFileProc()
self.updateStatus(message)
self.loaded_file_widget.setObjectName("load")
self.style().unpolish(self.loaded_file_widget)
self.style().polish(self.loaded_file_widget)
self.loaded_file_widget.setText(_filename_wgt_str)
#else:
# qm = QMessageBox()
# qm.setText("Unable to load data from file. See Log Window ")
# qm.exec()
else:
message = "No input file given!"
self.show_message(
MsgSeverity.WARN, _pymodule, _line(), message)
self.qsettings.setValue("H5LastLoadedFile", self.filename)
recentFiles = ', '.join(self.recent_files)
#recentFiles = (self.recentFiles) if self.recentFiles else None
self.qsettings.setValue("H5RecentFiles", (recentFiles))
print("loaded to qsettings", self.filename)
def resetFileWidget(self, obj_name):
self.loaded_file_widget.clear()
self.loaded_file_widget.setObjectName(obj_name)
self.style().unpolish(self.loaded_file_widget)
self.style().polish(self.loaded_file_widget)
def addRecentFile(self, fname):
if fname is None:
return
if self.recent_files is None:
self.recent_files.insert(0, fname)
if fname not in self.recent_files:
self.recent_files.insert(0, fname)
while len(self.recent_files) > self.max_no_files:
self.recent_files.pop((len(self.recent_files)-1))
print(self.recent_files)
def loadFromFileProcedure(self):
f = QFile(self.filename)
if f.open(QIODevice.ReadOnly):
self.fByteArray = f.readAll()
f.close()
else:
message = "Failed to load file='{0}'".format(self.filename)
self.show_message(
MsgSeverity.WARN, _pymodule, _line(), message)
def updateFileMenu(self):
self.file_menu.clear()
self.file_menu.addAction(self.file_open_action)
#self.parent.addActions(self._file_menu, self.fileMenuActions[:-1])
_current = (str(self.filename)
if self.filename is not None else None)
if _current is not None:
_recent_files = [_current]
else:
_recent_files = []
#print("update(1)--->", _recent_files, self.recent_files)
if _current is not None:
if self.recent_files:
for fname in self.recent_files:
#print ("fname, current", fname)
#print ("fname, current", len(fname), len(fname.strip()))
#print ("file exists? ", QFile.exists(fname.strip()))
#Just make last file available on start-up
#If you want all files, use fname.strip()
if fname != _current and QFile.exists(fname):
_recent_files.append(fname.strip())
#print("update(2)--->", _recent_files)
if _recent_files:
self.common_path = os.path.commonpath(_recent_files) + "/"
else:
self.common_path = None
#print("_common_path=====>", self.common_path)
if _recent_files:
self.file_menu.addSeparator()
for i, fname in enumerate(_recent_files):
_label_icon = QFileInfo(fname).fileName()
if self.common_path is not None:
print(self.common_path)
print(str(os.path.dirname(fname)))
_start = str(os.path.dirname(fname)).rfind(
str(self.common_path))
if _start == 0:
_addon_str = str(os.path.dirname(fname)).replace(
self.common_path, "")
print("Extra", _start)
#print (str(os.path.basename(fname))[_start:])
#_addon = str(os.path.basename(fname))[_start:]
print("filename", _label_icon)
if _addon_str:
_label_icon += " [..." + _addon_str + "/]"
action = QAction(QIcon(":/icon.png"),
"&{0} {1}".format(i + 1, _label_icon), self)
action.setData(str(fname))
print("update(3) ", i, fname)
action.triggered.connect(self.loadFile)
self.file_menu.addAction(action)
print("trigger for ", QFileInfo(fname).fileName(), fname)
#cplist = QFileInfo(fname).canonicalPath().split('/')
#print (cplist)
#print (cplist[-2])
#self._file_menu.addSeparator()
#self._file_menu.addAction(self.fileMenuActions[-1])
self.recent_files = _recent_files
class HDF5SaveLoad(HDF5File):
def __init__(self, parent, title="HDF5", file_dir=".",
obj_name="INNER", layout="Ver"):
super(HDF5SaveLoad, self).__init__(parent)
self.parent = parent
self.file_dir = file_dir
self.setTitle(title)
self.setObjectName(obj_name)
_qw = QWidget()
_font16 = QFont("sans-serif")
_font16.setPixelSize(16)
self.loaded_file_widget = QLineEdit()
self.loaded_file_widget.setObjectName("blank")
self.loaded_file_widget.setProperty("readOnly", True)
self.loaded_file_widget.setFixedHeight(35)
self.loaded_file_widget.setAlignment(Qt.AlignRight)
_menu_bar = QMenuBar()
_menu_bar.setFont(_font16)
_menu_bar.setFixedWidth(120)
_menu_bar.setFixedHeight(38)
_menu_bar.setObjectName("load")
self.file_menu = _menu_bar.addMenu('Load Matrix')
self.file_menu.setFont(_font16)
self.file_open_action = self.createAction(
"O&pen...", self.fileOpen, "Ctrl+Shift+P", "fileopen",
"Load file")
self.separator = QAction(self)
self.separator.setSeparator(True)
self.file_menu.addAction(self.file_open_action)
_menu_save_bar = QMenuBar()
_menu_save_bar.setFont(_font16)
_menu_save_bar.setFixedWidth(120)
_menu_save_bar.setFixedHeight(38)
_menu_save_bar.setObjectName("hdf")
self.save_menu = _menu_save_bar.addMenu('Save Matrix')
self.save_menu.setFont(_font16)
self.file_save_action = self.createAction(
"O&pen...", self.fileSaveAs, "Ctrl+Shift+S", "filesaveas",
"Save file")
self.save_menu.addAction(self.file_save_action)
_hb3 = QHBoxLayout()
_hb3.setContentsMargins(5, 0, 5, 0)
_hb3.setAlignment(Qt.AlignTop)
_hb3.addWidget(self.loaded_file_widget)
_hb = QHBoxLayout()
_hb.addWidget(_menu_bar)
_hb.addWidget(_menu_save_bar)
_hb.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
_hb.setSpacing(15)
_vb2 = QVBoxLayout()
_vb2.setContentsMargins(5, 0, 0, 0)
_vb2.setAlignment(Qt.AlignTop)
_vb2.addLayout(_hb3)
_vb2.addLayout(_hb)
self.setLayout(_vb2)
self.setFixedWidth(400)
self.setFixedHeight(100) #or 156/120
self.setAlignment(Qt.AlignTop | Qt.AlignLeft)
self.file_menu.aboutToShow.connect(self.updateFileMenu)
self.updateFileMenu()
class HDF5GroupBox(QGroupBox):
def __init__(self, parent, title="HDF5", layout="Box"):
super(HDF5GroupBox, self).__init__(parent)
self.parent = parent
self.show_message = self.parent.gui_frame.show_log_message
self.updateStatus = self.parent.statusbar.showMessage
self.createAction = self.parent.create_action
self.filename = None
self.common_path = None
self.recent_files = []
self.max_no_files = 9
self.setTitle(title)
self.qsettings = QSettings()
_qw = QWidget()
_font16 = QFont("sans-serif")
_font16.setPixelSize(16)
_menu_bar = QMenuBar()
_menu_bar.setFont(_font16)
_menu_bar.setFixedWidth(50)
_menu_bar.setFixedHeight(24)
_loaded_file_label = QLabel(" Loaded:")
_loaded_file_label.setFixedHeight(13)
_loaded_file_label.setAlignment(Qt.AlignLeft | Qt.AlignTop)
_loaded_file_label.setContentsMargins(0, 8, 0, 0)
self.loaded_file_widget = QLineEdit()
self.loaded_file_widget.setObjectName("hdf")
self.loaded_file_widget.setProperty("readOnly", True)
self.loaded_file_widget.setFixedHeight(35)
self.analyze_h5_widget = QPushButton("Analyze")
self.analyze_h5_widget.setObjectName("WriteData")
self.analyze_h5_widget.setFixedWidth(100)
self.analyze_h5_widget.setFixedHeight(34)
self.analyze_h5_widget.setToolTip("Analyze pre-loaded hdf5 data")
self.file_menu = _menu_bar.addMenu('File')
self.file_menu.setFont(_font16)
self.file_open_action = self.createAction(
"O&pen...", self.fileOpen, "Ctrl+Shift+P", "fileopen",
"Load file")
self.separator = QAction(self)
self.separator.setSeparator(True)
self.file_menu.addAction(self.file_open_action)
if layout == "Hor":
self.setObjectName("OUTER")
_hb = QHBoxLayout()
_hb.setContentsMargins(10, 8, 10, 8)
_hb.setAlignment(Qt.AlignTop)
_hb.addWidget(_menu_bar)
_hb.addWidget(self.loaded_file_widget)
_hb.addWidget(self.analyze_h5_widget)
_hb.setAlignment(Qt.AlignCenter)
_hb.setSpacing(15)
self.setAlignment(Qt.AlignCenter)
self.setLayout(_hb)
self.setFixedWidth(600)
self.setFixedHeight(64) #or 156/120
else:
self.setObjectName("OUTER")
_vb3 = QVBoxLayout()
_vb3.setContentsMargins(5, 0, 5, 0)
_vb3.setAlignment(Qt.AlignTop)
_loaded_file_label.setFixedHeight(30)
_loaded_file_label.setContentsMargins(0, 18, 0, 0)
_vb3.addWidget(_loaded_file_label)
_vb3.addWidget(self.loaded_file_widget)
_hb = QHBoxLayout()
_hb.addWidget(_menu_bar)
_hb.addWidget(self.analyze_h5_widget)
_hb.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
_hb.setSpacing(15)
_vb2 = QVBoxLayout()
_vb2.setContentsMargins(5, 0, 0, 0)
_vb2.setAlignment(Qt.AlignTop)
_vb2.addLayout(_vb3)
_vb2.addLayout(_hb)
self.setLayout(_vb2)
self.setFixedWidth(200)
self.setFixedHeight(136) #or 156/120
self.setAlignment(Qt.AlignTop | Qt.AlignLeft)
#self.recent_files_dict[fileOpenAction] = []
self.file_menu.aboutToShow.connect(self.updateFileMenu)
self.loadInitialFile()
self.updateFileMenu()
def fileOpen(self):
dir = (os.path.dirname(self.filename)
if self.filename is not None else ".")
print("dir for file open", dir)
fname, ffilter = QFileDialog.getOpenFileName(
self, "Select File", dir, (
"HDF5 files (*.hdf *.h5 *.hdf5 *.he5)"))
if fname:
self.loadFile(fname)
def loadInitialFile(self):
if self.qsettings.value("H5GroupLastFile"):
fname = str(self.qsettings.value("H5GroupLastFile"))
if fname and QFile.exists(fname):
print ("loadInitialFile=========================>", fname)
self.loadFile(fname)
def loadFile(self, fname):
print("load file", fname)
if not fname:
action = self.sender()
if isinstance(action, QAction):
fname = str(action.data())
print("from self.sender:")
print(fname)
if fname:
self.filename = None
if fname is None:
message = "Failed to read file='{0}'".format(fname)
self.show_message(
MsgSeverity.WARN, _pymodule, _line(), message)
else:
self.addRecentFile(fname)
self.filename = fname
message = "Loaded {0}".format(os.path.basename(fname))
message2 = "Loaded file='{0}'".format((fname))
self.show_message(
MsgSeverity.INFO, _pymodule, _line(), message2)
#self.loadFileProc()
self.updateStatus(message)
self.parent.h5_filename = fname
_filename_wgt_str = fname #os.path.basename(fname)
_start = str(fname).rfind(str(self.common_path))
print("common path in loadFile ============>", self.common_path)
print("start", _start)
if _start == 0:
_filename_wgt_str = str(fname).replace(self.common_path, "")
if _filename_wgt_str:
if _filename_wgt_str.count("/") > 1:
_filename_wgt_str = ".../" + _filename_wgt_str
else:
_filename_wgt_str = fname
self.loaded_file_widget.setText(_filename_wgt_str)
else:
message = "No input file given!"
self.show_message(
MsgSeverity.WARN, _pymodule, _line(), message)
self.qsettings.setValue("H5GroupLastFile", self.filename)
recentFiles = ', '.join(self.recent_files)
#recentFiles = (self.recentFiles) if self.recentFiles else None
self.qsettings.setValue("H5GroupRecentFiles", (recentFiles))
print("loaded to qsettings", self.filename)
def addRecentFile(self, fname):
if fname is None:
return
if self.recent_files is None:
self.recent_files.insert(0, fname)
if fname not in self.recent_files:
self.recent_files.insert(0, fname)
while len(self.recent_files) > self.max_no_files:
self.recent_files.pop((len(self.recent_files)-1))
print(self.recent_files)
def loadFileProc(self):
f = QFile(self.filename)
if f.open(QIODevice.ReadOnly):
self.fByteArray = f.readAll()
f.close()
else:
message = "Failed to load file='{0}'".format(self.filename)
self.show_message(
MsgSeverity.WARN, _pymodule, _line(), message)
def updateFileMenu(self):
self.file_menu.clear()
self.file_menu.addAction(self.file_open_action)
#self.parent.addActions(self.file_menu, self.fileMenuActions[:-1])
_current = (str(self.filename)
if self.filename is not None else None)
if _current is not None:
_recent_files = [_current]
else:
_recent_files = []
#print("update(1)--->", _recent_files)
if _current is not None:
if self.recent_files:
for fname in self.recent_files:
if fname != _current and QFile.exists(fname):
_recent_files.append(fname)
#print("update(2)--->", _recent_files)
if _recent_files:
self.common_path = os.path.commonpath(_recent_files) + "/"
else:
self.common_path = None
#print("_common_path=====>", self.common_path)
if _recent_files:
self.file_menu.addSeparator()
for i, fname in enumerate(_recent_files):
_label_icon = QFileInfo(fname).fileName()
if self.common_path is not None:
print(self.common_path)
print(str(os.path.dirname(fname)))
_start = str(os.path.dirname(fname)).rfind(
str(self.common_path))
if _start == 0:
_addon_str = str(os.path.dirname(fname)).replace(
self.common_path, "")
print("Extra", _start)
#print (str(os.path.basename(fname))[_start:])
#_addon = str(os.path.basename(fname))[_start:]
print("filename", _label_icon)
if _addon_str:
_label_icon += " [..." + _addon_str + "/]"
action = QAction(QIcon(":/icon.png"),
"&{0} {1}".format(i + 1, _label_icon), self)
action.setData(str(fname))
#print("update(3) ", i, fname)
action.triggered.connect(self.loadFile)
self.file_menu.addAction(action)
print("trigger for ", QFileInfo(fname).fileName(), fname)
#cplist = QFileInfo(fname).canonicalPath().split('/')
#print (cplist)
#print (cplist[-2])
#self.file_menu.addSeparator()
#self.file_menu.addAction(self.fileMenuActions[-1])
self.recent_files = _recent_files

47
helpbrowser.py Normal file
View File

@@ -0,0 +1,47 @@
""" Help pages
"""
from qtpy.QtCore import Signal, Qt, QUrl
from qtpy.QtGui import QIcon, QKeySequence
from qtpy.QtWidgets import (QAction, QApplication, QDialog,
QLabel, QTextBrowser, QToolBar, QVBoxLayout)
class HelpBrowser(QDialog):
def __init__(self, helpbase, page, parent=None, xlength=600, ylength=550):
super(HelpBrowser, self).__init__(parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setAttribute(Qt.WA_GroupLeader)
self.xlength = xlength
self.ylength = ylength
back_action = QAction(QIcon(":/back.png"), "&Back", self)
back_action.setShortcut(QKeySequence.Back)
home_action = QAction(QIcon(":/home.png"), "&Home", self)
home_action.setShortcut("Home")
self.page_label = QLabel()
tool_bar = QToolBar()
tool_bar.addAction(back_action)
tool_bar.addAction(home_action)
tool_bar.addWidget(self.page_label)
self.text_browser = QTextBrowser()
layout = QVBoxLayout()
layout.addWidget(tool_bar)
layout.addWidget(self.text_browser, 1)
self.setLayout(layout)
back_action.triggered.connect(self.text_browser.backward)
home_action.triggered.connect(self.text_browser.home)
self.text_browser.sourceChanged.connect(self.update_page_title)
self.text_browser.setSearchPaths([":/help", helpbase])
self.text_browser.setSource(QUrl(page))
self.resize(self.xlength, self.ylength)
self.setWindowTitle("{0} Help".format(parent.pymodule))
QApplication.processEvents()
def update_page_title(self):
self.page_label.setText(self.text_browser.documentTitle())

67
menubar.py Normal file
View File

@@ -0,0 +1,67 @@
import inspect
import platform
import os
import time
# Third-party modules
from qtpy.QtCore import (PYQT_VERSION_STR, Signal, Slot, QFile, QFileInfo,
QIODevice, QMutex, QSettings, QSize, Qt, QTimer,
qVersion)
from qtpy.QtCore import __version__ as QT_VERSION_STR, QTemporaryDir
from qtpy.QtGui import (QColor, QKeySequence, QFont, QIcon, QPainter, QPalette,
QPixmap)
from qtpy.QtPrintSupport import QPrinter, QPrintDialog
from qtpy.QtWidgets import (QAbstractItemView, QAction, QActionGroup,
QApplication, QButtonGroup, QComboBox, QDialog,
QDockWidget, QDoubleSpinBox, QFileDialog, QFrame,
QGridLayout, QGroupBox, QHBoxLayout, QLabel,
QLayout, QLineEdit, QListWidget, QMainWindow, QMenu,
QMenuBar, QMessageBox, QPlainTextEdit, QProgressBar,
QPushButton, QScrollArea, QSizePolicy, QSlider,
QSpinBox, QSplashScreen, QStyle, QStyleOptionSlider,
QToolButton, QVBoxLayout, QWidget)
import pyqtacc.bdbase.pyrcc5.qrc_resources
from pyqtacc.bdbase.enumkind import MsgSeverity, UsageMode
from pyqtacc.bdbase.readjson import ReadJSON
import PyCafe
_pymodule = os.path.basename(__file__)
_appname, _appext = _pymodule.split(".")
_appversion = "1.0.0"
def _line():
"""Macro to return the current line number.
The current line number within the file is used when
reporting messages to the message logging window.
Returns:
int: Current line number.
"""
return inspect.currentframe().f_back.f_lineno
class MenuBar(QMainWindow):
""" MenuBar
"""
def __init__(self, parent=None, pymodule=None, appversion=None, title=""):
super(MenuBar, self).__init__(parent)
pass
def create_action(self, text, slot=None, shortcut=None, icon=None, tip=None,
checkable=False, signal="triggered()"):
action = QAction(text, self)
if icon is not None:
action.setIcon(QIcon(":/{0}.png".format(icon)))
if shortcut is not None:
action.setShortcut(shortcut)
if tip is not None:
action.setToolTip(tip)
if slot is not None:
action.triggered.connect(slot)
if checkable:
action.setCheckable(True)
return action

18829
pyrc5/qrc_resources.py Normal file

File diff suppressed because it is too large Load Diff

131
readjson.py Normal file
View File

@@ -0,0 +1,131 @@
""" JSON
"""
import argparse
import json
import os
from qtpy.QtCore import PYQT_VERSION_STR, QFile, QIODevice, QTemporaryDir
from qtpy.QtGui import QColor
#from pyqtacc.bdbase.enumkind import MsgSeverity
#import pyqtacc.bdbase.pyrcc5.qrc_resources
class ReadJSON(object):
""" Reads three json configuration files.
1) The style guide and default menu configuration
2) The accelerator facility configuration file
3) The user-specified configuration file
"""
def __init__(self, appname: str = ""):
self.appname = 'user' if appname == "" else appname
json_qrc = ["style", "base", self.appname]
parser = argparse.ArgumentParser(description="configuration")
parser.add_argument("-c", "--config", action="store", dest="style")
parser.add_argument("-f", "--facility", action="store", dest="facility")
parser.add_argument("-u", "--user", action="store", dest="user")
parser.add_argument("-q", "--qss", action="store")
result = parser.parse_args()
temp_file = {}
self.data = {}
#Extract style adn facility config files from qrc_resources
temp_dir = QTemporaryDir()
if temp_dir.isValid():
for dest in json_qrc[0:2]:
temp_file[dest] = temp_dir.path() + "/" + dest + ".json"
if QFile.copy(":/{0}.json".format(dest), temp_file[dest]):
print(":/{0}.json successfully copied from qrc_resources".
format(dest))
else:
print("json file :/{0}.json was not found in qrc_resources".
format(dest))
else:
print("Invalid temporary directory: {0}".format(temp_dir))
#Overriding config files in qrc_resources with any supplied by user
if result.style:
if os.path.isfile(result.style):
temp_file[json_qrc[0]] = result.style
print("Config file {0} supplied by user".format(
temp_file[json_qrc[0]]))
else:
print("User supplied config file {0} does not exist".format(
result.style))
if result.facility:
if os.path.isfile(result.facility):
temp_file[json_qrc[1]] = result.facility
print("Config file {0} supplied by user".format(
temp_file[json_qrc[1]]))
else:
print("User supplied config file {0} does not exist".format(
result.facility))
if result.user:
if os.path.isfile(result.user):
temp_file[json_qrc[2]] = result.user
print("Config file {0} supplied by user".format(
temp_file[json_qrc[2]]))
else:
print("User supplied config file {0} does not exist".format(
result.user))
#Now open default config files
try:
with open(temp_file[json_qrc[0]]) as data_file:
self.data = json.load(data_file)
except IOError:
print("Config file: {0} not found!".format(
temp_file[json_qrc[0]]))
try:
with open(temp_file[json_qrc[1]]) as data_file:
self.data_facility = json.load(data_file)
for key, val in self.data_facility.items():
self.data[key] = val
#print(key, self.data[key])
except IOError:
print("Config file: {0} not found".format(
temp_file[json_qrc[1]]))
#Now open user supplied config files
json_file = self.appname + ".json"
if result.user is not None:
if os.path.isfile(result.user):
json_file = result.user
print("Local user config file: {0} found".format(json_file))
else:
print("Local user config file {0} not found!".format(json_file))
print("Searching local directory for user config file {0}".
format(json_file))
else:
print("Searching local directory for user config file {0}".
format(json_file))
try:
with open(json_file) as data_file:
data_user = json.load(data_file)
for key, val in data_user.items():
#self.data[key] = val
#print("======", key, val, type(key), type(val))
if key in self.data.keys():
for k, v in val.items():
#print(key, k, v, type(k), type(v))
self.data[key][k] = v
else:
self.data[key] = val
except IOError:
print("User {0} config file not found!" .format(json_file))
#self.show()
def show(self):
""" print key values of jason file
"""
for key in self.data:
print(str(key) + ': ' + str(self.data[key]))

236
savehdf.py Normal file
View File

@@ -0,0 +1,236 @@
import getpass
import os
import time
from qtpy.QtCore import Signal, Slot, Qt
from qtpy.QtWidgets import (QComboBox, QDialog, QFileDialog, QFrame,
QHBoxLayout, QLabel, QLineEdit, QPushButton,
QTextEdit, QVBoxLayout)
_version = "1.0.0"
_pymodule = os.path.basename(__file__)
_appname, _appext = _pymodule.split(".")
class QSaveHDF(QDialog):
def __init__(self, parent, input_options={'Comment':None}):
super(QSaveHDF, self).__init__(parent)
self.filesText = ''
self.fflag = False
widget_width = 220
self.user_dict = {}
self.user_dict['Comment'] = None
self.file_name = None
self.destination = parent.elog_dest + " / " + parent.appname
self.appName = parent.appname + " / " + _appname
self.setWindowTitle(self.appName)
self.parent = parent
self.files = []
self.attributes = {}
self.applicationBox = QHBoxLayout()
self.applicationBox.addWidget(QLabel('Application:'))
self.applicationLabel = QLabel(parent.pymodule)
self.applicationLabel.setObjectName("hdf")
self.applicationLabel.setFixedWidth(widget_width)
self.user_dict['Application'] = self.applicationLabel.text()
self.applicationBox.addWidget(self.applicationLabel)
self.applicationBox.setStretch(1,1)
self.layout = QVBoxLayout(self)
self.layout.addLayout(self.applicationBox)
authorBox = QHBoxLayout()
authorBox.addWidget(QLabel('Author: '))
self.author = QLineEdit()
self.author.setObjectName('hdf')
self.author.setFixedWidth(widget_width)
self.author.setAlignment(Qt.AlignCenter)
self.author.setText(getpass.getuser())
self.user_dict['Author'] = self.author.text()
authorBox.addWidget(self.author)
self.layout.addLayout(authorBox)
qframe = QFrame()
qframe.setFrameShape(QFrame.HLine)
qframe.setFrameShadow(QFrame.Sunken)
self.layout.addWidget(qframe)
i=0
self.wgt_dict = {}
self.wgt_list = [None] * len(input_options)
for key, value in input_options.items():
if key=='Comment':
self.user_dict['Comment'] = value
continue
hbox = QHBoxLayout()
hbox.addWidget(QLabel(str(key)+":"))
if isinstance(value, list):
self.wgt_list[i] = QComboBox()
self.wgt_list[i].setObjectName('hdf')
for _item in value:
self.wgt_list[i].addItem(_item)
self.wgt_list[i].setCurrentIndex(0)
self.user_dict[key] = self.wgt_list[i].currentText()
else:
self.wgt_list[i] = QLineEdit()
self.wgt_list[i].setObjectName('hdf')
self.wgt_list[i].setFixedWidth(widget_width)
self.wgt_list[i].setAlignment(Qt.AlignCenter)
if value is not None:
self.wgt_list[i].setText(str(value))
self.user_dict[key] = self.wgt_list[i].text()
self.wgt_dict[self.wgt_list[i]] = key
hbox.addWidget(self.wgt_list[i])
i += 1
self.layout.addLayout(hbox)
lbl = QLabel('Comment: ')
self.layout.addWidget(lbl)
self.comment = QTextEdit(self.user_dict['Comment'])
self.comment.setFixedHeight(70)
self.comment.setObjectName('hdf')
self.layout.addWidget(self.comment)
fileBox = QHBoxLayout()
qlFile = QLabel('Destination file:')
qlFile.setAlignment(Qt.AlignTop)
fileBox.addWidget(qlFile)
self.filesE = QTextEdit()
self.filesE.setAlignment(Qt.AlignTop)
self.filesE.setFixedHeight(84)
self.filesE.setMinimumWidth(270)
self.filesE.setReadOnly(False)
self.filesE.setObjectName('hdf')
self.attachFile = None
if self.attachFile is not None:
_attachFile = []
if isinstance(self.attachFile, str):
_attachFile.append(self.attachFile)
elif isinstance(self.attachFile, list):
_attachFile = self.attachFile
for i in range(0, len(_attachFile)):
_attach_base = os.path.basename(self.attachFile[i])
if i > 0:
self.filesText += "\n"
self.filesText += str(_attach_base)
self.filesE.setText(self.filesText)
self.fflag = True
openCloseVBox = QHBoxLayout()
openBtn = QPushButton('Select')
openBtn.setObjectName('hdflight')
openBtn.setAutoDefault(False)
openBtn.clicked.connect(self.openFiles)
# openBtn.clearFocus()
openCloseVBox.addWidget(openBtn)
closeBtn = QPushButton('Clear')
closeBtn.setObjectName('hdflight')
closeBtn.setAutoDefault(False)
closeBtn.clicked.connect(self.clearFiles)
openCloseVBox.addWidget(closeBtn)
fileBox.addLayout(openCloseVBox)
self.layout.addLayout(fileBox)
self.layout.addWidget(self.filesE)
btnLayout = QHBoxLayout()
okBtn = QPushButton('Save to HDF')
okBtn.setAutoDefault(False)
okBtn.clicked.connect(self.save)
okBtn.setObjectName('WriteData')
okBtn.setFixedHeight(45)
cancelBtn = QPushButton('Cancel')
cancelBtn.setAutoDefault(False)
cancelBtn.clicked.connect(self.cancel)
cancelBtn.setObjectName('Cancel')
cancelBtn.setFixedHeight(45)
btnLayout.addWidget(okBtn)
btnLayout.addWidget(cancelBtn)
self.messagelbl = QLabel('')
self.messagelbl.setStyleSheet("QLabel { color : red; }")
self.layout.addWidget(self.messagelbl)
self.layout.addLayout(btnLayout)
self.show()
def get_data(self):
self.user_dict['Application'] = self.applicationLabel.text()
self.user_dict['Author'] = self.author.text()
self.user_dict['Comment'] = self.comment.document().toPlainText()
if self.file_name:
self.user_dict['Destination'] = self.file_name
else:
self.user_dict['Destination'] = self.filesE.document().toPlainText()
message = self.comment.document().toPlainText()
for key in self.wgt_dict.keys():
if 'QLineEdit' in str(key):
self.user_dict[self.wgt_dict[key]] = key.text()
elif 'QComboBox' in str(key):
self.user_dict[self.wgt_dict[key]] = key.currentText()
return self.user_dict
def cancel(self):
self.clearFiles()
self.close()
def save(self):
message = self.comment.document().toPlainText()
if not message:
self.messagelbl.setText('Please enter a Comment')
return
author = self.author.text()
self.get_data()
print("Destination", self.user_dict['Destination'])
print("FileName", self.file_name)
self.close()
def clearFiles(self):
self.attachFile = []
self.filesE.clear()
self.files = []
self.filesText = ''
self.file_name =''
self.fflag = False
def openFiles(self):
# Notethat openFiles also gets called when qDialog cancel is clicked!
qFileDialog = QFileDialog()
# Returns a QStringList which maps onto a tuple in Python!!
# type (fileLocal) returns a tuple(!
filesLocal, ffilter = qFileDialog.getSaveFileName(
self, 'Save As', self.destination,
"HDF5 files (*.hdf *.h5 *.hdf5 *.he5)")
if filesLocal:
self.clearFiles()
self.filesE.setText(filesLocal)

152
screenshot.py Normal file
View File

@@ -0,0 +1,152 @@
import datetime
import os
import socket
from qtpy.QtCore import PYQT_VERSION_STR, QTimer
from qtpy.QtGui import QPixmap
from qtpy.QtPrintSupport import QPrinter, QPrintDialog
from qtpy.QtWidgets import (QApplication, QCheckBox, QDialog, QVBoxLayout,
QHBoxLayout, QPushButton, QWidget)
from pyqtacc.bdbase.enumkind import MsgSeverity
import inspect
_pymodule = os.path.basename(__file__)
# macro
def _line():
return inspect.currentframe().f_back.f_lineno
class QScreenshot(QDialog):
def __init__(self, parent, window_title: str = 'QScreenshot',
screen_items: list = [], screen_titles: list = []):
super(QScreenshot, self).__init__(parent)
self.setWindowTitle(window_title)
self.parent = parent
self.screenshot_titles = screen_titles
self.screenshot_items = screen_items
print(self.parent.appname)
self.layout = QVBoxLayout(self)
#elem1 = title + "_EntireWindow"
#elem2 = title + "_CentralWidget"
elem1 = "EntireWindow"
elem2 = "CentralWidget"
#self.checkText = [elem1, elem2] + \
self.checkText = [elem1] + \
self.screenshot_titles #grphTitle # +parent.gui.titles
self.checkBoxes = []
for i, t in enumerate(self.checkText):
self.checkBoxes.append(QCheckBox(t))
self.checkBoxes[i].setObjectName(str (i-len(self.checkText))) #(i-1)) #(i-2)
self.layout.addWidget(self.checkBoxes[i])
btnLayout = QHBoxLayout()
self.okBtn = QPushButton('OK')
self.okBtn.clicked.connect(self.ok)
self.cancelBtn = QPushButton('Cancel')
self.cancelBtn.clicked.connect(self.close)
btnLayout.addWidget(self.okBtn)
btnLayout.addWidget(self.cancelBtn)
self.layout.addLayout(btnLayout)
topLevelWidgets = QApplication.allWidgets() # topLevelWidgets()
#print(topLevelWidgets)
#for i in range (0, len(topLevelWidgets)):
# print (topLevelWidgets[i])
#print(self.parent.centralWidget())
#print(self.parent.parent.WidgetDB['CV_Plot'] )
#print(self.parent.grphs[0])
#print(self.parent.grphTitle[0])
self.show()
def ok(self):
self.close()
self.parent.update() # not really required
QTimer.singleShot(10, self.capture)
# QtGui.QPixmap.grabWindow -> QtGui.QScreen.grabWindow
# QtGui.QPixmap.grabWidget -> QtWidgets.QWidget.grab
# QPixmap check for true=success or false=failure
# Deprecated QPixmap replaced by QScreen in Qt 5
def capture(self):
now = datetime.datetime.now()
# '/afs/psi.ch/intranet/Controls/tmp/elog/ePic/SwissFEL+commissioning/'
folderName = self.parent.settings.data["screenshot"]["destination"] + self.parent.appname + "/" #elogDest
if not os.path.exists(folderName):
os.makedirs(folderName)
# os.makedirs(folderName)
maxI = [None] * len(self.checkBoxes)
##print(len(maxI), len(self.checkBoxes))
# Find MAXIMUM i
for i in range(0, len(self.checkBoxes)):
maxI[i] = 0
count = 0
for c in self.checkBoxes:
n = int(c.objectName())
i = 0
#cname = socket.gethostname()
#name = folderName+str(cname)+':screenshot_'+self.checkText[n+2]+'_'
#name = folderName+str(cname)+':'+self.checkText[n+2]+'_'
name = folderName+self.checkText[n+1]+'_' #n+2
while os.path.exists(name+str(i)+'.png'):
i += 1
if i > maxI[count]:
maxI[count] = i
count = count + 1
maxII = 0
for i in range(0, len(maxI)):
if maxI[i] > maxII:
maxII = maxI[i]
count = 0
for c in self.checkBoxes:
if c.isChecked():
n = int(c.objectName())
name = folderName+self.checkText[n+1]+'_' #n+2
name += now.strftime("%Y-%m-%d_%H:%M:%S") + '.png'
winid = self.parent.winId()
# THis is the desktop windowid. i.e. the console window
##winid1 = QApplication.desktop().winId()
#print(type(winid))
#print (" n == ", n)
_mess = ("Failed to save screenshot to:\nfile='%s'" % name)
_save_success = False
if n == -2:
qss = QApplication.screens()
qs = qss[len(qss)-1]
if qs.grabWindow(winid).save(name, 'png', 100):
_save_success = True
elif n == -1:
if QWidget.grab(self.parent.centralWidget()).save(name, 'png', 100):
_save_success = True
else:
if QWidget.grab(self.screenshot_items[n]).save(name, 'png', 100):
_save_success = True
if not _save_success:
self.parent.show_log_message(MsgSeverity.ERROR, _pymodule, _line(),
"Failed to save image to:\nfile='%s'" % name)
self.parent.show_log_message(MsgSeverity.INFO, _pymodule, _line(),
"Screenshot saved to:\nfile='%s'" % name)
self.parent.statusbar.showMessage("Screenshot saved to: %s" % name)
count = count + 1
QApplication.processEvents()

350
sendelog.py Normal file
View File

@@ -0,0 +1,350 @@
import getpass
import inspect
import os
import time
from qtpy.QtCore import Signal, Slot, Qt
from qtpy.QtWidgets import (QComboBox, QDialog, QFileDialog, QHBoxLayout,
QLabel, QLineEdit, QPushButton, QTextEdit,
QVBoxLayout)
import elog # https://github.com/paulscherrerinstitute/py_elog
from pyqtacc.bdbase.enumkind import MsgSeverity
_version = "1.0.0"
_pymodule = os.path.basename(__file__)
_appname, _appext = _pymodule.split(".")
def _line():
"""Macro to return the current line number.
The current line number within the file is used when
reporting messages to the message logging window.
Returns:
int: Current line number.
"""
return inspect.currentframe().f_back.f_lineno
class QSendToELOG(QDialog):
""" Grapghical interface to elog
"""
def __init__(self, parent, logbook=None, categoryIdx=0, domainIdx=0,
systemIdx=0, sectionIdx=0, title=None, message=None,
attachFile=None):
super(QSendToELOG, self).__init__(parent)
self.files_text = ''
self.fflag = False
self.destination = parent.elog_dest + " / " + parent.appname
self.window_title = parent.appname + ": " + _appname
self.parent = parent
self.pymodule = _pymodule
self.setWindowTitle(self.window_title)
elog_books = list(parent.settings.data["ElogBooks"])
self.elog_items = QComboBox()
self.elog_items.addItems(elog_books)
self.elog_items.currentIndexChanged.connect(self.on_elog_change)
idx = 0
if logbook is not None:
try:
idx = elog_books.index(logbook)
except:
mess = "Index not found for logbook {0}".format(logbook)
self.parent.show_log_message(MsgSeverity.WARN, self.pymodule,
_line(), mess)
else:
try:
idx = elog_books.index(self.parent.settings.data["Elog"]["book"])
except:
logbook = self.parent.settings.data["Elog"]["book"]
mess = "Index not found for logbook {0}".format(_logbook)
self.parent.show_log_message(MsgSeverity.WARN, self.pymodule,
_line(), mess)
self.elog_items.setCurrentIndex(idx)
self.elog_items.currentIndexChanged.emit(idx)
self.elog_items.setObjectName("Elog")
category_str = list(parent.settings.data["Elog"]['category'])
self.category = QHBoxLayout()
self.category.addWidget(QLabel('Category: '))
self.category_items = QComboBox()
self.category_items.setObjectName("Elog")
self.category_items.addItems(category_str)
self.category.addWidget(self.category_items)
self.category_items.setCurrentIndex(categoryIdx)
domain_str = list(parent.settings.data["Elog"]['domain'])
self.domain = QHBoxLayout()
self.domain.addWidget(QLabel('Domain: '))
self.domain_items = QComboBox()
self.domain_items.setObjectName("Elog")
self.domain_items.addItems(domain_str)
self.domain.addWidget(self.domain_items)
self.domain_items.setCurrentIndex(domainIdx)
self.domain_items.currentIndexChanged.connect(self.on_domain_change)
self.elog_section = list(parent.settings.data["Elog"]['section'])
self.section = QHBoxLayout()
self.section.addWidget(QLabel('Section: '))
self.section_items = QComboBox()
self.section_items.setObjectName("Elog")
self.section_items.addItems(self.elog_section[domainIdx])
self.section.addWidget(self.section_items)
self.section_items.setCurrentIndex(sectionIdx)
self.system = QHBoxLayout()
self.system.addWidget(QLabel('System: '))
self.system_items = QComboBox()
self.system_items.setObjectName("Elog")
self.system_items.addItems(list(parent.settings.data["Elog"]['system']))
self.system.addWidget(self.system_items)
self.system_items.setCurrentIndex(systemIdx)
self.title_items = QHBoxLayout()
self.title_items.addWidget(QLabel('Title: '))
self.titleline = QLineEdit()
self.titleline.setObjectName('Elog')
self.titleline.setStatusTip('elog')
if title is None:
title = parent.appname
self.titleline.setText(str(title))
self.titleline.setFixedWidth(300)
self.titleline.setAlignment(Qt.AlignCenter)
self.title_items.addWidget(self.titleline)
self.applicationbox = QHBoxLayout()
self.applicationbox.addWidget(QLabel('Application:'))
self.applicationlabel = QLabel(parent.pymodule)
self.applicationlabel.setObjectName("Elog")
# self.applicationbox.addStretch()
self.applicationbox.addWidget(self.applicationlabel)
logbook = QHBoxLayout()
logbook.addWidget(QLabel('Logbook: '))
logbook.addWidget(self.elog_items)
authorbox = QHBoxLayout()
authorbox.addWidget(QLabel('Author: '))
self.author = QLineEdit()
self.author.setObjectName('Elog')
self.author.setFixedWidth(195)
self.author.setStatusTip('elog')
self.author.setText(getpass.getuser())
authorbox.addWidget(self.author)
self.files = []
self.attributes = {}
self.layout = QVBoxLayout(self)
self.layout.addLayout(logbook)
self.layout.addLayout(self.applicationbox)
self.layout.addLayout(self.category)
self.layout.addLayout(self.domain)
self.layout.addLayout(self.section)
self.layout.addLayout(self.system)
self.layout.addLayout(authorbox)
self.layout.addLayout(self.title_items)
report = QLabel('Report: ')
self.layout.addWidget(report)
self.message = QTextEdit(message)
self.layout.addWidget(self.message)
filebox = QHBoxLayout()
qlfile = QLabel('Attach:')
qlfile.setAlignment(Qt.AlignTop)
filebox.addWidget(qlfile)
self.filesE = QTextEdit()
self.filesE.setAlignment(Qt.AlignTop)
self.filesE.setFixedHeight(80)
self.filesE.setReadOnly(True)
self.attachFile = attachFile
if self.attachFile is not None:
_attachFile = []
if isinstance(self.attachFile, str):
_attachFile.append(self.attachFile)
elif isinstance(self.attachFile, list):
_attachFile = self.attachFile
for i, file in enumerate(_attachFile):
_attach_base = os.path.basename(file)
if i > 0:
self.files_text += "\n"
self.files_text += str(_attach_base)
self.filesE.setText(self.files_text)
self.fflag = True
filebox.addWidget(self.filesE)
openCloseVBox = QVBoxLayout()
self.openBtn = QPushButton('Add')
self.openBtn.setAutoDefault(False)
self.openBtn.clicked.connect(self.openFiles)
openCloseVBox.addWidget(self.openBtn)
closeBtn = QPushButton('Clear')
closeBtn.setAutoDefault(False)
closeBtn.clicked.connect(self.clearFiles)
openCloseVBox.addWidget(closeBtn)
filebox.addLayout(openCloseVBox)
self.layout.addLayout(filebox)
btnLayout = QHBoxLayout()
self.okBtn = QPushButton('Send')
self.okBtn.setAutoDefault(False)
self.okBtn.clicked.connect(self.ok)
self.cancelBtn = QPushButton('Cancel')
self.cancelBtn.setAutoDefault(False)
self.cancelBtn.clicked.connect(self.close)
btnLayout.addWidget(self.okBtn)
btnLayout.addWidget(self.cancelBtn)
self.messagelbl = QLabel('')
self.messagelbl.setStyleSheet("QLabel { color : red; }")
self.layout.addWidget(self.messagelbl)
self.layout.addLayout(btnLayout)
self.show()
'''
autoDefault : bool
This property holds whether the push button is an auto default button
If this property is set to true then the push button is an auto default
button. In some GUI styles a default button is drawn with an extra frame
around it, up to 3 pixels or more. Qt automatically keeps this space
free around auto-default buttons, i.e., auto-default buttons may have a
slightly larger size hint. This property's default is true for buttons
that have a QDialog parent; otherwise it defaults to false. See the
default property for details of how default and auto-default interact.
That is, this is the responsible property of this problem. The
workaround is to set the autoDefault property to False for all QPushButtons.
'''
def on_elog_change(self, i):
if "test" in self.elog_items.currentText():
_bgcolor = "QComboBox {background: plum; color : black;}"
else:
_bgcolor = "QComboBox {background: lightblue; color : black;}"
self.elog_items.setStyleSheet(_bgcolor)
def on_domain_change(self, i):
self.section_items.clear()
self.section_items.addItems(self.elog_section[i])
return
def ok(self):
message = self.message.document().toPlainText()
if not message:
self.messagelbl.setText('Please enter a brief Report')
return
title = self.titleline.text()
if not title:
self.messagelbl.setText('Title attribute is required')
return
cat = self.category_items.currentText()
if not cat:
self.messagelbl.setText('Category attribute is required')
return
author = self.author.text()
application = self.applicationlabel.text()
self.attributes['Autor'] = author
self.attributes['Author'] = author
self.attributes['Application'] = application
# if title is not None: #!= '':
self.attributes['Titel'] = title
self.attributes['Title'] = title
self.attributes['Category'] = cat
self.attributes['Domain'] = self.domain_items.currentText()
self.attributes['Section'] = self.section_items.currentText()
self.attributes['System'] = self.system_items.currentText()
self.attributes['When'] = str(time.time())
el = self.elog_items.currentText()
if self.attachFile is not None:
_attachFile = []
if isinstance(self.attachFile, str):
_attachFile.append(self.attachFile)
elif isinstance(self.attachFile, list):
_attachFile = self.attachFile
for i in range(0, len(_attachFile)):
if "/tmp" in _attachFile[i]:
self.files.append(str(_attachFile[i])) # self.files_text)
elif "/afs/psi.ch" in _attachFile[i]:
self.files.append(str(_attachFile[i]))
else:
self.files.append(self.destination + str(_attachFile[i])) # self.files_text)
url = self.parent.settings.data["ElogBooks"][el]["url"]
self.logbook = elog.open(url, user='robot', password='robot')
print("send to elog: ", url)
print(message)
try:
if self.files:
self.logbook.post(message, attributes=self.attributes,
attachments=self.files)
else:
self.logbook.post(message, attributes=self.attributes)
#self.trigger_elog_entry.emit(True, url, "OK")
self.receive_elog_notification(True, url, "OK")
except Exception as ex:
#self.trigger_elog_entry.emit(False, url, str(ex))
self.receive_elog_notification(False, url, str(ex))
self.close()
def clearFiles(self):
self.attachFile = []
self.filesE.clear()
self.files = []
self.files_text = ''
self.fflag = False
def openFiles(self):
# Notethat openFiles also gets called when qDialog cacnel is clicked!
qFileDialog = QFileDialog()
extensions = ("Images (*.bmp *.eps *.gif *.jpeg *.jpg *.pdf *.png " +
"*.ps *.tiff *.xpm);;Text files (*.txt *.text);;" +
"JSON/XML files (*.json *.xml)")
flocal, ffilter = qFileDialog.getOpenFileNames(
self, 'Open File', self.destination, extensions)
self.files.append(flocal[0])
if (self.fflag == True):
self.files_text += '\n'
self.files_text += str(flocal[0].split('/')[-1])
self.fflag = True
self.filesE.setText(self.files_text)
def receive_elog_notification(self, is_accepted, logbook_url, elog_message):
'''Receive notification from ELOG, and report to log window'''
yes_no = "made" if is_accepted else "failed"
mess = "Entry into ELOG: {0} {1}".format(logbook_url, yes_no)
if is_accepted:
self.parent.show_log_message(MsgSeverity.INFO, self.pymodule,
_line(), mess)
else:
mess += ".\n" + elog_message
self.parent.show_log_message(MsgSeverity.WARN, self.pymodule,
_line(), mess)
self.parent.statusbar.showMessage(mess)