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