Prevent external devices being locked to launcher

Solution 1:

If you unlock a device from the Unity Launcher, it as actually blacklisted from the launcher. You can see which devices are currently blacklisted by the command:

gsettings get com.canonical.Unity.Devices blacklist

The script below is an alternative way to set your own blacklisted devices. The difference is that the script does it in a permanent way, untill you remove the file ~/.blacklist_data. (see explanation: How it works)

background script

Even for a background script, this one is extremely light weight, as a result of the fact that, if nothing changes to the blacklist, only the current blacklist is read by the gsettings command. It reads the dconf database, which is in binary format, and thus very light weight.

The script

#!/usr/bin/env python3
import subprocess
import os
import time

blacklist_data = os.environ["HOME"]+"/.blacklist_data"

def get_setlist():
    cmd = "gsettings get com.canonical.Unity.Devices blacklist"
    blacklist = subprocess.check_output(["/bin/bash", "-c", cmd]).decode("utf-8").strip()
    return "[]" if blacklist == "@as []" else blacklist

try:
    blacklist1 = str(open(blacklist_data).read()).strip()
    cmd = 'gsettings set com.canonical.Unity.Devices blacklist "'+blacklist1+'"'
    subprocess.call(["/bin/bash", "-c", cmd])
except FileNotFoundError:
    blacklist1 = "[]"
    open(blacklist_data, "wt").write(blacklist1)

while True:
    time.sleep(1)
    blacklist2 = get_setlist()
    if blacklist2 != blacklist1:
        oldlist = open(blacklist_data).read().strip()
        n_old = len(eval(oldlist))
        try:
            n_new = len(eval(blacklist2))
        except SyntaxError:
            n_new = 0
        if n_old < n_new:
            open(blacklist_data, "wt").write(blacklist2)
        else:
            cmd = 'gsettings set com.canonical.Unity.Devices blacklist "'+oldlist+'"'
            subprocess.call(["/bin/bash", "-c", cmd])
    blacklist1 = blacklist2

How to use

  1. Copy the script into an empty file, save it as myown_blacklist.py
  2. Test- run it by the command:

    python3 /pat/to/myown_blacklist.py`
    

    Now unlock your (any, it works not only usb devices) unwanted devices. Unlocking is only needed once.

  3. If all works fine, add it to Startup Applications: choose Dash > Startup Applications > Add. Add the command:

    python3 /pat/to/myown_blacklist.py`
    

How it works

The issue is that Unity "forgets" devices once they are unmounted. The script then keeps track of what happens to the output of:

gsettings get com.canonical.Unity.Devices blacklist

If an item is added to the list, the script writes the list into a hidden file in your home directory. If an item is removed, it reads the hidden file and restores the blacklist (this is only needed once on unmounting of the device)