Skip to content

Commit

Permalink
[MLV] Save last used path
Browse files Browse the repository at this point in the history
  • Loading branch information
tmolitor-stud-tu committed Jan 9, 2024
1 parent d29c81d commit edcfad9
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 28 deletions.
2 changes: 2 additions & 0 deletions src/LogViewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from PyQt5 import QtWidgets

from shared.utils import Paths
from LogViewer.storage import SettingsSingleton
from LogViewer.ui import MainWindow

def sigint_handler(sig, frame):
Expand Down Expand Up @@ -42,6 +43,7 @@ def sigint_handler(sig, frame):
main_window = MainWindow()
main_window.show()
if args.file != None:
SettingsSingleton()["lastDir"] = os.path.dirname(os.path.abspath(args.file))
main_window.openLogFile(args.file)
application.exec_()
except:
Expand Down
3 changes: 2 additions & 1 deletion src/LogViewer/data/conf/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
"font": "Consolas,10,-1,5,50,0,0,0,0,0,Regular",
"uiStyle": "default",
"usePythonFilter": true,
"usePythonSearch": true
"usePythonSearch": true,
"lastPath": ""
},
"formatter": {
"default": "def formatter(e, **g):\n\tglobals().update(g)\n\treturn \"%s %s\" % (e[\"timestamp\"], e[\"message\"])",
Expand Down
22 changes: 15 additions & 7 deletions src/LogViewer/storage/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,16 +79,24 @@ def loadState(self, widget):
if self._widgetName(widget) in self.data["state"]:
widget.restoreState(QtCore.QByteArray.fromBase64(bytes(self.data["state"][self._widgetName(widget)], "UTF-8")))

def getFontParameterList(self, qFont):
return qFont.toString()

def getQFont(self, fontString = None):
if fontString == None:
fontString = self.data["misc"]["font"]
def setQFont(self, font, miscKey="font"):
self[miscKey] = font.toString()
self._store()

def getQFont(self, miscKey="font"):
font = QtGui.QFont()
font.fromString(fontString)
font.fromString(self[miscKey])
return font

def getLastPath(self):
if self["lastPath"] == None or len(self["lastPath"]) == 0:
logger.debug("Returning default last dir: %s" % Paths.get_user_documents_dir())
return Paths.get_user_documents_dir()
return self["lastPath"]

def setLastPath(self, lastPath):
self["lastPath"] = lastPath

def clearAllFormatters(self):
self.data["formatter"].clear()

Expand Down
9 changes: 6 additions & 3 deletions src/LogViewer/ui/main_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,9 @@ def toggleUiItems(self):

def export(self):
if self.rawlog:
file, check = QtWidgets.QFileDialog.getSaveFileName(None, "Choose where to save this text logfile", "", "Compressed logfile (*.log.gz)(*.log.gz);;Logfile (*.log)(*.log);;All files (*)")
file, check = QtWidgets.QFileDialog.getSaveFileName(None, "Choose where to save this text logfile", SettingsSingleton().getLastPath(), "Compressed logfile (*.log.gz)(*.log.gz);;Logfile (*.log)(*.log);;All files (*)")
if check:
SettingsSingleton().setLastPath(os.path.dirname(os.path.abspath(file)))
status = self.rawlog.export_file(file, custom_store_callback = lambda entry: entry["data"] if not entry["uiItem"].isHidden() else None)
if status:
self.statusbar.showDynamicText(str("Done ✓ | Log export was successful"))
Expand All @@ -134,8 +135,9 @@ def export(self):

def save(self):
if self.rawlog:
file, check = QtWidgets.QFileDialog.getSaveFileName(None, "Choose where to save this rawlog logfile", "", "Compressed Monal rawlog (*.rawlog.gz)(*.rawlog.gz);;Monal rawlog (*.rawlog)(*.rawlog);;All files (*)")
file, check = QtWidgets.QFileDialog.getSaveFileName(None, "Choose where to save this rawlog logfile", SettingsSingleton().getLastPath(), "Compressed Monal rawlog (*.rawlog.gz)(*.rawlog.gz);;Monal rawlog (*.rawlog)(*.rawlog);;All files (*)")
if check:
SettingsSingleton().setLastPath(os.path.dirname(os.path.abspath(file)))
status = self.rawlog.store_file(file, custom_store_callback = lambda entry: entry["data"] if not entry["uiItem"].isHidden() else None)
if status:
self.statusbar.showDynamicText(str("Done ✓ | Rawlog saved successfully"))
Expand All @@ -153,8 +155,9 @@ def setCompleter(self, combobox):

@catch_exceptions(logger=logger)
def openFileBrowser(self, *args):
file, check = QtWidgets.QFileDialog.getOpenFileName(None, "Open rawlog logfile", "", "Monal rawlog (*.rawlog.gz *.rawlog)(*.rawlog.gz *.rawlog);;All files (*)")
file, check = QtWidgets.QFileDialog.getOpenFileName(None, "Open rawlog logfile", SettingsSingleton().getLastPath(), "Monal rawlog (*.rawlog.gz *.rawlog)(*.rawlog.gz *.rawlog);;All files (*)")
if check:
SettingsSingleton().setLastPath(os.path.dirname(os.path.abspath(file)))
self.openLogFile(file)

def openLogFile(self, file):
Expand Down
48 changes: 32 additions & 16 deletions src/LogViewer/ui/preferences_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,23 +38,29 @@ def accept(self, *args):
data = [self.history[comboboxName].item(item).text() for item in range(self.history[comboboxName].count())]
SettingsSingleton().setComboboxHistoryByName(comboboxName, data)
for miscName in self.misc:
SettingsSingleton()[miscName] = self._getMiscWidgetValue(self.misc[miscName])
SettingsSingleton()[miscName] = self._getMiscWidgetValue(miscName)
SettingsSingleton().clearAllFormatters()
for formatterNameLineEdit in self.formatter:
SettingsSingleton().setFormatter(formatterNameLineEdit.text(), self.formatter[formatterNameLineEdit].toPlainText())
super().accept()

def _getMiscWidgetValue(self, widget):
def _getMiscWidgetValue(self, miscName):
widget = self.misc[miscName]
if isinstance(widget, QtWidgets.QSpinBox):
return widget.value()
if isinstance(widget, QtWidgets.QLineEdit):
elif isinstance(widget, QtWidgets.QLineEdit):
return widget.text()
if isinstance(widget, QtWidgets.QComboBox):
elif isinstance(widget, QtWidgets.QComboBox):
return widget.currentText()
if isinstance(widget, QtWidgets.QCheckBox):
elif isinstance(widget, QtWidgets.QCheckBox):
return widget.isChecked()
if isinstance(widget, QtWidgets.QPushButton):
return SettingsSingleton().getFontParameterList(self.font)
elif isinstance(widget, QtWidgets.QPushButton):
if miscName == "font":
return self.font.toString()
else:
return self.lastPath
else:
raise RuntimeError("Unknown misc widget type: %s" % str(widget))

def _createUiTab_color(self):
colorNames = SettingsSingleton().getColorNames()
Expand Down Expand Up @@ -103,14 +109,14 @@ def _delColor(self, colorName, index, button):
button.setText("Add")

def _createUiTab_misc(self):
miscSection = QtWidgets.QFormLayout()
for miscName, miscValue in SettingsSingleton().items():
miscSection = QtWidgets.QHBoxLayout()
miscSection.addWidget(QtWidgets.QLabel(miscName, self))
widget = self._createMiscWidget(miscValue, miscName)
miscSection.addWidget(widget)
self.uiGridLayout_miscTab.setAlignment(QtCore.Qt.AlignTop)
self.uiGridLayout_miscTab.addLayout(miscSection)
self.misc[miscName] = widget
self.misc[miscName] = self._createMiscWidget(miscValue, miscName)
miscSection.addRow(QtWidgets.QLabel(miscName, self), self.misc[miscName])
miscSection.setFieldGrowthPolicy(QtWidgets.QFormLayout.AllNonFixedFieldsGrow)
miscSection.setLabelAlignment(QtCore.Qt.AlignRight)
self.uiGridLayout_miscTab.setAlignment(QtCore.Qt.AlignTop)
self.uiGridLayout_miscTab.addLayout(miscSection)

def _createMiscWidget(self, value, miscName):
if type(value) == int:
Expand All @@ -133,14 +139,24 @@ def _createMiscWidget(self, value, miscName):
self.currentFormatter = widget
elif miscName == "font":
widget = QtWidgets.QPushButton()
self.font = SettingsSingleton().getQFont(value)
self.font = SettingsSingleton().getQFont()
widget.setText("%s, %s" % (self.font.family(), str(self.font.pointSize())))
widget.setFont(self.font)
widget.clicked.connect(functools.partial(self._changeFont, widget))
elif miscName == "uiStyle":
widget = QtWidgets.QComboBox()
widget.addItems(StyleManager.getAvailableStyles())
widget.setCurrentText(SettingsSingleton()["uiStyle"])
widget.setCurrentText(value)
elif miscName == "lastPath":
self.lastPath = SettingsSingleton().getLastPath()
widget = QtWidgets.QPushButton()
widget.setText(self.lastPath)
def openLastDirDialog():
dirname = QtWidgets.QFileDialog.getExistingDirectory(self, "MLV | Choose default directory", self.lastPath)
if dirname != None and dirname != "":
self.lastPath = dirname
widget.setText(dirname)
widget.clicked.connect(openLastDirDialog)
else:
widget = QtWidgets.QLineEdit()
widget.setText(value)
Expand Down
14 changes: 13 additions & 1 deletion src/shared/utils/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,44 @@
logger = logging.getLogger(__name__)

class Paths:
@staticmethod
def set_personality(file):
basename = os.path.splitext(os.path.basename(file))[0]
Paths.PLATFORM_ARGS = (basename, "monal-im")
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
Paths.BASEDIR = os.path.join(sys._MEIPASS, basename)
else:
Paths.BASEDIR = os.path.join(os.path.dirname(os.path.abspath(file)), basename)


@staticmethod
def get_basedir_path():
return os.path.abspath(Paths.BASEDIR)

@staticmethod
def get_ui_filepath(filename):
return os.path.abspath(os.path.join(Paths.get_basedir_path(), "ui", filename))

@staticmethod
def get_art_filepath(filename):
return os.path.abspath(os.path.join(Paths.get_basedir_path(), "data", "art", filename))

@staticmethod
def get_default_conf_filepath(filename):
return os.path.abspath(os.path.join(Paths.get_basedir_path(), "data", "conf", filename))

@staticmethod
def get_user_documents_dir():
return os.path.abspath(platformdirs.user_documents_dir())

@staticmethod
def get_conf_filepath(filename):
return os.path.abspath(os.path.join(Paths.user_data_dir(), filename))

@staticmethod
def user_data_dir():
return os.path.abspath(platformdirs.user_data_dir(*Paths.PLATFORM_ARGS, roaming=True))

@staticmethod
def user_log_dir():
return os.path.abspath(platformdirs.user_log_dir(*Paths.PLATFORM_ARGS))

Expand Down

0 comments on commit edcfad9

Please sign in to comment.