]> git.saurik.com Git - wxWidgets.git/blob - src/gtk/textctrl.cpp
new graphics context implementation
[wxWidgets.git] / src / gtk / textctrl.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/gtk/textctrl.cpp
3 // Purpose:
4 // Author: Robert Roebling
5 // Id: $Id$
6 // Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin, 2005 Mart Raudsepp
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
12
13 #include "wx/textctrl.h"
14
15 #ifndef WX_PRECOMP
16 #include "wx/intl.h"
17 #include "wx/log.h"
18 #include "wx/utils.h"
19 #include "wx/settings.h"
20 #include "wx/math.h"
21 #endif
22
23 #include "wx/strconv.h"
24 #include "wx/fontutil.h" // for wxNativeFontInfo (GetNativeFontInfo())
25
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <ctype.h>
29
30 #include "wx/gtk/private.h"
31
32 // ----------------------------------------------------------------------------
33 // helpers
34 // ----------------------------------------------------------------------------
35
36 extern "C" {
37 static void wxGtkOnRemoveTag(GtkTextBuffer *buffer,
38 GtkTextTag *tag,
39 GtkTextIter *start,
40 GtkTextIter *end,
41 char *prefix)
42 {
43 gchar *name;
44 g_object_get (tag, "name", &name, NULL);
45
46 if (!name || strncmp(name, prefix, strlen(prefix)))
47 // anonymous tag or not starting with prefix - don't remove
48 g_signal_stop_emission_by_name (buffer, "remove_tag");
49
50 g_free(name);
51 }
52 }
53
54 extern "C" {
55 static void wxGtkTextApplyTagsFromAttr(GtkWidget *text,
56 GtkTextBuffer *text_buffer,
57 const wxTextAttr& attr,
58 GtkTextIter *start,
59 GtkTextIter *end)
60 {
61 static gchar buf[1024];
62 GtkTextTag *tag;
63
64 gulong remove_handler_id = g_signal_connect (text_buffer, "remove_tag",
65 G_CALLBACK (wxGtkOnRemoveTag), gpointer("WX"));
66 gtk_text_buffer_remove_all_tags(text_buffer, start, end);
67 g_signal_handler_disconnect (text_buffer, remove_handler_id);
68
69 if (attr.HasFont())
70 {
71 PangoFontDescription *font_description = attr.GetFont().GetNativeFontInfo()->description;
72 wxGtkString font_string(pango_font_description_to_string(font_description));
73 g_snprintf(buf, sizeof(buf), "WXFONT %s", font_string.c_str());
74 tag = gtk_text_tag_table_lookup( gtk_text_buffer_get_tag_table( text_buffer ),
75 buf );
76 if (!tag)
77 tag = gtk_text_buffer_create_tag( text_buffer, buf,
78 "font-desc", font_description,
79 NULL );
80 gtk_text_buffer_apply_tag (text_buffer, tag, start, end);
81
82 if (attr.GetFont().GetUnderlined())
83 {
84 g_snprintf(buf, sizeof(buf), "WXFONTUNDERLINE");
85 tag = gtk_text_tag_table_lookup( gtk_text_buffer_get_tag_table( text_buffer ),
86 buf );
87 if (!tag)
88 tag = gtk_text_buffer_create_tag( text_buffer, buf,
89 "underline-set", TRUE,
90 "underline", PANGO_UNDERLINE_SINGLE,
91 NULL );
92 gtk_text_buffer_apply_tag (text_buffer, tag, start, end);
93 }
94 }
95
96 if (attr.HasTextColour())
97 {
98 const GdkColor *colFg = attr.GetTextColour().GetColor();
99 g_snprintf(buf, sizeof(buf), "WXFORECOLOR %d %d %d",
100 colFg->red, colFg->green, colFg->blue);
101 tag = gtk_text_tag_table_lookup( gtk_text_buffer_get_tag_table( text_buffer ),
102 buf );
103 if (!tag)
104 tag = gtk_text_buffer_create_tag( text_buffer, buf,
105 "foreground-gdk", colFg, NULL );
106 gtk_text_buffer_apply_tag (text_buffer, tag, start, end);
107 }
108
109 if (attr.HasBackgroundColour())
110 {
111 const GdkColor *colBg = attr.GetBackgroundColour().GetColor();
112 g_snprintf(buf, sizeof(buf), "WXBACKCOLOR %d %d %d",
113 colBg->red, colBg->green, colBg->blue);
114 tag = gtk_text_tag_table_lookup( gtk_text_buffer_get_tag_table( text_buffer ),
115 buf );
116 if (!tag)
117 tag = gtk_text_buffer_create_tag( text_buffer, buf,
118 "background-gdk", colBg, NULL );
119 gtk_text_buffer_apply_tag (text_buffer, tag, start, end);
120 }
121
122 if (attr.HasAlignment())
123 {
124 GtkTextIter para_start, para_end = *end;
125 gtk_text_buffer_get_iter_at_line( text_buffer,
126 &para_start,
127 gtk_text_iter_get_line(start) );
128 gtk_text_iter_forward_line(&para_end);
129
130 remove_handler_id = g_signal_connect (text_buffer, "remove_tag",
131 G_CALLBACK(wxGtkOnRemoveTag),
132 gpointer("WXALIGNMENT"));
133 gtk_text_buffer_remove_all_tags( text_buffer, &para_start, &para_end );
134 g_signal_handler_disconnect (text_buffer, remove_handler_id);
135
136 GtkJustification align;
137 switch (attr.GetAlignment())
138 {
139 default:
140 align = GTK_JUSTIFY_LEFT;
141 break;
142 case wxTEXT_ALIGNMENT_RIGHT:
143 align = GTK_JUSTIFY_RIGHT;
144 break;
145 case wxTEXT_ALIGNMENT_CENTER:
146 align = GTK_JUSTIFY_CENTER;
147 break;
148 // gtk+ doesn't support justify as of gtk+-2.7.4
149 }
150
151 g_snprintf(buf, sizeof(buf), "WXALIGNMENT %d", align);
152 tag = gtk_text_tag_table_lookup( gtk_text_buffer_get_tag_table( text_buffer ),
153 buf );
154 if (!tag)
155 tag = gtk_text_buffer_create_tag( text_buffer, buf,
156 "justification", align, NULL );
157 gtk_text_buffer_apply_tag( text_buffer, tag, &para_start, &para_end );
158 }
159
160 if (attr.HasLeftIndent())
161 {
162 // Indentation attribute
163
164 // Clear old indentation tags
165 GtkTextIter para_start, para_end = *end;
166 gtk_text_buffer_get_iter_at_line( text_buffer,
167 &para_start,
168 gtk_text_iter_get_line(start) );
169 gtk_text_iter_forward_line(&para_end);
170
171 remove_handler_id = g_signal_connect (text_buffer, "remove_tag",
172 G_CALLBACK(wxGtkOnRemoveTag),
173 gpointer("WXINDENT"));
174 gtk_text_buffer_remove_all_tags( text_buffer, &para_start, &para_end );
175 g_signal_handler_disconnect (text_buffer, remove_handler_id);
176
177 // Convert indent from 1/10th of a mm into pixels
178 float factor;
179 #if GTK_CHECK_VERSION(2,2,0)
180 if (!gtk_check_version(2,2,0))
181 factor = (float)gdk_screen_get_width(gtk_widget_get_screen(text)) /
182 gdk_screen_get_width_mm(gtk_widget_get_screen(text)) / 10;
183 else
184 #endif
185 factor = (float)gdk_screen_width() / gdk_screen_width_mm() / 10;
186
187 const int indent = (int)(factor * attr.GetLeftIndent());
188 const int subIndent = (int)(factor * attr.GetLeftSubIndent());
189
190 gint gindent;
191 gint gsubindent;
192
193 if (subIndent >= 0)
194 {
195 gindent = indent;
196 gsubindent = -subIndent;
197 }
198 else
199 {
200 gindent = -subIndent;
201 gsubindent = indent;
202 }
203
204 g_snprintf(buf, sizeof(buf), "WXINDENT %d %d", gindent, gsubindent);
205 tag = gtk_text_tag_table_lookup( gtk_text_buffer_get_tag_table( text_buffer ),
206 buf );
207 if (!tag)
208 tag = gtk_text_buffer_create_tag( text_buffer, buf,
209 "left-margin", gindent, "indent", gsubindent, NULL );
210 gtk_text_buffer_apply_tag (text_buffer, tag, &para_start, &para_end);
211 }
212
213 if (attr.HasTabs())
214 {
215 // Set tab stops
216
217 // Clear old tabs
218 GtkTextIter para_start, para_end = *end;
219 gtk_text_buffer_get_iter_at_line( text_buffer,
220 &para_start,
221 gtk_text_iter_get_line(start) );
222 gtk_text_iter_forward_line(&para_end);
223
224 remove_handler_id = g_signal_connect (text_buffer, "remove_tag",
225 G_CALLBACK(wxGtkOnRemoveTag),
226 gpointer("WXTABS"));
227 gtk_text_buffer_remove_all_tags( text_buffer, &para_start, &para_end );
228 g_signal_handler_disconnect (text_buffer, remove_handler_id);
229
230 const wxArrayInt& tabs = attr.GetTabs();
231
232 wxString tagname = _T("WXTABS");
233 g_snprintf(buf, sizeof(buf), "WXTABS");
234 for (size_t i = 0; i < tabs.GetCount(); i++)
235 tagname += wxString::Format(_T(" %d"), tabs[i]);
236
237 const wxWX2MBbuf buf = tagname.mb_str(wxConvUTF8);
238
239 tag = gtk_text_tag_table_lookup( gtk_text_buffer_get_tag_table( text_buffer ),
240 buf );
241 if (!tag)
242 {
243 // Factor to convert from 1/10th of a mm into pixels
244 float factor;
245 #if GTK_CHECK_VERSION(2,2,0)
246 if (!gtk_check_version(2,2,0))
247 factor = (float)gdk_screen_get_width(gtk_widget_get_screen(text)) /
248 gdk_screen_get_width_mm(gtk_widget_get_screen(text)) / 10;
249 else
250 #endif
251 factor = (float)gdk_screen_width() / gdk_screen_width_mm() / 10;
252
253 PangoTabArray* tabArray = pango_tab_array_new(tabs.GetCount(), TRUE);
254 for (size_t i = 0; i < tabs.GetCount(); i++)
255 pango_tab_array_set_tab(tabArray, i, PANGO_TAB_LEFT, (gint)(tabs[i] * factor));
256 tag = gtk_text_buffer_create_tag( text_buffer, buf,
257 "tabs", tabArray, NULL );
258 pango_tab_array_free(tabArray);
259 }
260 gtk_text_buffer_apply_tag (text_buffer, tag, &para_start, &para_end);
261 }
262 }
263 }
264
265 extern "C" {
266 static void wxGtkTextInsert(GtkWidget *text,
267 GtkTextBuffer *text_buffer,
268 const wxTextAttr& attr,
269 const wxCharBuffer& buffer)
270
271 {
272 gint start_offset;
273 GtkTextIter iter, start;
274
275 gtk_text_buffer_get_iter_at_mark( text_buffer, &iter,
276 gtk_text_buffer_get_insert (text_buffer) );
277 start_offset = gtk_text_iter_get_offset (&iter);
278 gtk_text_buffer_insert( text_buffer, &iter, buffer, strlen(buffer) );
279
280 gtk_text_buffer_get_iter_at_offset (text_buffer, &start, start_offset);
281
282 wxGtkTextApplyTagsFromAttr(text, text_buffer, attr, &start, &iter);
283 }
284 }
285
286 // ----------------------------------------------------------------------------
287 // "insert_text" for GtkEntry
288 // ----------------------------------------------------------------------------
289
290 extern "C" {
291 static void
292 gtk_insert_text_callback(GtkEditable *editable,
293 const gchar *new_text,
294 gint new_text_length,
295 gint *position,
296 wxTextCtrl *win)
297 {
298 if (g_isIdle)
299 wxapp_install_idle_handler();
300
301 // we should only be called if we have a max len limit at all
302 GtkEntry *entry = GTK_ENTRY (editable);
303
304 wxCHECK_RET( entry->text_max_length, _T("shouldn't be called") );
305
306 // check that we don't overflow the max length limit
307 //
308 // FIXME: this doesn't work when we paste a string which is going to be
309 // truncated
310 if ( entry->text_length == entry->text_max_length )
311 {
312 // we don't need to run the base class version at all
313 g_signal_stop_emission_by_name (editable, "insert_text");
314
315 // remember that the next changed signal is to be ignored to avoid
316 // generating a dummy wxEVT_COMMAND_TEXT_UPDATED event
317 win->IgnoreNextTextUpdate();
318
319 // and generate the correct one ourselves
320 wxCommandEvent event(wxEVT_COMMAND_TEXT_MAXLEN, win->GetId());
321 event.SetEventObject(win);
322 event.SetString(win->GetValue());
323 win->GetEventHandler()->ProcessEvent( event );
324 }
325 }
326 }
327
328 // Implementation of wxTE_AUTO_URL for wxGTK2 by Mart Raudsepp,
329
330 extern "C" {
331 static void
332 au_apply_tag_callback(GtkTextBuffer *buffer,
333 GtkTextTag *tag,
334 GtkTextIter *start,
335 GtkTextIter *end,
336 gpointer textctrl)
337 {
338 if(tag == gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(buffer), "wxUrl"))
339 g_signal_stop_emission_by_name (buffer, "apply_tag");
340 }
341 }
342
343 //-----------------------------------------------------------------------------
344 // GtkTextCharPredicates for gtk_text_iter_*_find_char
345 //-----------------------------------------------------------------------------
346
347 extern "C" {
348 static gboolean
349 pred_whitespace (gunichar ch, gpointer user_data)
350 {
351 return g_unichar_isspace(ch);
352 }
353 }
354
355 extern "C" {
356 static gboolean
357 pred_non_whitespace (gunichar ch, gpointer user_data)
358 {
359 return !g_unichar_isspace(ch);
360 }
361 }
362
363 extern "C" {
364 static gboolean
365 pred_nonpunct (gunichar ch, gpointer user_data)
366 {
367 return !g_unichar_ispunct(ch);
368 }
369 }
370
371 extern "C" {
372 static gboolean
373 pred_nonpunct_or_slash (gunichar ch, gpointer user_data)
374 {
375 return !g_unichar_ispunct(ch) || ch == '/';
376 }
377 }
378
379 //-----------------------------------------------------------------------------
380 // Check for links between s and e and correct tags as necessary
381 //-----------------------------------------------------------------------------
382
383 // This function should be made match better while being efficient at one point.
384 // Most probably with a row of regular expressions.
385 extern "C" {
386 static void
387 au_check_word( GtkTextIter *s, GtkTextIter *e )
388 {
389 static const char *URIPrefixes[] =
390 {
391 "http://",
392 "ftp://",
393 "www.",
394 "ftp.",
395 "mailto://",
396 "https://",
397 "file://",
398 "nntp://",
399 "news://",
400 "telnet://",
401 "mms://",
402 "gopher://",
403 "prospero://",
404 "wais://",
405 };
406
407 GtkTextIter start = *s, end = *e;
408 GtkTextBuffer *buffer = gtk_text_iter_get_buffer(s);
409
410 // Get our special link tag
411 GtkTextTag *tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(buffer), "wxUrl");
412
413 // Get rid of punctuation from beginning and end.
414 // Might want to move this to au_check_range if an improved link checking doesn't
415 // use some intelligent punctuation checking itself (beware of undesired iter modifications).
416 if(g_unichar_ispunct( gtk_text_iter_get_char( &start ) ) )
417 gtk_text_iter_forward_find_char( &start, pred_nonpunct, NULL, e );
418
419 gtk_text_iter_backward_find_char( &end, pred_nonpunct_or_slash, NULL, &start );
420 gtk_text_iter_forward_char(&end);
421
422 gchar* text = gtk_text_iter_get_text( &start, &end );
423 size_t len = strlen(text), prefix_len;
424 size_t n;
425
426 for( n = 0; n < WXSIZEOF(URIPrefixes); ++n )
427 {
428 prefix_len = strlen(URIPrefixes[n]);
429 if((len > prefix_len) && !strncasecmp(text, URIPrefixes[n], prefix_len))
430 break;
431 }
432
433 if(n < WXSIZEOF(URIPrefixes))
434 {
435 gulong signal_id = g_signal_handler_find (buffer,
436 (GSignalMatchType) (G_SIGNAL_MATCH_FUNC),
437 0, 0, NULL,
438 (gpointer)au_apply_tag_callback, NULL);
439
440 g_signal_handler_block (buffer, signal_id);
441 gtk_text_buffer_apply_tag(buffer, tag, &start, &end);
442 g_signal_handler_unblock (buffer, signal_id);
443 }
444 }
445 }
446
447 extern "C" {
448 static void
449 au_check_range(GtkTextIter *s,
450 GtkTextIter *range_end)
451 {
452 GtkTextIter range_start = *s;
453 GtkTextIter word_end;
454 GtkTextBuffer *buffer = gtk_text_iter_get_buffer(s);
455 GtkTextTag *tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(buffer), "wxUrl");
456
457 gtk_text_buffer_remove_tag(buffer, tag, s, range_end);
458
459 if(g_unichar_isspace(gtk_text_iter_get_char(&range_start)))
460 gtk_text_iter_forward_find_char(&range_start, pred_non_whitespace, NULL, range_end);
461
462 while(!gtk_text_iter_equal(&range_start, range_end))
463 {
464 word_end = range_start;
465 gtk_text_iter_forward_find_char(&word_end, pred_whitespace, NULL, range_end);
466
467 // Now we should have a word delimited by range_start and word_end, correct link tags
468 au_check_word(&range_start, &word_end);
469
470 range_start = word_end;
471 gtk_text_iter_forward_find_char(&range_start, pred_non_whitespace, NULL, range_end);
472 }
473 }
474 }
475
476 //-----------------------------------------------------------------------------
477 // "insert-text" for GtkTextBuffer
478 //-----------------------------------------------------------------------------
479
480 extern "C" {
481 static void
482 au_insert_text_callback(GtkTextBuffer *buffer,
483 GtkTextIter *end,
484 gchar *text,
485 gint len,
486 wxTextCtrl *win)
487 {
488 if (!len || !(win->GetWindowStyleFlag() & wxTE_AUTO_URL) )
489 return;
490
491 GtkTextIter start = *end;
492 gtk_text_iter_backward_chars(&start, g_utf8_strlen(text, len));
493
494 GtkTextIter line_start = start;
495 GtkTextIter line_end = *end;
496 GtkTextIter words_start = start;
497 GtkTextIter words_end = *end;
498
499 gtk_text_iter_set_line(&line_start, gtk_text_iter_get_line(&start));
500 gtk_text_iter_forward_to_line_end(&line_end);
501 gtk_text_iter_backward_find_char(&words_start, pred_whitespace, NULL, &line_start);
502 gtk_text_iter_forward_find_char(&words_end, pred_whitespace, NULL, &line_end);
503
504 au_check_range(&words_start, &words_end);
505 }
506 }
507
508 //-----------------------------------------------------------------------------
509 // "delete-range" for GtkTextBuffer
510 //-----------------------------------------------------------------------------
511
512 extern "C" {
513 static void
514 au_delete_range_callback(GtkTextBuffer *buffer,
515 GtkTextIter *start,
516 GtkTextIter *end,
517 wxTextCtrl *win)
518 {
519 if( !(win->GetWindowStyleFlag() & wxTE_AUTO_URL) )
520 return;
521
522 GtkTextIter line_start = *start, line_end = *end;
523
524 gtk_text_iter_set_line(&line_start, gtk_text_iter_get_line(start));
525 gtk_text_iter_forward_to_line_end(&line_end);
526 gtk_text_iter_backward_find_char(start, pred_whitespace, NULL, &line_start);
527 gtk_text_iter_forward_find_char(end, pred_whitespace, NULL, &line_end);
528
529 au_check_range(start, end);
530 }
531 }
532
533
534 //-----------------------------------------------------------------------------
535 // "changed"
536 //-----------------------------------------------------------------------------
537
538 extern "C" {
539 static void
540 gtk_text_changed_callback( GtkWidget *widget, wxTextCtrl *win )
541 {
542 if ( win->IgnoreTextUpdate() )
543 return;
544
545 if (!win->m_hasVMT) return;
546
547 if (g_isIdle)
548 wxapp_install_idle_handler();
549
550 if ( win->MarkDirtyOnChange() )
551 win->MarkDirty();
552
553 win->SendTextUpdatedEvent();
554 }
555 }
556
557 //-----------------------------------------------------------------------------
558 // clipboard events: "copy-clipboard", "cut-clipboard", "paste-clipboard"
559 //-----------------------------------------------------------------------------
560
561 // common part of the event handlers below
562 static void
563 handle_text_clipboard_callback( GtkWidget *widget, wxTextCtrl *win,
564 wxEventType eventType, const gchar * signal_name)
565 {
566 wxClipboardTextEvent event( eventType, win->GetId() );
567 event.SetEventObject( win );
568 if ( win->GetEventHandler()->ProcessEvent( event ) )
569 {
570 // don't let the default processing to take place if we did something
571 // ourselves in the event handler
572 g_signal_stop_emission_by_name (widget, signal_name);
573 }
574 }
575
576 extern "C" {
577 static void
578 gtk_copy_clipboard_callback( GtkWidget *widget, wxTextCtrl *win )
579 {
580 handle_text_clipboard_callback(
581 widget, win, wxEVT_COMMAND_TEXT_COPY, "copy-clipboard" );
582 }
583
584 static void
585 gtk_cut_clipboard_callback( GtkWidget *widget, wxTextCtrl *win )
586 {
587 handle_text_clipboard_callback(
588 widget, win, wxEVT_COMMAND_TEXT_CUT, "cut-clipboard" );
589 }
590
591 static void
592 gtk_paste_clipboard_callback( GtkWidget *widget, wxTextCtrl *win )
593 {
594 handle_text_clipboard_callback(
595 widget, win, wxEVT_COMMAND_TEXT_PASTE, "paste-clipboard" );
596 }
597 }
598
599 //-----------------------------------------------------------------------------
600 // "expose_event" from scrolled window and textview
601 //-----------------------------------------------------------------------------
602
603 extern "C" {
604 static gboolean
605 gtk_text_exposed_callback( GtkWidget *widget, GdkEventExpose *event, wxTextCtrl *win )
606 {
607 return TRUE;
608 }
609 }
610
611
612 //-----------------------------------------------------------------------------
613 // wxTextCtrl
614 //-----------------------------------------------------------------------------
615
616 IMPLEMENT_DYNAMIC_CLASS(wxTextCtrl, wxTextCtrlBase)
617
618 BEGIN_EVENT_TABLE(wxTextCtrl, wxTextCtrlBase)
619 EVT_CHAR(wxTextCtrl::OnChar)
620
621 EVT_MENU(wxID_CUT, wxTextCtrl::OnCut)
622 EVT_MENU(wxID_COPY, wxTextCtrl::OnCopy)
623 EVT_MENU(wxID_PASTE, wxTextCtrl::OnPaste)
624 EVT_MENU(wxID_UNDO, wxTextCtrl::OnUndo)
625 EVT_MENU(wxID_REDO, wxTextCtrl::OnRedo)
626
627 EVT_UPDATE_UI(wxID_CUT, wxTextCtrl::OnUpdateCut)
628 EVT_UPDATE_UI(wxID_COPY, wxTextCtrl::OnUpdateCopy)
629 EVT_UPDATE_UI(wxID_PASTE, wxTextCtrl::OnUpdatePaste)
630 EVT_UPDATE_UI(wxID_UNDO, wxTextCtrl::OnUpdateUndo)
631 EVT_UPDATE_UI(wxID_REDO, wxTextCtrl::OnUpdateRedo)
632
633 // wxTE_AUTO_URL wxTextUrl support. Currently only creates
634 // wxTextUrlEvent in the same cases as wxMSW, more can be added here.
635 EVT_MOTION (wxTextCtrl::OnUrlMouseEvent)
636 EVT_LEFT_DOWN (wxTextCtrl::OnUrlMouseEvent)
637 EVT_LEFT_UP (wxTextCtrl::OnUrlMouseEvent)
638 EVT_LEFT_DCLICK (wxTextCtrl::OnUrlMouseEvent)
639 EVT_RIGHT_DOWN (wxTextCtrl::OnUrlMouseEvent)
640 EVT_RIGHT_UP (wxTextCtrl::OnUrlMouseEvent)
641 EVT_RIGHT_DCLICK(wxTextCtrl::OnUrlMouseEvent)
642 END_EVENT_TABLE()
643
644 void wxTextCtrl::Init()
645 {
646 m_dontMarkDirty =
647 m_modified = false;
648
649 m_countUpdatesToIgnore = 0;
650
651 SetUpdateFont(false);
652
653 m_text = NULL;
654 m_frozenness = 0;
655 m_gdkHandCursor = NULL;
656 m_gdkXTermCursor = NULL;
657 }
658
659 wxTextCtrl::~wxTextCtrl()
660 {
661 if(m_gdkHandCursor)
662 gdk_cursor_unref(m_gdkHandCursor);
663 if(m_gdkXTermCursor)
664 gdk_cursor_unref(m_gdkXTermCursor);
665 }
666
667 wxTextCtrl::wxTextCtrl( wxWindow *parent,
668 wxWindowID id,
669 const wxString &value,
670 const wxPoint &pos,
671 const wxSize &size,
672 long style,
673 const wxValidator& validator,
674 const wxString &name )
675 {
676 Init();
677
678 Create( parent, id, value, pos, size, style, validator, name );
679 }
680
681 bool wxTextCtrl::Create( wxWindow *parent,
682 wxWindowID id,
683 const wxString &value,
684 const wxPoint &pos,
685 const wxSize &size,
686 long style,
687 const wxValidator& validator,
688 const wxString &name )
689 {
690 m_needParent = true;
691 m_acceptsFocus = true;
692
693 if (!PreCreation( parent, pos, size ) ||
694 !CreateBase( parent, id, pos, size, style, validator, name ))
695 {
696 wxFAIL_MSG( wxT("wxTextCtrl creation failed") );
697 return false;
698 }
699
700 bool multi_line = (style & wxTE_MULTILINE) != 0;
701
702 if (multi_line)
703 {
704 // Create view
705 m_text = gtk_text_view_new();
706
707 m_buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(m_text) );
708
709 // create scrolled window
710 m_widget = gtk_scrolled_window_new( NULL, NULL );
711 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( m_widget ),
712 GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC );
713 // for ScrollLines/Pages
714 m_scrollBar[1] = (GtkRange*)((GtkScrolledWindow*)m_widget)->vscrollbar;
715
716 // Insert view into scrolled window
717 gtk_container_add( GTK_CONTAINER(m_widget), m_text );
718
719 // translate wx wrapping style to GTK+
720 GtkWrapMode wrap;
721 if ( HasFlag( wxTE_DONTWRAP ) )
722 wrap = GTK_WRAP_NONE;
723 else if ( HasFlag( wxTE_CHARWRAP ) )
724 wrap = GTK_WRAP_CHAR;
725 else if ( HasFlag( wxTE_WORDWRAP ) )
726 wrap = GTK_WRAP_WORD;
727 else // HasFlag(wxTE_BESTWRAP) always true as wxTE_BESTWRAP == 0
728 {
729 // GTK_WRAP_WORD_CHAR seems to be new in GTK+ 2.4
730 #ifdef __WXGTK24__
731 if ( !gtk_check_version(2,4,0) )
732 {
733 wrap = GTK_WRAP_WORD_CHAR;
734 }
735 else
736 #endif
737 wrap = GTK_WRAP_WORD;
738 }
739
740 gtk_text_view_set_wrap_mode( GTK_TEXT_VIEW( m_text ), wrap );
741
742 GtkScrolledWindowSetBorder(m_widget, style);
743
744 gtk_widget_add_events( GTK_WIDGET(m_text), GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK );
745
746 GTK_WIDGET_UNSET_FLAGS( m_widget, GTK_CAN_FOCUS );
747 }
748 else
749 {
750 // a single-line text control: no need for scrollbars
751 m_widget =
752 m_text = gtk_entry_new();
753
754 if (style & wxNO_BORDER)
755 g_object_set (m_text, "has-frame", FALSE, NULL);
756 }
757
758 m_parent->DoAddChild( this );
759
760 m_focusWidget = m_text;
761
762 PostCreation(size);
763
764 if (multi_line)
765 {
766 gtk_widget_show(m_text);
767 }
768
769 if (!value.empty())
770 {
771 SetValue( value );
772 }
773
774 if (style & wxTE_PASSWORD)
775 {
776 if (!multi_line)
777 gtk_entry_set_visibility( GTK_ENTRY(m_text), FALSE );
778 }
779
780 if (style & wxTE_READONLY)
781 {
782 if (!multi_line)
783 gtk_editable_set_editable( GTK_EDITABLE(m_text), FALSE );
784 else
785 gtk_text_view_set_editable( GTK_TEXT_VIEW( m_text), FALSE);
786 }
787
788 if (multi_line)
789 {
790 if (style & wxTE_RIGHT)
791 gtk_text_view_set_justification( GTK_TEXT_VIEW(m_text), GTK_JUSTIFY_RIGHT );
792 else if (style & wxTE_CENTRE)
793 gtk_text_view_set_justification( GTK_TEXT_VIEW(m_text), GTK_JUSTIFY_CENTER );
794 // Left justify (alignment) is the default and we don't need to apply GTK_JUSTIFY_LEFT
795 }
796 else
797 {
798 #ifdef __WXGTK24__
799 // gtk_entry_set_alignment was introduced in gtk+-2.3.5
800 if (!gtk_check_version(2,4,0))
801 {
802 if (style & wxTE_RIGHT)
803 gtk_entry_set_alignment( GTK_ENTRY(m_text), 1.0 );
804 else if (style & wxTE_CENTRE)
805 gtk_entry_set_alignment( GTK_ENTRY(m_text), 0.5 );
806 }
807 #endif
808 }
809
810 // We want to be notified about text changes.
811 if (multi_line)
812 {
813 g_signal_connect (m_buffer, "changed",
814 G_CALLBACK (gtk_text_changed_callback), this);
815
816 // .. and handle URLs on multi-line controls with wxTE_AUTO_URL style
817 if (style & wxTE_AUTO_URL)
818 {
819 GtkTextIter start, end;
820 m_gdkHandCursor = gdk_cursor_new(GDK_HAND2);
821 m_gdkXTermCursor = gdk_cursor_new(GDK_XTERM);
822
823 // We create our wxUrl tag here for slight efficiency gain - we
824 // don't have to check for the tag existance in callbacks,
825 // hereby it's guaranteed to exist.
826 gtk_text_buffer_create_tag(m_buffer, "wxUrl",
827 "foreground", "blue",
828 "underline", PANGO_UNDERLINE_SINGLE,
829 NULL);
830
831 // Check for URLs after each text change
832 g_signal_connect_after (m_buffer, "insert_text",
833 G_CALLBACK (au_insert_text_callback), this);
834 g_signal_connect_after (m_buffer, "delete_range",
835 G_CALLBACK (au_delete_range_callback), this);
836
837 // Block all wxUrl tag applying unless we do it ourselves, in which case we
838 // block this callback temporarily. This takes care of gtk+ internal
839 // gtk_text_buffer_insert_range* calls that would copy our URL tag otherwise,
840 // which is undesired because only a part of the URL might be copied.
841 // The insert-text signal emitted inside it will take care of newly formed
842 // or wholly copied URLs.
843 g_signal_connect (m_buffer, "apply_tag",
844 G_CALLBACK (au_apply_tag_callback), NULL);
845
846 // Check for URLs in the initial string passed to Create
847 gtk_text_buffer_get_start_iter(m_buffer, &start);
848 gtk_text_buffer_get_end_iter(m_buffer, &end);
849 au_check_range(&start, &end);
850 }
851 }
852 else
853 {
854 g_signal_connect (m_text, "changed",
855 G_CALLBACK (gtk_text_changed_callback), this);
856 }
857
858 g_signal_connect (m_text, "copy-clipboard",
859 G_CALLBACK (gtk_copy_clipboard_callback), this);
860 g_signal_connect (m_text, "cut-clipboard",
861 G_CALLBACK (gtk_cut_clipboard_callback), this);
862 g_signal_connect (m_text, "paste-clipboard",
863 G_CALLBACK (gtk_paste_clipboard_callback), this);
864
865 m_cursor = wxCursor( wxCURSOR_IBEAM );
866
867 wxTextAttr attrDef(GetForegroundColour(), GetBackgroundColour(), GetFont());
868 SetDefaultStyle( attrDef );
869
870 return true;
871 }
872
873
874 void wxTextCtrl::CalculateScrollbar()
875 {
876 }
877
878 wxString wxTextCtrl::GetValue() const
879 {
880 wxCHECK_MSG( m_text != NULL, wxEmptyString, wxT("invalid text ctrl") );
881
882 wxString tmp;
883 if ( IsMultiLine() )
884 {
885 GtkTextIter start;
886 gtk_text_buffer_get_start_iter( m_buffer, &start );
887 GtkTextIter end;
888 gtk_text_buffer_get_end_iter( m_buffer, &end );
889 wxGtkString text(gtk_text_buffer_get_text(m_buffer, &start, &end, true));
890
891 const wxWxCharBuffer buf = wxGTK_CONV_BACK(text);
892 if ( buf )
893 tmp = buf;
894 }
895 else
896 {
897 const gchar *text = gtk_entry_get_text( GTK_ENTRY(m_text) );
898 const wxWxCharBuffer buf = wxGTK_CONV_BACK( text );
899 if ( buf )
900 tmp = buf;
901 }
902
903 return tmp;
904 }
905
906 wxFontEncoding wxTextCtrl::GetTextEncoding() const
907 {
908 // GTK+ uses UTF-8 internally, we need to convert to it but from which
909 // encoding?
910
911 // first check the default text style (we intentionally don't check the
912 // style for the current position as it doesn't make sense for SetValue())
913 const wxTextAttr& style = GetDefaultStyle();
914 wxFontEncoding enc = style.HasFont() ? style.GetFont().GetEncoding()
915 : wxFONTENCODING_SYSTEM;
916
917 // fall back to the controls font if no style
918 if ( enc == wxFONTENCODING_SYSTEM && m_hasFont )
919 enc = GetFont().GetEncoding();
920
921 return enc;
922 }
923
924 bool wxTextCtrl::IsEmpty() const
925 {
926 if ( IsMultiLine() )
927 return gtk_text_buffer_get_char_count(m_buffer) != 0;
928
929 return wxTextCtrlBase::IsEmpty();
930 }
931
932 void wxTextCtrl::DoSetValue( const wxString &value, int flags )
933 {
934 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
935
936 // the control won't be modified any more as we programmatically replace
937 // all the existing text, so reset the flag and don't set it again (and do
938 // it now, before the text event handler is ran so that IsModified() called
939 // from there returns the expected value)
940 m_modified = false;
941 DontMarkDirtyOnNextChange();
942
943 const wxCharBuffer buffer(wxGTK_CONV_ENC(value, GetTextEncoding()));
944 if ( !buffer )
945 {
946 // see comment in WriteText() as to why we must warn the user about
947 // this
948 wxLogWarning(_("Failed to set text in the text control."));
949 return;
950 }
951
952 // if the control is not empty, two "changed" signals are emitted,
953 // otherwise only one and we need to ignore either both or one of them
954 int ignore = flags & SetValue_SendEvent ? 0 : 1;
955 if ( !IsEmpty() )
956 ignore++;
957
958 if ( ignore )
959 IgnoreNextTextUpdate(ignore);
960
961 if ( IsMultiLine() )
962 {
963 gtk_text_buffer_set_text( m_buffer, buffer, strlen(buffer) );
964 }
965 else // single line
966 {
967 gtk_entry_set_text( GTK_ENTRY(m_text), buffer );
968 }
969
970 // GRG, Jun/2000: Changed this after a lot of discussion in
971 // the lists. wxWidgets 2.2 will have a set of flags to
972 // customize this behaviour.
973 SetInsertionPoint(0);
974 }
975
976 void wxTextCtrl::WriteText( const wxString &text )
977 {
978 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
979
980 if ( text.empty() )
981 return;
982
983 // check if we have a specific style for the current position
984 wxFontEncoding enc = wxFONTENCODING_SYSTEM;
985 wxTextAttr style;
986 if ( GetStyle(GetInsertionPoint(), style) && style.HasFont() )
987 {
988 enc = style.GetFont().GetEncoding();
989 }
990
991 if ( enc == wxFONTENCODING_SYSTEM )
992 enc = GetTextEncoding();
993
994 const wxCharBuffer buffer(wxGTK_CONV_ENC(text, enc));
995 if ( !buffer )
996 {
997 // we must log an error here as losing the text like this can be a
998 // serious problem (e.g. imagine the document edited by user being
999 // empty instead of containing the correct text)
1000 wxLogWarning(_("Failed to insert text in the control."));
1001 return;
1002 }
1003
1004 // we're changing the text programmatically
1005 DontMarkDirtyOnNextChange();
1006
1007 if ( IsMultiLine() )
1008 {
1009 // First remove the selection if there is one
1010 // TODO: Is there an easier GTK specific way to do this?
1011 long from, to;
1012 GetSelection(&from, &to);
1013 if (from != to)
1014 Remove(from, to);
1015
1016 // Insert the text
1017 wxGtkTextInsert( m_text, m_buffer, m_defaultStyle, buffer );
1018
1019 GtkAdjustment *adj = gtk_scrolled_window_get_vadjustment( GTK_SCROLLED_WINDOW(m_widget) );
1020 // Scroll to cursor, but only if scrollbar thumb is at the very bottom
1021 if ( wxIsSameDouble(adj->value, adj->upper - adj->page_size) )
1022 {
1023 gtk_text_view_scroll_to_mark( GTK_TEXT_VIEW(m_text),
1024 gtk_text_buffer_get_insert( m_buffer ), 0.0, FALSE, 0.0, 1.0 );
1025 }
1026 }
1027 else // single line
1028 {
1029 // First remove the selection if there is one
1030 gtk_editable_delete_selection( GTK_EDITABLE(m_text) );
1031
1032 // This moves the cursor pos to behind the inserted text.
1033 gint len = gtk_editable_get_position(GTK_EDITABLE(m_text));
1034
1035 gtk_editable_insert_text( GTK_EDITABLE(m_text), buffer, strlen(buffer), &len );
1036
1037 // Bring entry's cursor uptodate.
1038 gtk_editable_set_position( GTK_EDITABLE(m_text), len );
1039 }
1040 }
1041
1042 void wxTextCtrl::AppendText( const wxString &text )
1043 {
1044 SetInsertionPointEnd();
1045 WriteText( text );
1046 }
1047
1048 wxString wxTextCtrl::GetLineText( long lineNo ) const
1049 {
1050 wxString result;
1051 if ( IsMultiLine() )
1052 {
1053 GtkTextIter line;
1054 gtk_text_buffer_get_iter_at_line(m_buffer,&line,lineNo);
1055 GtkTextIter end = line;
1056 gtk_text_iter_forward_to_line_end(&end);
1057 wxGtkString text(gtk_text_buffer_get_text(m_buffer, &line, &end, true));
1058 result = wxGTK_CONV_BACK(text);
1059 }
1060 else
1061 {
1062 if (lineNo == 0)
1063 result = GetValue();
1064 }
1065 return result;
1066 }
1067
1068 void wxTextCtrl::OnDropFiles( wxDropFilesEvent &WXUNUSED(event) )
1069 {
1070 /* If you implement this, don't forget to update the documentation!
1071 * (file docs/latex/wx/text.tex) */
1072 wxFAIL_MSG( wxT("wxTextCtrl::OnDropFiles not implemented") );
1073 }
1074
1075 bool wxTextCtrl::PositionToXY(long pos, long *x, long *y ) const
1076 {
1077 if ( IsMultiLine() )
1078 {
1079 GtkTextIter iter;
1080
1081 if (pos > GetLastPosition())
1082 return false;
1083
1084 gtk_text_buffer_get_iter_at_offset(m_buffer, &iter, pos);
1085
1086 if ( y )
1087 *y = gtk_text_iter_get_line(&iter);
1088 if ( x )
1089 *x = gtk_text_iter_get_line_offset(&iter);
1090 }
1091 else // single line control
1092 {
1093 if ( pos <= GTK_ENTRY(m_text)->text_length )
1094 {
1095 if ( y )
1096 *y = 0;
1097 if ( x )
1098 *x = pos;
1099 }
1100 else
1101 {
1102 // index out of bounds
1103 return false;
1104 }
1105 }
1106
1107 return true;
1108 }
1109
1110 long wxTextCtrl::XYToPosition(long x, long y ) const
1111 {
1112 if ( IsSingleLine() )
1113 return 0;
1114
1115 GtkTextIter iter;
1116 if (y >= gtk_text_buffer_get_line_count (m_buffer))
1117 return -1;
1118
1119 gtk_text_buffer_get_iter_at_line(m_buffer, &iter, y);
1120 if (x >= gtk_text_iter_get_chars_in_line (&iter))
1121 return -1;
1122
1123 return gtk_text_iter_get_offset(&iter) + x;
1124 }
1125
1126 int wxTextCtrl::GetLineLength(long lineNo) const
1127 {
1128 if ( IsMultiLine() )
1129 {
1130 int last_line = gtk_text_buffer_get_line_count( m_buffer ) - 1;
1131 if (lineNo > last_line)
1132 return -1;
1133
1134 GtkTextIter iter;
1135 gtk_text_buffer_get_iter_at_line(m_buffer, &iter, lineNo);
1136 // get_chars_in_line return includes paragraph delimiters, so need to subtract 1 IF it is not the last line
1137 return gtk_text_iter_get_chars_in_line(&iter) - ((lineNo == last_line) ? 0 : 1);
1138 }
1139 else
1140 {
1141 wxString str = GetLineText (lineNo);
1142 return (int) str.length();
1143 }
1144 }
1145
1146 int wxTextCtrl::GetNumberOfLines() const
1147 {
1148 if ( IsMultiLine() )
1149 {
1150 GtkTextIter iter;
1151 gtk_text_buffer_get_iter_at_offset( m_buffer, &iter, 0 );
1152
1153 // move forward by one display line until the end is reached
1154 int lineCount = 1;
1155 while ( gtk_text_view_forward_display_line(GTK_TEXT_VIEW(m_text), &iter) )
1156 {
1157 lineCount++;
1158 }
1159
1160 // If the last character in the text buffer is a newline,
1161 // gtk_text_view_forward_display_line() will return false without that
1162 // line being counted. Must add one manually in that case.
1163 GtkTextIter lastCharIter;
1164 gtk_text_buffer_get_iter_at_offset
1165 (
1166 m_buffer,
1167 &lastCharIter,
1168 gtk_text_buffer_get_char_count(m_buffer) - 1
1169 );
1170 gchar lastChar = gtk_text_iter_get_char( &lastCharIter );
1171 if ( lastChar == wxT('\n') )
1172 lineCount++;
1173
1174 return lineCount;
1175 }
1176 else // single line
1177 {
1178 return 1;
1179 }
1180 }
1181
1182 void wxTextCtrl::SetInsertionPoint( long pos )
1183 {
1184 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1185
1186 if ( IsMultiLine() )
1187 {
1188 GtkTextIter iter;
1189 gtk_text_buffer_get_iter_at_offset( m_buffer, &iter, pos );
1190 gtk_text_buffer_place_cursor( m_buffer, &iter );
1191 gtk_text_view_scroll_mark_onscreen
1192 (
1193 GTK_TEXT_VIEW(m_text),
1194 gtk_text_buffer_get_insert( m_buffer )
1195 );
1196 }
1197 else
1198 {
1199 // FIXME: Is the editable's cursor really uptodate without double set_position in GTK2?
1200 gtk_editable_set_position(GTK_EDITABLE(m_text), int(pos));
1201 }
1202 }
1203
1204 void wxTextCtrl::SetInsertionPointEnd()
1205 {
1206 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1207
1208 if ( IsMultiLine() )
1209 {
1210 GtkTextIter end;
1211 gtk_text_buffer_get_end_iter( m_buffer, &end );
1212 gtk_text_buffer_place_cursor( m_buffer, &end );
1213 }
1214 else
1215 {
1216 gtk_editable_set_position( GTK_EDITABLE(m_text), -1 );
1217 }
1218 }
1219
1220 void wxTextCtrl::SetEditable( bool editable )
1221 {
1222 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1223
1224 if ( IsMultiLine() )
1225 {
1226 gtk_text_view_set_editable( GTK_TEXT_VIEW(m_text), editable );
1227 }
1228 else
1229 {
1230 gtk_editable_set_editable( GTK_EDITABLE(m_text), editable );
1231 }
1232 }
1233
1234 bool wxTextCtrl::Enable( bool enable )
1235 {
1236 if (!wxWindowBase::Enable(enable))
1237 {
1238 // nothing to do
1239 return false;
1240 }
1241
1242 if ( IsMultiLine() )
1243 {
1244 SetEditable( enable );
1245 }
1246 else
1247 {
1248 gtk_widget_set_sensitive( m_text, enable );
1249 }
1250
1251 return true;
1252 }
1253
1254 // wxGTK-specific: called recursively by Enable,
1255 // to give widgets an oppprtunity to correct their colours after they
1256 // have been changed by Enable
1257 void wxTextCtrl::OnParentEnable( bool enable )
1258 {
1259 // If we have a custom background colour, we use this colour in both
1260 // disabled and enabled mode, or we end up with a different colour under the
1261 // text.
1262 wxColour oldColour = GetBackgroundColour();
1263 if (oldColour.Ok())
1264 {
1265 // Need to set twice or it'll optimize the useful stuff out
1266 if (oldColour == * wxWHITE)
1267 SetBackgroundColour(*wxBLACK);
1268 else
1269 SetBackgroundColour(*wxWHITE);
1270 SetBackgroundColour(oldColour);
1271 }
1272 }
1273
1274 void wxTextCtrl::MarkDirty()
1275 {
1276 m_modified = true;
1277 }
1278
1279 void wxTextCtrl::DiscardEdits()
1280 {
1281 m_modified = false;
1282 }
1283
1284 // ----------------------------------------------------------------------------
1285 // max text length support
1286 // ----------------------------------------------------------------------------
1287
1288 bool wxTextCtrl::IgnoreTextUpdate()
1289 {
1290 if ( m_countUpdatesToIgnore > 0 )
1291 {
1292 m_countUpdatesToIgnore--;
1293
1294 return true;
1295 }
1296
1297 return false;
1298 }
1299
1300 bool wxTextCtrl::MarkDirtyOnChange()
1301 {
1302 if ( m_dontMarkDirty )
1303 {
1304 m_dontMarkDirty = false;
1305
1306 return false;
1307 }
1308
1309 return true;
1310 }
1311
1312 void wxTextCtrl::SetMaxLength(unsigned long len)
1313 {
1314 if ( !HasFlag(wxTE_MULTILINE) )
1315 {
1316 gtk_entry_set_max_length(GTK_ENTRY(m_text), len);
1317
1318 // there is a bug in GTK+ 1.2.x: "changed" signal is emitted even if
1319 // we had tried to enter more text than allowed by max text length and
1320 // the text wasn't really changed
1321 //
1322 // to detect this and generate TEXT_MAXLEN event instead of
1323 // TEXT_CHANGED one in this case we also catch "insert_text" signal
1324 //
1325 // when max len is set to 0 we disconnect our handler as it means that
1326 // we shouldn't check anything any more
1327 if ( len )
1328 {
1329 g_signal_connect (m_text, "insert_text",
1330 G_CALLBACK (gtk_insert_text_callback), this);
1331 }
1332 else // no checking
1333 {
1334 g_signal_handlers_disconnect_by_func (m_text,
1335 (gpointer) gtk_insert_text_callback, this);
1336 }
1337 }
1338 }
1339
1340 void wxTextCtrl::SetSelection( long from, long to )
1341 {
1342 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1343
1344 if (from == -1 && to == -1)
1345 {
1346 from = 0;
1347 to = GetValue().length();
1348 }
1349
1350 if ( IsMultiLine() )
1351 {
1352 GtkTextIter fromi, toi;
1353 gtk_text_buffer_get_iter_at_offset( m_buffer, &fromi, from );
1354 gtk_text_buffer_get_iter_at_offset( m_buffer, &toi, to );
1355
1356 gtk_text_buffer_place_cursor( m_buffer, &toi );
1357 gtk_text_buffer_move_mark_by_name( m_buffer, "selection_bound", &fromi );
1358 }
1359 else
1360 {
1361 gtk_editable_select_region( GTK_EDITABLE(m_text), (gint)from, (gint)to );
1362 }
1363 }
1364
1365 void wxTextCtrl::ShowPosition( long pos )
1366 {
1367 if ( IsMultiLine() )
1368 {
1369 GtkTextIter iter;
1370 gtk_text_buffer_get_start_iter( m_buffer, &iter );
1371 gtk_text_iter_set_offset( &iter, pos );
1372 GtkTextMark *mark = gtk_text_buffer_create_mark( m_buffer, NULL, &iter, TRUE );
1373 gtk_text_view_scroll_to_mark( GTK_TEXT_VIEW(m_text), mark, 0.0, FALSE, 0.0, 0.0 );
1374 }
1375 }
1376
1377 wxTextCtrlHitTestResult
1378 wxTextCtrl::HitTest(const wxPoint& pt, long *pos) const
1379 {
1380 if ( !IsMultiLine() )
1381 {
1382 // not supported
1383 return wxTE_HT_UNKNOWN;
1384 }
1385
1386 int x, y;
1387 gtk_text_view_window_to_buffer_coords
1388 (
1389 GTK_TEXT_VIEW(m_text),
1390 GTK_TEXT_WINDOW_TEXT,
1391 pt.x, pt.y,
1392 &x, &y
1393 );
1394
1395 GtkTextIter iter;
1396 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(m_text), &iter, x, y);
1397 if ( pos )
1398 *pos = gtk_text_iter_get_offset(&iter);
1399
1400 return wxTE_HT_ON_TEXT;
1401 }
1402
1403 long wxTextCtrl::GetInsertionPoint() const
1404 {
1405 wxCHECK_MSG( m_text != NULL, 0, wxT("invalid text ctrl") );
1406
1407 if ( IsMultiLine() )
1408 {
1409 // There is no direct accessor for the cursor, but
1410 // internally, the cursor is the "mark" called
1411 // "insert" in the text view's btree structure.
1412
1413 GtkTextMark *mark = gtk_text_buffer_get_insert( m_buffer );
1414 GtkTextIter cursor;
1415 gtk_text_buffer_get_iter_at_mark( m_buffer, &cursor, mark );
1416
1417 return gtk_text_iter_get_offset( &cursor );
1418 }
1419 else
1420 {
1421 return (long) gtk_editable_get_position(GTK_EDITABLE(m_text));
1422 }
1423 }
1424
1425 wxTextPos wxTextCtrl::GetLastPosition() const
1426 {
1427 wxCHECK_MSG( m_text != NULL, 0, wxT("invalid text ctrl") );
1428
1429 int pos = 0;
1430
1431 if ( IsMultiLine() )
1432 {
1433 GtkTextIter end;
1434 gtk_text_buffer_get_end_iter( m_buffer, &end );
1435
1436 pos = gtk_text_iter_get_offset( &end );
1437 }
1438 else
1439 {
1440 pos = GTK_ENTRY(m_text)->text_length;
1441 }
1442
1443 return (long)pos;
1444 }
1445
1446 void wxTextCtrl::Remove( long from, long to )
1447 {
1448 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1449
1450 if ( IsMultiLine() )
1451 {
1452 GtkTextIter fromi, toi;
1453 gtk_text_buffer_get_iter_at_offset( m_buffer, &fromi, from );
1454 gtk_text_buffer_get_iter_at_offset( m_buffer, &toi, to );
1455
1456 gtk_text_buffer_delete( m_buffer, &fromi, &toi );
1457 }
1458 else // single line
1459 gtk_editable_delete_text( GTK_EDITABLE(m_text), (gint)from, (gint)to );
1460 }
1461
1462 void wxTextCtrl::Replace( long from, long to, const wxString &value )
1463 {
1464 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1465
1466 Remove( from, to );
1467
1468 if (!value.empty())
1469 {
1470 SetInsertionPoint( from );
1471 WriteText( value );
1472 }
1473 }
1474
1475 void wxTextCtrl::Cut()
1476 {
1477 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1478
1479 if ( IsMultiLine() )
1480 g_signal_emit_by_name (m_text, "cut-clipboard");
1481 else
1482 gtk_editable_cut_clipboard(GTK_EDITABLE(m_text));
1483 }
1484
1485 void wxTextCtrl::Copy()
1486 {
1487 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1488
1489 if ( IsMultiLine() )
1490 g_signal_emit_by_name (m_text, "copy-clipboard");
1491 else
1492 gtk_editable_copy_clipboard(GTK_EDITABLE(m_text));
1493 }
1494
1495 void wxTextCtrl::Paste()
1496 {
1497 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1498
1499 if ( IsMultiLine() )
1500 g_signal_emit_by_name (m_text, "paste-clipboard");
1501 else
1502 gtk_editable_paste_clipboard(GTK_EDITABLE(m_text));
1503 }
1504
1505 // Undo/redo
1506 void wxTextCtrl::Undo()
1507 {
1508 // TODO
1509 wxFAIL_MSG( wxT("wxTextCtrl::Undo not implemented") );
1510 }
1511
1512 void wxTextCtrl::Redo()
1513 {
1514 // TODO
1515 wxFAIL_MSG( wxT("wxTextCtrl::Redo not implemented") );
1516 }
1517
1518 bool wxTextCtrl::CanUndo() const
1519 {
1520 // TODO
1521 //wxFAIL_MSG( wxT("wxTextCtrl::CanUndo not implemented") );
1522 return false;
1523 }
1524
1525 bool wxTextCtrl::CanRedo() const
1526 {
1527 // TODO
1528 //wxFAIL_MSG( wxT("wxTextCtrl::CanRedo not implemented") );
1529 return false;
1530 }
1531
1532 // If the return values from and to are the same, there is no
1533 // selection.
1534 void wxTextCtrl::GetSelection(long* fromOut, long* toOut) const
1535 {
1536 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1537
1538 gint from = -1;
1539 gint to = -1;
1540 bool haveSelection = false;
1541
1542 if ( IsMultiLine() )
1543 {
1544 GtkTextIter ifrom, ito;
1545 if ( gtk_text_buffer_get_selection_bounds(m_buffer, &ifrom, &ito) )
1546 {
1547 haveSelection = true;
1548 from = gtk_text_iter_get_offset(&ifrom);
1549 to = gtk_text_iter_get_offset(&ito);
1550 }
1551 }
1552 else // not multi-line
1553 {
1554 if ( gtk_editable_get_selection_bounds( GTK_EDITABLE(m_text),
1555 &from, &to) )
1556 {
1557 haveSelection = true;
1558 }
1559 }
1560
1561 if (! haveSelection )
1562 from = to = GetInsertionPoint();
1563
1564 if ( from > to )
1565 {
1566 // exchange them to be compatible with wxMSW
1567 gint tmp = from;
1568 from = to;
1569 to = tmp;
1570 }
1571
1572 if ( fromOut )
1573 *fromOut = from;
1574 if ( toOut )
1575 *toOut = to;
1576 }
1577
1578
1579 bool wxTextCtrl::IsEditable() const
1580 {
1581 wxCHECK_MSG( m_text != NULL, false, wxT("invalid text ctrl") );
1582
1583 if ( IsMultiLine() )
1584 {
1585 return gtk_text_view_get_editable(GTK_TEXT_VIEW(m_text));
1586 }
1587 else
1588 {
1589 return gtk_editable_get_editable(GTK_EDITABLE(m_text));
1590 }
1591 }
1592
1593 bool wxTextCtrl::IsModified() const
1594 {
1595 return m_modified;
1596 }
1597
1598 void wxTextCtrl::Clear()
1599 {
1600 SetValue( wxEmptyString );
1601 }
1602
1603 void wxTextCtrl::OnChar( wxKeyEvent &key_event )
1604 {
1605 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1606
1607 if ( key_event.GetKeyCode() == WXK_RETURN )
1608 {
1609 if ( HasFlag(wxTE_PROCESS_ENTER) )
1610 {
1611 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId);
1612 event.SetEventObject(this);
1613 event.SetString(GetValue());
1614 if ( GetEventHandler()->ProcessEvent(event) )
1615 return;
1616 }
1617
1618 // FIXME: this is not the right place to do it, wxDialog::OnCharHook()
1619 // probably is
1620 if ( IsSingleLine() )
1621 {
1622 // This will invoke the dialog default action, such
1623 // as the clicking the default button.
1624
1625 wxWindow *top_frame = m_parent;
1626 while (top_frame->GetParent() && !(top_frame->IsTopLevel()))
1627 top_frame = top_frame->GetParent();
1628
1629 if (top_frame && GTK_IS_WINDOW(top_frame->m_widget))
1630 {
1631 GtkWindow *window = GTK_WINDOW(top_frame->m_widget);
1632
1633 if (window->default_widget)
1634 {
1635 gtk_widget_activate (window->default_widget);
1636 return;
1637 }
1638 }
1639 }
1640 }
1641
1642 key_event.Skip();
1643 }
1644
1645 GtkWidget* wxTextCtrl::GetConnectWidget()
1646 {
1647 return GTK_WIDGET(m_text);
1648 }
1649
1650 GdkWindow *wxTextCtrl::GTKGetWindow(wxArrayGdkWindows& WXUNUSED(windows)) const
1651 {
1652 if ( IsMultiLine() )
1653 {
1654 return gtk_text_view_get_window(GTK_TEXT_VIEW(m_text),
1655 GTK_TEXT_WINDOW_TEXT );
1656 }
1657 else
1658 {
1659 return GTK_ENTRY(m_text)->text_area;
1660 }
1661 }
1662
1663 // the font will change for subsequent text insertiongs
1664 bool wxTextCtrl::SetFont( const wxFont &font )
1665 {
1666 wxCHECK_MSG( m_text != NULL, false, wxT("invalid text ctrl") );
1667
1668 if ( !wxTextCtrlBase::SetFont(font) )
1669 {
1670 // font didn't change, nothing to do
1671 return false;
1672 }
1673
1674 if ( IsMultiLine() )
1675 {
1676 SetUpdateFont(true);
1677
1678 m_defaultStyle.SetFont(font);
1679
1680 ChangeFontGlobally();
1681 }
1682
1683 return true;
1684 }
1685
1686 void wxTextCtrl::ChangeFontGlobally()
1687 {
1688 // this method is very inefficient and hence should be called as rarely as
1689 // possible!
1690 //
1691 // TODO: it can be implemented much more efficiently for GTK2
1692 wxASSERT_MSG( IsMultiLine(),
1693 _T("shouldn't be called for single line controls") );
1694
1695 wxString value = GetValue();
1696 if ( !value.empty() )
1697 {
1698 SetUpdateFont(false);
1699
1700 Clear();
1701 AppendText(value);
1702 }
1703 }
1704
1705 bool wxTextCtrl::SetForegroundColour(const wxColour& colour)
1706 {
1707 if ( !wxControl::SetForegroundColour(colour) )
1708 return false;
1709
1710 // update default fg colour too
1711 m_defaultStyle.SetTextColour(colour);
1712
1713 return true;
1714 }
1715
1716 bool wxTextCtrl::SetBackgroundColour( const wxColour &colour )
1717 {
1718 wxCHECK_MSG( m_text != NULL, false, wxT("invalid text ctrl") );
1719
1720 if ( !wxControl::SetBackgroundColour( colour ) )
1721 return false;
1722
1723 if (!m_backgroundColour.Ok())
1724 return false;
1725
1726 // change active background color too
1727 m_defaultStyle.SetBackgroundColour( colour );
1728
1729 return true;
1730 }
1731
1732 bool wxTextCtrl::SetStyle( long start, long end, const wxTextAttr& style )
1733 {
1734 if ( IsMultiLine() )
1735 {
1736 if ( style.IsDefault() )
1737 {
1738 // nothing to do
1739 return true;
1740 }
1741
1742 gint l = gtk_text_buffer_get_char_count( m_buffer );
1743
1744 wxCHECK_MSG( start >= 0 && end <= l, false,
1745 _T("invalid range in wxTextCtrl::SetStyle") );
1746
1747 GtkTextIter starti, endi;
1748 gtk_text_buffer_get_iter_at_offset( m_buffer, &starti, start );
1749 gtk_text_buffer_get_iter_at_offset( m_buffer, &endi, end );
1750
1751 // use the attributes from style which are set in it and fall back
1752 // first to the default style and then to the text control default
1753 // colours for the others
1754 wxTextAttr attr = wxTextAttr::Combine(style, m_defaultStyle, this);
1755
1756 wxGtkTextApplyTagsFromAttr( m_widget, m_buffer, attr, &starti, &endi );
1757
1758 return true;
1759 }
1760
1761 // else single line
1762 // cannot do this for GTK+'s Entry widget
1763 return false;
1764 }
1765
1766 void wxTextCtrl::DoApplyWidgetStyle(GtkRcStyle *style)
1767 {
1768 gtk_widget_modify_style(m_text, style);
1769 }
1770
1771 void wxTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event))
1772 {
1773 Cut();
1774 }
1775
1776 void wxTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event))
1777 {
1778 Copy();
1779 }
1780
1781 void wxTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event))
1782 {
1783 Paste();
1784 }
1785
1786 void wxTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event))
1787 {
1788 Undo();
1789 }
1790
1791 void wxTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event))
1792 {
1793 Redo();
1794 }
1795
1796 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
1797 {
1798 event.Enable( CanCut() );
1799 }
1800
1801 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
1802 {
1803 event.Enable( CanCopy() );
1804 }
1805
1806 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
1807 {
1808 event.Enable( CanPaste() );
1809 }
1810
1811 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
1812 {
1813 event.Enable( CanUndo() );
1814 }
1815
1816 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
1817 {
1818 event.Enable( CanRedo() );
1819 }
1820
1821 wxSize wxTextCtrl::DoGetBestSize() const
1822 {
1823 // FIXME should be different for multi-line controls...
1824 wxSize ret( wxControl::DoGetBestSize() );
1825 wxSize best(80, ret.y);
1826 CacheBestSize(best);
1827 return best;
1828 }
1829
1830 // ----------------------------------------------------------------------------
1831 // freeze/thaw
1832 // ----------------------------------------------------------------------------
1833
1834 void wxTextCtrl::Freeze()
1835 {
1836 if ( HasFlag(wxTE_MULTILINE) )
1837 {
1838 if ( !m_frozenness++ )
1839 {
1840 // freeze textview updates and remove buffer
1841 g_signal_connect (m_text, "expose_event",
1842 G_CALLBACK (gtk_text_exposed_callback), this);
1843 g_signal_connect (m_widget, "expose_event",
1844 G_CALLBACK (gtk_text_exposed_callback), this);
1845 gtk_widget_set_sensitive(m_widget, false);
1846 g_object_ref(m_buffer);
1847 GtkTextBuffer* buf_new = gtk_text_buffer_new(NULL);
1848 gtk_text_view_set_buffer(GTK_TEXT_VIEW(m_text), buf_new);
1849 // gtk_text_view_set_buffer adds its own reference
1850 g_object_unref(buf_new);
1851 }
1852 }
1853 }
1854
1855 void wxTextCtrl::Thaw()
1856 {
1857 if ( HasFlag(wxTE_MULTILINE) )
1858 {
1859 wxASSERT_MSG( m_frozenness > 0, _T("Thaw() without matching Freeze()") );
1860
1861 if ( !--m_frozenness )
1862 {
1863 // Reattach buffer and thaw textview updates
1864 gtk_text_view_set_buffer(GTK_TEXT_VIEW(m_text), m_buffer);
1865 g_object_unref(m_buffer);
1866 gtk_widget_set_sensitive(m_widget, true);
1867 g_signal_handlers_disconnect_by_func (m_widget,
1868 (gpointer) gtk_text_exposed_callback, this);
1869 g_signal_handlers_disconnect_by_func (m_text,
1870 (gpointer) gtk_text_exposed_callback, this);
1871 }
1872 }
1873 }
1874
1875 // ----------------------------------------------------------------------------
1876 // wxTextUrlEvent passing if style & wxTE_AUTO_URL
1877 // ----------------------------------------------------------------------------
1878
1879 // FIXME: when dragging on a link the sample gets an "Unknown event".
1880 // This might be an excessive event from us or a buggy wxMouseEvent::Moving() or
1881 // a buggy sample, or something else
1882 void wxTextCtrl::OnUrlMouseEvent(wxMouseEvent& event)
1883 {
1884 event.Skip();
1885 if( !HasFlag(wxTE_AUTO_URL) )
1886 return;
1887
1888 gint x, y;
1889 GtkTextIter start, end;
1890 GtkTextTag *tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(m_buffer),
1891 "wxUrl");
1892
1893 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(m_text), GTK_TEXT_WINDOW_WIDGET,
1894 event.GetX(), event.GetY(), &x, &y);
1895
1896 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(m_text), &end, x, y);
1897 if (!gtk_text_iter_has_tag(&end, tag))
1898 {
1899 gdk_window_set_cursor(gtk_text_view_get_window(GTK_TEXT_VIEW(m_text),
1900 GTK_TEXT_WINDOW_TEXT), m_gdkXTermCursor);
1901 return;
1902 }
1903
1904 gdk_window_set_cursor(gtk_text_view_get_window(GTK_TEXT_VIEW(m_text),
1905 GTK_TEXT_WINDOW_TEXT), m_gdkHandCursor);
1906
1907 start = end;
1908 if(!gtk_text_iter_begins_tag(&start, tag))
1909 gtk_text_iter_backward_to_tag_toggle(&start, tag);
1910 if(!gtk_text_iter_ends_tag(&end, tag))
1911 gtk_text_iter_forward_to_tag_toggle(&end, tag);
1912
1913 // Native context menu is probably not desired on an URL.
1914 // Consider making this dependant on ProcessEvent(wxTextUrlEvent) return value
1915 if(event.GetEventType() == wxEVT_RIGHT_DOWN)
1916 event.Skip(false);
1917
1918 wxTextUrlEvent url_event(m_windowId, event,
1919 gtk_text_iter_get_offset(&start),
1920 gtk_text_iter_get_offset(&end));
1921
1922 InitCommandEvent(url_event);
1923 // Is that a good idea? Seems not (pleasure with gtk_text_view_start_selection_drag)
1924 //event.Skip(!GetEventHandler()->ProcessEvent(url_event));
1925 GetEventHandler()->ProcessEvent(url_event);
1926 }
1927
1928 bool wxTextCtrl::GTKProcessEvent(wxEvent& event) const
1929 {
1930 bool rc = wxTextCtrlBase::GTKProcessEvent(event);
1931
1932 // GtkTextView starts a drag operation when left mouse button is pressed
1933 // and ends it when it is released and if it doesn't get the release event
1934 // the next click on a control results in an assertion failure inside
1935 // gtk_text_view_start_selection_drag() which simply *kills* the program
1936 // without anything we can do about it, so always let GTK+ have this event
1937 return rc && (IsSingleLine() || event.GetEventType() != wxEVT_LEFT_UP);
1938 }
1939
1940 // static
1941 wxVisualAttributes
1942 wxTextCtrl::GetClassDefaultAttributes(wxWindowVariant WXUNUSED(variant))
1943 {
1944 return GetDefaultAttributesFromGTKWidget(gtk_entry_new, true);
1945 }