mintmenu/usr/lib/linuxmint/mintMenu/plugins/easybuttons.py

524 lines
18 KiB
Python
Raw Normal View History

2020-03-30 16:11:23 +01:00
#!/usr/bin/python3
2009-07-27 11:45:34 +01:00
import os.path
import shutil
2009-07-27 11:45:34 +01:00
import xdg.DesktopEntry
import xdg.Menu
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("MateDesktop", "2.0")
from gi.repository import Gtk, Gdk, GdkPixbuf, GLib, GObject, Pango, MateDesktop
from plugins.execute import Execute
from plugins.filemonitor import monitor as filemonitor
2009-07-27 11:45:34 +01:00
2013-03-04 16:50:14 +00:00
class IconManager(GObject.GObject):
2009-07-27 11:45:34 +01:00
2010-09-13 15:54:23 +01:00
__gsignals__ = {
"changed" : (GObject.SignalFlags.RUN_LAST, None, ())
}
2010-09-13 15:54:23 +01:00
def __init__(self):
GObject.GObject.__init__(self)
self.icons = {}
2010-09-13 15:54:23 +01:00
self.count = 0
# Some apps don't put a default icon in the default theme folder, so we will search all themes
# def createTheme(d):
# theme = Gtk.IconTheme()
# theme.set_custom_theme(d)
# return theme
2010-09-13 15:54:23 +01:00
# This takes to much time and there are only a very few applications that use icons from different themes
#self.themes = map( createTheme, [d for d in os.listdir("/usr/share/icons") if os.path.isdir(os.path.join("/usr/share/icons", d))])
2010-09-13 15:54:23 +01:00
self.defaultTheme = Gtk.IconTheme.get_default()
#defaultKdeTheme = createTheme("kde.default")
2010-09-13 15:54:23 +01:00
# Setup and clean up the temp icon dir
configDir = GLib.get_user_config_dir()
self.iconDir = os.path.join(configDir, "mintmenu")
if not os.path.exists(self.iconDir):
os.makedirs(self.iconDir)
contents = os.listdir(self.iconDir)
for fn in contents:
os.remove(os.path.join(self.iconDir, fn))
self.defaultTheme.append_search_path(self.iconDir)
2010-09-13 15:54:23 +01:00
# Themes with the same content as the default them aren't needed
#self.themes = [theme for theme in self.themes if theme.list_icons() != defaultTheme.list_icons()]
2010-09-13 15:54:23 +01:00
#self.themes = [self.defaultTheme, defaultKdeTheme]
self.themes = [self.defaultTheme]
2010-09-13 15:54:23 +01:00
# Listen for changes in the themes
# for theme in self.themes:
# theme.connect("changed", self.themeChanged)
2016-05-21 17:11:36 +01:00
def getIcon(self, iconName, iconSize):
2010-09-13 15:54:23 +01:00
if not iconName:
return None
try:
iconFileName = ""
realIconName = ""
needTempFile = False
#[iconWidth, iconHeight] = self.getIconSize(iconSize)
if iconSize <= 0:
2010-09-13 15:54:23 +01:00
return None
elif os.path.isabs(iconName):
2010-09-13 15:54:23 +01:00
iconFileName = iconName
needTempFile = True
2010-09-13 15:54:23 +01:00
else:
if iconName[-4:] in [".png", ".xpm", ".svg", ".gif"]:
realIconName = iconName[:-4]
else:
realIconName = iconName
if iconFileName and needTempFile and os.path.exists(iconFileName):
tmpIconName = iconFileName.replace("/", "-")
realIconName = tmpIconName[:-4]
if not os.path.exists(os.path.join(self.iconDir, tmpIconName)):
shutil.copyfile(iconFileName, os.path.join(self.iconDir, tmpIconName))
self.defaultTheme.append_search_path(self.iconDir)
image = Gtk.Image.new_from_icon_name(realIconName, Gtk.IconSize.DND)
image.set_pixel_size(iconSize)
return image
except Exception as e:
print("Exception %s: %s" % (e.__class__.__name__, e))
2010-09-13 15:54:23 +01:00
return None
def themeChanged(self, theme):
self.emit("changed")
2010-09-13 15:54:23 +01:00
2013-03-04 16:50:14 +00:00
GObject.type_register(IconManager)
2009-07-27 11:45:34 +01:00
class easyButton(Gtk.Button):
2009-07-27 11:45:34 +01:00
def __init__(self, iconName, iconSize, labels=None, buttonWidth=-1, buttonHeight=-1, ellipsis=True):
GObject.GObject.__init__(self)
self.connections = []
2010-09-13 15:54:23 +01:00
self.iconName = iconName
self.iconSize = iconSize
self.showIcon = True
self.ellipsis = ellipsis
2010-09-13 15:54:23 +01:00
self.set_relief(Gtk.ReliefStyle.NONE)
self.set_size_request(buttonWidth, buttonHeight)
2010-09-13 15:54:23 +01:00
Align1 = Gtk.Alignment.new(0, 0.5, 1.0, 0)
HBox1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
self.labelBox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
2010-09-13 15:54:23 +01:00
self.buttonImage = self.getIcon(self.iconSize)
if not self.buttonImage:
self.buttonImage = Gtk.Image()
self.buttonImage.set_size_request(self.iconSize, self.iconSize)
2010-09-13 15:54:23 +01:00
self.image_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
self.image_box.pack_start(self.buttonImage, False, False, 5)
self.image_box.show_all()
HBox1.pack_start(self.image_box, False, False, 0)
2010-09-13 15:54:23 +01:00
if labels:
for label in labels:
2020-03-30 16:11:23 +01:00
if isinstance(label, str):
self.addLabel(label)
elif isinstance(label, list):
self.addLabel(label[0], label[1])
2010-09-13 15:54:23 +01:00
self.labelBox.show()
HBox1.pack_start(self.labelBox , True, True, 0)
2010-09-13 15:54:23 +01:00
HBox1.show()
Align1.add(HBox1)
2010-09-13 15:54:23 +01:00
Align1.show()
self.add(Align1)
2010-09-13 15:54:23 +01:00
self.connectSelf("destroy", self.onDestroy)
self.connect("released", self.onRelease)
2010-09-13 15:54:23 +01:00
# Reload icons when the theme changed
# self.themeChangedHandlerId = iconManager.connect("changed", self.themeChanged)
2010-09-13 15:54:23 +01:00
def connectSelf(self, event, callback):
self.connections.append(self.connect(event, callback))
2010-09-13 15:54:23 +01:00
def onRelease(self, widget):
widget.get_style_context().set_state(Gtk.StateFlags.NORMAL)
2010-09-13 15:54:23 +01:00
def onDestroy(self, widget):
2010-09-13 15:54:23 +01:00
self.buttonImage.clear()
# iconManager.disconnect(self.themeChangedHandlerId)
2010-09-13 15:54:23 +01:00
for connection in self.connections:
self.disconnect(connection)
2010-09-13 15:54:23 +01:00
del self.connections
def addLabel(self, text, styles = None):
2013-03-04 16:50:14 +00:00
label = Gtk.Label()
2013-03-08 00:50:53 +00:00
if "<b>" in text or "<span" in text:
label.set_markup(text.replace('&', '&amp;')) # don't remove our pango
2010-09-13 15:54:23 +01:00
else:
label.set_text(text)
2010-09-13 15:54:23 +01:00
if styles:
2013-03-04 16:50:14 +00:00
labelStyle = Pango.AttrList()
2010-09-13 15:54:23 +01:00
for attr in styles:
labelStyle.insert(attr)
label.set_attributes(labelStyle)
2010-09-13 15:54:23 +01:00
if self.ellipsis:
label.set_ellipsize(Pango.EllipsizeMode.END)
label.set_alignment(0.0, 1.0)
2016-09-06 15:58:34 +01:00
label.set_max_width_chars(0)
2010-09-13 15:54:23 +01:00
label.show()
self.labelBox.pack_start(label , True, True, 0)
2010-09-13 15:54:23 +01:00
def getIcon(self, iconSize):
2010-09-13 15:54:23 +01:00
if not self.iconName:
return None
icon = iconManager.getIcon(self.iconName, iconSize)
2010-09-13 15:54:23 +01:00
return icon
def setIcon(self, iconName):
2010-09-13 15:54:23 +01:00
self.iconName = iconName
self.iconChanged()
# IconTheme changed, setup new button icons
def themeChanged(self, theme):
self.iconChanged()
2010-09-13 15:54:23 +01:00
def iconChanged(self):
icon = self.getIcon(self.iconSize)
self.buttonImage.destroy()
2010-09-13 15:54:23 +01:00
if icon:
self.buttonImage = icon
self.image_box.pack_start(self.buttonImage, False, False, 5)
self.image_box.show_all()
2010-09-13 15:54:23 +01:00
else:
#[iW, iH] = iconManager.getIconSize(self.iconSize)
self.buttonImage.set_size_request(self.iconSize, self.iconSize )
2010-09-13 15:54:23 +01:00
def setIconSize(self, size):
2010-09-13 15:54:23 +01:00
self.iconSize = size
icon = self.getIcon(self.iconSize)
self.buttonImage.destroy()
2010-09-13 15:54:23 +01:00
if icon:
self.buttonImage = icon
self.image_box.pack_start(self.buttonImage, False, False, 5)
self.image_box.show_all()
2010-09-13 15:54:23 +01:00
elif self.iconSize:
#[iW, iH] = iconManager.getIconSize(self.iconSize)
self.buttonImage.set_size_request(self.iconSize, self.iconSize )
2009-07-27 11:45:34 +01:00
class ApplicationLauncher(easyButton):
2009-07-27 11:45:34 +01:00
def __init__(self, desktopFile, iconSize):
2010-09-13 15:54:23 +01:00
if isinstance(desktopFile, xdg.Menu.MenuEntry):
2010-09-13 15:54:23 +01:00
desktopItem = desktopFile.DesktopEntry
desktopFile = desktopItem.filename
self.appDirs = desktopFile.AppDirs
elif isinstance(desktopFile, xdg.Menu.DesktopEntry):
2010-09-13 15:54:23 +01:00
desktopItem = desktopFile
desktopFile = desktopItem.filename
self.appDirs = [os.path.dirname(desktopItem.filename)]
2010-09-13 15:54:23 +01:00
else:
desktopItem = xdg.DesktopEntry.DesktopEntry(desktopFile)
self.appDirs = [os.path.dirname(desktopFile)]
2010-09-13 15:54:23 +01:00
self.desktopFile = desktopFile
self.startupMonitorId = 0
self.loadDesktopEntry(desktopItem)
2010-09-13 15:54:23 +01:00
self.desktopEntryMonitors = []
base = os.path.basename(self.desktopFile)
for directory in self.appDirs:
self.desktopEntryMonitors.append(filemonitor.addMonitor(os.path.join(directory, base) , self.desktopEntryFileChangedCallback))
2010-09-13 15:54:23 +01:00
easyButton.__init__(self, self.appIconName, iconSize)
2010-09-13 15:54:23 +01:00
self.setupLabels()
# Drag and Drop
self.connectSelf("drag-data-get", self.dragDataGet)
2010-09-13 15:54:23 +01:00
targets = (Gtk.TargetEntry.new("text/plain", 0, 100), Gtk.TargetEntry.new("text/uri-list", 0, 101))
self.drag_source_set(Gdk.ModifierType.BUTTON1_MASK, targets, Gdk.DragAction.COPY)
self.drag_source_set_icon_name(self.iconName)
2010-09-13 15:54:23 +01:00
self.connectSelf("focus-in-event", self.onFocusIn)
self.connectSelf("focus-out-event", self.onFocusOut)
self.connectSelf("clicked", self.execute)
2010-09-13 15:54:23 +01:00
def loadDesktopEntry(self, desktopItem):
2010-09-13 15:54:23 +01:00
try:
2013-05-02 23:08:56 +01:00
self.appName = self.strip_accents(desktopItem.getName())
self.appGenericName = self.strip_accents(desktopItem.getGenericName())
self.appComment = self.strip_accents(desktopItem.getComment())
self.appExec = self.strip_accents(desktopItem.getExec().replace('\\\\', '\\'))
2010-09-13 15:54:23 +01:00
self.appIconName = desktopItem.getIcon()
self.appCategories = desktopItem.getCategories()
self.appMateDocPath = desktopItem.get("X-MATE-DocPath") or ""
2010-09-13 15:54:23 +01:00
self.useTerminal = desktopItem.getTerminal()
self.appPath = desktopItem.getPath()
2010-09-13 15:54:23 +01:00
if not self.appMateDocPath:
2010-09-13 15:54:23 +01:00
self.appKdeDocPath = desktopItem.getDocPath() or ""
self.appName = self.appName.strip()
self.appGenericName = self.appGenericName.strip()
self.appComment = self.appComment.strip()
basename = os.path.basename(self.desktopFile)
self.startupFilePath = os.path.join(os.path.expanduser("~"), ".config/autostart", basename)
2010-09-13 15:54:23 +01:00
if self.startupMonitorId:
filemonitor.removeMonitor(self.startupMonitorId )
if os.path.exists(self.startupFilePath):
self.startupMonitorId = filemonitor.addMonitor(self.startupFilePath, self.startupFileChanged)
2010-09-13 15:54:23 +01:00
except Exception as e:
print(e)
2010-09-13 15:54:23 +01:00
self.appName = ""
self.appGenericName = ""
self.appComment = ""
self.appExec = ""
self.appIconName = ""
2010-09-13 15:54:23 +01:00
self.appCategories = ""
self.appDocPath = ""
self.startupMonitorId = 0
def onFocusIn(self, widget, event):
self.set_relief(Gtk.ReliefStyle.HALF)
2010-09-13 15:54:23 +01:00
def onFocusOut(self, widget, event):
self.set_relief(Gtk.ReliefStyle.NONE)
2010-09-13 15:54:23 +01:00
def setupLabels(self):
self.addLabel(self.appName)
2010-09-13 15:54:23 +01:00
def filterText(self, text):
2010-09-13 15:54:23 +01:00
keywords = text.lower().split()
2013-05-03 00:12:24 +01:00
appName = self.appName.lower()
appGenericName = self.appGenericName.lower()
appComment = self.appComment.lower()
appExec = self.appExec.lower()
2010-09-13 15:54:23 +01:00
for keyword in keywords:
keyw = self.strip_accents(keyword)
if keyw != "" and appName.find(keyw) == -1 and appGenericName.find(keyw) == -1 and appComment.find(keyw) == -1 and appExec.find(keyw) == -1:
2010-09-13 15:54:23 +01:00
self.hide()
return False
self.show()
return True
2016-05-21 17:11:36 +01:00
def strip_accents(self, string):
2020-03-30 16:11:23 +01:00
# FIXME: Is this right??
return string
# value = string
# print(value, "...")
# if isinstance(string, str):
# try:
# value = string.encode('UTF8', 'ignore')
# except:
# pass
# return value
2010-09-13 15:54:23 +01:00
def getTooltip(self):
2010-09-13 15:54:23 +01:00
tooltip = self.appName
if self.appComment != "" and self.appComment != self.appName:
tooltip = tooltip + "\n" + self.appComment
return tooltip
def dragDataGet(self, widget, context, selection, targetType, eventTime):
2010-09-13 15:54:23 +01:00
if targetType == 100: # text/plain
selection.set_text("'" + self.desktopFile + "'", -1)
2010-09-13 15:54:23 +01:00
elif targetType == 101: # text/uri-list
if self.desktopFile[0:7] == "file://":
selection.set_uris([self.desktopFile])
2010-09-13 15:54:23 +01:00
else:
selection.set_uris(["file://" + self.desktopFile])
2010-09-13 15:54:23 +01:00
def execute(self, *args, **kwargs):
2010-09-13 15:54:23 +01:00
if self.appExec:
if self.useTerminal:
cmd = "x-terminal-emulator -e \"" + self.appExec + "\""
if os.path.exists("/usr/bin/mate-terminal"):
cmd = "mate-terminal -e \"" + self.appExec + "\""
Execute(cmd, self.appPath)
2010-09-13 15:54:23 +01:00
else:
offload = False
try:
offload = kwargs["offload"]
except KeyError:
pass
Execute(None, desktopFile=self.desktopFile, offload=offload)
2010-09-13 15:54:23 +01:00
def uninstall(self, *args):
Execute("mint-remove-application " + self.desktopFile)
2010-09-13 15:54:23 +01:00
# IconTheme changed, setup new icons for button and drag 'n drop
def iconChanged(self):
easyButton.iconChanged(self)
2010-09-13 15:54:23 +01:00
icon = self.getIcon(Gtk.IconSize.DND)
2013-05-08 14:16:55 +01:00
if icon:
iconName, size = icon.get_icon_name()
self.drag_source_set_icon_name(iconName)
2010-09-13 15:54:23 +01:00
def startupFileChanged(self, *args):
self.inStartup = os.path.exists(self.startupFilePath)
2010-09-13 15:54:23 +01:00
def addToStartup(self):
startupDir = os.path.join(os.path.dirname(self.startupFilePath))
if not os.path.exists(startupDir):
os.makedirs(startupDir)
2010-09-13 15:54:23 +01:00
shutil.copyfile(self.desktopFile, self.startupFilePath)
2010-09-13 15:54:23 +01:00
# Remove %u, etc. from Exec entry, because MATE will not replace them when it starts the app
2017-04-28 16:00:31 +01:00
item = MateDesktop.DesktopItem.new_from_uri(self.startupFilePath, MateDesktop.DesktopItemLoadFlags.ONLY_IF_EXISTS)
2010-09-13 15:54:23 +01:00
if item:
r = re.compile("%[A-Za-z]")
tmp = r.sub("", item.get_string(MateDesktop.DESKTOP_ITEM_EXEC)).strip()
item.set_string(MateDesktop.DESKTOP_ITEM_EXEC, tmp)
item.save(self.startupFilePath, 0)
2010-09-13 15:54:23 +01:00
def removeFromStartup(self):
if os.path.exists(self.startupFilePath):
os.remove(self.startupFilePath)
2010-09-13 15:54:23 +01:00
def removeFromFavourites(self):
if os.path.exists(self.favouritesFilePath):
os.remove(self.favouritesFilePath)
2010-09-13 15:54:23 +01:00
def isInStartup(self):
2010-09-13 15:54:23 +01:00
#return self.inStartup
return os.path.exists(self.startupFilePath)
2010-09-13 15:54:23 +01:00
def onDestroy(self, widget):
easyButton.onDestroy(self, widget)
2010-09-13 15:54:23 +01:00
if self.startupMonitorId:
filemonitor.removeMonitor(self.startupMonitorId)
2010-09-13 15:54:23 +01:00
for id in self.desktopEntryMonitors:
filemonitor.removeMonitor(id)
2010-09-13 15:54:23 +01:00
def desktopEntryFileChangedCallback(self):
GLib.timeout_add(200, self.onDesktopEntryFileChanged)
def onDesktopEntryFileChanged(self):
2010-09-13 15:54:23 +01:00
exists = False
base = os.path.basename(self.desktopFile)
for directory in self.appDirs:
if os.path.exists(os.path.join(directory, base)):
# print os.path.join(dir, base), self.desktopFile
self.loadDesktopEntry(xdg.DesktopEntry.DesktopEntry(os.path.join(directory, base)))
2010-09-13 15:54:23 +01:00
for child in self.labelBox:
child.destroy()
self.iconName = self.appIconName
2010-09-13 15:54:23 +01:00
self.setupLabels()
self.iconChanged()
2010-09-13 15:54:23 +01:00
exists = True
break
if not exists:
# FIXME: What to do in this case?
self.destroy()
return False
2009-07-27 11:45:34 +01:00
class MenuApplicationLauncher(ApplicationLauncher):
2009-07-27 11:45:34 +01:00
def __init__(self, desktopFile, iconSize, category, showComment, highlight=False):
2010-09-13 15:54:23 +01:00
self.showComment = showComment
self.appCategory = category
self.highlight = highlight
ApplicationLauncher.__init__(self, desktopFile, iconSize)
2010-09-13 15:54:23 +01:00
def filterCategory(self, category):
2010-09-13 15:54:23 +01:00
if self.appCategory == category or category == "":
self.show()
else:
self.hide()
def setupLabels(self):
2010-09-13 15:54:23 +01:00
appName = self.appName
appComment = self.appComment
2016-05-21 17:11:36 +01:00
if self.highlight:
2010-09-13 15:54:23 +01:00
try:
appName = "<b>%s</b>" % appName
appComment = "<b>%s</b>" % appComment
except Exception as e:
print(e)
2016-05-21 17:11:36 +01:00
2013-03-08 00:50:53 +00:00
if self.showComment and self.appComment != "":
if self.iconSize <= 2:
self.addLabel('<span size="small">%s</span>\n<span size="x-small">%s</span>' %
(appName, appComment))
2013-03-08 00:50:53 +00:00
else:
self.addLabel('%s\n<span size="small">%s</span>' %
(appName, appComment))
2013-03-08 00:50:53 +00:00
else:
self.addLabel(appName)
2016-05-21 17:11:36 +01:00
def execute(self, *args, **kwargs):
2010-09-13 15:54:23 +01:00
self.highlight = False
for child in self.labelBox:
child.destroy()
self.setupLabels()
return super(MenuApplicationLauncher, self).execute(*args, **kwargs)
2010-09-13 15:54:23 +01:00
def setShowComment(self, showComment):
2010-09-13 15:54:23 +01:00
self.showComment = showComment
for child in self.labelBox:
child.destroy()
self.setupLabels()
2009-07-27 11:45:34 +01:00
class FavApplicationLauncher(ApplicationLauncher):
2009-07-27 11:45:34 +01:00
def __init__(self, desktopFile, iconSize, swapGeneric = False):
2010-09-13 15:54:23 +01:00
self.swapGeneric = swapGeneric
2009-07-27 11:45:34 +01:00
ApplicationLauncher.__init__(self, desktopFile, iconSize)
2009-07-27 11:45:34 +01:00
def setupLabels(self):
2010-09-13 15:54:23 +01:00
if self.appGenericName:
if self.swapGeneric:
self.addLabel('<span weight="bold">%s</span>' % self.appName)
self.addLabel(self.appGenericName)
2010-09-13 15:54:23 +01:00
else:
self.addLabel('<span weight="bold">%s</span>' % self.appGenericName)
self.addLabel(self.appName)
2010-09-13 15:54:23 +01:00
else:
self.addLabel('<span weight="bold">%s</span>' % self.appName)
2010-09-13 15:54:23 +01:00
if self.appComment != "":
self.addLabel(self.appComment)
2010-09-13 15:54:23 +01:00
else:
self.addLabel("")
2016-05-21 17:11:36 +01:00
def setSwapGeneric(self, swapGeneric):
2010-09-13 15:54:23 +01:00
self.swapGeneric = swapGeneric
for child in self.labelBox:
child.destroy()
2009-07-27 11:45:34 +01:00
2010-09-13 15:54:23 +01:00
self.setupLabels()
2009-07-27 11:45:34 +01:00
class CategoryButton(easyButton):
2009-07-27 11:45:34 +01:00
def __init__(self, iconName, iconSize, labels , f):
easyButton.__init__(self, iconName, iconSize, labels, ellipsis=False)
2010-09-13 15:54:23 +01:00
self.filter = f
2009-07-27 11:45:34 +01:00
iconManager = IconManager()