7.2. 为所有用户添加自定义 MIME 类型

您必须在 /usr/share/mime/packages/ 目录中创建一个新的 MIME 类型规范文件,并在 /usr/share/applications/ 目录中创建一个 .desktop 文件,以便在系统上为所有用户添加自定义 MIME 类型,并为该 MIME 类型注册默认应用程序。

流程

  1. 使用以下内容创建 /usr/share/mime/packages/application-x-newtype.xml 文件:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
      <mime-type type="application/x-newtype">
        <comment>new mime type</comment>
        <glob pattern="*.xyz"/>
      </mime-type>
    </mime-info>

    这里的示例 application-x-newtype.xml 文件定义了一个新的 MIME 类型 application/x-newtype,并将带有扩展名 .xyz 的文件名分配给该 MIME 类型。

  2. 创建一个新的 .desktop 文件,例如,在 /usr/share/applications/ 中创建 myapplication1.desktop,其中包含以下内容:

    [Desktop Entry]
    Type=Application
    MimeType=application/x-newtype
    Name=My Application 1
    Exec=myapplication1 field_code

    此处的示例 myapplication1.desktop 文件将 application/x-newtype MIME 类型与名为 My Application 1 的应用程序相关联。它通过命令 myapplication1 来运行。

    根据 myapplication1 的启动方式,从 Desktop Entry Specification 中选择一个相应的字段代码。例如,对于能够打开多个文件的应用程序,请使用:

    Exec=myapplication1 %F
  3. 以 root 用户身份,更新 MIME 数据库以使您的更改生效。

    # update-mime-database /usr/share/mime
  4. 以 root 用户身份,更新应用程序数据库。

    # update-desktop-database /usr/share/applications

验证步骤

  1. 要验证已将 *.xyz 文件与 application/x-newtype MIME 类型成功关联,请首先创建一个空文件,如 test.xyz ,然后执行以下命令:

    $ touch test.xyz
    
    $ gvfs-info test.xyz | grep "standard::content-type"
      standard::content-type: application/x-newtype
  2. 要验证 myapplication1.desktop 是否已正确设置为 application/x-newtype MIME 类型的默认注册的应用程序,请执行以下命令:

    $ gio mime --query application/x-newtype
    Default application for 'application/x-newtype': myapplication1.desktop
    Registered applications:
    	myapplication1.desktop
    Recommended applications:
    	myapplication1.desktop