/
VolcanoByte
/
vbNotes
Обзор
Документация
Войти
/
VolcanoByte
/
vbNotes
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
sources/uUtils.py
159 строк
5 KB
Eugene Gavrilyuk
mass changes
03 янв 2026, 18:03
03 янв 2026, 18:03
04d697b
Код
Авторство
О чём код?
""" Различные вспомогательные функции """ import os import datetime as dt from zipfile import ZipFile from pygments.formatters import HtmlFormatter import markdown as md from PyQt6.QtWidgets import (QMessageBox, QFileDialog, QDialog, QLabel, QVBoxLayout) from PyQt6.QtGui import QMovie from PyQt6.QtCore import Qt from uConsts import AppConsts, FILE_FILTERS, ZIP_LEVEL, ZIP_COMPRESSION from uGlobal import MessageLanguageConsts as mlc class PopUp(QDialog): def __init__(self, parent): super().__init__(parent) self.setWindowFlag(Qt.WindowType.FramelessWindowHint) self.resize(406, 216) self.setLayout(QVBoxLayout()) self.label = QLabel(self) self.layout().addWidget(self.label) # Интегрировать QMovie к метке и инициировать GIF self.movie = QMovie("sync.gif") self.label.setMovie(self.movie) self.movie.start() def getDict(d: dict, key: str, default): """Функция нужна для того, что бы быть уверенным, что из словаря получим значение корректного типа""" _res = d.get(key, default) if _res is None or not isinstance(_res, default): return default else: return _res def getBool(value) -> bool | None: """Функция для QSettings""" if isinstance(value, str): return value == 'true' else: return value def getInt(value) -> int | None: """Функция для QSettings""" if type(value) is str: return int(value) else: return value def getFloat(value) -> float | None: """Функция для QSettings""" if type(value) is str: return float(value) else: return value def timestamp2FileName(ts: float, syncId: str) -> str | None: """Преобразование timestamp в имя файла-бэкапа, типа 2025-12-20_16-28.Johnny_notes""" if isinstance(ts, float) and ts: _dt = dt.datetime.fromtimestamp(ts) return dt.datetime.strftime(_dt, f"%Y-%m-%d_%H-%M.{syncId}_" f"{AppConsts.CollectionKind}") def zipDB(dbfilename: str, archive: str): """Упаковывает базу в архив. Возвращает True, если архив создан.""" name = os.path.basename(dbfilename) with ZipFile(archive, 'w') as zipFile: zipFile.write(dbfilename, name, compress_type=ZIP_COMPRESSION, compresslevel=ZIP_LEVEL) def unzipDB(dbfilename: str, archive: str): """Распаковывает файлы из архива в указанную папку. Возвращает True, если папка существует.""" with ZipFile(archive, 'r') as zipFile: zipFile.extractall(dbfilename) def makeMarkdown(style: str, text: str) -> str: formatter = HtmlFormatter(style=style) _css = formatter.get_style_defs() _md = md.markdown(text, extensions=[ 'extra', 'toc', 'fenced_code', 'codehilite' ]) _res = (('<html><head><style>' + _css + '</style></head><body>') + _md + '</body></html>') return _res def errorDlg(parent, message: str, caption: str = mlc.error): msg = QMessageBox(parent) msg.setWindowTitle(caption) msg.setText(message) msg.setIcon(QMessageBox.Icon.Critical) msg.exec() def infoDlg(parent, message: str, caption: str = mlc.information): msg = QMessageBox(parent) msg.setWindowTitle(caption) msg.setText(message) msg.setIcon(QMessageBox.Icon.Information) msg.exec() def confirmOkCancelDlg(parent, message: str, caption: str = mlc.confirm): msg = QMessageBox(parent) msg.setWindowTitle(caption) msg.setText(message) msg.setIcon(QMessageBox.Icon.Question) msg.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel) msg.setDefaultButton(QMessageBox.StandardButton.Ok) return msg.exec() def confirmYesNoCancelDlg(parent, message: str, caption: str = mlc.confirm): msg = QMessageBox(parent) msg.setWindowTitle(caption) msg.setText(message) msg.setIcon(QMessageBox.Icon.Question) msg.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No | QMessageBox.StandardButton.Cancel) msg.setDefaultButton(QMessageBox.StandardButton.Ok) return msg.exec() def getFileNameDialog(caption: str, accept: QFileDialog.AcceptMode, mode: QFileDialog.FileMode) -> str | None: """Подготовка диалога и выбор файла""" dialog = QFileDialog() dialog.setWindowTitle(caption) dialog.setNameFilters(FILE_FILTERS) dialog.selectNameFilter(FILE_FILTERS[0]) dialog.setAcceptMode(accept) dialog.setFileMode(mode) ok = dialog.exec() if ok: return dialog.selectedFiles()[0]