mirror of
https://github.com/LorenEteval/Furious.git
synced 2026-09-22 15:04:34 +03:00
317 lines
9.2 KiB
Python
317 lines
9.2 KiB
Python
# Copyright (C) 2024–present Loren Eteval & contributors <loren.eteval@proton.me>
|
||
#
|
||
# This file is part of Furious.
|
||
#
|
||
# This program is free software: you can redistribute it and/or modify
|
||
# it under the terms of the GNU General Public License as published by
|
||
# the Free Software Foundation, either version 3 of the License, or
|
||
# (at your option) any later version.
|
||
#
|
||
# This program is distributed in the hope that it will be useful,
|
||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
# GNU General Public License for more details.
|
||
#
|
||
# You should have received a copy of the GNU General Public License
|
||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||
|
||
"""Provide Qt support for qt GUI."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from Furious.Frozenlib import *
|
||
from Furious.Qt.DynamicTranslate import gettext as _
|
||
|
||
from PySide6 import QtCore
|
||
from PySide6.QtGui import *
|
||
|
||
import logging
|
||
import functools
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
__all__ = [
|
||
'bootstrapIcon',
|
||
'bootstrapIconMask',
|
||
'bootstrapIconWithOpacity',
|
||
'bootstrapIconWhite',
|
||
'AppQIcon',
|
||
'AppQAction',
|
||
'AppQActionGroup',
|
||
'AppQSeperator',
|
||
]
|
||
|
||
|
||
class AppQIcon(QIcon):
|
||
"""Represent app q icon."""
|
||
|
||
def __init__(self, iconFileName: str):
|
||
"""Initialize the AppQIcon."""
|
||
super().__init__(iconFileName)
|
||
|
||
self.iconFileName = iconFileName
|
||
|
||
|
||
def iconFn(prefix, name):
|
||
"""Return the icon fn value used by the application."""
|
||
if name.startswith('rocket-takeoff'):
|
||
# Colorful. Use default
|
||
return AppQIcon(f':/Icons/bootstrap/{name}')
|
||
else:
|
||
return AppQIcon(f':/Icons/{prefix}/{name}')
|
||
|
||
|
||
bootstrapIcon = functools.partial(iconFn, 'bootstrap')
|
||
bootstrapIconWhite = functools.partial(iconFn, 'bootstrap/white')
|
||
|
||
|
||
def setIconAsMask(icon):
|
||
"""Set icon as mask."""
|
||
if hasattr(icon, 'setIsMask'):
|
||
icon.setIsMask(True)
|
||
|
||
return icon
|
||
|
||
|
||
@functools.lru_cache(None)
|
||
def bootstrapIconMask(name):
|
||
"""Return the bootstrap icon mask value used by the application."""
|
||
return setIconAsMask(bootstrapIconWhite(name))
|
||
|
||
|
||
@functools.lru_cache(None)
|
||
def bootstrapIconWithOpacity(name, opacity, isMask=False):
|
||
"""Return the bootstrap icon with opacity value used by the application."""
|
||
sourceIcon = bootstrapIconWhite(name)
|
||
icon = AppQIcon('')
|
||
|
||
for iconSize in (16, 18, 22, 24, 32, 64):
|
||
sourcePixmap = sourceIcon.pixmap(QtCore.QSize(iconSize, iconSize))
|
||
|
||
if sourcePixmap.isNull():
|
||
continue
|
||
|
||
pixmap = QPixmap(sourcePixmap.size())
|
||
pixmap.setDevicePixelRatio(sourcePixmap.devicePixelRatio())
|
||
pixmap.fill(QtCore.Qt.GlobalColor.transparent)
|
||
|
||
painter = QPainter(pixmap)
|
||
painter.setOpacity(opacity)
|
||
painter.drawPixmap(0, 0, sourcePixmap)
|
||
painter.end()
|
||
|
||
icon.addPixmap(pixmap)
|
||
|
||
if icon.isNull():
|
||
return sourceIcon
|
||
|
||
if isMask:
|
||
return setIconAsMask(icon)
|
||
else:
|
||
return icon
|
||
|
||
|
||
class AppQAction(Mixins.QTranslatable, Mixins.ThemeAware, QAction):
|
||
"""Handle the app q action."""
|
||
|
||
def __init__(
|
||
self,
|
||
text,
|
||
icon=None,
|
||
menu=None,
|
||
useSetMenu=True,
|
||
useActionGroup=True,
|
||
checkable=False,
|
||
checked=False,
|
||
statusTip=None,
|
||
callback=None,
|
||
shortcut=None,
|
||
isTrayAction=False,
|
||
**kwargs,
|
||
):
|
||
"""Initialize the AppQAction."""
|
||
super().__init__(text=text, **kwargs)
|
||
|
||
# Do not use QProtection because it's been managed somewhere else!!!
|
||
self.useQProtection = False
|
||
self.iconFileName = ''
|
||
self.isTrayAction = isTrayAction
|
||
|
||
self.setShortcutVisibleInContextMenu(True)
|
||
|
||
if icon is not None:
|
||
self.setIcon(icon)
|
||
|
||
if menu is not None:
|
||
# Create reference
|
||
self._menu = menu
|
||
|
||
# Some old version PySide6 does not have setMenu method
|
||
# for QAction. Protect it. Currently only used in SystemTrayIcon
|
||
if hasattr(self, 'setMenu') and useSetMenu:
|
||
self.setMenu(menu)
|
||
|
||
if useActionGroup:
|
||
# Create reference
|
||
self._actionGroup = AppQActionGroup(self, *menu.actions())
|
||
|
||
self.setActionGroup(self._actionGroup)
|
||
else:
|
||
self._actionGroup = None
|
||
else:
|
||
self._menu = None
|
||
self._actionGroup = None
|
||
|
||
self.setCheckable(checkable)
|
||
self.setChecked(checked)
|
||
|
||
if statusTip is not None:
|
||
self.setStatusTip(statusTip)
|
||
|
||
# Handy callback to be able to link with lambda
|
||
self.callback = callback
|
||
|
||
if shortcut is not None:
|
||
self.setShortcut(shortcut)
|
||
|
||
@QtCore.Slot(bool)
|
||
def triggerSignal(paramChecked):
|
||
"""Handle trigger signal for the app q action."""
|
||
logger.info(f'action is \'{self.textEnglish}\'. Checked is {paramChecked}')
|
||
|
||
if callable(self.callback):
|
||
self.callback()
|
||
|
||
self.triggeredCallback(paramChecked)
|
||
|
||
self.triggered.connect(triggerSignal)
|
||
|
||
def addAction(self, action):
|
||
"""Add action."""
|
||
if self._menu is not None:
|
||
self._menu.addAction(action)
|
||
|
||
if self._actionGroup is not None:
|
||
self._actionGroup.addAction(action)
|
||
|
||
def removeAction(self, action):
|
||
"""Remove action."""
|
||
if self._menu is not None:
|
||
self._menu.removeAction(action)
|
||
|
||
if self._actionGroup is not None:
|
||
self._actionGroup.removeAction(action)
|
||
|
||
@property
|
||
def textEnglish(self):
|
||
"""Return the text english value."""
|
||
return _(self.text(), 'EN')
|
||
|
||
def __str__(self):
|
||
"""Return the display text for the app q action."""
|
||
return self.__class__.__name__
|
||
|
||
def textCompare(self, compare):
|
||
"""Return the text compare value used by the app q action."""
|
||
return self.textEnglish == compare
|
||
|
||
@staticmethod
|
||
@functools.lru_cache(None)
|
||
def getIconFileName(fileName):
|
||
"""Return icon file name."""
|
||
try:
|
||
return fileName.split('/')[-1]
|
||
except Exception:
|
||
# Any non-exit exceptions
|
||
|
||
return ''
|
||
|
||
def setIconByTheme(self, theme):
|
||
"""Set icon by theme."""
|
||
if not self.iconFileName:
|
||
return
|
||
|
||
if AppSettings.isStateON_('DarkMode'):
|
||
# Custom dark mode
|
||
super().setIcon(bootstrapIconWhite(self.iconFileName))
|
||
|
||
return
|
||
|
||
if theme == 'Dark':
|
||
if PLATFORM == 'Windows':
|
||
# Windows
|
||
if versionToValue(PYSIDE6_VERSION) < versionToValue('6.7.0'):
|
||
# PySide6 < 6.7.0 has no system theme handling on Windows.
|
||
# Always use black icon
|
||
super().setIcon(bootstrapIcon(self.iconFileName))
|
||
else:
|
||
# PySide6 has system theme handling.
|
||
super().setIcon(bootstrapIconWhite(self.iconFileName))
|
||
else:
|
||
if SystemRuntime.ubuntuRelease() == '20.04' and self.isTrayAction:
|
||
# Ubuntu 20.04 system dark theme does not change tray menu color.
|
||
# Make it go black always
|
||
super().setIcon(bootstrapIcon(self.iconFileName))
|
||
else:
|
||
super().setIcon(bootstrapIconWhite(self.iconFileName))
|
||
else:
|
||
super().setIcon(bootstrapIcon(self.iconFileName))
|
||
|
||
def setIcon(self, icon: AppQIcon):
|
||
"""Set icon."""
|
||
self.iconFileName = self.getIconFileName(icon.iconFileName)
|
||
|
||
if not self.iconFileName:
|
||
# Fall back
|
||
super().setIcon(icon)
|
||
else:
|
||
self.setIconByTheme(APP().theme())
|
||
|
||
def themeChangedCallback(self, theme):
|
||
"""Update the app q action for a theme change."""
|
||
self.setIconByTheme(theme)
|
||
|
||
def retranslate(self):
|
||
"""Refresh translated text for the app q action."""
|
||
|
||
def recursiveTranslate(action, memo):
|
||
"""Handle recursive translate for the app q action."""
|
||
if action not in memo and not action.isSeparator() and action.translatable:
|
||
action.setText(_(action.text()))
|
||
action.setStatusTip(_(action.statusTip()))
|
||
|
||
memo[action] = True
|
||
|
||
# Some old version PySide6 does not have menu() method
|
||
# for QAction. Protect it
|
||
if hasattr(action, 'menu'):
|
||
if action.menu() is not None:
|
||
for childAction in action.menu().actions():
|
||
recursiveTranslate(childAction, memo)
|
||
|
||
recursiveTranslate(self, dict())
|
||
|
||
def triggeredCallback(self, checked):
|
||
# Not a mandatory re-implementation in child class
|
||
"""Handle activation of the action."""
|
||
pass
|
||
|
||
|
||
class AppQActionGroup(QActionGroup):
|
||
"""Represent app q action group."""
|
||
|
||
def __init__(self, parent, *actions):
|
||
"""Initialize the AppQActionGroup."""
|
||
super().__init__(parent)
|
||
|
||
for action in actions:
|
||
self.addAction(action)
|
||
|
||
|
||
class AppQSeperator(QAction):
|
||
"""Represent app q seperator."""
|
||
|
||
def __init__(self):
|
||
"""Initialize the AppQSeperator."""
|
||
super().__init__()
|