Argos:几秒内打造 Gnome Shell 扩展

原地址:https://github.com/p-e-w/argos/blob/master/README.md

Argos

几秒内打造 Gnome Shell 扩展

Screencast

大部分 GNOME Shell 扩展做一件事:在面板上添加一个有下拉菜单的按钮,以显示信息并公开功能。即使以最简单的形式,创建这样一个扩展也是一项艰巨的工作, 涉及了不足的记录以及不断变化的 JavaScript API.

Argos 让您用一种每个 Linux 用户都已熟悉的语言来写 GNOME Shell 扩展——Bash 脚本.

更确切地说,Argos 是一个 GNOME Shell 扩展,将程序的标准输出转换为面板下拉菜单。它的灵感来自并且完全兼容 macOS 应用 BitBar. Argos 不需修改就可支持许多 BitBar 插件,使您除了编写自己的脚本外,还能访问经过了大量测试的脚本库。

主要特性

  • 100% 的 API 兼容 BitBar 1.9.2: 所有在 Linux 上运行的 BitBar 插件(即不包含 macOS 特有代码)通过 Argos 工作(否则就是个 bug).
  • 比 BitBar 更好: Argos 能做不仅 BitBar 能做的所有事,还有一些 BitBar (目前)不能做的。详细信息请参见文档。
  • 复杂的异步执行引擎: 不管您的脚本运行了多长时间,Argos 都能智能地安排并防止阻塞。
  • 支持 Unicode: 只需将您的文本输出到标准输出。它将会以您所期待的方式呈现。
  • 优化以减少系统资源消耗: 即使有多个插件每秒刷新一次,Argos 通常只占用不到 1% 的 CPU.
  • 完整的 文档

安装

通过 GNOME Shell Extensions 网站安装 (推荐方法)

img

如果您有 GNOME 软件中心的最新版,您也可以简单地搜索它并直接从那里安装。注意这种方法可能并不总是给您 Argos 的最新版。

手动

将这个储存库克隆下来,然后复制或者链接目录 argos@pew.worldwidemann.com~/.local/share/gnome-shell/extensions。按下 Alt+F2,然后输入 r 以重启 GNOME Shell 。在一些系统上,您可能还需要用 GNOME Tweak Tool 启用 Argos 扩展。

范例

GNOME Shell 日志查看器

Argos 插件非常适合监控您的系统,在一个方便、不引人注目的地方显示命令行脚本输出的任何东西。

插件开发者常常依靠中央 GNOME Shell 日志来调试。日志可能是通过 journalctl /usr/bin/gnome-shell -f 来查看——但这也是我们第一个示例插件的绝佳目标:

shell_log.1s.sh

1
2
3
4
5
6
7
#!/usr/bin/env bash

LOG_ENTRY=$(journalctl /usr/bin/gnome-shell -n 1 --output=cat --no-pager)
echo "<span color='#9BF' weight='normal'><small><tt>$LOG_ENTRY</tt></small></span> | length=40"

echo "---"
echo "View GNOME Shell Log | bash='journalctl /usr/bin/gnome-shell -f'"

给予它执行权限并放到 ~/.config/argos,这样您就能看到想这样的东西:

Shell Log

因为这个插件每秒更新一次,新日志条目的显示几乎没有任何延迟。

简单的启动器

插件并不只限于显示信息——它们还可以在用户单击菜单项时执行操作。这允许您快速地创建启动器,使其外观和行为完全符合您的要求。

launcher.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env bash

echo "Launcher | iconName=starred"
echo "---"

WIKIPEDIA_ICON=$(curl -s "https://en.wikipedia.org/static/favicon/wikipedia.ico" | base64 -w 0)
echo "Wikipedia | image='$WIKIPEDIA_ICON' imageWidth=20 font=serif href='https://en.wikipedia.org'"

echo "---"
echo "Gedit | iconName=gedit bash=gedit terminal=false"
echo "Nautilus | iconName=system-file-manager bash=nautilus terminal=false"
echo "Process list (<span color='yellow'><tt>top</tt></span>) | iconName=utilities-terminal-symbolic bash=top"
echo "---"
echo "Looking Glass | eval='imports.ui.main.createLookingGlass(); imports.ui.main.lookingGlass.toggle();'"

Simple Launcher

注意维基百科的图标是从网上下载下来的并且被插入菜单项中,无需保存到硬盘中。所有这些都来自a file smaller than大部分专用“启动器”扩展的配置文件,同时提供更大的灵活性。Argos 插件模糊了配置与代码之间的的界限。

高级启动器

一个 Argos 插件只是一个写入标准输出的可执行文件。因此,任何语言都可以用来创建插件。从 Bash 切换到 Python 使您轻松访问 GNOME 平台 API,启用更强大的启动器。

launcher.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env python3

import re
from gi.repository import Gio

applications = {}

for app_info in Gio.AppInfo.get_all():
icon, categories = app_info.get_icon(), app_info.get_categories()
if icon is None or categories is None:
continue
# Remove "%U" and "%F" placeholders
command_line = re.sub("%\\w", "", app_info.get_commandline()).strip()
app = (app_info.get_name(), icon.to_string(), command_line)
for category in categories.split(";"):
if category not in ["GNOME", "GTK", ""]:
if category not in applications:
applications[category] = []
applications[category].append(app)
break

print("Applications\n---")

for category, apps in sorted(applications.items()):
print(category)
for app in sorted(apps):
print("--%s | useMarkup=false iconName=%s bash='%s' terminal=false" % app)

Advanced Launcher

然后您就有了:一个完善的 GNOME Shell 插件的有效克隆——仅适用少量代码实现。

top 查看器

Argos 基本上将标准输出传递到面板菜单中。这产生了一些很酷的插件,像这个 top 输出查看器:

top.3s+.sh

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env bash

echo "top"
echo "---"

if [ "$ARGOS_MENU_OPEN" == "true" ]; then
# http://stackoverflow.com/a/14853319
TOP_OUTPUT=$(top -b -n 1 | head -n 20 | awk 1 ORS="\\\\n")
echo "$TOP_OUTPUT | font=monospace bash=top"
else
echo "Loading..."
fi

top Viewer

它触手可及!当然,这种方法也适用于其他任何终端程序。

Note that the plugin checks the ARGOS_MENU_OPEN environment variable to ensure top is run only if the dropdown menu is visible, while the + in the filename forces a re-run whenever the user opens the menu. This pattern makes output available immediately when it is needed, but keeps idle resource consumption of the plugin near zero.

Usage

Argos monitors the directory ~/.config/argos for changes. Any executable file found in this directory is considered a plugin. Files whose name starts with a dot (.) and files in subdirectories are ignored.

Plugins are run and their standard output is interpreted as described below. For each plugin, a panel button with a dropdown menu is created. The arrangement of buttons from left to right follows the alphabetical order of the files they are generated from (except when a POSITION is explicitly specified in the filename). New plugins and edits to existing plugins are automatically detected and reflected in the panel.

Filename format

A plugin file may be named anything (it only needs to be executable), but if its name has the special form

1
NAME.POSITION.INTERVAL[+].EXTENSION

where

  • POSITION consists of an integer (optional) + one of l (left), c (center) or r (right), and
  • INTERVAL consists of an integer + one of s (seconds), m (minutes), h (hours) or d (days)

then

  • the dropdown menu button is placed in the panel at POSITION, and
  • the plugin is re-run and its output re-rendered every INTERVAL, and
  • if INTERVAL is followed by +, the plugin is additionally re-run each time the dropdown menu is opened.

POSITION may be omitted entirely (in which case the button is placed before all other buttons on the right-hand side of the panel) while INTERVAL can be left empty. For example, a script named plugin.10s.sh is updated every 10 seconds, the button belonging to plugin.1c..sh is positioned just right of the GNOME Shell clock, and plugin.l.1m.sh is displayed left of the “Activities” button and updated every minute.

Output format

Argos plugins are executables (such as shell scripts) that print to standard output lines of the following form:

1
TEXT | ATTRIBUTE_1=VALUE ATTRIBUTE_2=VALUE ...

All attributes are optional, so the most basic plugins simply print lines consisting of text to be displayed. To include whitespace, attribute values may be quoted using the same convention employed by most command line shells.

Rendering

Lines containing only dashes (---) are separators.

Lines above the first separator belong to the button itself. If there are multiple such lines, they are displayed in succession, each of them for 3 seconds before switching to the next. Additionally, all button lines get a dropdown menu item, except if their dropdown attribute is set to false.

Lines below the first separator are rendered as dropdown menu items. Further separators create graphical separator menu items.

Lines beginning with -- are rendered in a submenu associated with the preceding unindented line. While Argos supports nested submenus in principle, GNOME Shell does not render them correctly.

Emoji codes like :horse: horse and :smile: smile in the line text are replaced with their corresponding Unicode characters (unless the emojize attribute is set to false). Note that multicolor emoji rendering requires GNOME 3.26 or later.

ANSI SGR escape sequences and Pango markup tags may be used for styling. This can be disabled by setting the ansi and useMarkup attributes, respectively, to false.

Backslash escapes such as \n and \t in the line text are converted to their corresponding characters (newline and tab in this case), which can be prevented by setting the unescape attribute to false. Newline escapes can be used to create multi-line menu items.

Line attributes

Display

Control how the line is rendered.

Attribute Value Description
color Hex RGB/RGBA or color name Sets the text color for the item.
font Font name Sets the font for the item.
size Font size in points Sets the font size for the item.
iconName Icon name Sets a menu icon for the item. See the freedesktop.org icon naming specification for a list of names that should work anywhere, or run gtk3-icon-browser to see the names of all icons in your current icon theme. Argos only.
image, templateImage Base64-encoded image file Renders an image inside the item. The image is positioned to the left of the text and to the right of the icon. GNOME Shell does not have a concept of “template images”, so image and templateImage are interchangeable in Argos.
imageWidth, imageHeight Width/height in pixels Sets the dimensions of the image. If only one dimension is specified, the image’s original aspect ratio is maintained. Argos only.
length Length in characters Truncate the line text to the specified number of characters, ellipsizing the truncated part.
trim true or false If false, preserve leading and trailing whitespace of the line text.
dropdown true or false If false and the line is a button line (see above), exclude it from being displayed in the dropdown menu.
alternate true or false If true, the item is hidden by default, and shown in place of the preceding item when the Alt key is pressed.
emojize true or false If false, disable substitution of :emoji_name: with emoji characters in the line text.
ansi true or false If false, disable interpretation of ANSI escape sequences in the line text.
useMarkup true or false If false, disable interpretation of Pango markup in the line text. Argos only.
unescape true or false If false, disable interpretation of backslash escapes such as \n in the line text. Argos only.

Actions

Define actions to be performed when the user clicks on the line’s menu item.

Action attributes are not mutually exclusive. Any combination of them may be associated with the same item, and all actions are executed when the item is clicked.

Attribute Value Description
bash Bash command Runs a command using bash inside a GNOME Terminal window.
terminal true or false If false, runs the Bash command in the background (i.e. without opening a terminal window).
param1, param2, … Command line arguments Arguments to be passed to the Bash command. Note: Provided for compatibility with BitBar only. Argos allows placing arguments directly in the command string.
href URI Opens a URI in the application registered to handle it. URIs starting with http:// launch the web browser, while file:// URIs open the file in its associated default application.
eval JavaScript code Passes the code to JavaScript’s eval function. Argos only.
refresh true or false If true, re-runs the plugin, updating its output.

Environment variables

Plugin executables are run with the following special environment variables set:

Name Value
ARGOS_VERSION Version number of the Argos extension. The presence of this environment variable can also be used to determine that the plugin is actually running in Argos, rather than BitBar or kargos.
ARGOS_MENU_OPEN true if the dropdown menu was open at the time the plugin was run, and false otherwise.

BitBar plugins with Argos

These screenshots show how some scripts from the BitBar plugin repository look when rendered by Argos compared to the “canonical” BitBar rendering (macOS screenshots taken from https://getbitbar.com).

Plugin BitBar on macOS Argos on GNOME Shell
Ping Ping/BitBar Ping/Argos
Stock Ticker Stock Ticker/BitBar Stock Ticker/Argos
World Clock World Clock/BitBar World Clock/Argos
Unicorn Unicorn/BitBar Unicorn/Argos
ANSI ANSI/BitBar ANSI/Argos

Acknowledgments

GNOME Shell is a difficult platform to develop for. At the time this project was started, the Gjs documentation hadn’t been updated in three years and was missing important classes (new documentation has since appeared). Once again, Valadoc saved the day for me. While not fully identical to the Gjs API, Valadoc is the best manual for GNOME on the web today.

Argos includes emojilib‘s emoji name/character mappings. It’s wonderful that such a comprehensive and well-maintained library is so easily available.

Without BitBar, Argos wouldn’t be what it is today, or, more likely, wouldn’t exist at all. There have been many attempts on many platforms to simplify panel menu creation, but BitBar was the first to get it right by finding the balance between text-only configuration and dynamic output. Thank you for showing the way!

Contributing

Contributors are always welcome. However, please file an issue describing what you intend to add before opening a pull request, especially for new features! I have a clear vision of what I want (and do not want) Argos to be, so discussing potential additions might help you avoid duplication and wasted work.

By contributing, you agree to release your changes under the same license as the rest of the project (see below).

License

Copyright © 2016-2018 Philipp Emanuel Weidmann (pew@worldwidemann.com)

Released under the terms of the GNU General Public License, version 3