new commit

This commit is contained in:
2022-06-28 10:04:37 +02:00
parent e2ad99fe36
commit cedb77d270
10 changed files with 21253 additions and 1482 deletions

4
.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
*.*~
*.*-*
*.*+*
__pycache__

1643
base.py

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,37 +1,34 @@
import inspect
import os
from qtpy.QtCore import (PYQT_VERSION_STR, QFile, QFileInfo, QIODevice,
QSettings, Qt)
from qtpy.QtCore import 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 qtpy.QtWidgets import (QAction, QFileDialog, QGroupBox, QHBoxLayout,
QLabel, QLineEdit, QMenuBar, QPushButton,
QVBoxLayout)
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:
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.parent = parent
self.show_message = self.parent.show_log_message
self.updateStatus = self.parent.updateStatus
self.createAction = self.parent.create_action
@@ -44,10 +41,9 @@ class HDF5File(QGroupBox):
self.file_dir = "."
self.qsettings = QSettings()
self.loadInitialFile()
def show_common_path_only(self, yes=False):
self.show_common_path_only = yes
self.show_common_path_flag = yes
def saveToFileProcedure(self):
f = QFile(self.save_filename)
@@ -59,140 +55,78 @@ class HDF5File(QGroupBox):
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
"Saved file='{0}'".format(self.save_filename))
else:
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")
self.show_message(MsgSeverity.WARN, _pymodule, _line(),
"Unable to save as no filename was given")
return False
if self.save_filename:
self.showSaveFile()
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)
'''
def fileSaveAs(self):
_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]))
_fname = QFileDialog.getSaveFileName(
self, "Save File", _dir, "HDF5 files (*.hdf *.h5 *.hdf5 *.he5)")
if _fname == "('', '')":
return False
else:
fname = _fname[0]
if fname:
if "." not in os.path.basename(fname):
fname += ".h5"
##self.addRecentSaveFile(fname)
#self.addRecentSaveFile(fname)
self.save_filename = fname
print("fileSaveAs, filename ", self.save_filename)
self.fileSave()
return True
return True
return False
def showSaveFile(self):
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(
_dir = os.path.dirname(
self.filename) if self.filename is not None else self.file_dir
fname = QFileDialog.getOpenFileName(
self, "Select/Open File", str(_dir), (
"HDF5 files (*.hdf *.h5 *.hdf5 *.he5)"))
"HDF5 files (*.hdf *.h5 *.hdf5 *.he5)"))[0]
if fname:
self.loadFile(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()
self.recent_files = str(mylist).split(',')
if self.qsettings.value("H5LastLoadedFile"):
fname = str(self.qsettings.value("H5LastLoadedFile"))
if fname and QFile.exists(fname):
print ("loadInitialFile=========================>", fname)
#print ("loadInitialFile==============>", fname)
self.filename = fname
def loadFile(self, fname):
print("load file=>", fname)
if not fname:
def loadFile(self, 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:
@@ -204,16 +138,14 @@ class HDF5File(QGroupBox):
else:
self.addRecentFile(fname)
self.filename = fname
self.parent.h5_filename = fname
self.parent.hdf_filename_loaded = 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)
#print("common path in loadFile ========>", self.common_path)
if _start == 0:
_filename_wgt_str = str(fname).replace(self.common_path, "")
if _filename_wgt_str:
@@ -221,10 +153,8 @@ class HDF5File(QGroupBox):
_filename_wgt_str = ".../" + _filename_wgt_str
else:
_filename_wgt_str = fname
if self.loadFromFileProcedure():
if self.loadFromFileProcedure():
message = "Loaded {0}".format(os.path.basename(fname))
message2 = "Loaded file='{0}'".format((fname))
self.show_message(
@@ -236,100 +166,74 @@ class HDF5File(QGroupBox):
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)
#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)
#print(self.recent_files)
def loadFromFileProcedure(self):
f = QFile(self.filename)
if f.open(QIODevice.ReadOnly):
self.fByteArray = f.readAll()
self.fByteArray = f.readAll()
f.close()
else:
message = "Failed to load file='{0}'".format(self.filename)
self.show_message(
MsgSeverity.WARN, _pymodule, _line(), 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)
_current = str(
self.filename) if self.filename is not None else None
_recent_files = [_current] if _current is not None else []
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)))
@@ -338,52 +242,29 @@ class HDF5File(QGroupBox):
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"):
obj_name="INNER"):
super(HDF5SaveLoad, self).__init__(parent)
self.parent = parent
self.parent = parent
self.file_dir = file_dir
self.setTitle(title)
self.setObjectName(obj_name)
_qw = QWidget()
_font16 = QFont("sans-serif")
_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)
@@ -393,12 +274,11 @@ class HDF5SaveLoad(HDF5File):
_menu_bar = QMenuBar()
_menu_bar.setFont(_font16)
_menu_bar.setFixedWidth(120)
_menu_bar.setFixedHeight(38)
_menu_bar.setFixedHeight(38)
_menu_bar.setObjectName("load")
self.file_menu = _menu_bar.addMenu('Load Matrix')
self.file_menu.setFont(_font16)
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")
@@ -406,15 +286,15 @@ class HDF5SaveLoad(HDF5File):
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.setFixedHeight(38)
_menu_save_bar.setObjectName("hdf")
self.save_menu = _menu_save_bar.addMenu('Save Matrix')
self.save_menu.setFont(_font16)
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")
@@ -425,13 +305,13 @@ class HDF5SaveLoad(HDF5File):
_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)
@@ -442,16 +322,16 @@ class HDF5SaveLoad(HDF5File):
self.setFixedWidth(400)
self.setFixedHeight(100) #or 156/120
self.setAlignment(Qt.AlignTop | Qt.AlignLeft)
self.file_menu.aboutToShow.connect(self.updateFileMenu)
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.parent = parent
self.show_message = self.parent.gui_frame.show_log_message
self.updateStatus = self.parent.statusbar.showMessage
self.createAction = self.parent.create_action
@@ -462,16 +342,13 @@ class HDF5GroupBox(QGroupBox):
self.setTitle(title)
self.qsettings = QSettings()
_qw = QWidget()
_font16 = QFont("sans-serif")
_font16 = QFont("sans-serif")
_font16.setPixelSize(16)
_menu_bar = QMenuBar()
_menu_bar.setFont(_font16)
_menu_bar.setFixedWidth(50)
_menu_bar.setFixedHeight(24)
_menu_bar.setFixedHeight(24)
_loaded_file_label = QLabel(" Loaded:")
_loaded_file_label.setFixedHeight(13)
_loaded_file_label.setAlignment(Qt.AlignLeft | Qt.AlignTop)
@@ -482,25 +359,23 @@ class HDF5GroupBox(QGroupBox):
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.analyze_h5_widget.setToolTip("Analyze pre-loaded hdf data")
self.file_menu = _menu_bar.addMenu('File')
self.file_menu.setFont(_font16)
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.separator.setSeparator(True)
self.file_menu.addAction(self.file_open_action)
if layout == "Hor":
self.setObjectName("OUTER")
_hb = QHBoxLayout()
@@ -515,24 +390,22 @@ class HDF5GroupBox(QGroupBox):
self.setLayout(_hb)
self.setFixedWidth(600)
self.setFixedHeight(64) #or 156/120
else:
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(_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)
@@ -543,45 +416,37 @@ class HDF5GroupBox(QGroupBox):
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.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)"))
def fileOpen(self):
dir_name = os.path.dirname(
self.filename) if self.filename is not None else "."
fname = QFileDialog.getOpenFileName(
self, "Select File", dir_name, (
"HDF5 files (*.hdf *.h5 *.hdf5 *.he5)"))[0]
if fname:
self.loadFile(fname)
self.loadFile(fname)
def loadInitialFile(self):
def loadInitialFile(self):
if self.qsettings.value("H5GroupLastFile"):
fname = str(self.qsettings.value("H5GroupLastFile"))
if fname and QFile.exists(fname):
print ("loadInitialFile=========================>", fname)
#print ("loadInitialFile=============>", fname)
self.loadFile(fname)
def loadFile(self, fname):
print("load file", fname)
if not fname:
def loadFile(self, fname):
if not fname:
action = self.sender()
if isinstance(action, QAction):
fname = str(action.data())
print("from self.sender:")
print(fname)
print(fname)
if fname:
self.filename = None
if fname is None:
@@ -591,20 +456,19 @@ class HDF5GroupBox(QGroupBox):
else:
self.addRecentFile(fname)
self.filename = fname
message = "Loaded {0}".format(os.path.basename(fname))
message2 = "Loaded file='{0}'".format((fname))
message2 = "Loaded hdf file '{0}'".format((fname))
self.show_message(
MsgSeverity.INFO, _pymodule, _line(), message2)
#self.loadFileProc()
self.updateStatus(message)
self.parent.h5_filename = fname
#self.updateStatus(message)
self.parent.hdf_filename_loaded = 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)
#print("common path in loadFile ============>", self.common_path)
if _start == 0:
_filename_wgt_str = str(fname).replace(self.common_path, "")
if _filename_wgt_str:
@@ -617,110 +481,72 @@ class HDF5GroupBox(QGroupBox):
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)
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)
_current = str(self.filename) if self.filename is not None else None
_recent_files = [_current] if _current is not None else []
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)))
#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

View File

@@ -1,11 +1,10 @@
""" 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)
from qtpy.QtCore import 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):

18460
pyrcc5/qrc_resources.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -4,12 +4,7 @@ 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
from qtpy.QtCore import QFile, QTemporaryDir
class ReadJSON(object):
""" Reads three json configuration files.
@@ -23,7 +18,7 @@ class ReadJSON(object):
json_qrc = ["style", "base", self.appname]
parser = argparse.ArgumentParser(description="configuration")
parser.add_argument("-c", "--config", action="store", dest="style")
parser.add_argument("-s", "--style", 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")
@@ -32,7 +27,7 @@ class ReadJSON(object):
temp_file = {}
self.data = {}
#Extract style adn facility config files from qrc_resources
#Extract style and facility config files from qrc_resources
temp_dir = QTemporaryDir()
if temp_dir.isValid():
for dest in json_qrc[0:2]:
@@ -45,6 +40,7 @@ class ReadJSON(object):
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:
@@ -84,15 +80,26 @@ class ReadJSON(object):
try:
with open(temp_file[json_qrc[1]]) as data_file:
print(temp_file[json_qrc[1]])
self.data_facility = json.load(data_file)
for key, val in self.data_facility.items():
self.data[key] = val
if key in self.data.keys():
if hasattr(val, 'items'):
for k, v in val.items():
#print(key, k, v, type(k), type(v))
self.data[key][k] = v
else:
self.data[key] = val
#print(key, val, "////")
else:
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
#Now open user supplied config files
json_file = self.appname + ".json"
if result.user is not None:
if os.path.isfile(result.user):
@@ -114,9 +121,13 @@ class ReadJSON(object):
#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
if hasattr(val, 'items'):
for k, v in val.items():
#print(key, k, v, type(k), type(v))
self.data[key][k] = v
else:
self.data[key] = val
#print(key, val, "////")
else:
self.data[key] = val
except IOError:

View File

@@ -1,34 +1,68 @@
from datetime import datetime
import getpass
import inspect
import os
import time
from qtpy.QtCore import Signal, Slot, Qt
from qtpy.QtWidgets import (QComboBox, QDialog, QFileDialog, QFrame,
QHBoxLayout, QLabel, QLineEdit, QPushButton,
from qtpy.QtCore import 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(".")
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 QSaveHDF(QDialog):
def __init__(self, parent, input_options={'Comment':None}):
super(QSaveHDF, self).__init__(parent)
def __init__(self, parent, input_options={'Comment': None},
from_dialog=False):
super(QSaveHDF, self).__init__()
self.from_dialog = from_dialog
self.filesText = ''
self.fflag = False
widget_width = 220
self.parent = parent
self.user_dict = {}
self.user_dict['Comment'] = None
self.file_name = None
#self.file_name = None
#self.excluded_input = ['Year', 'Month', 'Date']
if 'Time in seconds' in input_options.keys():
time_in_seconds = input_options['Time in seconds']
now = datetime.fromtimestamp(time_in_seconds)
else:
now = datetime.now()
_date = now.strftime("%Y-%m-%d_%H:%M:%S")
_year = now.strftime("%Y")
_month = now.strftime("%m")
_day = now.strftime("%d")
if 'Destination' in input_options.keys():
self.destination = input_options['Destination']
else:
self.destination = (parent.hdf_dest + _year + "/" + _month + "/" +
_day + "/" + parent.appname + "_" + _date +
".h5")
self.destination = parent.elog_dest + " / " + parent.appname
self.appName = parent.appname + " / " + _appname
self.setWindowTitle(self.appName)
self.parent = parent
self.files = []
self.attributes = {}
@@ -36,19 +70,19 @@ class QSaveHDF(QDialog):
self.applicationBox.addWidget(QLabel('Application:'))
self.applicationLabel = QLabel(parent.pymodule)
self.applicationLabel.setObjectName("hdf")
self.applicationLabel.setFixedWidth(widget_width)
self.applicationLabel.setFixedWidth(widget_width)
self.user_dict['Application'] = self.applicationLabel.text()
self.applicationBox.addWidget(self.applicationLabel)
self.applicationBox.setStretch(1,1)
self.applicationBox.setStretch(1, 1)
self.layout = QVBoxLayout(self)
self.layout.addLayout(self.applicationBox)
authorBox = QHBoxLayout()
authorBox.addWidget(QLabel('Author: '))
self.author = QLineEdit()
authorBox.addWidget(QLabel('User: '))
self.author = QLabel()
self.author.setObjectName('hdf')
self.author.setFixedWidth(widget_width)
self.author.setFixedWidth(widget_width)
self.author.setAlignment(Qt.AlignCenter)
self.author.setText(getpass.getuser())
self.user_dict['Author'] = self.author.text()
@@ -56,80 +90,94 @@ class QSaveHDF(QDialog):
authorBox.addWidget(self.author)
self.layout.addLayout(authorBox)
dateBox = QHBoxLayout()
dateBox.addWidget(QLabel('Date: '))
self.date = QLabel()
self.date.setObjectName('hdf')
self.date.setFixedWidth(widget_width)
self.date.setAlignment(Qt.AlignCenter)
self.date.setText(_date)
self.user_dict['Date'] = self.date.text()
dateBox.addWidget(self.date)
self.layout.addLayout(dateBox)
qframe = QFrame()
qframe.setFrameShape(QFrame.HLine)
qframe.setFrameShadow(QFrame.Sunken)
self.layout.addWidget(qframe)
i=0
i = 0
self.wgt_dict = {}
self.wgt_list = [None] * len(input_options)
self.wgt_list = [None] * len(input_options)
for key, value in input_options.items():
if key=='Comment':
if key == 'Comment':
self.user_dict['Comment'] = value
continue
hbox = QHBoxLayout()
if key in ['Destination', 'Time in seconds']:
continue
#if key in self.excluded_input:
# 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.wgt_list[i].addItems(value)
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].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])
hbox.addWidget(self.wgt_list[i])
i += 1
self.layout.addLayout(hbox)
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)
qlFile = QLabel('File destination:')
qlFile.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
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.filesE.setText(self.destination)
self.attachFile = None
if self.attachFile is not None:
_attachFile = []
if isinstance(self.attachFile, str):
_attachFile.append(self.attachFile)
elif isinstance(self.attachFile, list):
elif isinstance(self.attachFile, list):
_attachFile = self.attachFile
for i in range(0, len(_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.filesText += str(_attach_base)
self.filesE.setText(self.filesText)
self.fflag = True
openCloseVBox = QHBoxLayout()
openBtn = QPushButton('Select')
openBtn.setObjectName('hdflight')
@@ -149,7 +197,7 @@ class QSaveHDF(QDialog):
self.layout.addLayout(fileBox)
self.layout.addWidget(self.filesE)
btnLayout = QHBoxLayout()
okBtn = QPushButton('Save to HDF')
okBtn.setAutoDefault(False)
@@ -168,69 +216,59 @@ class QSaveHDF(QDialog):
self.layout.addWidget(self.messagelbl)
self.layout.addLayout(btnLayout)
self.show()
self.exec()
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():
self.user_dict['Application'] = self.applicationLabel.text()
self.user_dict['User'] = 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()
self.destination = self.user_dict['Destination']
for key in self.wgt_dict:
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.parent.hdf_filename = self.user_dict['Destination']
self.parent.save_to_hdf(from_dialog=self.from_dialog)
self.close()
def clearFiles(self):
def clearFiles(self):
self.attachFile = []
self.filesE.clear()
self.files = []
self.filesText = ''
self.file_name =''
#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)")
filesLocal = qFileDialog.getSaveFileName(
self, 'Save As', self.destination,
"HDF5 files (*.hdf *.h5 *.hdf5 *.he5)")[0]
if filesLocal:
self.clearFiles()
self.filesE.setText(filesLocal)

View File

@@ -1,45 +1,40 @@
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
import os
from qtpy.QtCore import QTimer
from qtpy.QtWidgets import (QApplication, QCheckBox, QDialog, QHBoxLayout,
QPushButton, QVBoxLayout, QWidget)
from pyqtacc.bdbase.enumkind import MsgSeverity
_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',
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)
#print(self.parent.appname)
self.layout = QVBoxLayout(self)
#elem1 = title + "_EntireWindow"
#elem2 = title + "_CentralWidget"
elem1 = "EntireWindow"
#elem1 = "EntireWindow"
elem2 = "CentralWidget"
#self.checkText = [elem1, elem2] + \
self.checkText = [elem1] + \
self.checkText = [elem2] + \
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.checkBoxes[i].setObjectName(str(i-1))
# (i-len(self.checkText))) #(i-1)) #(i-2)
self.layout.addWidget(self.checkBoxes[i])
btnLayout = QHBoxLayout()
@@ -50,39 +45,30 @@ class QScreenshot(QDialog):
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])
#top_level_widgets = QApplication.allWidgets()
self.show()
def ok(self):
self.close()
self.parent.update() # not really required
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
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
@@ -108,44 +94,49 @@ class QScreenshot(QDialog):
maxII = maxI[i]
count = 0
print(self.checkBoxes)
print(self.screenshot_items)
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:
if n == -2:
qss = QApplication.screens()
qs = qss[len(qss)-1]
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):
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):
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.ERROR, _pymodule, _line(),
"Failed to save image to:\nfile='{0}'".format(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)
self.parent.show_log_message(
MsgSeverity.INFO, _pymodule, _line(),
"Screenshot saved to:\nfile='{0}'".format(name))
self.parent.statusbar.showMessage(
"Screenshot saved to: {0}".format(name))
count = count + 1
QApplication.processEvents()

View File

@@ -3,9 +3,9 @@ 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,
from qtpy.QtCore import Qt
from qtpy.QtWidgets import (QComboBox, QDialog, QFileDialog, QHBoxLayout,
QLabel, QLineEdit, QPushButton, QTextEdit,
QVBoxLayout)
import elog # https://github.com/paulscherrerinstitute/py_elog
@@ -27,70 +27,75 @@ def _line():
return inspect.currentframe().f_back.f_lineno
class QSendToELOG(QDialog):
""" Grapghical interface to elog
""" Graphical 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)
def __init__(self, parent, logbook=None, categoryIdx=0, domainIdx=0,
systemIdx=0, sectionIdx=0, title=None, message=None,
attachFile=None, destination_folder=None):
#super(QSendToELOG, self).__init__(parent)
super().__init__()
self.files_text = ''
self.fflag = False
self.destination = parent.elog_dest + " / " + parent.appname
self.window_title = parent.appname + ": " + _appname
self.parent = parent
if destination_folder is None:
self.destination = self.parent.elog_dest + " / " + self.parent.appname
else:
self.destination = destination_folder
self.window_title = self.parent.appname + ": " + _appname
self.pymodule = _pymodule
self.setWindowTitle(self.window_title)
elog_books = list(parent.settings.data["ElogBooks"])
elog_books = list(self.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)
idx = elog_books.index(logbook)
except Exception:
mess = "Index not found for logbook {0}".format(logbook)
self.parent.show_log_message(MsgSeverity.WARN, self.pymodule,
_line(), mess)
_line(), mess)
else:
try:
idx = elog_books.index(self.parent.settings.data["Elog"]["book"])
except:
idx = elog_books.index(self.parent.settings.data["Elog"][
"book"])
except Exception:
logbook = self.parent.settings.data["Elog"]["book"]
mess = "Index not found for logbook {0}".format(_logbook)
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")
_line(), mess)
category_str = list(parent.settings.data["Elog"]['category'])
self.elog_items.setCurrentIndex(idx)
self.elog_items.currentIndexChanged.emit(idx)
self.elog_items.setObjectName("Elog")
category_str = list(self.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.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'])
domain_str = list(self.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.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.elog_section = list(self.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.setObjectName("Elog")
self.section_items.addItems(self.elog_section[domainIdx])
self.section.addWidget(self.section_items)
self.section_items.setCurrentIndex(sectionIdx)
@@ -98,27 +103,28 @@ class QSendToELOG(QDialog):
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_items.setObjectName("Elog")
self.system_items.addItems(
list(self.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
title = self.parent.appname
self.titleline.setText(str(title))
self.titleline.setFixedWidth(300)
self.titleline.setAlignment(Qt.AlignCenter)
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 = QLabel(self.parent.pymodule)
self.applicationlabel.setObjectName("Elog")
# self.applicationbox.addStretch()
self.applicationbox.addWidget(self.applicationlabel)
@@ -131,11 +137,11 @@ class QSendToELOG(QDialog):
authorbox.addWidget(QLabel('Author: '))
self.author = QLineEdit()
self.author.setObjectName('Elog')
self.author.setFixedWidth(195)
self.author.setFixedWidth(195)
self.author.setStatusTip('elog')
self.author.setText(getpass.getuser())
authorbox.addWidget(self.author)
self.files = []
self.attributes = {}
@@ -153,7 +159,7 @@ class QSendToELOG(QDialog):
self.layout.addWidget(report)
self.message = QTextEdit(message)
self.layout.addWidget(self.message)
filebox = QHBoxLayout()
qlfile = QLabel('Attach:')
qlfile.setAlignment(Qt.AlignTop)
@@ -165,21 +171,21 @@ class QSendToELOG(QDialog):
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):
elif isinstance(self.attachFile, list):
_attachFile = self.attachFile
for i, file in enumerate(_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.files_text += str(_attach_base)
self.filesE.setText(self.files_text)
self.fflag = True
filebox.addWidget(self.filesE)
openCloseVBox = QVBoxLayout()
@@ -192,7 +198,7 @@ class QSendToELOG(QDialog):
closeBtn.setAutoDefault(False)
closeBtn.clicked.connect(self.clearFiles)
openCloseVBox.addWidget(closeBtn)
filebox.addLayout(openCloseVBox)
self.layout.addLayout(filebox)
@@ -211,37 +217,20 @@ class QSendToELOG(QDialog):
self.layout.addWidget(self.messagelbl)
self.layout.addLayout(btnLayout)
self.setMinimumWidth(440)
self.exec()
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):
def on_elog_change(self, elog_change_val):
if "test" in self.elog_items.currentText():
_bgcolor = "QComboBox {background: plum; color : black;}"
else:
_bgcolor = "QComboBox {background: lightblue; color : black;}"
_bgcolor = "QComboBox {background: lightblue; color : black;}"
self.elog_items.setStyleSheet(_bgcolor)
def on_domain_change(self, i):
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:
@@ -269,26 +258,27 @@ class QSendToELOG(QDialog):
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):
elif isinstance(self.attachFile, list):
_attachFile = self.attachFile
for i in range(0, len(_attachFile)):
for i in range(0, len(_attachFile)):
if "/tmp" in _attachFile[i]:
self.files.append(str(_attachFile[i])) # self.files_text)
self.files.append(str(_attachFile[i]))
elif "/afs/psi.ch" in _attachFile[i]:
self.files.append(str(_attachFile[i]))
elif "/sf/data/" in _attachFile[i]:
self.files.append(str(_attachFile[i]))
else:
self.files.append(self.destination + str(_attachFile[i])) # self.files_text)
self.files.append(self.destination + str(_attachFile[i]))
url = self.parent.settings.data["ElogBooks"][el]["url"]
self.logbook = elog.open(url, user='robot', password='robot')
print("send to elog: ", url)
@@ -296,18 +286,22 @@ class QSendToELOG(QDialog):
try:
if self.files:
self.logbook.post(message, attributes=self.attributes,
attachments=self.files)
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.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))
for file in self.files:
if os.path.exists(file):
os.remove(file)
self.close()
def clearFiles(self):
self.attachFile = []
@@ -319,15 +313,17 @@ class QSendToELOG(QDialog):
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);;" +
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)
flocal = qFileDialog.getOpenFileNames(
self, 'Open File', self.destination, extensions)[0]
if not flocal:
return
self.files.append(flocal[0])
if (self.fflag == True):
if self.fflag:
self.files_text += '\n'
self.files_text += str(flocal[0].split('/')[-1])
self.fflag = True
@@ -336,15 +332,15 @@ class QSendToELOG(QDialog):
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)
_line(), mess)
else:
mess += ".\n" + elog_message
mess += ".\n" + elog_message
self.parent.show_log_message(MsgSeverity.WARN, self.pymodule,
_line(), mess)
_line(), mess)
self.parent.statusbar.showMessage(mess)