Languages

Asynchronous GIO sample

No votes yet
/* Asynchronous GIO in Vala sample code */
 
using Gtk;
 
/**
 * Loads the list of files in users home directory and displays them
 * in a GTK+ list view.
 */
public class ASyncGIOSample : Gtk.Window {
 
    private File dir;
    private Gtk.ListStore model;
 
    construct {
        this.setup ();
    }
 
    /* Set up the window and widget */
    private void setup () {
        var sc = new Gtk.ScrolledWindow (null, null);
        sc.set_policy (Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC);
 
        var tv = new Gtk.TreeView ();
        sc.add (tv);
 
        tv.insert_column_with_attributes (-1, "Filename",
                                    new Gtk.CellRendererText (), "text", 0);
 
        this.model = new Gtk.ListStore (1, typeof (string));
        tv.set_model (model);
 
        this.add (sc);
 
        this.set_default_size (300, 200);
 
        this.destroy.connect (Gtk.main_quit);
 
        // start file listing process
        this.list_dir ();
    }
 
    private void list_dir () {
        stdout.printf ("startscan\n");
        this.dir = File.new_for_path (Environment.get_home_dir ());
        // asynchronous call, with callback, to get dir entries
        this.dir.enumerate_children_async (FILE_ATTRIBUTE_STANDARD_NAME, 0,
                                        Priority.DEFAULT, null, list_ready);
    }
 
    /* Callback for enumerate_children_async */
    private void list_ready (GLib.Object? file, AsyncResult res) {
        try {
            FileEnumerator e = ((File) file).enumerate_children_finish (res);
            // asynchronous call, with callback, to get entries so far
            e.next_files_async (10, Priority.DEFAULT, null, list_files);
        } catch (Error err) {
            stdout.printf ("error async_ready failed %s\n", err.message);
        }
    }
 
    /* Callback for next_files_async */
    private void list_files (GLib.Object? sender, AsyncResult res) {
        Gtk.TreeIter iter;
        try {
            var enumer = (FileEnumerator) sender;
 
            // get a list of the files found so far
            List<FileInfo> list = enumer.next_files_finish (res);
            foreach (FileInfo info in list) {
                this.model.append (out iter);
                this.model.set (iter, 0, info.get_name ());
            }
 
            // asynchronous call, with callback, to get any more entries
            enumer.next_files_async (10, Priority.DEFAULT, null, list_files);
        } catch (Error err) {
            stdout.printf ("error list_files failed %s\n", err.message);
        }
    }
 
    public static int main (string[] args) {
        Gtk.init (ref args);
 
        var test = new ASyncGIOSample ();
        test.show_all ();
 
        Gtk.main ();
        return 0;
    }
}