GNU/Linux >> Belajar Linux >  >> Ubuntu

Ubuntu 16.04:Bagaimana Cara Menambah/menghapus Aplikasi yang Disematkan Ke Unity Launcher Melalui Terminal?

jadi saya telah mencari di internet tentang topik saya tetapi saya tidak menemukan jawaban apa pun.

Apa itu mungkin? Jika ya, bisakah Anda memberi tahu saya? Terima kasih

Jawaban yang Diterima:

Isi:

  1. Teori umum operasi Peluncur
  2. Kemungkinan cara menghapus dan menambahkan ke peluncur Unity
  3. utilitas launcherctl.py

1. Teori umum operasi peluncur

Peluncur Unity pada dasarnya adalah daftar .desktop file. Mereka pada dasarnya adalah pintasan yang memungkinkan peluncuran aplikasi serta melakukan tindakan khusus. Biasanya mereka disimpan di /usr/share/applications , tetapi dapat juga ditemukan di ~/.local/share/applications , dan di mana pun di sistem. Untuk kasus umum, saya sarankan menyimpan file seperti itu di /usr/share/applications untuk semua pengguna atau ~/.local/share/applications untuk setiap pengguna individu.

Dconf database pengaturan memungkinkan penyimpanan daftar aplikasi tersebut untuk peluncur Unity dan dapat dilihat dan diubah dengan gsettings kegunaan. Misalnya:

$ gsettings get  com.canonical.Unity.Launcher favorites
['application://wps-office-et.desktop', 'application://wps-office-wpp.desktop', 'application://wps-office-wps.desktop', 'unity://running-apps', 'unity://devices']
$ gsettings set  com.canonical.Unity.Launcher favorites  "['wechat.desktop']"                                                         
$ gsettings get  com.canonical.Unity.Launcher favorites                                                                               
['application://wechat.desktop', 'unity://running-apps', 'unity://devices']

Seperti yang Anda lihat semua .desktop file memiliki application:// awalan pada mereka, namun tidak diperlukan saat mengatur daftar peluncur. Item dengan unity:// awalan tidak dapat diubah dan tidak dapat dihapus.

gsettings get com.canonical.Unity.Launcher favorites dan gsettings set com.canonical.Unity.Launcher favorites perintah dapat digunakan untuk membuat fungsi di ~/.bashrc , misalnya:

get_launcher()
{
    gsettings get  com.canonical.Unity.Launcher favorites
}

set_launcher()
{
    # call this as set_launcher "['file1.desktop','file2.desktop']"
    gsettings set  com.canonical.Unity.Launcher favorites "$1"
}

Contoh:

$ set_launcher "['firefox.desktop','gnome-terminal.desktop']"                                                                         
$ get_launcher                                                                                                                        
['application://firefox.desktop', 'application://gnome-terminal.desktop', 'unity://running-apps', 'unity://devices']

2. Kemungkinan cara menghapus dan menambahkan ke Unity Launcher

Contoh paling sederhana telah ditunjukkan – melalui gsettings kegunaan. Menghapus dan menambahkan item tertentu memerlukan penguraian gsettings keluaran. Ini dapat dilakukan melalui sed atau awk utilitas , dan dengan susah payah bahkan dalam bash . Namun, saya menemukan bahwa python memungkinkan pendekatan yang lebih mudah dan "jalur dengan resistensi paling sedikit". Jadi, contoh yang diberikan di sini menggunakan gsettings bersama dengan python.

Berikut kasus penghapusan:

$ gsettings get com.canonical.Unity.Launcher favorites|                                                                               
> python -c 'import ast,sys; x =[]; x = [i for l in sys.stdin for i in ast.literal_eval(l)]; 
> x.pop(x.index("application://"+sys.argv[1])); print x' firefox.desktop
['application://gnome-terminal.desktop', 'unity://running-apps', 'unity://devices']

Apa yang terjadi disini ? Kami melewatkan output dari gsettings get melalui pipa ke python. Python kemudian membaca aliran input standar dan menggunakan ast library mengevaluasi representasi teks dari daftar, dan mengonversinya menjadi daftar aktual yang dapat dikenali python. Ini sangat menyederhanakan pekerjaan – jika ini awk atau sed kita harus berurusan dengan menghapus dan menambahkan karakter individu. Akhirnya , kami menghapus ( pop ) argumen baris perintah kedua ( ditunjukkan oleh sys.argv[1] ) dengan menemukan indeksnya dalam daftar. Kami sekarang memiliki daftar baru, yang dapat diteruskan lebih lanjut melalui pipa ke gsettings set

Perintah lengkapnya adalah ini:

$ gsettings get com.canonical.Unity.Launcher favorites|
> python -c 'import ast,sys; x =[]; x = [i for l in sys.stdin for i in ast.literal_eval(l)]; 
> x.pop(x.index("application://"+sys.argv[1])); print "\""+repr(x)+"\""' firefox.desktop |
> xargs -I {} gsettings set  com.canonical.Unity.Launcher favorites {}

Yang dapat dengan baik dimasukkan ke dalam ~/.bashrc fungsinya seperti ini:

remove_launcher_item()
{
  gsettings get com.canonical.Unity.Launcher favorites|
  python -c 'import ast,sys; x =[]; x = [i for l in sys.stdin for i in ast.literal_eval(l)];\
  x.pop(x.index("application://"+sys.argv[1])); print "\""+repr(x)+"\""' "$1" |
  xargs -I {} gsettings set  com.canonical.Unity.Launcher favorites {}
}

Beberapa hal yang perlu diperhatikan di sini adalah kita perlu mencetak lagi representasi “string” dari daftar yang diapit tanda kutip dan meneruskannya melalui xargs . Ide dengan menambahkan serupa, kecuali alih-alih pop kami menggunakan append fungsi:

append_launcher_item()
{
  gsettings get com.canonical.Unity.Launcher favorites|
  python -c 'import ast,sys; x =[]; x = [i for l in sys.stdin for i in ast.literal_eval(l)];\
  x.append("application://"+sys.argv[1]); print "\""+repr(x)+"\""' "$1" |
  xargs -I {} gsettings set  com.canonical.Unity.Launcher favorites {}

}

Contoh dijalankan:

$ get_launcher                                                                                                                        
['unity://running-apps', 'unity://devices', 'application://firefox.desktop']
$ append_launcher_item gnome-terminal.desktop                                                                                         
$ get_launcher                                                                                                                        
['unity://running-apps', 'unity://devices', 'application://firefox.desktop', 'application://gnome-terminal.desktop']
$ 

Fungsi-fungsi ini tidak harus menjadi bagian dari ~/.bashrc . Anda dapat menempatkannya ke dalam skrip juga

3. utilitas launcherctl.py

Seiring waktu, saya telah meneliti dan membangun serangkaian fungsi dalam python yang secara efektif dapat melakukan hal yang sama seperti gsettings kegunaan. Menempatkan kekuatan python bersama dengan fungsi-fungsi itu, saya telah membuat launcherctl.py utilitas.

Terkait:Driver untuk Intel HD diinstal, tetapi masih ada game yang mengeluh 3D tidak didukung?

Ini adalah pekerjaan yang sedang berjalan dan akan diperluas untuk mencakup lebih banyak fungsi di masa mendatang. Untuk pertanyaan khusus ini, saya akan membiarkan kode sumber seperti yang muncul di versi pertama. Versi dan peningkatan lebih lanjut dapat ditemukan di GitHub.

Apa kelebihan skrip ini dibandingkan dengan fungsi bash ?
1. Ini adalah utilitas "terpusat" dengan tujuan tertentu. Anda tidak harus memiliki skrip/fungsi terpisah untuk setiap tindakan.
2. Mudah digunakan, opsi baris perintah minimalis
3. Saat digunakan bersama dengan utilitas lain, ini menyediakan kode yang lebih mudah dibaca .

Penggunaan :

Seperti yang ditunjukkan oleh -h opsi baris perintah:

$ ./launcherctl.py -h                                                                                                                 
usage: launcherctl.py [-h] [-f FILE] [-a] [-r] [-l] [-c]

Copyright 2016. Sergiy Kolodyazhnyy.
    This command line utility allows appending and removing items
    from Unity launcher, as well as listing and clearing the
    Launcher items.

    --file option is required for --append and --remove 


optional arguments:
  -h, --help            show this help message and exit
  -f FILE, --file FILE
  -a, --append
  -r, --remove
  -l, --list
  -c, --clear

Penggunaan baris perintah sederhana.

Menambahkan:

$ ./launcherctl.py -a -f wechat.desktop

Penghapusan:

$ ./launcherctl.py -r -f wechat.desktop

Membersihkan peluncur sepenuhnya:

$ ./launcherctl.py -c 

Mencantumkan item di peluncur:

$ ./launcherctl.py -l                                                                                                                 
chromium-browser.desktop
firefox.desktop
opera.desktop
vivaldi-beta.desktop

Seperti disebutkan sebelumnya, ini dapat digunakan dengan perintah lain. Misalnya, menambahkan dari file:

$ cat new_list.txt                                                                                                                    
firefox.desktop
wechat.desktop
gnome-terminal.desktop    
$ cat new_list.txt | xargs -L 1 launcherctl.py -a -f

Hal yang sama dapat digunakan dengan penghapusan item yang diberikan dari file teks

Menghapus item ke-3 dari dash tombol:

$ launcherctl.py  -l | awk 'NR==3' | xargs -L 1 launcherctl.py -r -f  

Mendapatkan kode sumber dan pemasangan

Cara manual:

  1. Buat direktori ~/bin .
  2. Simpan kode sumber dari bawah ke dalam file ~/bin/launcherctl.py
  3. Jika Anda bash pengguna, Anda dapat mencari ~/.profile , atau logout dan login. ~/bin direktori akan ditambahkan ke $PATH . Anda variabel secara otomatis. Bagi yang tidak menggunakan bash , tambahkan ~/bin ke $PATH . Anda variabel di dalam file konfigurasi shell Anda, seperti:PATH="$PATH:$HOME/bin

Seperti yang telah saya sebutkan, perubahan terbaru pada kode masuk ke repositori GitHub. Jika Anda memiliki git terinstal, langkah-langkahnya lebih sederhana:

  1. git clone https://github.com/SergKolo/sergrep.git ~/bin/sergrep
  2. echo "PATH=$PATH:$HOME/bin/sergrep" >> ~/.bashrc
  3. source ~/.bashrc . Setelah langkah ini, Anda dapat memanggil launcherctl.py seperti perintah lainnya. Mendapatkan pembaruan semudah cd ~/bin/sergrep;git pull

Mendapatkan kode dari GitHub tanpa git :

  1. cd /tmp
  2. wget https://github.com/SergKolo/sergrep/archive/master.zip
  3. unzip master.zip
  4. Jika Anda tidak memiliki ~/bin , buat dengan mkdir ~/bin
  5. mv sergrep-master/launcherctl.py ~/bin/launcherctl.py

Dalam semua kasus, aturan yang sama berlaku – skrip harus berada di direktori yang ditambahkan ke PATH variabel dan harus memiliki izin yang dapat dieksekusi yang disetel dengan chmod +x launcherctl.py

Kode sumber asli :

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#
# Author: Serg Kolo , contact: [email protected]
# Date: Sept 24, 2016
# Purpose: command-line utility for controling the launcher
#          settings
# Tested on: Ubuntu 16.04 LTS
#
#
# Licensed under The MIT License (MIT).
# See included LICENSE file or the notice below.
#
# Copyright © 2016 Sergiy Kolodyazhnyy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import gi
from gi.repository import Gio
import argparse
import sys

def gsettings_get(schema, path, key):
    """Get value of gsettings schema"""
    if path is None:
        gsettings = Gio.Settings.new(schema)
    else:
        gsettings = Gio.Settings.new_with_path(schema, path)
    return gsettings.get_value(key)

def gsettings_set(schema, path, key, value):
    """Set value of gsettings schema"""
    if path is None:
        gsettings = Gio.Settings.new(schema)
    else:
        gsettings = Gio.Settings.new_with_path(schema, path)
    if isinstance(value,list ):
        return gsettings.set_strv(key, value)
    if isinstance(value,int):
        return gsettings.set_int(key, value)

def puts_error(string):
    sys.stderr.write(string+"\n")
    sys.exit(1)

def list_items():
    """ lists all applications pinned to launcher """
    schema = 'com.canonical.Unity.Launcher'
    path = None
    key = 'favorites'
    items = list(gsettings_get(schema,path,key))
    for item in items:
        if 'application://' in item:
            print(item.replace("application://","").lstrip())

def append_item(item):
    """ appends specific item to launcher """
    schema = 'com.canonical.Unity.Launcher'
    path = None
    key = 'favorites'
    items = list(gsettings_get(schema,path,key))

    if not item.endswith(".desktop"):
        puts_error( ">>> Bad file.Must have .desktop extension!!!")

    items.append('application://' + item)
    gsettings_set(schema,path,key,items)

def remove_item(item):
    """ removes specific item from launcher """
    schema = 'com.canonical.Unity.Launcher'
    path = None
    key = 'favorites'
    items = list(gsettings_get(schema,path,key))

    if not item.endswith(".desktop"):
       puts_error(">>> Bad file. Must have .desktop extension!!!")
    items.pop(items.index('application://'+item))
    gsettings_set(schema,path,key,items)

def clear_all():
    """ clears the launcher completely """
    schema = 'com.canonical.Unity.Launcher'
    path = None
    key = 'favorites'

    gsettings_set(schema,path,key,[])

def parse_args():
    """parse command line arguments"""

    info="""Copyright 2016. Sergiy Kolodyazhnyy.
    This command line utility allows appending and removing items
    from Unity launcher, as well as listing and clearing the
    Launcher items.

    --file option is required for --append and --remove 
    """
    arg_parser = argparse.ArgumentParser(
                 description=info,
                 formatter_class=argparse.RawTextHelpFormatter)
    arg_parser.add_argument('-f','--file',action='store',
                            type=str,required=False)
    arg_parser.add_argument('-a','--append',
                            action='store_true',required=False)

    arg_parser.add_argument('-r','--remove',
                            action='store_true',required=False)
    arg_parser.add_argument('-l','--list',
                            action='store_true',required=False)

    arg_parser.add_argument('-c','--clear',
                            action='store_true',required=False)
    return arg_parser.parse_args()

def main():
    """ Defines program entry point """
    args = parse_args()

    if args.list:
       list_items()
       sys.exit(0)

    if args.append:
       if not args.file:
          puts_error(">>>Specify .desktop file with --file option")

       append_item(args.file)
       sys.exit(0)

    if args.remove:
       if not args.file:
          puts_error(">>>Specify .desktop file with --file option")

       remove_item(args.file)
       sys.exit(0)

    if args.clear:
       clear_all()
       sys.exit(0)

    sys.exit(0)

if __name__ == '__main__':
    main()

Catatan tambahan:

  • di masa lalu saya telah membuat jawaban yang memungkinkan pengaturan daftar peluncur dari file:https://askubuntu.com/a/761021/295286
  • Saya juga telah membuat indikator Unity untuk beralih di antara beberapa daftar. Lihat instruksi di sini:http://www.omgubuntu.co.uk/2016/09/launcher-list-indicator-update-ppa-workspaces
Terkait:Tidak ada suara di Ubuntu 13.04, hanya perangkat keluaran Dum yang terdaftar?
Ubuntu
  1. Cara Menambahkan File Swap Di Ubuntu

  2. Bagaimana Menambahkan Pencetak di Ubuntu 11.10 | Tambahkan Pencetak di Ubuntu

  3. Cara Menginstal Emulator Terminal Alacritty melalui PPA di Ubuntu 20.04

  1. Cara menghapus peluncur dasbor Amazon di Ubuntu 20.04 Focal Fossa Linux

  2. Cara membuka terminal di Ubuntu 22.04

  3. Cara Menghapus Desktop Unity dari Ubuntu 17.10

  1. Cara Menambah dan Menghapus Pengguna di Ubuntu 20.04

  2. Cara membuat beberapa profil untuk peluncur Unity di Ubuntu menggunakan indikator daftar peluncur

  3. Cara Menghapus Paket Yatim Piatu di Ubuntu