utils.py 12.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# This file is part of gnome-tweak-tool.
#
# Copyright (c) 2011 John Stowers
#
# gnome-tweak-tool is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# gnome-tweak-tool is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with gnome-tweak-tool.  If not, see <http://www.gnu.org/licenses/>.

import os.path
19
import logging
20 21
import tempfile
import shutil
22
import subprocess
23
import glob
24

25
import gtweak
26
from gtweak.gsettings import GSettingsSetting
27

28 29
import gi
gi.require_version("Notify", "0.7")
30
from gi.repository import GObject
31
from gi.repository import GLib
Alex Muñoz's avatar
Alex Muñoz committed
32
from gi.repository import Gio
33 34
from gi.repository import Notify

35 36 37 38 39 40 41 42 43 44 45 46 47
def singleton(cls):
    """
    Singleton decorator that works with GObject derived types. The 'recommended'
    python one - http://wiki.python.org/moin/PythonDecoratorLibrary#Singleton
    does not (interacts badly with GObjectMeta
    """
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

48
def make_combo_list_with_default(opts, default, title=True, default_text=None):
49 50 51 52 53 54 55 56 57
    """
    Turns a list of values into a list of value,name (where name is the
    display name a user will see in a combo box). If a value is opt is
    equal to that supplied in default the display name for that value is
    modified to "value <i>(default)</i>"

    @opts: a list of value
    @returns: a list of 2-tuples (value, name)
    """
58 59
    themes = []
    for t in opts:
60
        if t.lower() == "default" and t != default:
61 62
            #some themes etc are actually called default. Ick. Dont show them if they
            #are not the actual default value
63 64
            continue

65
        if title and len(t):
66 67 68 69 70
            name = t[0].upper() + t[1:]
        else:
            name = t

        if t == default:
71
            #indicates the default theme, e.g Adwaita (default)
John Stowers's avatar
John Stowers committed
72
            name = default_text or _("%s <i>(default)</i>") % name
73 74 75 76

        themes.append((t, name))
    return themes

77 78 79 80 81 82 83 84 85 86 87 88
def walk_directories(dirs, filter_func):
    valid = []
    try:
        for thdir in dirs:
            if os.path.isdir(thdir):
                for t in os.listdir(thdir):
                    if filter_func(os.path.join(thdir, t)):
                         valid.append(t)
    except:
        logging.critical("Error parsing directories", exc_info=True)
    return valid

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
def extract_zip_file(z, members_path, dest):
    """ returns (true_if_extracted_ok, true_if_updated) """
    tmp = tempfile.mkdtemp()
    tmpdest = os.path.join(tmp, members_path)

    ok = True
    updated = False
    try:
        if os.path.exists(dest):
            shutil.rmtree(dest)
            updated = True
        z.extractall(tmp)
        shutil.copytree(tmpdest, dest)
    except OSError:
        ok = False
        logging.warning("Error extracting zip", exc_info=True)

    if ok:
        logging.info("Extracted zip to %s, copied to %s" % (tmpdest, dest))

    return ok, updated

111 112 113
def execute_subprocess(cmd_then_args, block=True):
    p = subprocess.Popen(
            cmd_then_args,
114 115
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True,
            universal_newlines=True)
116 117 118 119
    if block:
        stdout, stderr = p.communicate()
        return stdout, stderr, p.returncode

120
@singleton
121
class AutostartManager:
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

    @staticmethod
    def get_desktop_files():
        return [a.get_filename() for a in Gio.app_info_get_all()]

    @staticmethod
    def get_user_autostart_files():
        return glob.glob(
                    os.path.join(
                        GLib.get_user_config_dir(), "autostart", "*.desktop")) 

    @staticmethod
    def get_system_autostart_files():
        f = []
        for d in GLib.get_system_config_dirs():
            f.extend( glob.glob(os.path.join(d, "autostart", "*.desktop")) )
        return f

class AutostartFile:
    def __init__(self, appinfo, autostart_desktop_filename="", exec_cmd="", extra_exec_args=""):
142 143 144 145 146 147 148 149 150 151 152
        if appinfo:
            self._desktop_file = appinfo.get_filename()
            self._autostart_desktop_filename = autostart_desktop_filename or os.path.basename(self._desktop_file)
            self._create_file = False
        elif autostart_desktop_filename:
            self._desktop_file = None
            self._autostart_desktop_filename = autostart_desktop_filename
            self._create_file = True
        else:
            raise Exception("Need either an appinfo or a file name")

153
        self._exec_cmd = exec_cmd
154
        self._extra_exec_args = " %s\n" % extra_exec_args
155

156 157 158 159 160 161
        user_autostart_dir = os.path.join(GLib.get_user_config_dir(), "autostart")
        if not os.path.isdir(user_autostart_dir):
            try:
                os.makedirs(user_autostart_dir)
            except:
                logging.critical("Could not create autostart dir: %s" % user_autostart_dir)
162 163 164

        self._user_autostart_file = os.path.join(user_autostart_dir, self._autostart_desktop_filename)

165 166
        if self._desktop_file:
            logging.debug("Found desktop file: %s" % self._desktop_file)
167 168
        logging.debug("User autostart desktop file: %s" % self._user_autostart_file)

169 170 171 172 173 174
    def _create_user_autostart_file(self):
        f = open(self._user_autostart_file, "w")
        f.write("[Desktop Entry]\nType=Application\nName=%s\nExec=%s\n" %
                (self._autostart_desktop_filename[0:-len('.desktop')], self._exec_cmd + self._extra_exec_args))
        f.close()

175
    def is_start_at_login_enabled(self):
176 177
        if os.path.exists(self._user_autostart_file):
            #prefer user directories first
178 179 180
            #if it contains X-GNOME-Autostart-enabled=false then it has
            #has been disabled by the user in the session applet, otherwise
            #it is enabled
181
            return open(self._user_autostart_file).read().find("X-GNOME-Autostart-enabled=false") == -1
182
        else:
183
            #check the system directories
184 185
            for f in AutostartManager().get_system_autostart_files():
                if os.path.basename(f) == self._autostart_desktop_filename:
186 187
                    return True
        return False
188 189 190

    def update_start_at_login(self, update):

191 192 193
        if os.path.exists(self._user_autostart_file):
            logging.info("Removing user autostart file %s" % self._user_autostart_file)
            os.remove(self._user_autostart_file)
194 195

        if update:
196
            if (not self._desktop_file) or (not os.path.exists(self._desktop_file)):
197 198 199 200
                if self._create_file:
                    self._create_user_autostart_file()
                else:
                    logging.critical("Could not find desktop file: %s" % self._desktop_file)
201 202
                return

203
            logging.info("Adding autostart %s" % self._user_autostart_file)
204 205
            #copy the original file to the new file, but add the extra exec args
            old = open(self._desktop_file, "r")
206
            new = open(self._user_autostart_file, "w")
207 208 209

            for l in old.readlines():         
                if l.startswith("Exec="):
210 211 212 213 214
                    if self._exec_cmd:
                        new.write("Exec=%s\n" % self._exec_cmd)
                    else:
                        new.write(l[0:-1])
                        new.write(self._extra_exec_args)
215 216 217 218 219
                else:
                    new.write(l)

            old.close()
            new.close()
220

Alex Muñoz's avatar
Alex Muñoz committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
class SchemaList:

    __list = None

    def __init__(self):

        if SchemaList.__list == None:
            SchemaList.__list = []
            
    def get(self):
        return SchemaList.__list
    
    def insert(self, key_name, schema_name):
        v = [key_name, schema_name]
        SchemaList.__list.append(v)
    
    def reset(self):
        for i in SchemaList.__list:
            s = Gio.Settings(i[1])
            s.reset(i[0])
241 242 243 244
@singleton
class DisableExtension(GObject.GObject):
    
    __gsignals__ = {
245
        "disable-extension": (GObject.SignalFlags.RUN_FIRST, GObject.TYPE_NONE,()),
246 247 248 249 250 251 252
    }    
    
    def __init__(self):
        GObject.GObject.__init__(self)
    
    def disable(self):
        self.emit("disable-extension")
Alex Muñoz's avatar
Alex Muñoz committed
253

254 255 256 257 258 259
@singleton
class XSettingsOverrides:

    VARIANT_TYPES = {
        'Gtk/ShellShowsAppMenu': GLib.Variant.new_int32,
        'Gtk/EnablePrimaryPaste': GLib.Variant.new_int32,
260
        'Gdk/WindowScalingFactor': GLib.Variant.new_int32,
261 262 263
    }

    def __init__(self):
264
        self._settings = Gio.Settings(schema='org.gnome.settings-daemon.plugins.xsettings')
265 266 267 268
        self._variant = self._settings.get_value("overrides")

    def _dup_variant_as_dict(self):
        items = {}
269
        for k in list(self._variant.keys()):
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
            try:
                #variant override doesnt support .items()
                v = self._variant[k]
                items[k] = self.VARIANT_TYPES[k](v)
            except KeyError:
                pass
        return items

    def _dup_variant(self):
        return GLib.Variant('a{sv}', self._dup_variant_as_dict())

    def _set_override(self, name, v):
        items = self._dup_variant_as_dict()
        items[name] = self.VARIANT_TYPES[name](v)
        n = GLib.Variant('a{sv}', items)
        self._settings.set_value('overrides', n)
286
        self._variant = self._settings.get_value("overrides")
287 288 289 290 291 292 293 294 295 296 297 298 299

    def _get_override(self, name, default):
        try:
            return self._variant[name]
        except KeyError:
            return default

    #while I could store meta type information in the VARIANT_TYPES
    #dict, its easiest to do default value handling and missing value
    #checks in dedicated functions
    def set_shell_shows_app_menu(self, v):
        self._set_override('Gtk/ShellShowsAppMenu', int(v))
    def get_shell_shows_app_menu(self):
300
        return self._get_override('Gtk/ShellShowsAppMenu', True)
301 302 303
    def set_enable_primary_paste(self, v):
        self._set_override('Gtk/EnablePrimaryPaste', int(v))
    def get_enable_primary_paste(self):
304
        return self._get_override('Gtk/EnablePrimaryPaste', True)
305 306 307 308
    def set_window_scaling_factor(self, v):
        self._set_override('Gdk/WindowScalingFactor', int(v))
    def get_window_scaling_factor(self):
        return self._get_override('Gdk/WindowScalingFactor', 1)
309

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
class Notification:
    def __init__(self, summary, body):
        if Notify.is_initted() or Notify.init("GNOME Tweak Tool"):
            self.notification = Notify.Notification.new(
                                    summary,
                                    body,
                                    'gnome-tweak-tool'
            )
            self.notification.set_hint(
                                "desktop-entry",
                                GLib.Variant('s', 'gnome-tweak-tool'))
            self.notification.show()
        else:
            raise Exception("Not Supported")

@singleton
326 327
class LogoutNotification:
    def __init__(self):
328
        if Notify.is_initted() or Notify.init(_("GNOME Tweak Tool")):
329
            self.notification = Notify.Notification.new(
330 331
                                _("Configuration changes require restart"),
                                _("Your session needs to be restarted for settings to take effect"),
332
                                'gnome-tweak-tool')
333 334
            self.notification.add_action(
                                "restart",
335
                                _("Restart Session"),
336
                                self._logout, None, None)
337 338 339
            self.notification.set_hint(
                                "desktop-entry",
                                GLib.Variant('s', 'gnome-tweak-tool'))
340
            self.notification.show()
341
        else:
342
            raise Exception("Not Supported")
343

344
    def _logout(self, btn, action, user_data, unknown):
Alex Muñoz's avatar
Alex Muñoz committed
345 346 347 348 349 350 351 352
        d = Gio.bus_get_sync(Gio.BusType.SESSION, None)
        proxy = Gio.DBusProxy.new_sync(
                       d,Gio.DBusProxyFlags.NONE, None,
                       'org.gnome.SessionManager', 
                       '/org/gnome/SessionManager', 
                       'org.gnome.SessionManager',
                       None)
        proxy.Logout('(u)', 0)
353