further cleanup, mostly coding style

This commit is contained in:
gm10 2019-01-22 21:16:59 +01:00
parent cc75da5868
commit 8b42c0f32f
No known key found for this signature in database
GPG Key ID: A981D4EA8CF993A9
11 changed files with 1145 additions and 1165 deletions

View File

@ -1,6 +1,5 @@
#!/usr/bin/python2 #!/usr/bin/python2
import gc import gc
import gettext import gettext
import os import os
@ -21,6 +20,7 @@ import pointerMonitor
import setproctitle import setproctitle
from plugins.execute import Execute from plugins.execute import Execute
GObject.threads_init() GObject.threads_init()
# Rename the process # Rename the process
@ -30,60 +30,59 @@ setproctitle.setproctitle('mintmenu')
gettext.install("mintmenu", "/usr/share/linuxmint/locale") gettext.install("mintmenu", "/usr/share/linuxmint/locale")
NAME = _("Menu") NAME = _("Menu")
PATH = os.path.abspath( os.path.dirname( sys.argv[0] ) ) PATH = os.path.abspath(os.path.dirname(sys.argv[0]))
sys.path.append( os.path.join( PATH , "plugins") ) sys.path.append(os.path.join(PATH , "plugins"))
windowManager = os.getenv("DESKTOP_SESSION") windowManager = os.getenv("DESKTOP_SESSION")
if not windowManager: if not windowManager:
windowManager = "MATE" windowManager = "MATE"
xdg.Config.setWindowManager( windowManager.upper() ) xdg.Config.setWindowManager(windowManager.upper())
class MainWindow( object ): class MainWindow(object):
"""This is the main class for the application""" """This is the main class for the application"""
def __init__( self, toggleButton, settings, de ): def __init__(self, toggleButton, settings, de):
self.settings = settings self.settings = settings
self.path = PATH self.path = PATH
sys.path.append( os.path.join( self.path, "plugins") ) sys.path.append(os.path.join(self.path, "plugins"))
self.de = de self.de = de
self.icon = "/usr/lib/linuxmint/mintMenu/visualisation-logo.png" self.icon = "/usr/lib/linuxmint/mintMenu/visualisation-logo.png"
self.toggle = toggleButton self.toggle = toggleButton
# Load UI file and extract widgets # Load UI file and extract widgets
builder = Gtk.Builder() builder = Gtk.Builder()
builder.add_from_file(os.path.join( self.path, "mintMenu.glade" )) builder.add_from_file(os.path.join(self.path, "mintMenu.glade"))
self.window = builder.get_object( "mainWindow" ) self.window = builder.get_object("mainWindow")
self.paneholder = builder.get_object( "paneholder" ) self.paneholder = builder.get_object("paneholder")
builder.connect_signals(self) builder.connect_signals(self)
self.panesToColor = [ ] self.panesToColor = []
self.headingsToColor = [ ] self.headingsToColor = []
self.window.connect( "key-press-event", self.onKeyPress ) self.window.connect("key-press-event", self.onKeyPress)
self.window.connect( "focus-in-event", self.onFocusIn ) self.window.connect("focus-in-event", self.onFocusIn)
self.loseFocusId = self.window.connect( "focus-out-event", self.onFocusOut ) self.loseFocusId = self.window.connect("focus-out-event", self.onFocusOut)
self.loseFocusBlocked = False self.loseFocusBlocked = False
self.window.stick() self.window.stick()
plugindir = os.path.join( os.path.expanduser( "~" ), ".linuxmint/mintMenu/plugins" ) plugindir = os.path.join(os.path.expanduser("~"), ".linuxmint/mintMenu/plugins")
sys.path.append( plugindir ) sys.path.append(plugindir)
self.panelSettings = Gio.Settings.new("org.mate.panel") self.panelSettings = Gio.Settings.new("org.mate.panel")
self.panelSettings.connect( "changed::tooltips-enabled", self.toggleTooltipsEnabled ) self.panelSettings.connect("changed::tooltips-enabled", self.toggleTooltipsEnabled)
self.settings.connect( "changed::plugins-list", self.RegenPlugins ) self.settings.connect("changed::plugins-list", self.RegenPlugins)
self.settings.connect( "changed::start-with-favorites", self.toggleStartWithFavorites ) self.settings.connect("changed::start-with-favorites", self.toggleStartWithFavorites)
self.settings.connect( "changed::tooltips-enabled", self.toggleTooltipsEnabled ) self.settings.connect("changed::tooltips-enabled", self.toggleTooltipsEnabled)
self.settings.connect( "changed::use-custom-color", self.toggleUseCustomColor ) self.settings.connect("changed::use-custom-color", self.toggleUseCustomColor)
self.settings.connect( "changed::custom-heading-color", self.toggleCustomHeadingColor ) self.settings.connect("changed::custom-heading-color", self.toggleCustomHeadingColor)
self.settings.connect( "changed::custom-color", self.toggleCustomBackgroundColor ) self.settings.connect("changed::custom-color", self.toggleCustomBackgroundColor)
self.getSetGSettingEntries() self.getSetGSettingEntries()
@ -91,7 +90,7 @@ class MainWindow( object ):
if self.globalEnableTooltips and self.enableTooltips: if self.globalEnableTooltips and self.enableTooltips:
self.tooltipsEnable() self.tooltipsEnable()
else: else:
self.tooltipsEnable( False ) self.tooltipsEnable(False)
self.PopulatePlugins() self.PopulatePlugins()
self.firstTime = True self.firstTime = True
@ -101,13 +100,13 @@ class MainWindow( object ):
Gtk.main_quit() Gtk.main_quit()
sys.exit(0) sys.exit(0)
def wakePlugins( self ): def wakePlugins(self):
# Call each plugin and let them know we're showing up # Call each plugin and let them know we're showing up
for plugin in self.plugins.values(): for plugin in self.plugins.values():
if hasattr( plugin, "wake" ): if hasattr(plugin, "wake"):
plugin.wake() plugin.wake()
def toggleTooltipsEnabled( self, settings, key, args = None): def toggleTooltipsEnabled(self, settings, key, args = None):
if key == "tooltips-enabled": if key == "tooltips-enabled":
self.globalEnableTooltips = settings.get_boolean(key) self.globalEnableTooltips = settings.get_boolean(key)
else: else:
@ -116,48 +115,48 @@ class MainWindow( object ):
if self.globalEnableTooltips and self.enableTooltips: if self.globalEnableTooltips and self.enableTooltips:
self.tooltipsEnable() self.tooltipsEnable()
else: else:
self.tooltipsEnable( False ) self.tooltipsEnable(False)
def toggleStartWithFavorites( self, settings, key ): def toggleStartWithFavorites(self, settings, key):
self.startWithFavorites = settings.get_boolean(key) self.startWithFavorites = settings.get_boolean(key)
def toggleUseCustomColor( self, settings, key ): def toggleUseCustomColor(self, settings, key):
self.usecustomcolor = settings.get_boolean(key) self.usecustomcolor = settings.get_boolean(key)
self.loadTheme() self.loadTheme()
def toggleCustomBackgroundColor( self, settings, key ): def toggleCustomBackgroundColor(self, settings, key):
self.customcolor = settings.get_string(key) self.customcolor = settings.get_string(key)
self.SetPaneColors( self.panesToColor ) self.SetPaneColors(self.panesToColor)
def toggleCustomHeadingColor( self, settings, key ): def toggleCustomHeadingColor(self, settings, key):
self.customheadingcolor = settings.get_string(key) self.customheadingcolor = settings.get_string(key)
self.SetHeadingStyle( self.headingsToColor ) self.SetHeadingStyle(self.headingsToColor)
def getSetGSettingEntries( self ): def getSetGSettingEntries(self):
self.dottedfile = os.path.join( self.path, "dotted.png") self.dottedfile = os.path.join(self.path, "dotted.png")
self.pluginlist = self.settings.get_strv( "plugins-list" ) self.pluginlist = self.settings.get_strv("plugins-list")
self.usecustomcolor = self.settings.get_boolean( "use-custom-color" ) self.usecustomcolor = self.settings.get_boolean("use-custom-color")
self.customcolor = self.settings.get_string( "custom-color" ) self.customcolor = self.settings.get_string("custom-color")
self.customheadingcolor = self.settings.get_string( "custom-heading-color" ) self.customheadingcolor = self.settings.get_string("custom-heading-color")
self.offset = self.settings.get_int( "offset" ) self.offset = self.settings.get_int("offset")
self.enableTooltips = self.settings.get_boolean( "tooltips-enabled" ) self.enableTooltips = self.settings.get_boolean("tooltips-enabled")
self.startWithFavorites = self.settings.get_boolean( "start-with-favorites" ) self.startWithFavorites = self.settings.get_boolean("start-with-favorites")
self.globalEnableTooltips = self.panelSettings.get_boolean( "tooltips-enabled" ) self.globalEnableTooltips = self.panelSettings.get_boolean("tooltips-enabled")
def PopulatePlugins( self ): def PopulatePlugins(self):
self.panesToColor = [ ] self.panesToColor = []
self.headingsToColor = [ ] self.headingsToColor = []
PluginPane = Gtk.EventBox() PluginPane = Gtk.EventBox()
PluginPane.show() PluginPane.show()
PaneLadder = Gtk.Box( orientation=Gtk.Orientation.VERTICAL ) PaneLadder = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
PluginPane.add( PaneLadder ) PluginPane.add(PaneLadder)
ImageBox = Gtk.EventBox() ImageBox = Gtk.EventBox()
ImageBox.show() ImageBox.show()
self.panesToColor.extend( [ PluginPane, ImageBox ] ) self.panesToColor.extend([PluginPane, ImageBox])
seperatorImage = GdkPixbuf.Pixbuf.new_from_file( self.dottedfile ) seperatorImage = GdkPixbuf.Pixbuf.new_from_file(self.dottedfile)
self.plugins = {} self.plugins = {}
@ -168,22 +167,22 @@ class MainWindow( object ):
if plugin != "newpane": if plugin != "newpane":
try: try:
X = __import__( plugin ) X = __import__(plugin)
# If no parameter passed to plugin it is autonomous # If no parameter passed to plugin it is autonomous
if X.pluginclass.__init__.func_code.co_argcount == 1: if X.pluginclass.__init__.func_code.co_argcount == 1:
MyPlugin = X.pluginclass() MyPlugin = X.pluginclass()
else: else:
# pass mintMenu and togglebutton instance so that the plugin can use it # pass mintMenu and togglebutton instance so that the plugin can use it
MyPlugin = X.pluginclass( self, self.toggle, self.de ) MyPlugin = X.pluginclass(self, self.toggle, self.de)
if not MyPlugin.icon: if not MyPlugin.icon:
MyPlugin.icon = "mate-logo-icon.png" MyPlugin.icon = "mate-logo-icon.png"
#if hasattr( MyPlugin, "hideseparator" ) and not MyPlugin.hideseparator: #if hasattr(MyPlugin, "hideseparator") and not MyPlugin.hideseparator:
# Image1 = Gtk.Image() # Image1 = Gtk.Image()
# Image1.set_from_pixbuf( seperatorImage ) # Image1.set_from_pixbuf(seperatorImage)
# if not ImageBox.get_child(): # if not ImageBox.get_child():
# ImageBox.add( Image1 ) # ImageBox.add(Image1)
# Image1.show() # Image1.show()
#print u"Loading plugin '" + plugin + "' : sucessful" #print u"Loading plugin '" + plugin + "' : sucessful"
@ -195,55 +194,55 @@ class MainWindow( object ):
# create traceback # create traceback
info = sys.exc_info() info = sys.exc_info()
errorLabel = Gtk.Label( "\n".join(traceback.format_exception( info[0], info[1], info[2] )).replace("\\n", "\n") ) errorLabel = Gtk.Label("\n".join(traceback.format_exception(info[0], info[1], info[2])).replace("\\n", "\n"))
errorLabel.set_selectable( True ) errorLabel.set_selectable(True)
errorLabel.set_line_wrap( True ) errorLabel.set_line_wrap(True)
errorLabel.set_alignment( 0.0, 0.0 ) errorLabel.set_alignment(0.0, 0.0)
errorLabel.set_padding( 5, 5 ) errorLabel.set_padding(5, 5)
errorLabel.show() errorLabel.show()
MyPlugin.content_holder.add( errorLabel ) MyPlugin.content_holder.add(errorLabel)
MyPlugin.add( MyPlugin.content_holder ) MyPlugin.add(MyPlugin.content_holder)
MyPlugin.width = 270 MyPlugin.width = 270
MyPlugin.icon = 'mate-logo-icon.png' MyPlugin.icon = 'mate-logo-icon.png'
print u"Unable to load " + plugin + " plugin :-(" print u"Unable to load " + plugin + " plugin :-("
self.panesToColor.append( MyPlugin.content_holder ) self.panesToColor.append(MyPlugin.content_holder)
MyPlugin.content_holder.show() MyPlugin.content_holder.show()
VBox1 = Gtk.Box( orientation=Gtk.Orientation.VERTICAL ) VBox1 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
if MyPlugin.heading != "": if MyPlugin.heading != "":
Label1 = Gtk.Label(label= MyPlugin.heading ) Label1 = Gtk.Label(label= MyPlugin.heading)
Align1 = Gtk.Alignment.new( 0, 0, 0, 0 ) Align1 = Gtk.Alignment.new(0, 0, 0, 0)
Align1.set_padding( 10, 5, 10, 0 ) Align1.set_padding(10, 5, 10, 0)
Align1.add( Label1 ) Align1.add(Label1)
self.headingsToColor.append( Label1 ) self.headingsToColor.append(Label1)
Align1.show() Align1.show()
Label1.show() Label1.show()
if not hasattr( MyPlugin, 'sticky' ) or MyPlugin.sticky == True: if not hasattr(MyPlugin, 'sticky') or MyPlugin.sticky:
heading = Gtk.EventBox() heading = Gtk.EventBox()
Align1.set_padding( 0, 0, 10, 0 ) Align1.set_padding(0, 0, 10, 0)
heading.set_visible_window( False ) heading.set_visible_window(False)
heading.set_size_request( MyPlugin.width, 30 ) heading.set_size_request(MyPlugin.width, 30)
else: else:
heading = Gtk.Box( orientation=Gtk.Orientation.HORIZONTAL ) heading = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
#heading.set_relief( Gtk.ReliefStyle.NONE ) #heading.set_relief(Gtk.ReliefStyle.NONE)
heading.set_size_request( MyPlugin.width, -1 ) heading.set_size_request(MyPlugin.width, -1)
#heading.set_sensitive(False) #heading.set_sensitive(False)
#heading.connect( "button_press_event", self.TogglePluginView, VBox1, MyPlugin.icon, MyPlugin.heading, MyPlugin ) #heading.connect("button_press_event", self.TogglePluginView, VBox1, MyPlugin.icon, MyPlugin.heading, MyPlugin)
heading.add( Align1 ) heading.add(Align1)
heading.show() heading.show()
VBox1.pack_start( heading, False, False, 0 ) VBox1.pack_start(heading, False, False, 0)
VBox1.show() VBox1.show()
#Add plugin to Plugin Box under heading button #Add plugin to Plugin Box under heading button
MyPlugin.content_holder.get_parent().remove(MyPlugin.content_holder) MyPlugin.content_holder.get_parent().remove(MyPlugin.content_holder)
VBox1.add( MyPlugin.content_holder ) VBox1.add(MyPlugin.content_holder)
#Add plugin to main window #Add plugin to main window
PaneLadder.pack_start( VBox1 , True, True, 0) PaneLadder.pack_start(VBox1 , True, True, 0)
PaneLadder.show() PaneLadder.show()
try: try:
@ -252,84 +251,84 @@ class MainWindow( object ):
pass pass
try: try:
if hasattr( MyPlugin, 'do_plugin' ): if hasattr(MyPlugin, 'do_plugin'):
MyPlugin.do_plugin() MyPlugin.do_plugin()
if hasattr( MyPlugin, 'height' ): if hasattr(MyPlugin, 'height'):
MyPlugin.content_holder.set_size_request( -1, MyPlugin.height ) MyPlugin.content_holder.set_size_request(-1, MyPlugin.height)
if hasattr( MyPlugin, 'itemstocolor' ): if hasattr(MyPlugin, 'itemstocolor'):
self.panesToColor.extend( MyPlugin.itemstocolor ) self.panesToColor.extend(MyPlugin.itemstocolor)
if hasattr( MyPlugin, 'headingstocolor' ): if hasattr(MyPlugin, 'headingstocolor'):
self.headingsToColor.extend( MyPlugin.headingstocolor ) self.headingsToColor.extend(MyPlugin.headingstocolor)
except: except:
# create traceback # create traceback
info = sys.exc_info() info = sys.exc_info()
error = _("Couldn't initialize plugin") + " " + plugin + " : " + "\n".join(traceback.format_exception( info[0], info[1], info[2] )).replace("\\n", "\n") error = _("Couldn't initialize plugin") + " " + plugin + " : " + "\n".join(traceback.format_exception(info[0], info[1], info[2])).replace("\\n", "\n")
msgDlg = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, error ) msgDlg = Gtk.MessageDialog(None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, error)
msgDlg.run() msgDlg.run()
msgDlg.destroy() msgDlg.destroy()
self.plugins[plugin] = MyPlugin self.plugins[plugin] = MyPlugin
else: else:
self.paneholder.pack_start( ImageBox, False, False, 0 ) self.paneholder.pack_start(ImageBox, False, False, 0)
self.paneholder.pack_start( PluginPane, False, False, 0 ) self.paneholder.pack_start(PluginPane, False, False, 0)
PluginPane = Gtk.EventBox() PluginPane = Gtk.EventBox()
PaneLadder = Gtk.Box( orientation=Gtk.Orientation.VERTICAL ) PaneLadder = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
PluginPane.add( PaneLadder ) PluginPane.add(PaneLadder)
ImageBox = Gtk.EventBox() ImageBox = Gtk.EventBox()
self.panesToColor.extend( [ PluginPane, ImageBox ] ) self.panesToColor.extend([PluginPane, ImageBox])
ImageBox.show() ImageBox.show()
PluginPane.show_all() PluginPane.show_all()
if self.plugins and hasattr( MyPlugin, 'hideseparator' ) and not MyPlugin.hideseparator: if self.plugins and hasattr(MyPlugin, 'hideseparator') and not MyPlugin.hideseparator:
Image1 = Gtk.Image() Image1 = Gtk.Image()
Image1.set_from_pixbuf( seperatorImage ) Image1.set_from_pixbuf(seperatorImage)
Image1.show() Image1.show()
#ImageBox.add( Image1 ) #ImageBox.add(Image1)
Align1 = Gtk.Alignment.new(0, 0, 0, 0) Align1 = Gtk.Alignment.new(0, 0, 0, 0)
Align1.set_padding( 0, 0, 6, 6 ) Align1.set_padding(0, 0, 6, 6)
Align1.add(Image1) Align1.add(Image1)
ImageBox.add(Align1) ImageBox.add(Align1)
ImageBox.show_all() ImageBox.show_all()
self.paneholder.pack_start( ImageBox, False, False, 0 ) self.paneholder.pack_start(ImageBox, False, False, 0)
self.paneholder.pack_start( PluginPane, False, False, 0 ) self.paneholder.pack_start(PluginPane, False, False, 0)
self.tooltipsEnable( False ) self.tooltipsEnable(False)
# A little bit hacky but works. # A little bit hacky but works.
def getDefaultColors( self ): def getDefaultColors(self):
widget = Gtk.EventBox() widget = Gtk.EventBox()
widget.show() widget.show()
context = widget.get_style_context() context = widget.get_style_context()
context.set_state( Gtk.StateFlags.NORMAL ) context.set_state(Gtk.StateFlags.NORMAL)
context.add_class( Gtk.STYLE_CLASS_DEFAULT ) context.add_class(Gtk.STYLE_CLASS_DEFAULT)
context.add_class( Gtk.STYLE_CLASS_BACKGROUND ) context.add_class(Gtk.STYLE_CLASS_BACKGROUND)
fgColor = context.get_color( context.get_state() ) fgColor = context.get_color(context.get_state())
bgColor = context.get_background_color( context.get_state() ) bgColor = context.get_background_color(context.get_state())
return { "fg": fgColor, "bg": bgColor } return {"fg": fgColor, "bg": bgColor}
def loadTheme( self ): def loadTheme(self):
colors = self.getDefaultColors() colors = self.getDefaultColors()
self.SetPaneColors( self.panesToColor, colors["bg"] ) self.SetPaneColors(self.panesToColor, colors["bg"])
self.SetHeadingStyle( self.headingsToColor ) self.SetHeadingStyle(self.headingsToColor)
def SetPaneColors( self, items, color = None ): def SetPaneColors(self, items, color = None):
for item in items: for item in items:
context = item.get_style_context() context = item.get_style_context()
if self.usecustomcolor: if self.usecustomcolor:
bgColor = Gdk.RGBA() bgColor = Gdk.RGBA()
bgColor.parse( self.customcolor ) bgColor.parse(self.customcolor)
item.override_background_color( context.get_state(), bgColor ) item.override_background_color(context.get_state(), bgColor)
elif color is not None: elif color is not None:
item.override_background_color( context.get_state(), color ) item.override_background_color(context.get_state(), color)
def SetHeadingStyle( self, items ): def SetHeadingStyle(self, items):
if self.usecustomcolor: if self.usecustomcolor:
color = self.customheadingcolor color = self.customheadingcolor
else: else:
@ -342,24 +341,24 @@ class MainWindow( object ):
markup = '<span size="12000" weight="bold">%s</span>' % (text) markup = '<span size="12000" weight="bold">%s</span>' % (text)
else: else:
markup = '<span size="12000" weight="bold" color="%s">%s</span>' % (color, text) markup = '<span size="12000" weight="bold" color="%s">%s</span>' % (color, text)
item.set_markup( markup ) item.set_markup(markup)
def tooltipsEnable( self, enable = True ): def tooltipsEnable(self, enable = True):
for widget in self.tooltipsWidgets: for widget in self.tooltipsWidgets:
widget.set_has_tooltip( enable ) widget.set_has_tooltip(enable)
def setTooltip( self, widget, tip ): def setTooltip(self, widget, tip):
self.tooltipsWidgets.append( widget ) self.tooltipsWidgets.append(widget)
widget.set_tooltip_text( tip ) widget.set_tooltip_text(tip)
def RegenPlugins( self, *args, **kargs ): def RegenPlugins(self, *args, **kargs):
#print #print
#print u"Reloading Plugins..." #print u"Reloading Plugins..."
for item in self.paneholder: for item in self.paneholder:
item.destroy() item.destroy()
for plugin in self.plugins.values(): for plugin in self.plugins.values():
if hasattr( plugin, "destroy" ): if hasattr(plugin, "destroy"):
plugin.destroy() plugin.destroy()
try: try:
@ -380,13 +379,13 @@ class MainWindow( object ):
#print NAME+u" reloaded" #print NAME+u" reloaded"
def onKeyPress( self, widget, event ): def onKeyPress(self, widget, event):
if event.keyval == Gdk.KEY_Escape: if event.keyval == Gdk.KEY_Escape:
self.hide() self.hide()
return True return True
return False return False
def show( self ): def show(self):
self.window.present() self.window.present()
# Hack for opacity not showing on first composited draw # Hack for opacity not showing on first composited draw
@ -394,43 +393,44 @@ class MainWindow( object ):
self.firstTime = False self.firstTime = False
self.window.set_opacity(1.0) self.window.set_opacity(1.0)
self.window.get_window().focus( Gdk.CURRENT_TIME ) self.window.get_window().focus(Gdk.CURRENT_TIME)
for plugin in self.plugins.values(): for plugin in self.plugins.values():
if hasattr( plugin, "onShowMenu" ): if hasattr(plugin, "onShowMenu"):
plugin.onShowMenu() plugin.onShowMenu()
if ( "applications" in self.plugins ) and ( hasattr( self.plugins["applications"], "focusSearchEntry" ) ): if "applications" in self.plugins and hasattr(self.plugins["applications"], "focusSearchEntry"):
if (self.startWithFavorites): if self.startWithFavorites:
self.plugins["applications"].changeTab(0) self.plugins["applications"].changeTab(0)
self.plugins["applications"].focusSearchEntry() self.plugins["applications"].focusSearchEntry()
def hide( self ): def hide(self):
for plugin in self.plugins.values(): for plugin in self.plugins.values():
if hasattr( plugin, "onHideMenu" ): if hasattr(plugin, "onHideMenu"):
plugin.onHideMenu() plugin.onHideMenu()
self.window.hide() self.window.hide()
def onFocusIn( self, *args ): def onFocusIn(self, *args):
if self.loseFocusBlocked: if self.loseFocusBlocked:
self.window.handler_unblock( self.loseFocusId ) self.window.handler_unblock(self.loseFocusId)
self.loseFocusBlocked = False self.loseFocusBlocked = False
return False return False
def onFocusOut( self, *args): def onFocusOut(self, *args):
if self.window.get_visible(): if self.window.get_visible():
self.hide() self.hide()
return False return False
def stopHiding( self ): def stopHiding(self):
if not self.loseFocusBlocked: if not self.loseFocusBlocked:
self.window.handler_block( self.loseFocusId ) self.window.handler_block(self.loseFocusId)
self.loseFocusBlocked = True self.loseFocusBlocked = True
class MenuWin( object ): class MenuWin(object):
def __init__( self, applet, iid ):
def __init__(self, applet, iid):
self.applet = applet self.applet = applet
self.detect_desktop_environment() self.detect_desktop_environment()
self.settings = Gio.Settings.new("com.linuxmint.mintmenu") self.settings = Gio.Settings.new("com.linuxmint.mintmenu")
@ -439,40 +439,40 @@ class MenuWin( object ):
self.createPanelButton() self.createPanelButton()
self.mate_settings = Gio.Settings.new("org.mate.interface") self.mate_settings = Gio.Settings.new("org.mate.interface")
self.mate_settings.connect( "changed::gtk-theme", self.changeTheme ) self.mate_settings.connect("changed::gtk-theme", self.changeTheme)
self.settings.connect( "changed::applet-text", self.reloadSettings ) self.settings.connect("changed::applet-text", self.reloadSettings)
self.settings.connect( "changed::theme-name", self.changeTheme ) self.settings.connect("changed::theme-name", self.changeTheme)
self.settings.connect( "changed::hot-key", self.reloadSettings ) self.settings.connect("changed::hot-key", self.reloadSettings)
self.settings.connect( "changed::applet-icon", self.reloadSettings ) self.settings.connect("changed::applet-icon", self.reloadSettings)
self.settings.connect( "changed::hide-applet-icon", self.reloadSettings ) self.settings.connect("changed::hide-applet-icon", self.reloadSettings)
self.settings.connect( "changed::applet-icon-size", self.reloadSettings ) self.settings.connect("changed::applet-icon-size", self.reloadSettings)
self.applet.set_flags( MatePanelApplet.AppletFlags.EXPAND_MINOR ) self.applet.set_flags(MatePanelApplet.AppletFlags.EXPAND_MINOR)
self.applet.connect( "button-press-event", self.showMenu ) self.applet.connect("button-press-event", self.showMenu)
self.applet.connect( "change-orient", self.changeOrientation ) self.applet.connect("change-orient", self.changeOrientation)
self.applet.connect("enter-notify-event", self.enter_notify) self.applet.connect("enter-notify-event", self.enter_notify)
self.applet.connect("leave-notify-event", self.leave_notify) self.applet.connect("leave-notify-event", self.leave_notify)
self.mainwin = MainWindow( self.button_box, self.settings, self.de ) self.mainwin = MainWindow(self.button_box, self.settings, self.de)
self.mainwin.window.connect( "map-event", self.onWindowMap ) self.mainwin.window.connect("map-event", self.onWindowMap)
self.mainwin.window.connect( "unmap-event", self.onWindowUnmap ) self.mainwin.window.connect("unmap-event", self.onWindowUnmap)
self.mainwin.window.connect( "size-allocate", lambda *args: self.positionMenu() ) self.mainwin.window.connect("size-allocate", lambda *args: self.positionMenu())
self.mainwin.window.set_name("mintmenu") # Name used in Gtk RC files self.mainwin.window.set_name("mintmenu") # Name used in Gtk RC files
self.applyTheme() self.applyTheme()
self.mainwin.loadTheme() self.mainwin.loadTheme()
if self.mainwin.icon: if self.mainwin.icon:
Gtk.Window.set_default_icon_name( self.mainwin.icon ) Gtk.Window.set_default_icon_name(self.mainwin.icon)
try: try:
self.keybinder = keybinding.GlobalKeyBinding() self.keybinder = keybinding.GlobalKeyBinding()
if self.hotkeyText != "": if self.hotkeyText != "":
self.keybinder.grab( self.hotkeyText ) self.keybinder.grab(self.hotkeyText)
self.keybinder.connect("activate", self.onBindingPress) self.keybinder.connect("activate", self.onBindingPress)
self.keybinder.start() self.keybinder.start()
self.settings.connect( "changed::hot-key", self.hotkeyChanged ) self.settings.connect("changed::hot-key", self.hotkeyChanged)
print "Binding to Hot Key: " + self.hotkeyText print "Binding to Hot Key: " + self.hotkeyText
except Exception, cause: except Exception, cause:
self.keybinder = None self.keybinder = None
@ -484,28 +484,28 @@ class MenuWin( object ):
try: try:
self.pointerMonitor = pointerMonitor.PointerMonitor() self.pointerMonitor = pointerMonitor.PointerMonitor()
self.pointerMonitor.connect("activate", self.onPointerOutside) self.pointerMonitor.connect("activate", self.onPointerOutside)
self.mainwin.window.connect( "realize", self.onRealize ) self.mainwin.window.connect("realize", self.onRealize)
except Exception, cause: except Exception, cause:
print "** WARNING ** - Pointer Monitor Error" print "** WARNING ** - Pointer Monitor Error"
print "Error Report :\n", str(cause) print "Error Report :\n", str(cause)
def onWindowMap( self, *args ): def onWindowMap(self, *args):
self.applet.get_style_context().set_state( Gtk.StateFlags.SELECTED ) self.applet.get_style_context().set_state(Gtk.StateFlags.SELECTED)
self.button_box.get_style_context().set_state( Gtk.StateFlags.SELECTED ) self.button_box.get_style_context().set_state(Gtk.StateFlags.SELECTED)
if self.keybinder is not None: if self.keybinder is not None:
self.keybinder.set_focus_window( self.mainwin.window.get_window() ) self.keybinder.set_focus_window(self.mainwin.window.get_window())
return False return False
def onWindowUnmap( self, *args ): def onWindowUnmap(self, *args):
self.applet.get_style_context().set_state( Gtk.StateFlags.NORMAL ) self.applet.get_style_context().set_state(Gtk.StateFlags.NORMAL)
self.button_box.get_style_context().set_state( Gtk.StateFlags.NORMAL ) self.button_box.get_style_context().set_state(Gtk.StateFlags.NORMAL)
if self.keybinder is not None: if self.keybinder is not None:
self.keybinder.set_focus_window() self.keybinder.set_focus_window()
return False return False
def onRealize( self, *args): def onRealize(self, *args):
self.pointerMonitor.addWindowToMonitor( self.mainwin.window.get_window() ) self.pointerMonitor.addWindowToMonitor(self.mainwin.window.get_window())
self.pointerMonitor.addWindowToMonitor( self.applet.get_window() ) self.pointerMonitor.addWindowToMonitor(self.applet.get_window())
self.pointerMonitor.start() self.pointerMonitor.start()
return False return False
@ -537,10 +537,10 @@ class MenuWin( object ):
GdkPixbuf.Pixbuf.saturate_and_pixelate(pixbuf, pixbuf, 1.5, False) GdkPixbuf.Pixbuf.saturate_and_pixelate(pixbuf, pixbuf, 1.5, False)
self.button_icon.set_from_pixbuf(pixbuf) self.button_icon.set_from_pixbuf(pixbuf)
def createPanelButton( self ): def createPanelButton(self):
self.button_icon = Gtk.Image() self.button_icon = Gtk.Image()
self.do_image(self.buttonIcon, False) self.do_image(self.buttonIcon, False)
self.systemlabel = Gtk.Label(label= "%s " % self.buttonText ) self.systemlabel = Gtk.Label(label= "%s " % self.buttonText)
if os.path.isfile("/etc/linuxmint/info"): if os.path.isfile("/etc/linuxmint/info"):
info = open("/etc/linuxmint/info").readlines() #TODO py3 encoding="utf-8" info = open("/etc/linuxmint/info").readlines() #TODO py3 encoding="utf-8"
for line in info: for line in info:
@ -550,44 +550,44 @@ class MenuWin( object ):
self.button_icon.set_tooltip_text(tooltip) self.button_icon.set_tooltip_text(tooltip)
break break
if self.applet.get_orient() == MatePanelApplet.AppletOrient.UP or self.applet.get_orient() == MatePanelApplet.AppletOrient.DOWN: if self.applet.get_orient() == MatePanelApplet.AppletOrient.UP or self.applet.get_orient() == MatePanelApplet.AppletOrient.DOWN:
self.button_box = Gtk.Box( orientation=Gtk.Orientation.HORIZONTAL ) self.button_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
self.button_box.pack_start( self.button_icon, False, False, 0 ) self.button_box.pack_start(self.button_icon, False, False, 0)
self.button_box.pack_start( self.systemlabel, False, False, 0 ) self.button_box.pack_start(self.systemlabel, False, False, 0)
self.button_icon.set_padding( 5, 0 ) self.button_icon.set_padding(5, 0)
# if we have a vertical panel # if we have a vertical panel
elif self.applet.get_orient() == MatePanelApplet.AppletOrient.LEFT: elif self.applet.get_orient() == MatePanelApplet.AppletOrient.LEFT:
self.button_box = Gtk.Box( orientation=Gtk.Orientation.VERTICAL ) self.button_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.systemlabel.set_angle( 270 ) self.systemlabel.set_angle(270)
self.button_box.pack_start( self.button_icon , False, False, 0) self.button_box.pack_start(self.button_icon , False, False, 0)
self.button_box.pack_start( self.systemlabel , False, False, 0) self.button_box.pack_start(self.systemlabel , False, False, 0)
self.button_icon.set_padding( 0, 5 ) self.button_icon.set_padding(0, 5)
elif self.applet.get_orient() == MatePanelApplet.AppletOrient.RIGHT: elif self.applet.get_orient() == MatePanelApplet.AppletOrient.RIGHT:
self.button_box = Gtk.Box( orientation=Gtk.Orientation.VERTICAL ) self.button_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.systemlabel.set_angle( 90 ) self.systemlabel.set_angle(90)
self.button_box.pack_start( self.systemlabel , False, False, 0) self.button_box.pack_start(self.systemlabel , False, False, 0)
self.button_box.pack_start( self.button_icon , False, False, 0) self.button_box.pack_start(self.button_icon , False, False, 0)
self.button_icon.set_padding( 0, 5 ) self.button_icon.set_padding(0, 5)
self.button_box.set_homogeneous( False ) self.button_box.set_homogeneous(False)
self.button_box.show_all() self.button_box.show_all()
self.sizeButton() self.sizeButton()
self.button_box.get_style_context().add_class('mintmenu') self.button_box.get_style_context().add_class('mintmenu')
self.applet.add( self.button_box ) self.applet.add(self.button_box)
self.applet.set_background_widget( self.applet ) self.applet.set_background_widget(self.applet)
def loadSettings( self, *args, **kargs ): def loadSettings(self, *args, **kargs):
self.hideIcon = self.settings.get_boolean( "hide-applet-icon" ) self.hideIcon = self.settings.get_boolean("hide-applet-icon")
self.buttonText = self.settings.get_string("applet-text") self.buttonText = self.settings.get_string("applet-text")
self.theme_name = self.settings.get_string( "theme-name" ) self.theme_name = self.settings.get_string("theme-name")
self.hotkeyText = self.settings.get_string( "hot-key" ) self.hotkeyText = self.settings.get_string("hot-key")
if not os.path.exists(self.settings.get_string("applet-icon")): if not os.path.exists(self.settings.get_string("applet-icon")):
self.settings.reset("applet-icon") self.settings.reset("applet-icon")
self.buttonIcon = self.settings.get_string( "applet-icon" ) self.buttonIcon = self.settings.get_string("applet-icon")
self.iconSize = self.settings.get_int( "applet-icon-size" ) self.iconSize = self.settings.get_int("applet-icon-size")
def changeTheme(self, *args): def changeTheme(self, *args):
self.reloadSettings() self.reloadSettings()
@ -605,28 +605,28 @@ class MenuWin( object ):
except: except:
style_settings.set_property("gtk-theme-name", desktop_theme) style_settings.set_property("gtk-theme-name", desktop_theme)
def changeOrientation( self, *args, **kargs ): def changeOrientation(self, *args, **kargs):
if self.applet.get_orient() == MatePanelApplet.AppletOrient.UP or self.applet.get_orient() == MatePanelApplet.AppletOrient.DOWN: if self.applet.get_orient() == MatePanelApplet.AppletOrient.UP or self.applet.get_orient() == MatePanelApplet.AppletOrient.DOWN:
tmpbox = Gtk.Box( orientation=Gtk.Orientation.HORIZONTAL ) tmpbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
self.systemlabel.set_angle( 0 ) self.systemlabel.set_angle(0)
self.button_box.reorder_child( self.button_icon, 0 ) self.button_box.reorder_child(self.button_icon, 0)
self.button_icon.set_padding( 5, 0 ) self.button_icon.set_padding(5, 0)
elif self.applet.get_orient() == MatePanelApplet.AppletOrient.LEFT: elif self.applet.get_orient() == MatePanelApplet.AppletOrient.LEFT:
tmpbox = Gtk.Box( orientation=Gtk.Orientation.VERTICAL ) tmpbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.systemlabel.set_angle( 270 ) self.systemlabel.set_angle(270)
self.button_box.reorder_child( self.button_icon, 0 ) self.button_box.reorder_child(self.button_icon, 0)
self.button_icon.set_padding( 0, 5 ) self.button_icon.set_padding(0, 5)
elif self.applet.get_orient() == MatePanelApplet.AppletOrient.RIGHT: elif self.applet.get_orient() == MatePanelApplet.AppletOrient.RIGHT:
tmpbox = Gtk.Box( orientation=Gtk.Orientation.VERTICAL ) tmpbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.systemlabel.set_angle( 90 ) self.systemlabel.set_angle(90)
self.button_box.reorder_child( self.button_icon, 1 ) self.button_box.reorder_child(self.button_icon, 1)
self.button_icon.set_padding( 0, 5 ) self.button_icon.set_padding(0, 5)
tmpbox.set_homogeneous( False ) tmpbox.set_homogeneous(False)
# reparent all the hboxes to the new tmpbox # reparent all the hboxes to the new tmpbox
for i in self.button_box: for i in self.button_box:
i.reparent( tmpbox ) i.reparent(tmpbox)
self.button_box.destroy() self.button_box.destroy()
@ -635,20 +635,20 @@ class MenuWin( object ):
# this call makes sure width stays intact # this call makes sure width stays intact
self.updateButton() self.updateButton()
self.applet.add( self.button_box ) self.applet.add(self.button_box)
def updateButton( self ): def updateButton(self):
self.systemlabel.set_text( self.buttonText ) self.systemlabel.set_text(self.buttonText)
self.button_icon.clear() self.button_icon.clear()
self.do_image(self.buttonIcon, False) self.do_image(self.buttonIcon, False)
self.sizeButton() self.sizeButton()
def hotkeyChanged (self, schema, key ): def hotkeyChanged (self, schema, key):
self.hotkeyText = self.settings.get_string( "hot-key" ) self.hotkeyText = self.settings.get_string("hot-key")
self.keybinder.rebind(self.hotkeyText) self.keybinder.rebind(self.hotkeyText)
def sizeButton( self ): def sizeButton(self):
if self.hideIcon: if self.hideIcon:
self.button_icon.hide() self.button_icon.hide()
else: else:
@ -662,20 +662,20 @@ class MenuWin( object ):
sl_scale = self.systemlabel.get_scale_factor() sl_scale = self.systemlabel.get_scale_factor()
if self.applet.get_orient() == MatePanelApplet.AppletOrient.UP or self.applet.get_orient() == MatePanelApplet.AppletOrient.DOWN: if self.applet.get_orient() == MatePanelApplet.AppletOrient.UP or self.applet.get_orient() == MatePanelApplet.AppletOrient.DOWN:
if self.hideIcon: if self.hideIcon:
self.applet.set_size_request( sl_req.width / sl_scale + 2, bi_req.height ) self.applet.set_size_request(sl_req.width / sl_scale + 2, bi_req.height)
else: else:
self.applet.set_size_request( sl_req.width / sl_scale + bi_req.width / bi_scale + 5, bi_req.height ) self.applet.set_size_request(sl_req.width / sl_scale + bi_req.width / bi_scale + 5, bi_req.height)
else: else:
if self.hideIcon: if self.hideIcon:
self.applet.set_size_request( bi_req.width, sl_req.height / sl_scale + 2 ) self.applet.set_size_request(bi_req.width, sl_req.height / sl_scale + 2)
else: else:
self.applet.set_size_request( bi_req.width, sl_req.height / sl_scale + bi_req.height / bi_scale + 5 ) self.applet.set_size_request(bi_req.width, sl_req.height / sl_scale + bi_req.height / bi_scale + 5)
def reloadSettings( self, *args ): def reloadSettings(self, *args):
self.loadSettings() self.loadSettings()
self.updateButton() self.updateButton()
def showAboutDialog( self, action, userdata = None ): def showAboutDialog(self, action, userdata = None):
about = Gtk.AboutDialog() about = Gtk.AboutDialog()
about.set_name("mintMenu") about.set_name("mintMenu")
@ -692,23 +692,23 @@ class MenuWin( object ):
about.set_license(gpl) about.set_license(gpl)
except Exception, detail: except Exception, detail:
print detail print detail
about.set_comments( _("Advanced MATE Menu") ) about.set_comments(_("Advanced MATE Menu"))
# about.set_authors( ["Clement Lefebvre <clem@linuxmint.com>", "Lars-Peter Clausen <lars@laprican.de>"] ) # about.set_authors(["Clement Lefebvre <clem@linuxmint.com>", "Lars-Peter Clausen <lars@laprican.de>"])
about.set_translator_credits(("translator-credits") ) about.set_translator_credits(("translator-credits"))
#about.set_copyright( _("Based on USP from S.Chanderbally") ) # about.set_copyright(_("Based on USP from S.Chanderbally"))
about.set_logo( GdkPixbuf.Pixbuf.new_from_file("/usr/lib/linuxmint/mintMenu/icon.svg") ) about.set_logo(GdkPixbuf.Pixbuf.new_from_file("/usr/lib/linuxmint/mintMenu/icon.svg"))
about.connect( "response", lambda dialog, r: dialog.destroy() ) about.connect("response", lambda dialog, r: dialog.destroy())
about.show() about.show()
def showPreferences( self, action, userdata = None ): def showPreferences(self, action, userdata = None):
# Execute( "mateconf-editor /apps/mintMenu" ) # Execute("mateconf-editor /apps/mintMenu")
Execute( os.path.join( PATH, "mintMenuConfig.py" ) ) Execute(os.path.join(PATH, "mintMenuConfig.py"))
def showMenuEditor( self, action, userdata = None): def showMenuEditor(self, action, userdata = None):
Execute( "mozo" ) Execute("mozo")
def showMenu( self, widget=None, event=None ): def showMenu(self, widget=None, event=None):
if event == None or event.button == 1: if event == None or event.button == 1:
self.toggleMenu() self.toggleMenu()
# show right click menu # show right click menu
@ -718,7 +718,7 @@ class MenuWin( object ):
elif event.button == 2: elif event.button == 2:
self.mainwin.hide() self.mainwin.hide()
def toggleMenu( self ): def toggleMenu(self):
if self.applet.get_style_context().get_state() & Gtk.StateFlags.SELECTED: if self.applet.get_style_context().get_state() & Gtk.StateFlags.SELECTED:
self.mainwin.hide() self.mainwin.hide()
else: else:
@ -726,10 +726,10 @@ class MenuWin( object ):
self.mainwin.show() self.mainwin.show()
self.wakePlugins() self.wakePlugins()
def wakePlugins( self ): def wakePlugins(self):
self.mainwin.wakePlugins() self.mainwin.wakePlugins()
def positionMenu( self ): def positionMenu(self):
# Get our own dimensions & position # Get our own dimensions & position
ourWidth = self.mainwin.window.get_size()[0] ourWidth = self.mainwin.window.get_size()[0]
ourHeight = self.mainwin.window.get_size()[1] + self.mainwin.offset ourHeight = self.mainwin.window.get_size()[1] + self.mainwin.offset
@ -796,7 +796,7 @@ class MenuWin( object ):
newY -= entryHeight newY -= entryHeight
# Move window # Move window
self.mainwin.window.move( newX, newY ) self.mainwin.window.move(newX, newY)
# this callback is to create a context menu # this callback is to create a context menu
def create_menu(self): def create_menu(self):
@ -815,7 +815,7 @@ class MenuWin( object ):
action_group.add_action(action) action_group.add_action(action)
action_group.set_translation_domain ("mintmenu") action_group.set_translation_domain ("mintmenu")
xml = os.path.join( os.path.join( os.path.dirname( __file__ )), "popup.xml" ) xml = os.path.join(os.path.join(os.path.dirname(__file__)), "popup.xml")
self.applet.setup_menu_from_file(xml, action_group) self.applet.setup_menu_from_file(xml, action_group)
def detect_desktop_environment (self): def detect_desktop_environment (self):
@ -834,8 +834,8 @@ class MenuWin( object ):
except Exception, detail: except Exception, detail:
print detail print detail
def applet_factory( applet, iid, data ): def applet_factory(applet, iid, data):
MenuWin( applet, iid ) MenuWin(applet, iid)
applet.show() applet.show()
return True return True

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,6 @@
#!/usr/bin/python2 #!/usr/bin/python2
import os.path import os.path
import re
import shutil import shutil
import xdg.DesktopEntry import xdg.DesktopEntry
@ -12,7 +11,6 @@ gi.require_version('MateDesktop', '2.0')
from gi.repository import Gtk, Gdk, GLib from gi.repository import Gtk, Gdk, GLib
from gi.repository import Pango from gi.repository import Pango
from gi.repository import GObject from gi.repository import GObject
from gi.repository import MateDesktop
from plugins.execute import Execute from plugins.execute import Execute
from plugins.filemonitor import monitor as filemonitor from plugins.filemonitor import monitor as filemonitor
@ -21,25 +19,25 @@ from plugins.filemonitor import monitor as filemonitor
class IconManager(GObject.GObject): class IconManager(GObject.GObject):
__gsignals__ = { __gsignals__ = {
"changed" : (GObject.SignalFlags.RUN_LAST, None, () ) "changed" : (GObject.SignalFlags.RUN_LAST, None, ())
} }
def __init__( self ): def __init__(self):
GObject.GObject.__init__( self ) GObject.GObject.__init__(self)
self.icons = { } self.icons = {}
self.count = 0 self.count = 0
# Some apps don't put a default icon in the default theme folder, so we will search all themes # Some apps don't put a default icon in the default theme folder, so we will search all themes
def createTheme( d ): def createTheme(d):
theme = Gtk.IconTheme() theme = Gtk.IconTheme()
theme.set_custom_theme( d ) theme.set_custom_theme(d)
return theme return theme
# This takes to much time and there are only a very few applications that use icons from different themes # 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 ) ) ] ) #self.themes = map( createTheme, [d for d in os.listdir("/usr/share/icons") if os.path.isdir(os.path.join("/usr/share/icons", d))])
self.defaultTheme = Gtk.IconTheme.get_default() self.defaultTheme = Gtk.IconTheme.get_default()
defaultKdeTheme = createTheme( "kde.default" ) defaultKdeTheme = createTheme("kde.default")
# Setup and clean up the temp icon dir # Setup and clean up the temp icon dir
configDir = GLib.get_user_config_dir() configDir = GLib.get_user_config_dir()
@ -53,16 +51,16 @@ class IconManager(GObject.GObject):
self.defaultTheme.append_search_path(self.iconDir) self.defaultTheme.append_search_path(self.iconDir)
# Themes with the same content as the default them aren't needed # 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() ] #self.themes = [theme for theme in self.themes if theme.list_icons() != defaultTheme.list_icons()]
self.themes = [ self.defaultTheme, defaultKdeTheme ] self.themes = [self.defaultTheme, defaultKdeTheme]
# Listen for changes in the themes # Listen for changes in the themes
for theme in self.themes: for theme in self.themes:
theme.connect("changed", self.themeChanged ) theme.connect("changed", self.themeChanged)
def getIcon( self, iconName, iconSize ): def getIcon(self, iconName, iconSize):
if not iconName: if not iconName:
return None return None
@ -71,11 +69,11 @@ class IconManager(GObject.GObject):
iconFileName = "" iconFileName = ""
realIconName = "" realIconName = ""
needTempFile = False needTempFile = False
#[ iconWidth, iconHeight ] = self.getIconSize( iconSize ) #[iconWidth, iconHeight] = self.getIconSize(iconSize)
if iconSize <= 0: if iconSize <= 0:
return None return None
elif os.path.isabs( iconName ): elif os.path.isabs(iconName):
iconFileName = iconName iconFileName = iconName
needTempFile = True needTempFile = True
else: else:
@ -84,7 +82,7 @@ class IconManager(GObject.GObject):
else: else:
realIconName = iconName realIconName = iconName
if iconFileName and needTempFile and os.path.exists( iconFileName ): if iconFileName and needTempFile and os.path.exists(iconFileName):
tmpIconName = iconFileName.replace("/", "-") tmpIconName = iconFileName.replace("/", "-")
realIconName = tmpIconName[:-4] realIconName = tmpIconName[:-4]
if not os.path.exists(os.path.join(self.iconDir, tmpIconName)): if not os.path.exists(os.path.join(self.iconDir, tmpIconName)):
@ -109,74 +107,74 @@ class IconManager(GObject.GObject):
print "Exception " + e.__class__.__name__ + ": " + e.message print "Exception " + e.__class__.__name__ + ": " + e.message
return None return None
def themeChanged( self, theme ): def themeChanged(self, theme):
self.emit( "changed" ) self.emit("changed")
GObject.type_register(IconManager) GObject.type_register(IconManager)
class easyButton( Gtk.Button ): class easyButton(Gtk.Button):
def __init__( self, iconName, iconSize, labels = None, buttonWidth = -1, buttonHeight = -1 ): def __init__(self, iconName, iconSize, labels = None, buttonWidth = -1, buttonHeight = -1):
GObject.GObject.__init__( self ) GObject.GObject.__init__(self)
self.connections = [ ] self.connections = []
self.iconName = iconName self.iconName = iconName
self.iconSize = iconSize self.iconSize = iconSize
self.showIcon = True self.showIcon = True
self.set_relief( Gtk.ReliefStyle.NONE ) self.set_relief(Gtk.ReliefStyle.NONE)
self.set_size_request( buttonWidth, buttonHeight ) self.set_size_request(buttonWidth, buttonHeight)
Align1 = Gtk.Alignment.new( 0, 0.5, 1.0, 0 ) Align1 = Gtk.Alignment.new(0, 0.5, 1.0, 0)
HBox1 = Gtk.Box( orientation=Gtk.Orientation.HORIZONTAL ) HBox1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
self.labelBox = Gtk.Box( orientation=Gtk.Orientation.VERTICAL, spacing=2 ) self.labelBox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
self.buttonImage = Gtk.Image() self.buttonImage = Gtk.Image()
icon = self.getIcon( self.iconSize ) icon = self.getIcon(self.iconSize)
if icon: if icon:
self.buttonImage = icon self.buttonImage = icon
else: else:
#[ iW, iH ] = iconManager.getIconSize( self.iconSize ) #[iW, iH] = iconManager.getIconSize(self.iconSize)
self.buttonImage.set_size_request( self.iconSize, self.iconSize ) self.buttonImage.set_size_request(self.iconSize, self.iconSize )
self.image_box = Gtk.Box( orientation=Gtk.Orientation.HORIZONTAL ) self.image_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
self.image_box.pack_start(self.buttonImage, False, False, 5) self.image_box.pack_start(self.buttonImage, False, False, 5)
self.image_box.show_all() self.image_box.show_all()
HBox1.pack_start( self.image_box, False, False, 0 ) HBox1.pack_start(self.image_box, False, False, 0)
if labels: if labels:
for label in labels: for label in labels:
if isinstance( label, basestring ): if isinstance(label, basestring):
self.addLabel( label ) self.addLabel(label)
elif isinstance( label, list ): elif isinstance(label, list):
self.addLabel( label[0], label[1] ) self.addLabel(label[0], label[1])
self.labelBox.show() self.labelBox.show()
HBox1.pack_start( self.labelBox , True, True, 0) HBox1.pack_start(self.labelBox , True, True, 0)
HBox1.show() HBox1.show()
Align1.add( HBox1 ) Align1.add(HBox1)
Align1.show() Align1.show()
self.add( Align1 ) self.add(Align1)
self.connectSelf( "destroy", self.onDestroy ) self.connectSelf("destroy", self.onDestroy)
self.connect( "released", self.onRelease ) self.connect("released", self.onRelease)
# Reload icons when the theme changed # Reload icons when the theme changed
self.themeChangedHandlerId = iconManager.connect("changed", self.themeChanged ) self.themeChangedHandlerId = iconManager.connect("changed", self.themeChanged)
def connectSelf( self, event, callback ): def connectSelf(self, event, callback):
self.connections.append( self.connect( event, callback ) ) self.connections.append(self.connect(event, callback))
def onRelease( self, widget ): def onRelease(self, widget):
widget.get_style_context().set_state( Gtk.StateFlags.NORMAL ) widget.get_style_context().set_state(Gtk.StateFlags.NORMAL)
def onDestroy( self, widget ): def onDestroy(self, widget):
self.buttonImage.clear() self.buttonImage.clear()
iconManager.disconnect( self.themeChangedHandlerId ) iconManager.disconnect(self.themeChangedHandlerId)
for connection in self.connections: for connection in self.connections:
self.disconnect( connection ) self.disconnect(connection)
del self.connections del self.connections
def addLabel( self, text, styles = None ): def addLabel(self, text, styles = None):
label = Gtk.Label() label = Gtk.Label()
if "<b>" in text or "<span" in text: if "<b>" in text or "<span" in text:
label.set_markup(text.replace('&', '&amp;')) # don't remove our pango label.set_markup(text.replace('&', '&amp;')) # don't remove our pango
@ -186,104 +184,104 @@ class easyButton( Gtk.Button ):
if styles: if styles:
labelStyle = Pango.AttrList() labelStyle = Pango.AttrList()
for attr in styles: for attr in styles:
labelStyle.insert( attr ) labelStyle.insert(attr)
label.set_attributes( labelStyle ) label.set_attributes(labelStyle)
label.set_ellipsize( Pango.EllipsizeMode.END ) label.set_ellipsize(Pango.EllipsizeMode.END)
label.set_alignment( 0.0, 1.0 ) label.set_alignment(0.0, 1.0)
label.set_max_width_chars(0) label.set_max_width_chars(0)
label.show() label.show()
self.labelBox.pack_start( label , True, True, 0) self.labelBox.pack_start(label , True, True, 0)
def getIcon ( self, iconSize ): def getIcon(self, iconSize):
if not self.iconName: if not self.iconName:
return None return None
icon = iconManager.getIcon( self.iconName, iconSize ) icon = iconManager.getIcon(self.iconName, iconSize)
if icon is None: if icon is None:
icon = iconManager.getIcon( "application-default-icon", iconSize ) icon = iconManager.getIcon("application-default-icon", iconSize)
return icon return icon
def setIcon ( self, iconName ): def setIcon(self, iconName):
self.iconName = iconName self.iconName = iconName
self.iconChanged() self.iconChanged()
# IconTheme changed, setup new button icons # IconTheme changed, setup new button icons
def themeChanged( self, theme ): def themeChanged(self, theme):
self.iconChanged() self.iconChanged()
def iconChanged( self ): def iconChanged(self):
icon = self.getIcon( self.iconSize ) icon = self.getIcon(self.iconSize)
self.buttonImage.destroy() self.buttonImage.destroy()
if icon: if icon:
self.buttonImage = icon self.buttonImage = icon
self.image_box.pack_start(self.buttonImage, False, False, 5) self.image_box.pack_start(self.buttonImage, False, False, 5)
self.image_box.show_all() self.image_box.show_all()
else: else:
#[iW, iH ] = iconManager.getIconSize( self.iconSize ) #[iW, iH] = iconManager.getIconSize(self.iconSize)
self.buttonImage.set_size_request( self.iconSize, self.iconSize ) self.buttonImage.set_size_request(self.iconSize, self.iconSize )
def setIconSize( self, size ): def setIconSize(self, size):
self.iconSize = size self.iconSize = size
icon = self.getIcon( self.iconSize ) icon = self.getIcon(self.iconSize)
self.buttonImage.destroy() self.buttonImage.destroy()
if icon: if icon:
self.buttonImage = icon self.buttonImage = icon
self.image_box.pack_start(self.buttonImage, False, False, 5) self.image_box.pack_start(self.buttonImage, False, False, 5)
self.image_box.show_all() self.image_box.show_all()
elif self.iconSize: elif self.iconSize:
#[ iW, iH ] = iconManager.getIconSize( self.iconSize ) #[iW, iH] = iconManager.getIconSize(self.iconSize)
self.buttonImage.set_size_request( self.iconSize, self.iconSize ) self.buttonImage.set_size_request(self.iconSize, self.iconSize )
class ApplicationLauncher( easyButton ): class ApplicationLauncher(easyButton):
def __init__( self, desktopFile, iconSize): def __init__(self, desktopFile, iconSize):
if isinstance( desktopFile, xdg.Menu.MenuEntry ): if isinstance(desktopFile, xdg.Menu.MenuEntry):
desktopItem = desktopFile.DesktopEntry desktopItem = desktopFile.DesktopEntry
desktopFile = desktopItem.filename desktopFile = desktopItem.filename
self.appDirs = desktopFile.AppDirs self.appDirs = desktopFile.AppDirs
elif isinstance( desktopFile, xdg.Menu.DesktopEntry ): elif isinstance(desktopFile, xdg.Menu.DesktopEntry):
desktopItem = desktopFile desktopItem = desktopFile
desktopFile = desktopItem.filename desktopFile = desktopItem.filename
self.appDirs = [ os.path.dirname( desktopItem.filename ) ] self.appDirs = [os.path.dirname(desktopItem.filename)]
else: else:
# XXX: All menu entries on LM19.1 end here # XXX: All menu entries on LM19.1 end here
desktopItem = xdg.DesktopEntry.DesktopEntry( desktopFile ) desktopItem = xdg.DesktopEntry.DesktopEntry(desktopFile)
self.appDirs = [ os.path.dirname( desktopFile ) ] self.appDirs = [os.path.dirname(desktopFile)]
self.desktopFile = desktopFile self.desktopFile = desktopFile
self.startupMonitorId = 0 self.startupMonitorId = 0
self.loadDesktopEntry( desktopItem ) self.loadDesktopEntry(desktopItem)
self.desktopEntryMonitors = [] self.desktopEntryMonitors = []
base = os.path.basename( self.desktopFile ) base = os.path.basename(self.desktopFile)
for dir in self.appDirs: for dir in self.appDirs:
self.desktopEntryMonitors.append( filemonitor.addMonitor( os.path.join(dir, base) , self.desktopEntryFileChangedCallback ) ) self.desktopEntryMonitors.append(filemonitor.addMonitor(os.path.join(dir, base) , self.desktopEntryFileChangedCallback))
easyButton.__init__( self, self.appIconName, iconSize ) easyButton.__init__(self, self.appIconName, iconSize)
self.setupLabels() self.setupLabels()
# Drag and Drop # Drag and Drop
self.connectSelf( "drag-data-get", self.dragDataGet ) self.connectSelf("drag-data-get", self.dragDataGet)
targets = ( Gtk.TargetEntry.new( "text/plain", 0, 100 ), Gtk.TargetEntry.new( "text/uri-list", 0, 101 ) ) 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(Gdk.ModifierType.BUTTON1_MASK, targets, Gdk.DragAction.COPY)
icon = self.getIcon( Gtk.IconSize.DND ) icon = self.getIcon(Gtk.IconSize.DND)
if icon: if icon:
iconName, s = icon.get_icon_name() iconName, s = icon.get_icon_name()
self.drag_source_set_icon_name( iconName ) self.drag_source_set_icon_name(iconName)
self.connectSelf( "focus-in-event", self.onFocusIn ) self.connectSelf("focus-in-event", self.onFocusIn)
self.connectSelf( "focus-out-event", self.onFocusOut ) self.connectSelf("focus-out-event", self.onFocusOut)
self.connectSelf( "clicked", self.execute ) self.connectSelf("clicked", self.execute)
def loadDesktopEntry( self, desktopItem ): def loadDesktopEntry(self, desktopItem):
try: try:
self.appName = self.strip_accents(desktopItem.getName()) self.appName = self.strip_accents(desktopItem.getName())
self.appGenericName = self.strip_accents(desktopItem.getGenericName()) self.appGenericName = self.strip_accents(desktopItem.getGenericName())
@ -291,7 +289,7 @@ class ApplicationLauncher( easyButton ):
self.appExec = self.strip_accents(desktopItem.getExec().replace('\\\\', '\\')) self.appExec = self.strip_accents(desktopItem.getExec().replace('\\\\', '\\'))
self.appIconName = desktopItem.getIcon() self.appIconName = desktopItem.getIcon()
self.appCategories = desktopItem.getCategories() self.appCategories = desktopItem.getCategories()
self.appMateDocPath = desktopItem.get( "X-MATE-DocPath" ) or "" self.appMateDocPath = desktopItem.get("X-MATE-DocPath") or ""
self.useTerminal = desktopItem.getTerminal() self.useTerminal = desktopItem.getTerminal()
self.appPath = desktopItem.getPath() self.appPath = desktopItem.getPath()
@ -302,12 +300,12 @@ class ApplicationLauncher( easyButton ):
self.appGenericName = self.appGenericName.strip() self.appGenericName = self.appGenericName.strip()
self.appComment = self.appComment.strip() self.appComment = self.appComment.strip()
basename = os.path.basename( self.desktopFile ) basename = os.path.basename(self.desktopFile)
self.startupFilePath = os.path.join( os.path.expanduser("~"), ".config", "autostart", basename ) self.startupFilePath = os.path.join(os.path.expanduser("~"), ".config", "autostart", basename)
if self.startupMonitorId: if self.startupMonitorId:
filemonitor.removeMonitor( self.startupMonitorId ) filemonitor.removeMonitor(self.startupMonitorId )
if os.path.exists (self.startupFilePath): if os.path.exists(self.startupFilePath):
self.startupMonitorId = filemonitor.addMonitor( self.startupFilePath, self.startupFileChanged ) self.startupMonitorId = filemonitor.addMonitor(self.startupFilePath, self.startupFileChanged)
except Exception, e: except Exception, e:
print e print e
@ -320,16 +318,16 @@ class ApplicationLauncher( easyButton ):
self.appDocPath = "" self.appDocPath = ""
self.startupMonitorId = 0 self.startupMonitorId = 0
def onFocusIn( self, widget, event ): def onFocusIn(self, widget, event):
self.set_relief( Gtk.ReliefStyle.HALF ) self.set_relief(Gtk.ReliefStyle.HALF)
def onFocusOut( self, widget, event ): def onFocusOut(self, widget, event):
self.set_relief( Gtk.ReliefStyle.NONE ) self.set_relief(Gtk.ReliefStyle.NONE)
def setupLabels( self ): def setupLabels(self):
self.addLabel( self.appName ) self.addLabel(self.appName)
def filterText( self, text ): def filterText(self, text):
keywords = text.lower().split() keywords = text.lower().split()
appName = self.appName.lower() appName = self.appName.lower()
appGenericName = self.appGenericName.lower() appGenericName = self.appGenericName.lower()
@ -337,7 +335,7 @@ class ApplicationLauncher( easyButton ):
appExec = self.appExec.lower() appExec = self.appExec.lower()
for keyword in keywords: for keyword in keywords:
keyw = self.strip_accents(keyword) 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: if keyw != "" and appName.find(keyw) == -1 and appGenericName.find(keyw) == -1 and appComment.find(keyw) == -1 and appExec.find(keyw) == -1:
self.hide() self.hide()
return False return False
@ -353,23 +351,23 @@ class ApplicationLauncher( easyButton ):
pass pass
return value return value
def getTooltip( self ): def getTooltip(self):
tooltip = self.appName tooltip = self.appName
if self.appComment != "" and self.appComment != self.appName: if self.appComment != "" and self.appComment != self.appName:
tooltip = tooltip + "\n" + self.appComment tooltip = tooltip + "\n" + self.appComment
return tooltip return tooltip
def dragDataGet( self, widget, context, selection, targetType, eventTime ): def dragDataGet(self, widget, context, selection, targetType, eventTime):
if targetType == 100: # text/plain if targetType == 100: # text/plain
selection.set_text( "'" + self.desktopFile + "'", -1 ) selection.set_text("'" + self.desktopFile + "'", -1)
elif targetType == 101: # text/uri-list elif targetType == 101: # text/uri-list
if self.desktopFile[0:7] == "file://": if self.desktopFile[0:7] == "file://":
selection.set_uris( [ self.desktopFile ] ) selection.set_uris([self.desktopFile])
else: else:
selection.set_uris( [ "file://" + self.desktopFile ] ) selection.set_uris(["file://" + self.desktopFile])
def execute( self, *args ): def execute(self, *args):
if self.appExec: if self.appExec:
if self.useTerminal: if self.useTerminal:
cmd = "x-terminal-emulator -e \"" + self.appExec + "\"" cmd = "x-terminal-emulator -e \"" + self.appExec + "\""
@ -379,72 +377,72 @@ class ApplicationLauncher( easyButton ):
else: else:
Execute(None, desktopFile=self.desktopFile) Execute(None, desktopFile=self.desktopFile)
def uninstall (self, *args ): def uninstall(self, *args):
Execute("mint-remove-application " + self.desktopFile) Execute("mint-remove-application " + self.desktopFile)
# IconTheme changed, setup new icons for button and drag 'n drop # IconTheme changed, setup new icons for button and drag 'n drop
def iconChanged( self ): def iconChanged(self):
easyButton.iconChanged( self ) easyButton.iconChanged(self)
icon = self.getIcon( Gtk.IconSize.DND ) icon = self.getIcon(Gtk.IconSize.DND)
if icon: if icon:
iconName, size = icon.get_icon_name() iconName, size = icon.get_icon_name()
self.drag_source_set_icon_name( iconName ) self.drag_source_set_icon_name(iconName)
def startupFileChanged( self, *args ): def startupFileChanged(self, *args):
self.inStartup = os.path.exists( self.startupFilePath ) self.inStartup = os.path.exists(self.startupFilePath)
# def addToStartup( self ): # def addToStartup(self):
# startupDir = os.path.join( os.path.expanduser("~"), ".config", "autostart" ) # startupDir = os.path.join(os.path.expanduser("~"), ".config", "autostart")
# if not os.path.exists( startupDir ): # if not os.path.exists(startupDir):
# os.makedirs( startupDir ) # os.makedirs(startupDir)
# shutil.copyfile( self.desktopFile, self.startupFilePath ) # shutil.copyfile(self.desktopFile, self.startupFilePath)
# # Remove %u, etc. from Exec entry, because MATE will not replace them when it starts the app # # Remove %u, etc. from Exec entry, because MATE will not replace them when it starts the app
# item = MateDesktop.DesktopItem.new_from_uri(self.startupFilePath, MateDesktop.DesktopItemLoadFlags.ONLY_IF_EXISTS) # item = MateDesktop.DesktopItem.new_from_uri(self.startupFilePath, MateDesktop.DesktopItemLoadFlags.ONLY_IF_EXISTS)
# if item: # if item:
# r = re.compile("%[A-Za-z]"); # r = re.compile("%[A-Za-z]");
# tmp = r.sub("", item.get_string( MateDesktop.DESKTOP_ITEM_EXEC ) ).strip() # tmp = r.sub("", item.get_string(MateDesktop.DESKTOP_ITEM_EXEC)).strip()
# item.set_string( MateDesktop.DESKTOP_ITEM_EXEC, tmp ) # item.set_string(MateDesktop.DESKTOP_ITEM_EXEC, tmp)
# item.save( self.startupFilePath, 0 ) # item.save(self.startupFilePath, 0)
# def removeFromStartup( self ): # def removeFromStartup(self):
# if os.path.exists( self.startupFilePath ): # if os.path.exists(self.startupFilePath):
# os.remove( self.startupFilePath ) # os.remove(self.startupFilePath)
# def addToFavourites( self ): # def addToFavourites(self):
# favouritesDir = os.path.join( os.path.expanduser("~"), ".linuxmint", "mintMenu", "applications" ) # favouritesDir = os.path.join(os.path.expanduser("~"), ".linuxmint", "mintMenu", "applications")
# if not os.path.exists( favouritesDir ): # if not os.path.exists(favouritesDir):
# os.makedirs( favouritesDir ) # os.makedirs(favouritesDir)
# shutil.copyfile( self.desktopFile, self.favouritesFilePath ) # shutil.copyfile(self.desktopFile, self.favouritesFilePath)
# def removeFromFavourites( self ): # def removeFromFavourites(self):
# if os.path.exists( self.favouritesFilePath ): # if os.path.exists(self.favouritesFilePath):
# os.remove( self.favouritesFilePath ) # os.remove(self.favouritesFilePath)
# def isInStartup( self ): # def isInStartup(self):
# #return self.inStartup # #return self.inStartup
# return os.path.exists( self.startupFilePath ) # return os.path.exists(self.startupFilePath)
def onDestroy( self, widget ): def onDestroy(self, widget):
easyButton.onDestroy( self, widget ) easyButton.onDestroy(self, widget)
if self.startupMonitorId: if self.startupMonitorId:
filemonitor.removeMonitor( self.startupMonitorId ) filemonitor.removeMonitor(self.startupMonitorId)
for id in self.desktopEntryMonitors: for id in self.desktopEntryMonitors:
filemonitor.removeMonitor( id ) filemonitor.removeMonitor(id)
def desktopEntryFileChangedCallback (self): def desktopEntryFileChangedCallback(self):
GLib.timeout_add(200, self.onDesktopEntryFileChanged) GLib.timeout_add(200, self.onDesktopEntryFileChanged)
def onDesktopEntryFileChanged( self ): def onDesktopEntryFileChanged(self):
exists = False exists = False
base = os.path.basename( self.desktopFile ) base = os.path.basename(self.desktopFile)
for dir in self.appDirs: for dir in self.appDirs:
if os.path.exists( os.path.join( dir, base ) ): if os.path.exists(os.path.join(dir, base)):
# print os.path.join( dir, base ), self.desktopFile # print os.path.join(dir, base), self.desktopFile
self.loadDesktopEntry( xdg.DesktopEntry.DesktopEntry( os.path.join( dir, base ) ) ) self.loadDesktopEntry(xdg.DesktopEntry.DesktopEntry(os.path.join(dir, base)))
for child in self.labelBox: for child in self.labelBox:
child.destroy() child.destroy()
@ -460,29 +458,29 @@ class ApplicationLauncher( easyButton ):
self.destroy() self.destroy()
return False return False
class MenuApplicationLauncher( ApplicationLauncher ): class MenuApplicationLauncher(ApplicationLauncher):
def __init__( self, desktopFile, iconSize, category, showComment, highlight=False ): def __init__(self, desktopFile, iconSize, category, showComment, highlight=False):
self.showComment = showComment self.showComment = showComment
self.appCategory = category self.appCategory = category
self.highlight = highlight self.highlight = highlight
ApplicationLauncher.__init__( self, desktopFile, iconSize ) ApplicationLauncher.__init__(self, desktopFile, iconSize)
def filterCategory( self, category ): def filterCategory(self, category):
if self.appCategory == category or category == "": if self.appCategory == category or category == "":
self.show() self.show()
else: else:
self.hide() self.hide()
def setupLabels( self ): def setupLabels(self):
appName = self.appName appName = self.appName
appComment = self.appComment appComment = self.appComment
if self.highlight: if self.highlight:
try: try:
#color = self.labelBox.get_style_context().get_color( Gtk.StateFlags.SELECTED ).to_string() #color = self.labelBox.get_style_context().get_color(Gtk.StateFlags.SELECTED).to_string()
#if len(color) > 0 and color[0] == "#": #if len(color) > 0 and color[0] == "#":
#appName = "<span foreground=\"%s\"><b>%s</b></span>" % (color, appName); #appName = "<span foreground=\"%s\"><b>%s</b></span>" % (color, appName);
#appComment = "<span foreground=\"%s\"><b>%s</b></span>" % (color, appComment); #appComment = "<span foreground=\"%s\"><b>%s</b></span>" % (color, appComment);
@ -491,59 +489,59 @@ class MenuApplicationLauncher( ApplicationLauncher ):
#else: #else:
#appName = "<b>%s</b>" % (appName); #appName = "<b>%s</b>" % (appName);
#appComment = "<b>%s</b>" % (appComment); #appComment = "<b>%s</b>" % (appComment);
appName = "<b>%s</b>" % (appName); appName = "<b>%s</b>" % appName
appComment = "<b>%s</b>" % (appComment); appComment = "<b>%s</b>" % appComment
except Exception, detail: except Exception, detail:
print detail print detail
pass pass
if self.showComment and self.appComment != "": if self.showComment and self.appComment != "":
if self.iconSize <= 2: if self.iconSize <= 2:
self.addLabel( '<span size="small">%s</span>' % appName) self.addLabel('<span size="small">%s</span>' % appName)
self.addLabel( '<span size="x-small">%s</span>' % appComment) self.addLabel('<span size="x-small">%s</span>' % appComment)
else: else:
self.addLabel( appName ) self.addLabel(appName)
self.addLabel( '<span size="small">%s</span>' % appComment) self.addLabel('<span size="small">%s</span>' % appComment)
else: else:
self.addLabel( appName ) self.addLabel(appName)
def execute( self, *args ): def execute(self, *args):
self.highlight = False self.highlight = False
for child in self.labelBox: for child in self.labelBox:
child.destroy() child.destroy()
self.setupLabels() self.setupLabels()
return super(MenuApplicationLauncher, self).execute(*args) return super(MenuApplicationLauncher, self).execute(*args)
def setShowComment( self, showComment ): def setShowComment(self, showComment):
self.showComment = showComment self.showComment = showComment
for child in self.labelBox: for child in self.labelBox:
child.destroy() child.destroy()
self.setupLabels() self.setupLabels()
class FavApplicationLauncher( ApplicationLauncher ): class FavApplicationLauncher(ApplicationLauncher):
def __init__( self, desktopFile, iconSize, swapGeneric = False ): def __init__(self, desktopFile, iconSize, swapGeneric = False):
self.swapGeneric = swapGeneric self.swapGeneric = swapGeneric
ApplicationLauncher.__init__( self, desktopFile, iconSize ) ApplicationLauncher.__init__(self, desktopFile, iconSize)
def setupLabels( self ): def setupLabels(self):
if self.appGenericName: if self.appGenericName:
if self.swapGeneric: if self.swapGeneric:
self.addLabel( '<span weight="bold">%s</span>' % self.appName ) self.addLabel('<span weight="bold">%s</span>' % self.appName)
self.addLabel( self.appGenericName ) self.addLabel(self.appGenericName)
else: else:
self.addLabel( '<span weight="bold">%s</span>' % self.appGenericName ) self.addLabel('<span weight="bold">%s</span>' % self.appGenericName)
self.addLabel( self.appName ) self.addLabel(self.appName)
else: else:
self.addLabel( '<span weight="bold">%s</span>' % self.appName ) self.addLabel('<span weight="bold">%s</span>' % self.appName)
if self.appComment != "": if self.appComment != "":
self.addLabel( self.appComment ) self.addLabel(self.appComment)
else: else:
self.addLabel ( "" ) self.addLabel("")
def setSwapGeneric( self, swapGeneric ): def setSwapGeneric(self, swapGeneric):
self.swapGeneric = swapGeneric self.swapGeneric = swapGeneric
for child in self.labelBox: for child in self.labelBox:
child.destroy() child.destroy()
@ -551,10 +549,10 @@ class FavApplicationLauncher( ApplicationLauncher ):
self.setupLabels() self.setupLabels()
class CategoryButton( easyButton ): class CategoryButton(easyButton):
def __init__( self, iconName, iconSize, labels , f ): def __init__(self, iconName, iconSize, labels , f):
easyButton.__init__( self, iconName, iconSize, labels ) easyButton.__init__(self, iconName, iconSize, labels)
self.filter = f self.filter = f

View File

@ -2,6 +2,7 @@
import urllib import urllib
def GetFilePath(uri): def GetFilePath(uri):
path = urllib.url2pathname(uri) # escape special chars path = urllib.url2pathname(uri) # escape special chars
path = path.strip('\r\n\x00') # remove \r\n and NULL path = path.strip('\r\n\x00') # remove \r\n and NULL

View File

@ -1,92 +1,92 @@
#!/usr/bin/python2 #!/usr/bin/python2
from gi.repository import Gio from gi.repository import Gio
class EasyGSettings: class EasyGSettings:
def __init__( self, schema = None ): def __init__(self, schema = None):
self.schema = schema self.schema = schema
self.settings = Gio.Settings.new(self.schema) self.settings = Gio.Settings.new(self.schema)
self.handlerIds = [ ] self.handlerIds = []
def get( self, type, key ): def get(self, type, key):
if type == "bool": if type == "bool":
return self.settings.get_boolean( key ) return self.settings.get_boolean(key)
if type == "string": if type == "string":
return self.settings.get_string( key ) return self.settings.get_string(key)
if type == "int": if type == "int":
return self.settings.get_int( key ) return self.settings.get_int(key)
if type == "color": if type == "color":
color = self.settings.get_string( key ) color = self.settings.get_string(key)
if not self.evalColor( color ): if not self.evalColor(color):
self.settings.set_string(key, "#ffffff") self.settings.set_string(key, "#ffffff")
return "#ffffff" return "#ffffff"
return color return color
t = type.split("-") t = type.split("-")
if len(t) == 2 and t[0] == "list": if len(t) == 2 and t[0] == "list":
return self.settings.get_strv( key ) return self.settings.get_strv(key)
return self.settings.get( key ) return self.settings.get(key)
def set( self, type, key, value ): def set(self, type, key, value):
if type == "bool": if type == "bool":
return self.settings.set_boolean( key, value ) return self.settings.set_boolean(key, value)
if type == "string": if type == "string":
return self.settings.set_string( key, value ) return self.settings.set_string(key, value)
if type == "int": if type == "int":
return self.settings.set_int( key, value ) return self.settings.set_int(key, value)
if type == "color": if type == "color":
if self.evalColor( value ): if self.evalColor(value):
return self.settings.set_string( key, value ) return self.settings.set_string(key, value)
else: else:
return self.settings.set_string( key, "#ffffff" ) return self.settings.set_string(key, "#ffffff")
t = type.split("-") t = type.split("-")
if len(t) == 2 and t[0] == "list": if len(t) == 2 and t[0] == "list":
return self.settings.set_strv( key, value ) return self.settings.set_strv(key, value)
return self.settings.set( key, value ) return self.settings.set(key, value)
def notifyAdd( self, key, callback, args = None ): def notifyAdd(self, key, callback, args = None):
handlerId = self.settings.connect("changed::"+key, callback, args) handlerId = self.settings.connect("changed::"+key, callback, args)
self.handlerIds.append( handlerId ) self.handlerIds.append(handlerId)
return handlerId return handlerId
def notifyRemove( self, handlerId ): def notifyRemove(self, handlerId):
return self.settings.disconnect(handlerId) return self.settings.disconnect(handlerId)
def notifyRemoveAll( self ): def notifyRemoveAll(self):
for handlerId in self.handlerIds: for handlerId in self.handlerIds:
self.settings.disconnect( handlerId ) self.settings.disconnect(handlerId)
def evalColor(self, colorToTest ): def evalColor(self, colorToTest):
if colorToTest[0] != '#' or len( colorToTest ) != 7: if colorToTest[0] != '#' or len(colorToTest) != 7:
return False return False
for i in colorToTest[1:]: for i in colorToTest[1:]:
if i not in ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: if i not in ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
return False return False
return True return True
def bindGSettingsEntryToVar( self, type, key, obj, varName ): def bindGSettingsEntryToVar(self, type, key, obj, varName):
return self.notifyAdd( key, self.setVar, ( type, obj, varName ) ) return self.notifyAdd(key, self.setVar, (type, obj, varName))
def setVar( self, settings, key, args ): def setVar(self, settings, key, args):
type, obj, varName = args type, obj, varName = args
if type == "string": if type == "string":
setattr( obj, varName, settings.get_string(key) ) setattr(obj, varName, settings.get_string(key))
elif type == "int": elif type == "int":
setattr( obj, varName, settings.get_int(key) ) setattr(obj, varName, settings.get_int(key))
elif type == "float": elif type == "float":
setattr( obj, varName, settings.get_float(key) ) setattr(obj, varName, settings.get_float(key))
elif type == "bool": elif type == "bool":
setattr( obj, varName, settings.get_boolean(key) ) setattr(obj, varName, settings.get_boolean(key))
else: else:
setattr( obj, varName, settings.get_value(key) ) setattr(obj, varName, settings.get_value(key))

View File

@ -3,6 +3,7 @@
import os import os
from gi.repository import Gio from gi.repository import Gio
def RemoveArgs(Execline): def RemoveArgs(Execline):
if isinstance(Execline, list): if isinstance(Execline, list):
Execline = ' '.join(Execline) Execline = ' '.join(Execline)

View File

@ -12,65 +12,66 @@ try:
except ImportError: except ImportError:
hasInotify = False hasInotify = False
if hasInotify: if hasInotify:
class FileMonitor(object): class FileMonitor(object):
def __init__( self ): def __init__(self):
self.monitorId = 0 self.monitorId = 0
self.wm = pyinotify.WatchManager() self.wm = pyinotify.WatchManager()
self.wdds = {} self.wdds = {}
self.callbacks = {} self.callbacks = {}
self.notifier = pyinotify.ThreadedNotifier(self.wm, self.fileChanged) self.notifier = pyinotify.ThreadedNotifier(self.wm, self.fileChanged)
self.notifier.setDaemon( True ) self.notifier.setDaemon(True)
self.notifier.start() self.notifier.start()
def addMonitor( self, filename, callback, args = None ): def addMonitor(self, filename, callback, args = None):
try: try:
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MODIFY mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MODIFY
mId = self.wm.add_watch( filename, mask, rec = True)[filename] mId = self.wm.add_watch(filename, mask, rec = True)[filename]
if mId >= 0: if mId >= 0:
self.callbacks[mId] = ( callback, args ) self.callbacks[mId] = (callback, args)
except Exception, detail: except Exception, detail:
mId = 0 mId = 0
return mId return mId
def removeMonitor( self, monitorId ): def removeMonitor(self, monitorId):
if monitorId in self.callbacks: if monitorId in self.callbacks:
self.wm.rm_watch( monitorId ) self.wm.rm_watch(monitorId)
del self.callbacks[monitorId] del self.callbacks[monitorId]
def fileChanged(self, event ): def fileChanged(self, event):
if event.wd in self.callbacks: if event.wd in self.callbacks:
# print event.path # print event.path
callback = self.callbacks[event.wd] callback = self.callbacks[event.wd]
if callback[1]: if callback[1]:
GLib.idle_add( callback[0], callback[1] ) GLib.idle_add(callback[0], callback[1])
else: else:
GLib.idle_add( callback[0] ) GLib.idle_add(callback[0])
else: else:
class _MonitoredFile( object ): class _MonitoredFile(object):
def __init__( self, filename, callback, monitorId, args ): def __init__(self, filename, callback, monitorId, args):
self.filename = filename self.filename = filename
self.callback = callback self.callback = callback
self.monitorId = monitorId self.monitorId = monitorId
self.args = args self.args = args
self.exists = os.path.exists( self.filename ) self.exists = os.path.exists(self.filename)
if self.exists: if self.exists:
self.mtime = os.stat( filename ).st_mtime self.mtime = os.stat(filename).st_mtime
else: else:
self.mtime = 0 self.mtime = 0
def hasChanged( self ): def hasChanged(self):
if os.path.exists( self.filename ): if os.path.exists(self.filename):
if not self.exists: if not self.exists:
self.exists = True self.exists = True
self.mtime = os.stat( self.filename ).st_mtime self.mtime = os.stat(self.filename).st_mtime
return True return True
else: else:
mtime = os.stat( self.filename ).st_mtime mtime = os.stat(self.filename).st_mtime
if mtime != self.mtime: if mtime != self.mtime:
self.mtime = mtime self.mtime = mtime
return True return True
@ -83,7 +84,7 @@ else:
class MonitorThread(threading.Thread): class MonitorThread(threading.Thread):
def __init__(self, monitor): def __init__(self, monitor):
threading.Thread.__init__ ( self ) threading.Thread.__init__(self)
self.monitor = monitor self.monitor = monitor
def run(self): def run(self):
@ -91,34 +92,31 @@ else:
self.monitor.checkFiles() self.monitor.checkFiles()
time.sleep(1) time.sleep(1)
class FileMonitor(object): class FileMonitor(object):
def __init__( self ): def __init__(self):
self.monitorId = 0 self.monitorId = 0
self.monitoredFiles = [] self.monitoredFiles = []
self.monitorThread = MonitorThread( self ) self.monitorThread = MonitorThread(self)
self.monitorThread.setDaemon( True ) self.monitorThread.setDaemon(True)
self.monitorThread.start() self.monitorThread.start()
def addMonitor( self, filename, callback, args = None ): def addMonitor(self, filename, callback, args = None):
self.monitorId += 1 self.monitorId += 1
self.monitoredFiles.append( _MonitoredFile( filename, callback, self.monitorId, args ) ) self.monitoredFiles.append(_MonitoredFile(filename, callback, self.monitorId, args))
return self.monitorId return self.monitorId
def removeMonitor( self, monitorId ): def removeMonitor(self, monitorId):
for monitored in self.monitoredFiles: for monitored in self.monitoredFiles:
if monitorId == monitored.monitorId: if monitorId == monitored.monitorId:
self.monitoredFiles.remove( monitored ) self.monitoredFiles.remove(monitored)
break break
def checkFiles( self ): def checkFiles(self):
for monitored in self.monitoredFiles: for monitored in self.monitoredFiles:
if monitored.hasChanged(): if monitored.hasChanged():
if monitored.args: if monitored.args:
GLib.idle_add( monitored.callback, monitored.args ) GLib.idle_add(monitored.callback, monitored.args)
else: else:
GLib.idle_add( monitored.callback ) GLib.idle_add(monitored.callback)
monitor = FileMonitor() monitor = FileMonitor()

View File

@ -15,12 +15,13 @@ from plugins.easybuttons import easyButton
from plugins.easygsettings import EasyGSettings from plugins.easygsettings import EasyGSettings
from plugins.execute import Execute from plugins.execute import Execute
# i18n # i18n
gettext.install("mintmenu", "/usr/share/linuxmint/locale") gettext.install("mintmenu", "/usr/share/linuxmint/locale")
class pluginclass( object ): class pluginclass(object):
def __init__( self, mintMenuWin, toggleButton, de ): def __init__(self, mintMenuWin, toggleButton, de):
self.mintMenuWin = mintMenuWin self.mintMenuWin = mintMenuWin
self.toggleButton = toggleButton self.toggleButton = toggleButton
@ -28,103 +29,103 @@ class pluginclass( object ):
# Read UI file # Read UI file
builder = Gtk.Builder() builder = Gtk.Builder()
builder.add_from_file(os.path.join( os.path.dirname( __file__ ), "places.glade" )) builder.add_from_file(os.path.join(os.path.dirname(__file__), "places.glade"))
self.placesBtnHolder = builder.get_object( "places_button_holder" ) self.placesBtnHolder = builder.get_object("places_button_holder")
self.editableBtnHolder = builder.get_object( "editable_button_holder" ) self.editableBtnHolder = builder.get_object("editable_button_holder")
self.scrolledWindow=builder.get_object("scrolledwindow2") self.scrolledWindow=builder.get_object("scrolledwindow2")
# These properties are NECESSARY to maintain consistency # These properties are NECESSARY to maintain consistency
# Set 'window' property for the plugin (Must be the root widget) # Set 'window' property for the plugin (Must be the root widget)
self.window = builder.get_object( "mainWindow" ) self.window = builder.get_object("mainWindow")
# Set 'heading' property for plugin # Set 'heading' property for plugin
self.heading = _("Places") self.heading = _("Places")
# This should be the first item added to the window in glade # This should be the first item added to the window in glade
self.content_holder = builder.get_object( "Places" ) self.content_holder = builder.get_object("Places")
# Items to get custom colors # Items to get custom colors
self.itemstocolor = [ builder.get_object( "viewport2" ) ] self.itemstocolor = [builder.get_object("viewport2")]
# Settings # Settings
self.settings = EasyGSettings("com.linuxmint.mintmenu.plugins.places") self.settings = EasyGSettings("com.linuxmint.mintmenu.plugins.places")
self.settings.notifyAdd( "icon-size", self.RegenPlugin ) self.settings.notifyAdd("icon-size", self.RegenPlugin)
self.settings.notifyAdd( "show-computer", self.RegenPlugin ) self.settings.notifyAdd("show-computer", self.RegenPlugin)
self.settings.notifyAdd( "show-desktop", self.RegenPlugin ) self.settings.notifyAdd("show-desktop", self.RegenPlugin)
self.settings.notifyAdd( "show-home_folder", self.RegenPlugin ) self.settings.notifyAdd("show-home_folder", self.RegenPlugin)
self.settings.notifyAdd( "show-network", self.RegenPlugin ) self.settings.notifyAdd("show-network", self.RegenPlugin)
self.settings.notifyAdd( "show-trash", self.RegenPlugin ) self.settings.notifyAdd("show-trash", self.RegenPlugin)
self.settings.notifyAdd( "custom-names", self.RegenPlugin ) self.settings.notifyAdd("custom-names", self.RegenPlugin)
self.settings.notifyAdd( "allow-scrollbar", self.RegenPlugin ) self.settings.notifyAdd("allow-scrollbar", self.RegenPlugin)
self.settings.notifyAdd( "show-gtk-bookmarks", self.RegenPlugin ) self.settings.notifyAdd("show-gtk-bookmarks", self.RegenPlugin)
self.settings.notifyAdd( "height", self.changePluginSize ) self.settings.notifyAdd("height", self.changePluginSize)
self.settings.notifyAdd( "width", self.changePluginSize ) self.settings.notifyAdd("width", self.changePluginSize)
self.loadSettings() self.loadSettings()
self.content_holder.set_size_request( self.width, self.height ) self.content_holder.set_size_request(self.width, self.height)
def wake (self) : def wake(self):
if ( self.showtrash == True ): if self.showtrash:
self.refreshTrash() self.refreshTrash()
def destroy( self ): def destroy(self):
self.settings.notifyRemoveAll() self.settings.notifyRemoveAll()
def changePluginSize( self, settings, key, args = None): def changePluginSize(self, settings, key, args = None):
self.allowScrollbar = self.settings.get( "bool", "allow-scrollbar" ) self.allowScrollbar = self.settings.get("bool", "allow-scrollbar")
self.width = self.settings.get( "int", "width" ) self.width = self.settings.get("int", "width")
if (self.allowScrollbar == False): if not self.allowScrollbar:
self.height = -1 self.height = -1
self.scrolledWindow.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.NEVER ) self.scrolledWindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.NEVER)
else: else:
self.scrolledWindow.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.scrolledWindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self.height = self.settings.get( "int", "height" ) self.height = self.settings.get("int", "height")
self.content_holder.set_size_request( self.width, self.height ) self.content_holder.set_size_request(self.width, self.height)
def RegenPlugin( self, *args, **kargs ): def RegenPlugin(self, *args, **kargs):
self.loadSettings() self.loadSettings()
self.ClearAll() self.ClearAll()
self.do_standard_places() self.do_standard_places()
self.do_custom_places() self.do_custom_places()
self.do_gtk_bookmarks() self.do_gtk_bookmarks()
def loadSettings( self ): def loadSettings(self):
self.width = self.settings.get( "int", "width" ) self.width = self.settings.get("int", "width")
self.allowScrollbar = self.settings.get( "bool", "allow-scrollbar" ) self.allowScrollbar = self.settings.get("bool", "allow-scrollbar")
self.showGTKBookmarks = self.settings.get( "bool", "show-gtk-bookmarks" ) self.showGTKBookmarks = self.settings.get("bool", "show-gtk-bookmarks")
self.scrolledWindow.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.scrolledWindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self.height = self.settings.get( "int", "height" ) self.height = self.settings.get("int", "height")
self.content_holder.set_size_request( self.width, self.height ) self.content_holder.set_size_request(self.width, self.height)
if (self.allowScrollbar == False): if not self.allowScrollbar:
self.height = -1 self.height = -1
self.scrolledWindow.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.NEVER ) self.scrolledWindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.NEVER)
self.content_holder.set_size_request( self.width, self.height ) self.content_holder.set_size_request(self.width, self.height)
self.iconsize = self.settings.get( "int", "icon-size" ) self.iconsize = self.settings.get("int", "icon-size")
# Check default items # Check default items
self.showcomputer = self.settings.get( "bool", "show-computer" ) self.showcomputer = self.settings.get("bool", "show-computer")
self.showhomefolder = self.settings.get( "bool", "show-home-folder" ) self.showhomefolder = self.settings.get("bool", "show-home-folder")
self.shownetwork = self.settings.get( "bool", "show-network" ) self.shownetwork = self.settings.get("bool", "show-network")
self.showdesktop = self.settings.get( "bool", "show-desktop" ) self.showdesktop = self.settings.get("bool", "show-desktop")
self.showtrash = self.settings.get( "bool", "show-trash" ) self.showtrash = self.settings.get("bool", "show-trash")
# Get paths for custom items # Get paths for custom items
self.custompaths = self.settings.get( "list-string", "custom-paths" ) self.custompaths = self.settings.get("list-string", "custom-paths")
# Get names for custom items # Get names for custom items
self.customnames = self.settings.get( "list-string", "custom-names" ) self.customnames = self.settings.get("list-string", "custom-names")
# Hide vertical dotted separator # Hide vertical dotted separator
self.hideseparator = self.settings.get( "bool", "hide-separator" ) self.hideseparator = self.settings.get("bool", "hide-separator")
# Plugin icon # Plugin icon
self.icon = self.settings.get( "string", "icon" ) self.icon = self.settings.get("string", "icon")
# Allow plugin to be minimized to the left plugin pane # Allow plugin to be minimized to the left plugin pane
self.sticky = self.settings.get( "bool", "sticky") self.sticky = self.settings.get("bool", "sticky")
self.minimized = self.settings.get( "bool", "minimized") self.minimized = self.settings.get("bool", "minimized")
def ClearAll(self): def ClearAll(self):
for child in self.placesBtnHolder.get_children(): for child in self.placesBtnHolder.get_children():
@ -133,35 +134,35 @@ class pluginclass( object ):
child.destroy() child.destroy()
#Add standard places #Add standard places
def do_standard_places( self ): def do_standard_places(self):
if ( self.showcomputer == True ): if self.showcomputer:
Button1 = easyButton( "computer", self.iconsize, [_("Computer")], -1, -1 ) Button1 = easyButton("computer", self.iconsize, [_("Computer")], -1, -1)
Button1.connect( "clicked", self.ButtonClicked, "xdg-open computer:" ) Button1.connect("clicked", self.ButtonClicked, "xdg-open computer:")
Button1.show() Button1.show()
self.placesBtnHolder.pack_start( Button1, False, False, 0) self.placesBtnHolder.pack_start(Button1, False, False, 0)
self.mintMenuWin.setTooltip( Button1, _("Browse all local and remote disks and folders accessible from this computer") ) self.mintMenuWin.setTooltip(Button1, _("Browse all local and remote disks and folders accessible from this computer"))
if ( self.showhomefolder == True ): if self.showhomefolder:
Button2 = easyButton( "user-home", self.iconsize, [_("Home Folder")], -1, -1 ) Button2 = easyButton("user-home", self.iconsize, [_("Home Folder")], -1, -1)
Button2.connect( "clicked", self.ButtonClicked, "xdg-open %s " % home ) Button2.connect("clicked", self.ButtonClicked, "xdg-open %s " % home)
Button2.show() Button2.show()
self.placesBtnHolder.pack_start( Button2, False, False, 0) self.placesBtnHolder.pack_start(Button2, False, False, 0)
self.mintMenuWin.setTooltip( Button2, _("Open your personal folder") ) self.mintMenuWin.setTooltip(Button2, _("Open your personal folder"))
if ( self.shownetwork == True and self.de == "mate"): if self.shownetwork and self.de == "mate":
mate_settings = Gio.Settings.new("org.mate.interface") mate_settings = Gio.Settings.new("org.mate.interface")
icon_theme = mate_settings.get_string( "icon-theme" ) icon_theme = mate_settings.get_string("icon-theme")
if "Mint-X" in icon_theme: if "Mint-X" in icon_theme:
Button3 = easyButton( "notification-network-ethernet-connected", self.iconsize, [_("Network")], -1, -1) Button3 = easyButton("notification-network-ethernet-connected", self.iconsize, [_("Network")], -1, -1)
else: else:
Button3 = easyButton( "network-workgroup", self.iconsize, [_("Network")], -1, -1) Button3 = easyButton("network-workgroup", self.iconsize, [_("Network")], -1, -1)
Button3.connect( "clicked", self.ButtonClicked, "xdg-open network:" ) Button3.connect("clicked", self.ButtonClicked, "xdg-open network:")
Button3.show() Button3.show()
self.placesBtnHolder.pack_start( Button3, False, False, 0) self.placesBtnHolder.pack_start(Button3, False, False, 0)
self.mintMenuWin.setTooltip( Button3, _("Browse bookmarked and local network locations") ) self.mintMenuWin.setTooltip(Button3, _("Browse bookmarked and local network locations"))
if ( self.showdesktop == True ): if self.showdesktop:
# Determine where the Desktop folder is (could be localized) # Determine where the Desktop folder is (could be localized)
desktopDir = home + "/Desktop" desktopDir = home + "/Desktop"
try: try:
@ -174,33 +175,33 @@ class pluginclass( object ):
desktopDir = tmpdesktopDir desktopDir = tmpdesktopDir
except Exception, detail: except Exception, detail:
print detail print detail
Button4 = easyButton( "desktop", self.iconsize, [_("Desktop")], -1, -1 ) Button4 = easyButton("desktop", self.iconsize, [_("Desktop")], -1, -1)
Button4.connect( "clicked", self.ButtonClicked, "xdg-open \"" + desktopDir + "\"") Button4.connect("clicked", self.ButtonClicked, "xdg-open \"" + desktopDir + "\"")
Button4.show() Button4.show()
self.placesBtnHolder.pack_start( Button4, False, False, 0) self.placesBtnHolder.pack_start(Button4, False, False, 0)
self.mintMenuWin.setTooltip( Button4, _("Browse items placed on the desktop") ) self.mintMenuWin.setTooltip(Button4, _("Browse items placed on the desktop"))
if ( self.showtrash == True ): if self.showtrash:
self.trashButton = easyButton( "user-trash", self.iconsize, [_("Trash")], -1, -1 ) self.trashButton = easyButton("user-trash", self.iconsize, [_("Trash")], -1, -1)
self.trashButton.connect( "clicked", self.ButtonClicked, "xdg-open trash:" ) self.trashButton.connect("clicked", self.ButtonClicked, "xdg-open trash:")
self.trashButton.show() self.trashButton.show()
self.trashButton.connect( "button-release-event", self.trashPopup ) self.trashButton.connect("button-release-event", self.trashPopup)
self.trash_path = os.path.join(home, "/.local/share/Trash/info") self.trash_path = os.path.join(home, "/.local/share/Trash/info")
self.refreshTrash() self.refreshTrash()
self.placesBtnHolder.pack_start( self.trashButton, False, False, 0) self.placesBtnHolder.pack_start(self.trashButton, False, False, 0)
self.mintMenuWin.setTooltip( self.trashButton, _("Browse deleted files") ) self.mintMenuWin.setTooltip(self.trashButton, _("Browse deleted files"))
def do_custom_places( self ): def do_custom_places(self):
for index in range( len(self.custompaths) ): for index in range(len(self.custompaths)):
path = self.custompaths[index] path = self.custompaths[index]
path = path.replace("~", home) path = path.replace("~", home)
command = ( "xdg-open \"" + path + "\"") command = 'xdg-open "%s"' % path
currentbutton = easyButton( "folder", self.iconsize, [self.customnames[index]], -1, -1 ) currentbutton = easyButton("folder", self.iconsize, [self.customnames[index]], -1, -1)
currentbutton.connect( "clicked", self.ButtonClicked, command ) currentbutton.connect("clicked", self.ButtonClicked, command)
currentbutton.show() currentbutton.show()
self.placesBtnHolder.pack_start( currentbutton, False, False, 0) self.placesBtnHolder.pack_start(currentbutton, False, False, 0)
def do_gtk_bookmarks( self ): def do_gtk_bookmarks(self):
if self.showGTKBookmarks: if self.showGTKBookmarks:
bookmarksFile = os.path.join(GLib.get_user_config_dir(), "gtk-3.0", "bookmarks") bookmarksFile = os.path.join(GLib.get_user_config_dir(), "gtk-3.0", "bookmarks")
if not os.path.exists(bookmarksFile): if not os.path.exists(bookmarksFile):
@ -225,42 +226,42 @@ class pluginclass( object ):
for name, path in bookmarks: for name, path in bookmarks:
name = unquote(name) name = unquote(name)
currentbutton = easyButton( "folder", self.iconsize, [name], -1, -1 ) currentbutton = easyButton("folder", self.iconsize, [name], -1, -1)
currentbutton.connect( "clicked", self.launch_gtk_bookmark, path ) currentbutton.connect("clicked", self.launch_gtk_bookmark, path)
currentbutton.show() currentbutton.show()
self.placesBtnHolder.pack_start( currentbutton, False, False, 0) self.placesBtnHolder.pack_start(currentbutton, False, False, 0)
def launch_gtk_bookmark (self, widget, path): def launch_gtk_bookmark(self, widget, path):
self.mintMenuWin.hide() self.mintMenuWin.hide()
os.system("xdg-open \"%s\" &" % path) os.system("xdg-open \"%s\" &" % path)
def trashPopup( self, widget, event ): def trashPopup(self, widget, event):
if event.button == 3: if event.button == 3:
trashMenu = Gtk.Menu() trashMenu = Gtk.Menu()
emptyTrashMenuItem = Gtk.MenuItem(_("Empty trash")) emptyTrashMenuItem = Gtk.MenuItem(_("Empty trash"))
trashMenu.append(emptyTrashMenuItem) trashMenu.append(emptyTrashMenuItem)
trashMenu.show_all() trashMenu.show_all()
emptyTrashMenuItem.connect ( "activate", self.emptyTrash, widget ) emptyTrashMenuItem.connect("activate", self.emptyTrash, widget)
self.mintMenuWin.stopHiding() self.mintMenuWin.stopHiding()
trashMenu.attach_to_widget(widget, None) trashMenu.attach_to_widget(widget, None)
trashMenu.popup(None, None, None, None, 3, 0) trashMenu.popup(None, None, None, None, 3, 0)
def emptyTrash( self, menu, widget): def emptyTrash(self, menu, widget):
os.system("rm -rf " + home + "/.local/share/Trash/info/*") os.system("rm -rf " + home + "/.local/share/Trash/info/*")
os.system("rm -rf " + home + "/.local/share/Trash/files/*") os.system("rm -rf " + home + "/.local/share/Trash/files/*")
self.trashButton.setIcon("user-trash") self.trashButton.setIcon("user-trash")
def ButtonClicked( self, widget, Exec ): def ButtonClicked(self, widget, Exec):
self.mintMenuWin.hide() self.mintMenuWin.hide()
if Exec: if Exec:
Execute( Exec ) Execute(Exec)
def do_plugin( self ): def do_plugin(self):
self.do_standard_places() self.do_standard_places()
self.do_custom_places() self.do_custom_places()
self.do_gtk_bookmarks() self.do_gtk_bookmarks()
def refreshTrash (self): def refreshTrash(self):
if os.path.exists(self.trash_path) and glob(os.path.join(self.trash_path, "*")): if os.path.exists(self.trash_path) and glob(os.path.join(self.trash_path, "*")):
iconName = "user-trash-full" iconName = "user-trash-full"
else: else:

View File

@ -16,7 +16,7 @@ class pluginclass:
It MUST be named pluginclass It MUST be named pluginclass
""" """
def __init__( self, mintMenuWin, toggleButton, de ): def __init__(self, mintMenuWin, toggleButton, de):
self.Win = mintMenuWin self.Win = mintMenuWin
self.toggleButton = toggleButton self.toggleButton = toggleButton
@ -24,16 +24,16 @@ class pluginclass:
self.builder = Gtk.Builder() self.builder = Gtk.Builder()
#The Glade file for the plugin #The Glade file for the plugin
self.builder.add_from_file (os.path.join( os.path.dirname( __file__ ), "recent.glade" )) self.builder.add_from_file(os.path.join(os.path.dirname(__file__), "recent.glade"))
#Set 'window' property for the plugin (Must be the root widget) #Set 'window' property for the plugin (Must be the root widget)
self.window = self.builder.get_object( "window1" ) self.window = self.builder.get_object("window1")
#Set 'heading' property for plugin #Set 'heading' property for plugin
self.heading = _("Recently used") self.heading = _("Recently used")
#This should be the first item added to the window in glade #This should be the first item added to the window in glade
self.content_holder = self.builder.get_object( "eventbox1" ) self.content_holder = self.builder.get_object("eventbox1")
self.recentBox = self.builder.get_object("RecentBox") self.recentBox = self.builder.get_object("RecentBox")
self.recentAppBox = self.builder.get_object("RecentApps") self.recentAppBox = self.builder.get_object("RecentApps")
@ -41,7 +41,7 @@ class pluginclass:
#self.recentApps = [] #self.recentApps = []
self.recentVBox = self.builder.get_object( "vbox1" ) self.recentVBox = self.builder.get_object("vbox1")
#Specify plugin width #Specify plugin width
self.width = 250 self.width = 250
@ -49,90 +49,90 @@ class pluginclass:
#Plugin icon #Plugin icon
self.icon = 'mate-folder.png' self.icon = 'mate-folder.png'
self.settings = EasyGSettings ("com.linuxmint.mintmenu.plugins.recent") self.settings = EasyGSettings("com.linuxmint.mintmenu.plugins.recent")
self.settings.notifyAdd( 'height', self.RegenPlugin ) self.settings.notifyAdd('height', self.RegenPlugin)
self.settings.notifyAdd( 'width', self.RegenPlugin ) self.settings.notifyAdd('width', self.RegenPlugin)
self.settings.notifyAdd( 'num-recent-docs', self.RegenPlugin ) self.settings.notifyAdd('num-recent-docs', self.RegenPlugin)
self.settings.notifyAdd( 'recent-font-size', self.RegenPlugin ) self.settings.notifyAdd('recent-font-size', self.RegenPlugin)
self.appSettings = EasyGSettings( "com.linuxmint.mintmenu.plugins.applications" ) self.appSettings = EasyGSettings("com.linuxmint.mintmenu.plugins.applications")
self.appSettings.notifyAdd( "icon-size", self.RegenPlugin ) self.appSettings.notifyAdd("icon-size", self.RegenPlugin)
self.FileList=[] self.FileList=[]
self.RecManagerInstance = Gtk.RecentManager.get_default() self.RecManagerInstance = Gtk.RecentManager.get_default()
self.recentManagerId = self.RecManagerInstance.connect("changed", self.DoRecent) self.recentManagerId = self.RecManagerInstance.connect("changed", self.DoRecent)
self.RegenPlugin() self.RegenPlugin()
self.builder.get_object( "RecentTabs" ).set_current_page(0) self.builder.get_object("RecentTabs").set_current_page(0)
#Connect event handlers #Connect event handlers
self.builder.get_object("ClrBtn").connect("clicked", self.clrmenu) self.builder.get_object("ClrBtn").connect("clicked", self.clrmenu)
def wake (self) : def wake(self):
pass pass
def destroy( self ): def destroy(self):
self.recentBox.destroy() self.recentBox.destroy()
self.recentVBox.destroy() self.recentVBox.destroy()
self.builder.get_object( "RecentTabs" ).destroy() self.builder.get_object("RecentTabs").destroy()
self.builder.get_object("ClrBtn").destroy() self.builder.get_object("ClrBtn").destroy()
self.content_holder.destroy() self.content_holder.destroy()
self.settings.notifyRemoveAll() self.settings.notifyRemoveAll()
if self.recentManagerId: if self.recentManagerId:
self.RecManagerInstance.disconnect(self.recentManagerId) self.RecManagerInstance.disconnect(self.recentManagerId)
def RegenPlugin( self, *args, **kargs ): def RegenPlugin(self, *args, **kargs):
self.GetGSettingsEntries() self.GetGSettingsEntries()
def GetGSettingsEntries( self ): def GetGSettingsEntries(self):
self.recenth = self.settings.get( 'int', 'height' ) self.recenth = self.settings.get('int', 'height')
self.recentw = self.settings.get( 'int', 'width' ) self.recentw = self.settings.get('int', 'width')
self.numentries = self.settings.get( 'int', 'num-recent-docs' ) self.numentries = self.settings.get('int', 'num-recent-docs')
RecentHelper.numentries = self.numentries RecentHelper.numentries = self.numentries
self.recentfontsize = self.settings.get( 'int', 'recent-font-size' ) self.recentfontsize = self.settings.get('int', 'recent-font-size')
# Hide vertical dotted separator # Hide vertical dotted separator
self.hideseparator = self.settings.get( "bool", "hide-separator" ) self.hideseparator = self.settings.get("bool", "hide-separator")
# Plugin icon # Plugin icon
self.icon = self.settings.get( "string", 'icon' ) self.icon = self.settings.get("string", 'icon')
# Allow plugin to be minimized to the left plugin pane # Allow plugin to be minimized to the left plugin pane
self.sticky = self.settings.get( "bool", "sticky" ) self.sticky = self.settings.get("bool", "sticky")
self.minimized = self.settings.get( "bool", "minimized" ) self.minimized = self.settings.get("bool", "minimized")
RecentHelper.iconSize = self.appSettings.get( "int", "icon-size") RecentHelper.iconSize = self.appSettings.get("int", "icon-size")
self.RebuildPlugin() self.RebuildPlugin()
def SetHidden( self, state ): def SetHidden(self, minimized):
if state == True: if minimized:
self.settings.set( "bool", "minimized", True ) self.settings.set("bool", "minimized", True)
else: else:
self.settings.set( "bool", "minimized", False ) self.settings.set("bool", "minimized", False)
def RebuildPlugin(self): def RebuildPlugin(self):
self.content_holder.set_size_request(self.recentw, self.recenth ) self.content_holder.set_size_request(self.recentw, self.recenth)
# TODO # TODO
print "recent.RebuildPlugin calling recent.DoRecent" print "recent.RebuildPlugin calling recent.DoRecent"
self.DoRecent() self.DoRecent()
def DoRecent( self, *args, **kargs ): def DoRecent(self, *args, **kargs):
for i in self.recentBox.get_children(): for i in self.recentBox.get_children():
i.destroy() i.destroy()
self.recentVBox.set_size_request( self.recentw, self.recenth ) self.recentVBox.set_size_request(self.recentw, self.recenth)
if len( self.recentBox.get_children() ) < self.numentries: if len(self.recentBox.get_children()) < self.numentries:
n=len( self.recentBox.get_children() )-1 n=len(self.recentBox.get_children())-1
else: else:
n=self.numentries-1 n=self.numentries-1
while n >= 0: while n >= 0:
self.recentBox.remove( self.recentBox.get_children()[n] ) self.recentBox.remove(self.recentBox.get_children()[n])
n-=1 n-=1
self.FileList, self.IconList = self.GetRecent() self.FileList, self.IconList = self.GetRecent()
loc = 0 loc = 0
for Name in self.FileList: for Name in self.FileList:
if Name != None: if Name != None:
self.AddRecentBtn( Name, self.IconList[loc] ) self.AddRecentBtn(Name, self.IconList[loc])
loc = loc + 1 loc = loc + 1
# TODO # TODO
@ -148,14 +148,14 @@ class pluginclass:
self.DoRecent() self.DoRecent()
return return
def AddRecentBtn( self, Name, RecentImage ): def AddRecentBtn(self, Name, RecentImage):
DispName=os.path.basename( Name ) DispName=os.path.basename(Name)
AButton = Gtk.Button( "", "ok", True ) AButton = Gtk.Button("", "ok", True)
AButton.remove( AButton.get_children()[0] ) AButton.remove(AButton.get_children()[0])
AButton.set_size_request( 200, -1 ) AButton.set_size_request(200, -1)
AButton.set_relief( Gtk.ReliefStyle.NONE ) AButton.set_relief(Gtk.ReliefStyle.NONE)
AButton.connect( "clicked", self.callback, Name ) AButton.connect("clicked", self.callback, Name)
AButton.show() AButton.show()
Box1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5) Box1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=5)
@ -165,14 +165,14 @@ class pluginclass:
ButtonIcon.set_from_pixbuf(RecentImage) ButtonIcon.set_from_pixbuf(RecentImage)
Box1.add(ButtonIcon) Box1.add(ButtonIcon)
Label1 = Gtk.Label( DispName ) Label1 = Gtk.Label(DispName)
Label1.set_ellipsize( Pango.EllipsizeMode.END ) Label1.set_ellipsize(Pango.EllipsizeMode.END)
Box1.add( Label1 ) Box1.add(Label1)
AButton.add( Box1 ) AButton.add(Box1)
AButton.show_all() AButton.show_all()
self.recentBox.pack_start( AButton, False, True, 0 ) self.recentBox.pack_start(AButton, False, True, 0)
def callback(self, widget, filename=None): def callback(self, widget, filename=None):
self.Win.hide() self.Win.hide()
@ -207,23 +207,23 @@ class pluginclass:
break break
return FileString, IconString return FileString, IconString
def ButtonClicked( self, widget, event, Exec ): def ButtonClicked(self, widget, event, Exec):
self.press_x = event.x self.press_x = event.x
self.press_y = event.y self.press_y = event.y
self.Exec = Exec self.Exec = Exec
def ButtonReleased( self, w, ev, ev2 ): def ButtonReleased(self, w, ev, ev2):
if ev.button == 1: if ev.button == 1:
if not hasattr( self, "press_x" ) or \ if not hasattr(self, "press_x") or \
not w.drag_check_threshold( int( self.press_x ), not w.drag_check_threshold(int(self.press_x),
int( self.press_y ), int(self.press_y),
int( ev.x ), int(ev.x),
int( ev.y ) ): int(ev.y)):
if self.Win.pinmenu == False: if self.Win.pinmenu == False:
self.Win.wTree.get_widget( "window1" ).hide() self.Win.wTree.get_widget("window1").hide()
if "applications" in self.Win.plugins: if "applications" in self.Win.plugins:
self.Win.plugins["applications"].wTree.get_widget( "entry1" ).grab_focus() self.Win.plugins["applications"].wTree.get_widget("entry1").grab_focus()
Execute( w, self.Exec ) Execute(w, self.Exec)
# TODO - skipping this because we're already doing this on __init__ # TODO - skipping this because we're already doing this on __init__
# def do_plugin(self): # def do_plugin(self):

View File

@ -9,53 +9,50 @@ from gi.repository import Gtk
from plugins.easybuttons import ApplicationLauncher from plugins.easybuttons import ApplicationLauncher
recentApps = [] recentApps = []
mintMenuWin = None mintMenuWin = None
recentAppBox = None recentAppBox = None
numentries = 10 numentries = 10
iconSize = 16 iconSize = 16
def recentAppsAdd( recentAppsButton ): def recentAppsAdd(recentAppsButton):
if recentAppsButton: if recentAppsButton:
recentApps.insert(0, recentAppsButton)
recentApps.insert(0, recentAppsButton )
counter = 0 counter = 0
for recentApp in recentApps: for recentApp in recentApps:
if counter != 0 and ( recentApp.desktopFile == recentAppsButton.desktopFile or counter >= numentries ): if counter != 0 and (recentApp.desktopFile == recentAppsButton.desktopFile or counter >= numentries):
del recentApps[counter] del recentApps[counter]
counter = counter + 1 counter = counter + 1
def recentAppsSave(): def recentAppsSave():
try: try:
if (not os.path.exists(home + "/.linuxmint/mintMenu/recentApplications.list")): path = os.path.join(home, ".linuxmint/mintMenu/recentApplications.list")
os.system("touch " + home + "/.linuxmint/mintMenu/recentApplications.list") with open(path, "w") as recentAppListFile:
recentAppListFile = open( os.path.join( os.path.expanduser( "~"), ".linuxmint", "mintMenu", "recentApplications.list" ) , "w" ) for recentApp in recentApps:
if not hasattr(recentApp, "type") or recentApp.type == "location":
recentAppListFile.write("location:" + recentApp.desktopFile + "\n")
else:
recentAppListFile.write(recentApp.type + "\n")
for recentApp in recentApps:
if not hasattr(recentApp, "type") or recentApp.type == "location":
recentAppListFile.write( "location:" + recentApp.desktopFile + "\n" )
else:
recentAppListFile.write( recentApp.type + "\n" )
recentAppListFile.close( )
except Exception, e: except Exception, e:
print e print e
msgDlg = Gtk.MessageDialog( None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Couldn't save recent apps. Check if you have write access to ~/.linuxmint/mintMenu")+"\n(" + e.__str__() + ")" ) msgDlg = Gtk.MessageDialog(None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK,
_("Couldn't save recent apps. Check if you have write access to ~/.linuxmint/mintMenu")+"\n(" + e.__str__() + ")")
msgDlg.run() msgDlg.run()
msgDlg.destroy() msgDlg.destroy()
def recentAppBuildLauncher( location ): def recentAppBuildLauncher(location):
try: try:
# For Folders and Network Shares # For Folders and Network Shares
location = "".join( location.split( "%20" ) ) location = "".join(location.split("%20"))
# ButtonIcon = None # ButtonIcon = None
# if location.startswith( "file" ): # if location.startswith("file"):
# ButtonIcon = "mate-fs-directory" # ButtonIcon = "mate-fs-directory"
# if location.startswith( "smb" ) or location.startswith( "ssh" ) or location.startswith( "network" ): # if location.startswith("smb") or location.startswith("ssh") or location.startswith("network"):
# ButtonIcon = "mate-fs-network" # ButtonIcon = "mate-fs-network"
#For Special locations #For Special locations
@ -65,16 +62,16 @@ def recentAppBuildLauncher( location ):
location = "/usr/share/applications/nautilus-home.desktop" location = "/usr/share/applications/nautilus-home.desktop"
elif location == "x-nautilus-desktop:///network": elif location == "x-nautilus-desktop:///network":
location = "/usr/share/applications/network-scheme.desktop" location = "/usr/share/applications/network-scheme.desktop"
elif location.startswith( "x-nautilus-desktop:///" ): elif location.startswith("x-nautilus-desktop:///"):
location = "/usr/share/applications/nautilus-computer.desktop" location = "/usr/share/applications/nautilus-computer.desktop"
if location.startswith( "file://" ): if location.startswith("file://"):
location = location[7:] location = location[7:]
appButton = ApplicationLauncher( location, iconSize) appButton = ApplicationLauncher(location, iconSize)
if appButton.appExec: if appButton.appExec:
appButton.show() appButton.show()
appButton.connect( "clicked", applicationButtonClicked ) appButton.connect("clicked", applicationButtonClicked)
appButton.type = "location" appButton.type = "location"
return appButton return appButton
except Exception, e: except Exception, e:
@ -82,7 +79,6 @@ def recentAppBuildLauncher( location ):
return None return None
def buildRecentApps(): def buildRecentApps():
print "-- recentHelper.buildRecentApps" print "-- recentHelper.buildRecentApps"
del recentApps[:] del recentApps[:]
@ -90,7 +86,6 @@ def buildRecentApps():
path = os.path.join(home, ".linuxmint/mintMenu/recentApplications.list") path = os.path.join(home, ".linuxmint/mintMenu/recentApplications.list")
if not os.path.exists(path): if not os.path.exists(path):
print "does not exist" print "does not exist"
#os.system("touch " + path)
recentApplicationsList = [] recentApplicationsList = []
else: else:
recentApplicationsList = open(path).readlines() recentApplicationsList = open(path).readlines()
@ -99,15 +94,15 @@ def buildRecentApps():
app = app.strip() app = app.strip()
if app[0:9] == "location:": if app[0:9] == "location:":
appButton = recentAppBuildLauncher( app[9:] ) appButton = recentAppBuildLauncher(app[9:])
else: else:
if ( app.endswith( ".desktop" ) ): if (app.endswith(".desktop")):
appButton = recentAppBuildLauncher( app ) appButton = recentAppBuildLauncher(app)
else: else:
appButton = None appButton = None
if appButton: if appButton:
recentApps.append( appButton ) recentApps.append(appButton)
except Exception, e: except Exception, e:
print e print e
return recentApps return recentApps
@ -124,15 +119,13 @@ def doRecentApps():
# recent apps # recent apps
buildRecentApps() buildRecentApps()
for AButton in recentApps: for AButton in recentApps:
AButton.set_size_request(200, -1)
AButton.set_size_request( 200, -1 ) AButton.set_relief(Gtk.ReliefStyle.NONE)
AButton.set_relief( Gtk.ReliefStyle.NONE ) recentAppBox.pack_start(AButton, False, True, 0)
recentAppBox.pack_start( AButton, False, True, 0 )
return True return True
def applicationButtonClicked( widget ): def applicationButtonClicked(widget):
# TODO all this runs whether the plugin is enabled or not # TODO all this runs whether the plugin is enabled or not
mintMenuWin.hide() mintMenuWin.hide()
recentAppsAdd(widget) recentAppsAdd(widget)

View File

@ -14,103 +14,102 @@ from plugins.execute import Execute
# i18n # i18n
gettext.install("mintmenu", "/usr/share/linuxmint/locale") gettext.install("mintmenu", "/usr/share/linuxmint/locale")
class pluginclass( object ): class pluginclass(object):
def __init__( self, mintMenuWin, toggleButton, de ): def __init__(self, mintMenuWin, toggleButton, de):
self.mintMenuWin = mintMenuWin self.mintMenuWin = mintMenuWin
self.toggleButton = toggleButton self.toggleButton = toggleButton
self.de = de self.de = de
self.builder = Gtk.Builder() self.builder = Gtk.Builder()
self.builder.add_from_file (os.path.join( os.path.dirname( __file__ ), "system_management.glade" )) self.builder.add_from_file(os.path.join(os.path.dirname(__file__), "system_management.glade"))
self.systemBtnHolder = self.builder.get_object( "system_button_holder" ) self.systemBtnHolder = self.builder.get_object("system_button_holder")
self.editableBtnHolder = self.builder.get_object( "editable_button_holder" ) self.editableBtnHolder = self.builder.get_object("editable_button_holder")
self.scrolledWindow = self.builder.get_object( "scrolledwindow2" ) self.scrolledWindow = self.builder.get_object("scrolledwindow2")
# These properties are NECESSARY to maintain consistency # These properties are NECESSARY to maintain consistency
# Set 'window' property for the plugin (Must be the root widget) # Set 'window' property for the plugin (Must be the root widget)
self.window = self.builder.get_object( "mainWindow" ) self.window = self.builder.get_object("mainWindow")
# Set 'heading' property for plugin # Set 'heading' property for plugin
self.heading = _("System") self.heading = _("System")
# This should be the first item added to the window in glade # This should be the first item added to the window in glade
self.content_holder = self.builder.get_object( "System" ) self.content_holder = self.builder.get_object("System")
# Items to get custom colors # Items to get custom colors
self.itemstocolor = [ self.builder.get_object( "viewport2" ) ] self.itemstocolor = [self.builder.get_object("viewport2")]
# Gconf stuff # Gconf stuff
self.settings = EasyGSettings( "com.linuxmint.mintmenu.plugins.system_management" ) self.settings = EasyGSettings("com.linuxmint.mintmenu.plugins.system_management")
self.settings.notifyAdd( "icon-size", self.RegenPlugin ) self.settings.notifyAdd("icon-size", self.RegenPlugin)
self.settings.notifyAdd( "show-control-center", self.RegenPlugin ) self.settings.notifyAdd("show-control-center", self.RegenPlugin)
self.settings.notifyAdd( "show-lock-screen", self.RegenPlugin ) self.settings.notifyAdd("show-lock-screen", self.RegenPlugin)
self.settings.notifyAdd( "show-logout", self.RegenPlugin ) self.settings.notifyAdd("show-logout", self.RegenPlugin)
self.settings.notifyAdd( "show-package-manager", self.RegenPlugin ) self.settings.notifyAdd("show-package-manager", self.RegenPlugin)
self.settings.notifyAdd( "show-software-manager", self.RegenPlugin ) self.settings.notifyAdd("show-software-manager", self.RegenPlugin)
self.settings.notifyAdd( "show-terminal", self.RegenPlugin ) self.settings.notifyAdd("show-terminal", self.RegenPlugin)
self.settings.notifyAdd( "show-quit", self.RegenPlugin ) self.settings.notifyAdd("show-quit", self.RegenPlugin)
self.settings.notifyAdd( "allow-scrollbar", self.RegenPlugin ) self.settings.notifyAdd("allow-scrollbar", self.RegenPlugin)
self.settings.notifyAdd( "height", self.changePluginSize ) self.settings.notifyAdd("height", self.changePluginSize)
self.settings.notifyAdd( "width", self.changePluginSize ) self.settings.notifyAdd("width", self.changePluginSize)
self.settings.bindGSettingsEntryToVar( "bool", "sticky", self, "sticky" ) self.settings.bindGSettingsEntryToVar("bool", "sticky", self, "sticky")
self.GetGSettingsEntries() self.GetGSettingsEntries()
self.content_holder.set_size_request( self.width, self.height ) self.content_holder.set_size_request(self.width, self.height)
def destroy( self ): def destroy(self):
self.settings.notifyRemoveAll() self.settings.notifyRemoveAll()
def wake (self) : def wake(self) :
pass pass
def changePluginSize( self, settings, key, args ): def changePluginSize(self, settings, key, args):
self.allowScrollbar = self.settings.get( "bool", "allow-scrollbar") self.allowScrollbar = self.settings.get("bool", "allow-scrollbar")
if key == "width": if key == "width":
self.width = settings.get_int(key) self.width = settings.get_int(key)
elif key == "height": elif key == "height":
if (self.allowScrollbar == False): if not self.allowScrollbar:
self.height = -1 self.height = -1
self.scrolledWindow.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.NEVER ) self.scrolledWindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.NEVER)
else: else:
self.scrolledWindow.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.scrolledWindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self.height = settings.get_int(key) self.height = settings.get_int(key)
self.content_holder.set_size_request( self.width, self.height ) self.content_holder.set_size_request(self.width, self.height)
def RegenPlugin( self, *args, **kargs ): def RegenPlugin(self, *args, **kargs):
self.GetGSettingsEntries() self.GetGSettingsEntries()
self.ClearAll() self.ClearAll()
self.do_standard_items() self.do_standard_items()
def GetGSettingsEntries( self ): def GetGSettingsEntries(self):
self.width = self.settings.get( "int", "width") self.width = self.settings.get("int", "width")
self.allowScrollbar = self.settings.get( "bool", "allow-scrollbar") self.allowScrollbar = self.settings.get("bool", "allow-scrollbar")
self.scrolledWindow.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.scrolledWindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
self.height = self.settings.get( "int", "height") self.height = self.settings.get("int", "height")
self.content_holder.set_size_request( self.width, self.height ) self.content_holder.set_size_request(self.width, self.height)
if (self.allowScrollbar == False): if not self.allowScrollbar:
self.height = -1 self.height = -1
self.scrolledWindow.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.NEVER ) self.scrolledWindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.NEVER)
self.content_holder.set_size_request( self.width, self.height ) self.content_holder.set_size_request(self.width, self.height)
self.iconsize = self.settings.get( "int","icon-size") self.iconsize = self.settings.get("int","icon-size")
# Check toggles # Check toggles
self.showSoftwareManager = self.settings.get( "bool", "show-software-manager") self.showSoftwareManager = self.settings.get("bool", "show-software-manager")
self.showPackageManager = self.settings.get( "bool", "show-package-manager") self.showPackageManager = self.settings.get("bool", "show-package-manager")
self.showControlCenter = self.settings.get( "bool", "show-control-center") self.showControlCenter = self.settings.get("bool", "show-control-center")
self.showTerminal = self.settings.get( "bool", "show-terminal") self.showTerminal = self.settings.get("bool", "show-terminal")
self.showLockScreen = self.settings.get( "bool", "show-lock-screen") self.showLockScreen = self.settings.get("bool", "show-lock-screen")
self.showLogout = self.settings.get( "bool", "show-logout") self.showLogout = self.settings.get("bool", "show-logout")
self.showQuit = self.settings.get( "bool", "show-quit") self.showQuit = self.settings.get("bool", "show-quit")
if self.de == "cinnamon": if self.de == "cinnamon":
self.lock_cmd = "cinnamon-screensaver-command --lock" self.lock_cmd = "cinnamon-screensaver-command --lock"
@ -134,12 +133,12 @@ class pluginclass( object ):
self.settings_cmd = "mate-control-center" self.settings_cmd = "mate-control-center"
# Hide vertical dotted separator # Hide vertical dotted separator
self.hideseparator = self.settings.get( "bool", "hide-separator") self.hideseparator = self.settings.get("bool", "hide-separator")
# Plugin icon # Plugin icon
self.icon = self.settings.get( "string", "icon" ) self.icon = self.settings.get("string", "icon")
# Allow plugin to be minimized to the left plugin pane # Allow plugin to be minimized to the left plugin pane
self.sticky = self.settings.get( "bool", "sticky") self.sticky = self.settings.get("bool", "sticky")
self.minimized = self.settings.get( "bool", "minimized") self.minimized = self.settings.get("bool", "minimized")
def ClearAll(self): def ClearAll(self):
for child in self.systemBtnHolder.get_children(): for child in self.systemBtnHolder.get_children():
@ -148,65 +147,65 @@ class pluginclass( object ):
child.destroy() child.destroy()
#Add standard items #Add standard items
def do_standard_items( self ): def do_standard_items(self):
if ( self.showSoftwareManager == True ): if self.showSoftwareManager:
if os.path.exists("/usr/bin/mintinstall"): if os.path.exists("/usr/bin/mintinstall"):
Button1 = easyButton( "mintinstall", self.iconsize, [_("Software Manager")], -1, -1 ) Button1 = easyButton("mintinstall", self.iconsize, [_("Software Manager")], -1, -1)
Button1.connect( "clicked", self.ButtonClicked, "mintinstall" ) Button1.connect("clicked", self.ButtonClicked, "mintinstall")
Button1.show() Button1.show()
self.systemBtnHolder.pack_start( Button1, False, False, 0) self.systemBtnHolder.pack_start(Button1, False, False, 0)
self.mintMenuWin.setTooltip( Button1, _("Browse and install available software") ) self.mintMenuWin.setTooltip(Button1, _("Browse and install available software"))
if ( self.showPackageManager == True ): if self.showPackageManager:
Button2 = easyButton( "applications-system", self.iconsize, [_("Package Manager")], -1, -1 ) Button2 = easyButton("applications-system", self.iconsize, [_("Package Manager")], -1, -1)
Button2.connect( "clicked", self.ButtonClicked, "synaptic-pkexec" ) Button2.connect("clicked", self.ButtonClicked, "synaptic-pkexec")
Button2.show() Button2.show()
self.systemBtnHolder.pack_start( Button2, False, False, 0 ) self.systemBtnHolder.pack_start(Button2, False, False, 0)
self.mintMenuWin.setTooltip( Button2, _("Install, remove and upgrade software packages") ) self.mintMenuWin.setTooltip(Button2, _("Install, remove and upgrade software packages"))
if ( self.showControlCenter == True ): if self.showControlCenter:
Button3 = easyButton( "gtk-preferences", self.iconsize, [_("Control Center")], -1, -1 ) Button3 = easyButton("gtk-preferences", self.iconsize, [_("Control Center")], -1, -1)
Button3.connect( "clicked", self.ButtonClicked, self.settings_cmd ) Button3.connect("clicked", self.ButtonClicked, self.settings_cmd)
Button3.show() Button3.show()
self.systemBtnHolder.pack_start( Button3, False, False, 0 ) self.systemBtnHolder.pack_start(Button3, False, False, 0)
self.mintMenuWin.setTooltip( Button3, _("Configure your system") ) self.mintMenuWin.setTooltip(Button3, _("Configure your system"))
if ( self.showTerminal == True ): if self.showTerminal:
Button4 = easyButton( "terminal", self.iconsize, [_("Terminal")], -1, -1 ) Button4 = easyButton("terminal", self.iconsize, [_("Terminal")], -1, -1)
if os.path.exists(self.terminal_cmd): if os.path.exists(self.terminal_cmd):
Button4.connect( "clicked", self.ButtonClicked, self.terminal_cmd ) Button4.connect("clicked", self.ButtonClicked, self.terminal_cmd)
else: else:
Button4.connect( "clicked", self.ButtonClicked, "x-terminal-emulator" ) Button4.connect("clicked", self.ButtonClicked, "x-terminal-emulator")
Button4.show() Button4.show()
self.systemBtnHolder.pack_start( Button4, False, False, 0 ) self.systemBtnHolder.pack_start(Button4, False, False, 0)
self.mintMenuWin.setTooltip( Button4, _("Use the command line") ) self.mintMenuWin.setTooltip(Button4, _("Use the command line"))
if ( self.showLockScreen == True ): if self.showLockScreen:
Button5 = easyButton( "system-lock-screen", self.iconsize, [_("Lock Screen")], -1, -1 ) Button5 = easyButton("system-lock-screen", self.iconsize, [_("Lock Screen")], -1, -1)
Button5.connect( "clicked", self.ButtonClicked, self.lock_cmd ) Button5.connect("clicked", self.ButtonClicked, self.lock_cmd)
Button5.show() Button5.show()
self.systemBtnHolder.pack_start( Button5, False, False, 0 ) self.systemBtnHolder.pack_start(Button5, False, False, 0)
self.mintMenuWin.setTooltip( Button5, _("Requires password to unlock") ) self.mintMenuWin.setTooltip(Button5, _("Requires password to unlock"))
if ( self.showLogout == True ): if self.showLogout:
Button6 = easyButton( "system-log-out", self.iconsize, [_("Logout")], -1, -1 ) Button6 = easyButton("system-log-out", self.iconsize, [_("Logout")], -1, -1)
Button6.connect( "clicked", self.ButtonClicked, self.logout_cmd ) Button6.connect("clicked", self.ButtonClicked, self.logout_cmd)
Button6.show() Button6.show()
self.systemBtnHolder.pack_start( Button6, False, False, 0 ) self.systemBtnHolder.pack_start(Button6, False, False, 0)
self.mintMenuWin.setTooltip( Button6, _("Log out or switch user") ) self.mintMenuWin.setTooltip(Button6, _("Log out or switch user"))
if ( self.showQuit == True ): if self.showQuit:
Button7 = easyButton( "system-shutdown", self.iconsize, [_("Quit")], -1, -1 ) Button7 = easyButton("system-shutdown", self.iconsize, [_("Quit")], -1, -1)
Button7.connect( "clicked", self.ButtonClicked, self.shutdown_cmd ) Button7.connect("clicked", self.ButtonClicked, self.shutdown_cmd)
Button7.show() Button7.show()
self.systemBtnHolder.pack_start( Button7, False, False, 0 ) self.systemBtnHolder.pack_start(Button7, False, False, 0)
self.mintMenuWin.setTooltip( Button7, _("Shutdown, restart, suspend or hibernate") ) self.mintMenuWin.setTooltip(Button7, _("Shutdown, restart, suspend or hibernate"))
def ButtonClicked( self, widget, Exec ): def ButtonClicked(self, widget, Exec):
self.mintMenuWin.hide() self.mintMenuWin.hide()
if Exec: if Exec:
Execute( Exec ) Execute(Exec)
def do_plugin( self ): def do_plugin(self):
self.do_standard_items() self.do_standard_items()