2

我正在尝试使用Gjs编写一个 GNOME GTK3 应用程序,它处理作为命令行参数传递的文件。为此,我连接了 的open信号Gtk.Application并设置了Gio.ApplicationFlags.HANDLES_OPEN标志:

#!/usr/bin/gjs

const Gio = imports.gi.Gio
const Gtk = imports.gi.Gtk
const Lang = imports.lang

const MyApplication = new Lang.Class({
  Name: 'MyApplication',

  _init: function() {
    this.application = new Gtk.Application({
      application_id: 'com.example.my-application',
      flags: Gio.ApplicationFlags.HANDLES_OPEN
    })

    this.application.connect('startup', this._onStartup.bind(this))
    this.application.connect('open', this._onOpen.bind(this))
    this.application.connect('activate', this._onActivate.bind(this))
  },

  _onStartup: function() {
    log('starting application')
  },

  _onOpen: function(application, files) {
    log('opening ' + files.length + ' files')
    this._onStartup()
  },

  _onActivate: function() {
    log('activating application')
  }
})

let app = new MyApplication()
app.application.run(ARGV)

当我使用文件参数运行程序时,我希望_onOpen使用传入的参数来调用它GFile。而是_onActivate被调用,就像我在没有任何文件参数的情况下运行它一样:

$ ./open-files.js open-files.js 
Gjs-Message: JS LOG: starting application
Gjs-Message: JS LOG: activating application

我正在运行 gjs@1.44。

4

1 回答 1

2

ARGV相对于其他语言的约定,GJS 的定义方式存在差异。例如,Cargv[0]是程序的名称,第一个参数从 开始argv[1]。在 GJS 中,程序的名称是System.programInvocationName,第一个参数是ARGV[0]

不幸的是,作为 C 库的一部分,Gtk.Application希望您根据 C 约定传入参数。你可以这样做:

ARGV.unshift(System.programInvocationName);

发生的事情是./open-files.js open-files.js['open-files.js']as解释为程序的名称,没有其他参数ARGVGtk.Application如果你用两个文件参数运行程序,你会看到它只“打开”了第二个文件。

PS。不幸的是,GJS 1.44 中似乎有一个错误会阻止open信号正常工作。现在,我建议通过子类Gtk.Application化而不是代理来解决这个问题。您的程序将如下所示:

const Gio = imports.gi.Gio
const Gtk = imports.gi.Gtk
const Lang = imports.lang
const System = imports.system

const MyApplication = new Lang.Class({
  Name: 'MyApplication',
  Extends: Gtk.Application,

  _init: function(props={}) {
    this.parent(props)
  },

  vfunc_startup: function() {
    log('starting application')
    this.parent()
  },

  vfunc_open: function(files, hint) {
    log('opening ' + files.length + ' files')
  },

  vfunc_activate: function() {
    log('activating application')
    this.parent()
  }
})

let app = new MyApplication({
  application_id: 'com.example.my-application',
  flags: Gio.ApplicationFlags.HANDLES_OPEN
})
ARGV.unshift(System.programInvocationName)
app.run(ARGV)
于 2016-02-06T05:23:35.283 回答