Files
bdbase/savehdf.py
2024-07-03 16:19:24 +02:00

274 lines
9.1 KiB
Python

from datetime import datetime
import getpass
import inspect
import os
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},
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.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.appName = parent.appname + " / " + _appname
self.setWindowTitle(self.appName)
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('User: '))
self.author = QLabel()
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)
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
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
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')
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].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('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):
_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.exec()
def get_data(self):
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):
self.get_data()
self.parent.hdf_user_dict = self.user_dict
self.parent.hdf_filename = self.user_dict['Destination']
self.parent.save_to_hdf(from_dialog=self.from_dialog)
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 = qFileDialog.getSaveFileName(
self, 'Save As', self.destination,
"HDF5 files (*.hdf *.h5 *.hdf5 *.he5)")[0]
if filesLocal:
self.clearFiles()
self.filesE.setText(filesLocal)