496. How to display a text file in GtkTextView with drag and drop?

Problem

You want to allow users to display a text file in a GtkTextView with drag-and-drop as shown below:

How to display a text file in GtkTextView with drag and drop?


Solution

  • Read the entire file into a string with file_get_contents($filename).
  • Insert the text into the text buffer with GtkTextbuffer::set_text().

Sample Code

1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
12   
13   
14   
15   
16   
17   
18   
20   
25   
26   
27   
28   
29   
30   
31   
32   
33   
34   
35   
36   
37   
38   
39   
40   
41   
42   
43   
44   
46   
47   
48   
49   
50   
51   
52   
<?php
$window = new GtkWindow();
$window->set_size_request(400, 240);
$window->connect_simple('destroy', array('Gtk','main_quit'));
$window->add($vbox = new GtkVBox());

// display title
$title = new GtkLabel("Display a text file in GtkTextView with drag-and-drop");
$title->modify_font(new PangoFontDescription("Times New Roman Italic 10"));
$title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#0000ff"));
$title->set_size_request(-1, 40);
$vbox->pack_start($title, 0, 0);
$vbox->pack_start(new GtkLabel(), 0, 0);

// Create a new buffer and a new view to show the buffer.
$buffer = new GtkTextBuffer();
$view = new GtkTextView();
$view->set_buffer($buffer);
$view->set_wrap_mode(Gtk::WRAP_WORD);
$view->drag_dest_set(Gtk::DEST_DEFAULT_ALL, // note 1
    array( array( 'text/uri-list', 0, 0)), Gdk::ACTION_COPY); 
$view->connect('drag-data-received', 'on_drop', $view); // note 1

$scrolled_win = new GtkScrolledWindow();
$scrolled_win->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
$vbox->pack_start($scrolled_win);

$scrolled_win->add($view);

$window->show_all();
Gtk::main();

// process drop
function on_drop($widget, $context, $x, $y, $data, $info, $time, $view) {
    $uri_list = explode("\n",$data->data);
    $filename = $uri_list[0];
    $filename = str_replace("file:///", "", $filename);
    $filename = str_replace("\r", "", $filename);

    $contents = file_get_contents($filename); // note 2
    $buffer = $view->get_buffer();
    $buffer->set_text($contents); // note 3

}

?>

Output

As shown above.
 

Explanation

  1. Set up the text view so that it allows users to drop a text file onto it.
  2. Read in the entire file.
  3. Insert the text into the text buffer.

Related Links

Add comment


Security code
Refresh