GJS と GNOME プラットフォーム (GTK+、GLib、Gio、GObject) を使用して JavaScript で簡単なデスクトップ アプリケーションを作成しています。以下のコードは、私が直面している状況を示しており、アプリケーションが使用するファイルにアクセスする必要がないため、簡単に再現できます。要するに、一連の非同期タスク (一連のファイルの内容の読み込み) を完了した後、指定されたコード行を実行したいと思います。どうすれば GJS でこれを行うことができますか?
#!/usr/bin/gjs
const Lang = imports.lang;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
const Home = new Lang.Class({
Name: "Home",
// Start snippet 1
_enumerateChildrenAsyncCallback: function(dir, result) {
let fileEnumerator = dir.enumerate_children_finish(result);
let displayName, file, fileInfo, fileType, iter;
while ((fileInfo = fileEnumerator.next_file(null))) {
iter = this.model.append();
displayName = fileInfo.get_display_name();
this.model.set(iter, [0], [displayName], 1);
file = dir.get_child(fileInfo.get_name());
fileType = file.query_file_type(Gio.FileQueryInfoFlags.NONE, null);
if (fileType != Gio.FileType.REGULAR) continue;
file.load_contents_async(null, function(file, result) {
let [success, contents, etag] = file.load_contents_finish(result);
let message = "";
if (success) {
message = "Finished loading file %s";
} else {
message = "Couldn't load file %s";
}
log(message.replace("%s", file.get_basename()));
});
}
},
_init: function() {
this.application = new Gtk.Application();
this.application.connect("activate", Lang.bind(this, this._onActivate));
this.application.connect("startup", Lang.bind(this, this._onStartup));
},
_onActivate: function() {
this._window.show_all();
},
_onStartup: function() {
this.model = new Gtk.ListStore();
this.model.set_column_types([GObject.TYPE_STRING]);
let renderer = new Gtk.CellRendererText();
let dir = Gio.file_new_for_path(GLib.get_home_dir());
dir.enumerate_children_async("standard::*",
Gio.FileQueryInfoFlags.NONE,
GLib.PRIORITY_DEFAULT,
null,
Lang.bind(this, this._enumerateChildrenAsyncCallback),
null);
/*
* I would like this line to be run after all files have been read.
*
*/
this.model.set_sort_column_id(0, Gtk.SortType.ASCENDING);
let column = new Gtk.TreeViewColumn({
title: "Files"
});
column.pack_start(renderer, true);
column.add_attribute(renderer, "text", 0);
let view = new Gtk.TreeView({
model: this.model
});
view.append_column(column);
let scrolled = new Gtk.ScrolledWindow();
scrolled.hscrollbar_policy = Gtk.PolicyType.AUTOMATIC;
scrolled.Vscrollbar_policy = Gtk.PolicyType.AUTOMATIC;
scrolled.add(view);
this._window = new Gtk.ApplicationWindow({
application: this.application,
default_height: 300,
default_width: 400,
title: "Home, sweet home"
});
this._window.add(scrolled);
}
});
let home = new Home();
home.application.run(ARGV);
PS: 提供されたコードでは、すべての非同期タスクを終了する前に示されたコード行を実行しても、アプリケーションが正しく動作することは妨げられません。ただし、ファイルが読み込まれるたびにリストをソートするのではなく、アプリケーションの起動時に一度だけリストをソートしたいと考えています。そしてもちろん、その方法を知っていれば、別の状況でも役立ちます。