Wednesday, August 22, 2012

Easily Create Menu Entries

So I lied in my last post. Big deal!

The following is a script you can use to create the right menu entry for an application you downloaded. Just save the script to the same directory as the application. Edit the variables, then run the script.

One pre-requisite is to have a 48x48 pixel icon in PNG format in that folder too, named "product_logo_48.png". This should work for Gnome, LXDE, XFCE, KDE - pretty much everything. The script is based off of one made by the Chromium developers.



#!/bin/bash

# Generic desktop wrapper
BINARY="PMS.sh"
DESKTOPN="pms"
TITLE="PS3 Media Server"
CATEGORIES="Application;Network;AudioVideo"

usage() {
  echo "$0 [--help] [--] [options]"
  echo
  echo "        --help                  This help screen"
}

# Check to see if there is a desktop file of the given name.
exists_desktop_file() {
    # Build a search list from $XDG_DATA_HOME and $XDG_DATA_DIRS, the latter
    # of which can itself be a colon-separated list of directories to search.
    search="${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
    IFS=:
    for dir in $search; do
        unset IFS
        [ "$dir" -a -d "$dir/applications" ] || continue
        [ -r "$dir/applications/$DESKTOPN.desktop" ] && return
    done
    # Didn't find it in the search path.
    return 1
}


# Generate a desktop file that will run this script.
generate_desktop_file() {
    apps="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
    mkdir -p "$apps"
    cat > "$apps/$DESKTOPN.desktop" << EOF
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Name=$TITLE
Exec=$WRAPPER %U
Terminal=false
Icon=$HERE/product_logo_48.png
Type=Application
Categories=$CATEGORIES
EOF
}

# Let the wrapped binary know that it has been run through the wrapper.
export WRAPPER="`readlink -f "$0"`"
export DESKTOP="$DESKTOPN.desktop"

HERE="`dirname "$WRAPPER"`"

# Use system xdg utilities. But first create mimeapps.list if it doesn't
# exist; some systems have bugs in xdg-mime that make it fail without it.
xdg_app_dir="${XDG_DATA_HOME:-$HOME/.local/share/applications}"
mkdir -p "$xdg_app_dir"
[ -f "$xdg_app_dir/mimeapps.list" ] || touch "$xdg_app_dir/mimeapps.list"

exists_desktop_file || generate_desktop_file

CMD_PREFIX=
ARGS=()
while [ "$#" -gt 0 ]; do
    case "$1" in
    "--")
        shift
        break ;;
    "--help")
        usage
        exit 0 ;;
    *)
        ARGS=( "${ARGS[@]}" "$1" ) ;;
    esac
    shift
done
set -- "${ARGS[@]}" "$@"

exec $CMD_PREFIX "$HERE/$BINARY" "$@"

The above was made to wrap up PS3 Media Server but obviously you replace BINARY with the script to call to start the program, DESKTOPN with the name of the ".desktop" file without the file extension, TITLE with the name of the program and CATEGORIES with the FreeDesktop spec list of program categories.

No comments:

Post a Comment