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