146. How to paste text from clipboard into GtkTextView - Part 1?

Problem

You want to paste text from clipboard into GtkTextView by pressing the Insert key as shown below:

How to paste text from clipboard into GtkTextView - Part 1?


Solution


Sample Code

Note: Copy some text into clipboard from other applications, then press the Insert button. Text will be inserted at the cursor position.

1   
2   
3   
4   
5   
6   
7   
8   
9   
10   
11   
12   
13   
14   
15   
17   
18   
19   
20   
21   
22   
23   
24   
25   
30   
31   
32   
33   
34   
35   
36   
37   
38   
39   
40   
41   
42   
43   
44   
45   
47   
48   
49   
51   
56   
57   
58   
59   
60   
61   
62   
<?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("Paste Text from clipboard into GtkTextView - Part 1\n".
"Press insert to paste the text");
$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);
$title->set_justify(Gtk::JUSTIFY_CENTER);
$alignment = new GtkAlignment(0.5, 0, 0, 0);
$alignment->add($title);
$vbox->pack_start($alignment, 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->modify_font(new PangoFontDescription("Arial 12"));
$view->set_wrap_mode(Gtk::WRAP_WORD);

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

$scrolled_win->add($view);

$clipboard = new GtkClipboard($view->get_display(), 
    Gdk::atom_intern('CLIPBOARD')); // note 1
$window->connect('key-press-event', 'on_keypress');
$window->show_all();
Gtk::main();

// process toolbar
function on_keypress($widget, $event) {
    if ($event->keyval==Gdk::KEY_Insert) { // note 2
        // use if ($event->keyval!=65379) if your version of php-gtk2
        // does not have Gdk::KEY_Insert defined
        global $buffer, $clipboard;
        $buffer->paste_clipboard($clipboard, null, true); // note 2
        return true;
    } else {
        return false; // note 3
    }
}

?>

Output

As shown above.
 

Explanation

  1. Set up the clipboard.
  2. If insert key is pressed, paste the text from clipboard into GtkTextBuffer at the cursor position.
  3. For all other keys, pass them back to the default keypress handler.

Note

Note that you can also press Ctrl-V to paste the text. It's inherently supported by php-gtk. So why go through all the trouble to duplicate the same functionality? For more control, of course...!

In the next article, we will see how we can do some processing before inserting the text into the GtkTextBuffer.

Related Links

Add comment


Security code
Refresh