]> git.saurik.com Git - wxWidgets.git/blob - src/gtk/textctrl.cpp
eedc7c026f6bbe7f20d79c6406a17285f2bf2868
[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 static void
465 au_insert_text_callback(GtkTextBuffer * WXUNUSED(buffer),
466 GtkTextIter *end,
467 gchar *text,
468 gint len,
469 wxTextCtrl *win)
470 {
471 if (!len || !(win->GetWindowStyleFlag() & wxTE_AUTO_URL) )
472 return;
473
474 GtkTextIter start = *end;
475 gtk_text_iter_backward_chars(&start, g_utf8_strlen(text, len));
476
477 GtkTextIter line_start = start;
478 GtkTextIter line_end = *end;
479 GtkTextIter words_start = start;
480 GtkTextIter words_end = *end;
481
482 gtk_text_iter_set_line(&line_start, gtk_text_iter_get_line(&start));
483 gtk_text_iter_forward_to_line_end(&line_end);
484 gtk_text_iter_backward_find_char(&words_start, pred_whitespace, NULL, &line_start);
485 gtk_text_iter_forward_find_char(&words_end, pred_whitespace, NULL, &line_end);
486
487 au_check_range(&words_start, &words_end);
488 }
489 }
490
491 //-----------------------------------------------------------------------------
492 // "delete-range" for GtkTextBuffer
493 //-----------------------------------------------------------------------------
494
495 extern "C" {
496 static void
497 au_delete_range_callback(GtkTextBuffer * WXUNUSED(buffer),
498 GtkTextIter *start,
499 GtkTextIter *end,
500 wxTextCtrl *win)
501 {
502 if( !(win->GetWindowStyleFlag() & wxTE_AUTO_URL) )
503 return;
504
505 GtkTextIter line_start = *start, line_end = *end;
506
507 gtk_text_iter_set_line(&line_start, gtk_text_iter_get_line(start));
508 gtk_text_iter_forward_to_line_end(&line_end);
509 gtk_text_iter_backward_find_char(start, pred_whitespace, NULL, &line_start);
510 gtk_text_iter_forward_find_char(end, pred_whitespace, NULL, &line_end);
511
512 au_check_range(start, end);
513 }
514 }
515
516 //-----------------------------------------------------------------------------
517 // "populate_popup" from text control and "unmap" from its poup menu
518 //-----------------------------------------------------------------------------
519
520 extern "C" {
521 static void
522 gtk_textctrl_popup_unmap( GtkMenu *WXUNUSED(menu), wxTextCtrl* win )
523 {
524 win->GTKEnableFocusOutEvent();
525 }
526 }
527
528 extern "C" {
529 static void
530 gtk_textctrl_populate_popup( GtkEntry *WXUNUSED(entry), GtkMenu *menu, wxTextCtrl *win )
531 {
532 win->GTKDisableFocusOutEvent();
533
534 g_signal_connect (menu, "unmap", G_CALLBACK (gtk_textctrl_popup_unmap), win );
535 }
536 }
537
538 //-----------------------------------------------------------------------------
539 // "changed"
540 //-----------------------------------------------------------------------------
541
542 extern "C" {
543 static void
544 gtk_text_changed_callback( GtkWidget *WXUNUSED(widget), wxTextCtrl *win )
545 {
546 if ( win->IgnoreTextUpdate() )
547 return;
548
549 if (!win->m_hasVMT) return;
550
551 if ( win->MarkDirtyOnChange() )
552 win->MarkDirty();
553
554 win->SendTextUpdatedEvent();
555 }
556 }
557
558 //-----------------------------------------------------------------------------
559 // clipboard events: "copy-clipboard", "cut-clipboard", "paste-clipboard"
560 //-----------------------------------------------------------------------------
561
562 // common part of the event handlers below
563 static void
564 handle_text_clipboard_callback( GtkWidget *widget, wxTextCtrl *win,
565 wxEventType eventType, const gchar * signal_name)
566 {
567 wxClipboardTextEvent event( eventType, win->GetId() );
568 event.SetEventObject( win );
569 if ( win->HandleWindowEvent( event ) )
570 {
571 // don't let the default processing to take place if we did something
572 // ourselves in the event handler
573 g_signal_stop_emission_by_name (widget, signal_name);
574 }
575 }
576
577 extern "C" {
578 static void
579 gtk_copy_clipboard_callback( GtkWidget *widget, wxTextCtrl *win )
580 {
581 handle_text_clipboard_callback(
582 widget, win, wxEVT_COMMAND_TEXT_COPY, "copy-clipboard" );
583 }
584
585 static void
586 gtk_cut_clipboard_callback( GtkWidget *widget, wxTextCtrl *win )
587 {
588 handle_text_clipboard_callback(
589 widget, win, wxEVT_COMMAND_TEXT_CUT, "cut-clipboard" );
590 }
591
592 static void
593 gtk_paste_clipboard_callback( GtkWidget *widget, wxTextCtrl *win )
594 {
595 handle_text_clipboard_callback(
596 widget, win, wxEVT_COMMAND_TEXT_PASTE, "paste-clipboard" );
597 }
598 }
599
600 //-----------------------------------------------------------------------------
601 // "mark_set"
602 //-----------------------------------------------------------------------------
603
604 extern "C" {
605 static void mark_set(GtkTextBuffer*, GtkTextIter*, GtkTextMark* mark, GSList** markList)
606 {
607 if (gtk_text_mark_get_name(mark) == NULL)
608 *markList = g_slist_prepend(*markList, mark);
609 }
610 }
611
612 //-----------------------------------------------------------------------------
613 // wxTextCtrl
614 //-----------------------------------------------------------------------------
615
616 BEGIN_EVENT_TABLE(wxTextCtrl, wxTextCtrlBase)
617 EVT_CHAR(wxTextCtrl::OnChar)
618
619 EVT_MENU(wxID_CUT, wxTextCtrl::OnCut)
620 EVT_MENU(wxID_COPY, wxTextCtrl::OnCopy)
621 EVT_MENU(wxID_PASTE, wxTextCtrl::OnPaste)
622 EVT_MENU(wxID_UNDO, wxTextCtrl::OnUndo)
623 EVT_MENU(wxID_REDO, wxTextCtrl::OnRedo)
624
625 EVT_UPDATE_UI(wxID_CUT, wxTextCtrl::OnUpdateCut)
626 EVT_UPDATE_UI(wxID_COPY, wxTextCtrl::OnUpdateCopy)
627 EVT_UPDATE_UI(wxID_PASTE, wxTextCtrl::OnUpdatePaste)
628 EVT_UPDATE_UI(wxID_UNDO, wxTextCtrl::OnUpdateUndo)
629 EVT_UPDATE_UI(wxID_REDO, wxTextCtrl::OnUpdateRedo)
630
631 // wxTE_AUTO_URL wxTextUrl support. Currently only creates
632 // wxTextUrlEvent in the same cases as wxMSW, more can be added here.
633 EVT_MOTION (wxTextCtrl::OnUrlMouseEvent)
634 EVT_LEFT_DOWN (wxTextCtrl::OnUrlMouseEvent)
635 EVT_LEFT_UP (wxTextCtrl::OnUrlMouseEvent)
636 EVT_LEFT_DCLICK (wxTextCtrl::OnUrlMouseEvent)
637 EVT_RIGHT_DOWN (wxTextCtrl::OnUrlMouseEvent)
638 EVT_RIGHT_UP (wxTextCtrl::OnUrlMouseEvent)
639 EVT_RIGHT_DCLICK(wxTextCtrl::OnUrlMouseEvent)
640 END_EVENT_TABLE()
641
642 void wxTextCtrl::Init()
643 {
644 m_dontMarkDirty =
645 m_modified = false;
646
647 m_countUpdatesToIgnore = 0;
648
649 SetUpdateFont(false);
650
651 m_text = NULL;
652 m_showPositionOnThaw = NULL;
653 m_anonymousMarkList = NULL;
654 }
655
656 wxTextCtrl::~wxTextCtrl()
657 {
658 if (m_anonymousMarkList)
659 g_slist_free(m_anonymousMarkList);
660 }
661
662 wxTextCtrl::wxTextCtrl( 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 Init();
672
673 Create( parent, id, value, pos, size, style, validator, name );
674 }
675
676 bool wxTextCtrl::Create( wxWindow *parent,
677 wxWindowID id,
678 const wxString &value,
679 const wxPoint &pos,
680 const wxSize &size,
681 long style,
682 const wxValidator& validator,
683 const wxString &name )
684 {
685 if (!PreCreation( parent, pos, size ) ||
686 !CreateBase( parent, id, pos, size, style, validator, name ))
687 {
688 wxFAIL_MSG( wxT("wxTextCtrl creation failed") );
689 return false;
690 }
691
692 bool multi_line = (style & wxTE_MULTILINE) != 0;
693
694 if (multi_line)
695 {
696 m_buffer = gtk_text_buffer_new(NULL);
697 gulong sig_id = g_signal_connect(m_buffer, "mark_set", G_CALLBACK(mark_set), &m_anonymousMarkList);
698 // Create view
699 m_text = gtk_text_view_new_with_buffer(m_buffer);
700 // gtk_text_view_set_buffer adds its own reference
701 g_object_unref(m_buffer);
702 g_signal_handler_disconnect(m_buffer, sig_id);
703
704 // create "ShowPosition" marker
705 GtkTextIter iter;
706 gtk_text_buffer_get_start_iter(m_buffer, &iter);
707 gtk_text_buffer_create_mark(m_buffer, "ShowPosition", &iter, true);
708
709 // create scrolled window
710 m_widget = gtk_scrolled_window_new( NULL, NULL );
711 gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( m_widget ),
712 GTK_POLICY_AUTOMATIC,
713 style & wxTE_NO_VSCROLL
714 ? GTK_POLICY_NEVER
715 : GTK_POLICY_AUTOMATIC );
716 // for ScrollLines/Pages
717 m_scrollBar[1] = GTK_RANGE(gtk_scrolled_window_get_vscrollbar(GTK_SCROLLED_WINDOW(m_widget)));
718
719 // Insert view into scrolled window
720 gtk_container_add( GTK_CONTAINER(m_widget), m_text );
721
722 GTKSetWrapMode();
723
724 GTKScrolledWindowSetBorder(m_widget, style);
725
726 gtk_widget_add_events( GTK_WIDGET(m_text), GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK );
727
728 gtk_widget_set_can_focus(m_widget, FALSE);
729 }
730 else
731 {
732 // a single-line text control: no need for scrollbars
733 m_widget =
734 m_text = gtk_entry_new();
735 // work around probable bug in GTK+ 2.18 when calling WriteText on a
736 // new, empty control, see http://trac.wxwidgets.org/ticket/11409
737 gtk_entry_get_text((GtkEntry*)m_text);
738
739 if (style & wxNO_BORDER)
740 g_object_set (m_text, "has-frame", FALSE, NULL);
741
742 }
743 g_object_ref(m_widget);
744
745 m_parent->DoAddChild( this );
746
747 m_focusWidget = m_text;
748
749 PostCreation(size);
750
751 if (multi_line)
752 {
753 gtk_widget_show(m_text);
754 }
755
756 // We want to be notified about text changes.
757 if (multi_line)
758 {
759 g_signal_connect (m_buffer, "changed",
760 G_CALLBACK (gtk_text_changed_callback), this);
761 }
762 else
763 {
764 g_signal_connect (m_text, "changed",
765 G_CALLBACK (gtk_text_changed_callback), this);
766 }
767
768 // Catch to disable focus out handling
769 g_signal_connect (m_text, "populate_popup",
770 G_CALLBACK (gtk_textctrl_populate_popup),
771 this);
772
773 if (!value.empty())
774 {
775 SetValue( value );
776 }
777
778 if (style & wxTE_PASSWORD)
779 GTKSetVisibility();
780
781 if (style & wxTE_READONLY)
782 GTKSetEditable();
783
784 // left justification (alignment) is the default anyhow
785 if ( style & (wxTE_RIGHT | wxTE_CENTRE) )
786 GTKSetJustification();
787
788 if (multi_line)
789 {
790 // Handle URLs on multi-line controls with wxTE_AUTO_URL style
791 if (style & wxTE_AUTO_URL)
792 {
793 GtkTextIter start, end;
794
795 // We create our wxUrl tag here for slight efficiency gain - we
796 // don't have to check for the tag existence in callbacks,
797 // hereby it's guaranteed to exist.
798 gtk_text_buffer_create_tag(m_buffer, "wxUrl",
799 "foreground", "blue",
800 "underline", PANGO_UNDERLINE_SINGLE,
801 NULL);
802
803 // Check for URLs after each text change
804 g_signal_connect_after (m_buffer, "insert_text",
805 G_CALLBACK (au_insert_text_callback), this);
806 g_signal_connect_after (m_buffer, "delete_range",
807 G_CALLBACK (au_delete_range_callback), this);
808
809 // Block all wxUrl tag applying unless we do it ourselves, in which case we
810 // block this callback temporarily. This takes care of gtk+ internal
811 // gtk_text_buffer_insert_range* calls that would copy our URL tag otherwise,
812 // which is undesired because only a part of the URL might be copied.
813 // The insert-text signal emitted inside it will take care of newly formed
814 // or wholly copied URLs.
815 g_signal_connect (m_buffer, "apply_tag",
816 G_CALLBACK (au_apply_tag_callback), NULL);
817
818 // Check for URLs in the initial string passed to Create
819 gtk_text_buffer_get_start_iter(m_buffer, &start);
820 gtk_text_buffer_get_end_iter(m_buffer, &end);
821 au_check_range(&start, &end);
822 }
823 }
824 else // single line
825 {
826 // do the right thing with Enter presses depending on whether we have
827 // wxTE_PROCESS_ENTER or not
828 GTKSetActivatesDefault();
829 }
830
831
832 g_signal_connect (m_text, "copy-clipboard",
833 G_CALLBACK (gtk_copy_clipboard_callback), this);
834 g_signal_connect (m_text, "cut-clipboard",
835 G_CALLBACK (gtk_cut_clipboard_callback), this);
836 g_signal_connect (m_text, "paste-clipboard",
837 G_CALLBACK (gtk_paste_clipboard_callback), this);
838
839 m_cursor = wxCursor( wxCURSOR_IBEAM );
840
841 return true;
842 }
843
844 GtkEditable *wxTextCtrl::GetEditable() const
845 {
846 wxCHECK_MSG( IsSingleLine(), NULL, "shouldn't be called for multiline" );
847
848 return GTK_EDITABLE(m_text);
849 }
850
851 GtkEntry *wxTextCtrl::GetEntry() const
852 {
853 return GTK_ENTRY(m_text);
854 }
855
856 // ----------------------------------------------------------------------------
857 // flags handling
858 // ----------------------------------------------------------------------------
859
860 void wxTextCtrl::GTKSetEditable()
861 {
862 gboolean editable = !HasFlag(wxTE_READONLY);
863 if ( IsSingleLine() )
864 gtk_editable_set_editable(GTK_EDITABLE(m_text), editable);
865 else
866 gtk_text_view_set_editable(GTK_TEXT_VIEW(m_text), editable);
867 }
868
869 void wxTextCtrl::GTKSetVisibility()
870 {
871 wxCHECK_RET( IsSingleLine(),
872 "wxTE_PASSWORD is for single line text controls only" );
873
874 gtk_entry_set_visibility(GTK_ENTRY(m_text), !HasFlag(wxTE_PASSWORD));
875 }
876
877 void wxTextCtrl::GTKSetActivatesDefault()
878 {
879 wxCHECK_RET( IsSingleLine(),
880 "wxTE_PROCESS_ENTER is for single line text controls only" );
881
882 gtk_entry_set_activates_default(GTK_ENTRY(m_text),
883 !HasFlag(wxTE_PROCESS_ENTER));
884 }
885
886 void wxTextCtrl::GTKSetWrapMode()
887 {
888 // no wrapping in single line controls
889 if ( !IsMultiLine() )
890 return;
891
892 // translate wx wrapping style to GTK+
893 GtkWrapMode wrap;
894 if ( HasFlag( wxTE_DONTWRAP ) )
895 wrap = GTK_WRAP_NONE;
896 else if ( HasFlag( wxTE_CHARWRAP ) )
897 wrap = GTK_WRAP_CHAR;
898 else if ( HasFlag( wxTE_WORDWRAP ) )
899 wrap = GTK_WRAP_WORD;
900 else // HasFlag(wxTE_BESTWRAP) always true as wxTE_BESTWRAP == 0
901 wrap = GTK_WRAP_WORD_CHAR;
902
903 gtk_text_view_set_wrap_mode( GTK_TEXT_VIEW( m_text ), wrap );
904 }
905
906 void wxTextCtrl::GTKSetJustification()
907 {
908 if ( IsMultiLine() )
909 {
910 GtkJustification just;
911 if ( HasFlag(wxTE_RIGHT) )
912 just = GTK_JUSTIFY_RIGHT;
913 else if ( HasFlag(wxTE_CENTRE) )
914 just = GTK_JUSTIFY_CENTER;
915 else // wxTE_LEFT == 0
916 just = GTK_JUSTIFY_LEFT;
917
918 gtk_text_view_set_justification(GTK_TEXT_VIEW(m_text), just);
919 }
920 else // single line
921 {
922 gfloat align;
923 if ( HasFlag(wxTE_RIGHT) )
924 align = 1.0;
925 else if ( HasFlag(wxTE_CENTRE) )
926 align = 0.5;
927 else // single line
928 align = 0.0;
929
930 gtk_entry_set_alignment(GTK_ENTRY(m_text), align);
931 }
932 }
933
934 void wxTextCtrl::SetWindowStyleFlag(long style)
935 {
936 long styleOld = GetWindowStyleFlag();
937
938 wxTextCtrlBase::SetWindowStyleFlag(style);
939
940 if ( (style & wxTE_READONLY) != (styleOld & wxTE_READONLY) )
941 GTKSetEditable();
942
943 if ( (style & wxTE_PASSWORD) != (styleOld & wxTE_PASSWORD) )
944 GTKSetVisibility();
945
946 if ( (style & wxTE_PROCESS_ENTER) != (styleOld & wxTE_PROCESS_ENTER) )
947 GTKSetActivatesDefault();
948
949 static const long flagsWrap = wxTE_WORDWRAP | wxTE_CHARWRAP | wxTE_DONTWRAP;
950 if ( (style & flagsWrap) != (styleOld & flagsWrap) )
951 GTKSetWrapMode();
952
953 static const long flagsAlign = wxTE_LEFT | wxTE_CENTRE | wxTE_RIGHT;
954 if ( (style & flagsAlign) != (styleOld & flagsAlign) )
955 GTKSetJustification();
956 }
957
958 // ----------------------------------------------------------------------------
959 // control value
960 // ----------------------------------------------------------------------------
961
962 wxString wxTextCtrl::GetValue() const
963 {
964 wxCHECK_MSG( m_text != NULL, wxEmptyString, wxT("invalid text ctrl") );
965
966 if ( IsMultiLine() )
967 {
968 GtkTextIter start;
969 gtk_text_buffer_get_start_iter( m_buffer, &start );
970 GtkTextIter end;
971 gtk_text_buffer_get_end_iter( m_buffer, &end );
972 wxGtkString text(gtk_text_buffer_get_text(m_buffer, &start, &end, true));
973
974 return wxGTK_CONV_BACK(text);
975 }
976 else // single line
977 {
978 return wxTextEntry::GetValue();
979 }
980 }
981
982 wxFontEncoding wxTextCtrl::GetTextEncoding() const
983 {
984 // GTK+ uses UTF-8 internally, we need to convert to it but from which
985 // encoding?
986
987 // first check the default text style (we intentionally don't check the
988 // style for the current position as it doesn't make sense for SetValue())
989 const wxTextAttr& style = GetDefaultStyle();
990 wxFontEncoding enc = style.HasFontEncoding() ? style.GetFontEncoding()
991 : wxFONTENCODING_SYSTEM;
992
993 // fall back to the controls font if no style
994 if ( enc == wxFONTENCODING_SYSTEM && m_hasFont )
995 enc = GetFont().GetEncoding();
996
997 return enc;
998 }
999
1000 bool wxTextCtrl::IsEmpty() const
1001 {
1002 if ( IsMultiLine() )
1003 return gtk_text_buffer_get_char_count(m_buffer) == 0;
1004
1005 return wxTextEntry::IsEmpty();
1006 }
1007
1008 void wxTextCtrl::DoSetValue( const wxString &value, int flags )
1009 {
1010 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1011
1012 m_modified = false;
1013
1014 if ( !IsMultiLine() )
1015 {
1016 wxTextEntry::DoSetValue(value, flags);
1017 return;
1018 }
1019
1020 if (value.IsEmpty())
1021 {
1022 if ( !(flags & SetValue_SendEvent) )
1023 EnableTextChangedEvents(false);
1024
1025 gtk_text_buffer_set_text( m_buffer, "", 0 );
1026
1027 if ( !(flags & SetValue_SendEvent) )
1028 EnableTextChangedEvents(true);
1029
1030 return;
1031 }
1032
1033 #if wxUSE_UNICODE
1034 const wxCharBuffer buffer(value.utf8_str());
1035 #else
1036 wxFontEncoding enc = m_defaultStyle.HasFont()
1037 ? m_defaultStyle.GetFont().GetEncoding()
1038 : wxFONTENCODING_SYSTEM;
1039 if ( enc == wxFONTENCODING_SYSTEM )
1040 enc = GetTextEncoding();
1041
1042 const wxCharBuffer buffer(wxGTK_CONV_ENC(value, enc));
1043 if ( !buffer )
1044 {
1045 // see comment in WriteText() as to why we must warn the user about
1046 // this
1047 wxLogWarning(_("Failed to set text in the text control."));
1048 return;
1049 }
1050 #endif
1051
1052 if ( !(flags & SetValue_SendEvent) )
1053 {
1054 EnableTextChangedEvents(false);
1055 }
1056
1057 gtk_text_buffer_set_text( m_buffer, buffer, strlen(buffer) );
1058
1059 if ( !m_defaultStyle.IsDefault() )
1060 {
1061 GtkTextIter start, end;
1062 gtk_text_buffer_get_bounds( m_buffer, &start, &end );
1063 wxGtkTextApplyTagsFromAttr(m_widget, m_buffer, m_defaultStyle,
1064 &start, &end);
1065 }
1066
1067 if ( !(flags & SetValue_SendEvent) )
1068 {
1069 EnableTextChangedEvents(true);
1070 }
1071 }
1072
1073 void wxTextCtrl::WriteText( const wxString &text )
1074 {
1075 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1076
1077 // we're changing the text programmatically
1078 DontMarkDirtyOnNextChange();
1079
1080 if ( !IsMultiLine() )
1081 {
1082 wxTextEntry::WriteText(text);
1083 return;
1084 }
1085
1086 #if wxUSE_UNICODE
1087 const wxCharBuffer buffer(text.utf8_str());
1088 #else
1089 // check if we have a specific style for the current position
1090 wxFontEncoding enc = wxFONTENCODING_SYSTEM;
1091 wxTextAttr style;
1092 if ( GetStyle(GetInsertionPoint(), style) && style.HasFontEncoding() )
1093 {
1094 enc = style.GetFontEncoding();
1095 }
1096
1097 if ( enc == wxFONTENCODING_SYSTEM )
1098 enc = GetTextEncoding();
1099
1100 const wxCharBuffer buffer(wxGTK_CONV_ENC(text, enc));
1101 if ( !buffer )
1102 {
1103 // we must log an error here as losing the text like this can be a
1104 // serious problem (e.g. imagine the document edited by user being
1105 // empty instead of containing the correct text)
1106 wxLogWarning(_("Failed to insert text in the control."));
1107 return;
1108 }
1109 #endif
1110
1111 // First remove the selection if there is one
1112 // TODO: Is there an easier GTK specific way to do this?
1113 long from, to;
1114 GetSelection(&from, &to);
1115 if (from != to)
1116 Remove(from, to);
1117
1118 // Insert the text
1119 wxGtkTextInsert( m_text, m_buffer, m_defaultStyle, buffer );
1120
1121 // Scroll to cursor, but only if scrollbar thumb is at the very bottom
1122 // won't work when frozen, text view is not using m_buffer then
1123 if (!IsFrozen())
1124 {
1125 GtkAdjustment* adj = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(m_widget));
1126 const double value = gtk_adjustment_get_value(adj);
1127 const double upper = gtk_adjustment_get_upper(adj);
1128 const double page_size = gtk_adjustment_get_page_size(adj);
1129 if (wxIsSameDouble(value, upper - page_size))
1130 {
1131 gtk_text_view_scroll_to_mark(GTK_TEXT_VIEW(m_text),
1132 gtk_text_buffer_get_insert(m_buffer), 0, false, 0, 1);
1133 }
1134 }
1135 }
1136
1137 wxString wxTextCtrl::GetLineText( long lineNo ) const
1138 {
1139 wxString result;
1140 if ( IsMultiLine() )
1141 {
1142 GtkTextIter line;
1143 gtk_text_buffer_get_iter_at_line(m_buffer,&line,lineNo);
1144
1145 GtkTextIter end = line;
1146 // avoid skipping to the next line end if this one is empty
1147 if ( !gtk_text_iter_ends_line(&line) )
1148 gtk_text_iter_forward_to_line_end(&end);
1149
1150 wxGtkString text(gtk_text_buffer_get_text(m_buffer, &line, &end, true));
1151 result = wxGTK_CONV_BACK(text);
1152 }
1153 else
1154 {
1155 if (lineNo == 0)
1156 result = GetValue();
1157 }
1158 return result;
1159 }
1160
1161 void wxTextCtrl::OnDropFiles( wxDropFilesEvent &WXUNUSED(event) )
1162 {
1163 /* If you implement this, don't forget to update the documentation!
1164 * (file docs/latex/wx/text.tex) */
1165 wxFAIL_MSG( wxT("wxTextCtrl::OnDropFiles not implemented") );
1166 }
1167
1168 bool wxTextCtrl::PositionToXY(long pos, long *x, long *y ) const
1169 {
1170 if ( IsMultiLine() )
1171 {
1172 GtkTextIter iter;
1173
1174 if (pos > GetLastPosition())
1175 return false;
1176
1177 gtk_text_buffer_get_iter_at_offset(m_buffer, &iter, pos);
1178
1179 if ( y )
1180 *y = gtk_text_iter_get_line(&iter);
1181 if ( x )
1182 *x = gtk_text_iter_get_line_offset(&iter);
1183 }
1184 else // single line control
1185 {
1186 if (pos <= gtk_entry_get_text_length(GTK_ENTRY(m_text)))
1187 {
1188 if ( y )
1189 *y = 0;
1190 if ( x )
1191 *x = pos;
1192 }
1193 else
1194 {
1195 // index out of bounds
1196 return false;
1197 }
1198 }
1199
1200 return true;
1201 }
1202
1203 long wxTextCtrl::XYToPosition(long x, long y ) const
1204 {
1205 if ( IsSingleLine() )
1206 return 0;
1207
1208 GtkTextIter iter;
1209 if (y >= gtk_text_buffer_get_line_count (m_buffer))
1210 return -1;
1211
1212 gtk_text_buffer_get_iter_at_line(m_buffer, &iter, y);
1213 if (x >= gtk_text_iter_get_chars_in_line (&iter))
1214 return -1;
1215
1216 return gtk_text_iter_get_offset(&iter) + x;
1217 }
1218
1219 int wxTextCtrl::GetLineLength(long lineNo) const
1220 {
1221 if ( IsMultiLine() )
1222 {
1223 int last_line = gtk_text_buffer_get_line_count( m_buffer ) - 1;
1224 if (lineNo > last_line)
1225 return -1;
1226
1227 GtkTextIter iter;
1228 gtk_text_buffer_get_iter_at_line(m_buffer, &iter, lineNo);
1229 // get_chars_in_line return includes paragraph delimiters, so need to subtract 1 IF it is not the last line
1230 return gtk_text_iter_get_chars_in_line(&iter) - ((lineNo == last_line) ? 0 : 1);
1231 }
1232 else
1233 {
1234 wxString str = GetLineText (lineNo);
1235 return (int) str.length();
1236 }
1237 }
1238
1239 wxPoint wxTextCtrl::DoPositionToCoords(long pos) const
1240 {
1241 if ( !IsMultiLine() )
1242 {
1243 // Single line text entry (GtkTextEntry) doesn't have support for
1244 // getting the coordinates for the given offset. Perhaps we could
1245 // find them ourselves by using GetTextExtent() but for now just leave
1246 // it unimplemented, this function is more useful for multiline
1247 // controls anyhow.
1248 return wxDefaultPosition;
1249 }
1250
1251 // Window coordinates for the given position is calculated by getting
1252 // the buffer coordinates and converting them to window coordinates.
1253 GtkTextView *textview = GTK_TEXT_VIEW(m_text);
1254
1255 GtkTextIter iter;
1256 gtk_text_buffer_get_iter_at_offset(m_buffer, &iter, pos);
1257
1258 GdkRectangle bufferCoords;
1259 gtk_text_view_get_iter_location(textview, &iter, &bufferCoords);
1260
1261 gint winCoordX = 0,
1262 winCoordY = 0;
1263 gtk_text_view_buffer_to_window_coords(textview, GTK_TEXT_WINDOW_WIDGET,
1264 bufferCoords.x, bufferCoords.y,
1265 &winCoordX, &winCoordY);
1266
1267 return wxPoint(winCoordX, winCoordY);
1268 }
1269
1270 int wxTextCtrl::GetNumberOfLines() const
1271 {
1272 if ( IsMultiLine() )
1273 {
1274 return gtk_text_buffer_get_line_count( m_buffer );
1275 }
1276 else // single line
1277 {
1278 return 1;
1279 }
1280 }
1281
1282 void wxTextCtrl::SetInsertionPoint( long pos )
1283 {
1284 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1285
1286 if ( IsMultiLine() )
1287 {
1288 GtkTextIter iter;
1289 gtk_text_buffer_get_iter_at_offset( m_buffer, &iter, pos );
1290 gtk_text_buffer_place_cursor( m_buffer, &iter );
1291 GtkTextMark* mark = gtk_text_buffer_get_insert(m_buffer);
1292 if (IsFrozen())
1293 // defer until Thaw, text view is not using m_buffer now
1294 m_showPositionOnThaw = mark;
1295 else
1296 gtk_text_view_scroll_mark_onscreen(GTK_TEXT_VIEW(m_text), mark);
1297 }
1298 else // single line
1299 {
1300 wxTextEntry::SetInsertionPoint(pos);
1301 }
1302 }
1303
1304 void wxTextCtrl::SetEditable( bool editable )
1305 {
1306 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1307
1308 if ( IsMultiLine() )
1309 {
1310 gtk_text_view_set_editable( GTK_TEXT_VIEW(m_text), editable );
1311 }
1312 else // single line
1313 {
1314 wxTextEntry::SetEditable(editable);
1315 }
1316 }
1317
1318 bool wxTextCtrl::Enable( bool enable )
1319 {
1320 if (!wxWindowBase::Enable(enable))
1321 {
1322 // nothing to do
1323 return false;
1324 }
1325
1326 gtk_widget_set_sensitive( m_text, enable );
1327 SetCursor(enable ? wxCursor(wxCURSOR_IBEAM) : wxCursor());
1328
1329 return true;
1330 }
1331
1332 // wxGTK-specific: called recursively by Enable,
1333 // to give widgets an opportunity to correct their colours after they
1334 // have been changed by Enable
1335 void wxTextCtrl::OnEnabled(bool WXUNUSED(enable))
1336 {
1337 // If we have a custom background colour, we use this colour in both
1338 // disabled and enabled mode, or we end up with a different colour under the
1339 // text.
1340 wxColour oldColour = GetBackgroundColour();
1341 if (oldColour.IsOk())
1342 {
1343 // Need to set twice or it'll optimize the useful stuff out
1344 if (oldColour == * wxWHITE)
1345 SetBackgroundColour(*wxBLACK);
1346 else
1347 SetBackgroundColour(*wxWHITE);
1348 SetBackgroundColour(oldColour);
1349 }
1350 }
1351
1352 void wxTextCtrl::MarkDirty()
1353 {
1354 m_modified = true;
1355 }
1356
1357 void wxTextCtrl::DiscardEdits()
1358 {
1359 m_modified = false;
1360 }
1361
1362 // ----------------------------------------------------------------------------
1363 // event handling
1364 // ----------------------------------------------------------------------------
1365
1366 void wxTextCtrl::EnableTextChangedEvents(bool enable)
1367 {
1368 if ( enable )
1369 {
1370 g_signal_handlers_unblock_by_func(GetTextObject(),
1371 (gpointer)gtk_text_changed_callback, this);
1372 }
1373 else // disable events
1374 {
1375 g_signal_handlers_block_by_func(GetTextObject(),
1376 (gpointer)gtk_text_changed_callback, this);
1377 }
1378 }
1379
1380 bool wxTextCtrl::IgnoreTextUpdate()
1381 {
1382 if ( m_countUpdatesToIgnore > 0 )
1383 {
1384 m_countUpdatesToIgnore--;
1385
1386 return true;
1387 }
1388
1389 return false;
1390 }
1391
1392 bool wxTextCtrl::MarkDirtyOnChange()
1393 {
1394 if ( m_dontMarkDirty )
1395 {
1396 m_dontMarkDirty = false;
1397
1398 return false;
1399 }
1400
1401 return true;
1402 }
1403
1404 void wxTextCtrl::SetSelection( long from, long to )
1405 {
1406 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1407
1408 if ( IsMultiLine() )
1409 {
1410 if (from == -1 && to == -1)
1411 {
1412 from = 0;
1413 to = GetValue().length();
1414 }
1415
1416 GtkTextIter fromi, toi;
1417 gtk_text_buffer_get_iter_at_offset( m_buffer, &fromi, from );
1418 gtk_text_buffer_get_iter_at_offset( m_buffer, &toi, to );
1419
1420 gtk_text_buffer_select_range( m_buffer, &fromi, &toi );
1421 }
1422 else // single line
1423 {
1424 wxTextEntry::SetSelection(from, to);
1425 }
1426 }
1427
1428 void wxTextCtrl::ShowPosition( long pos )
1429 {
1430 if (IsMultiLine())
1431 {
1432 GtkTextIter iter;
1433 gtk_text_buffer_get_iter_at_offset(m_buffer, &iter, int(pos));
1434 GtkTextMark* mark = gtk_text_buffer_get_mark(m_buffer, "ShowPosition");
1435 gtk_text_buffer_move_mark(m_buffer, mark, &iter);
1436 if (IsFrozen())
1437 // defer until Thaw, text view is not using m_buffer now
1438 m_showPositionOnThaw = mark;
1439 else
1440 gtk_text_view_scroll_mark_onscreen(GTK_TEXT_VIEW(m_text), mark);
1441 }
1442 }
1443
1444 wxTextCtrlHitTestResult
1445 wxTextCtrl::HitTest(const wxPoint& pt, long *pos) const
1446 {
1447 if ( !IsMultiLine() )
1448 {
1449 // not supported
1450 return wxTE_HT_UNKNOWN;
1451 }
1452
1453 int x, y;
1454 gtk_text_view_window_to_buffer_coords
1455 (
1456 GTK_TEXT_VIEW(m_text),
1457 GTK_TEXT_WINDOW_TEXT,
1458 pt.x, pt.y,
1459 &x, &y
1460 );
1461
1462 GtkTextIter iter;
1463 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(m_text), &iter, x, y);
1464 if ( pos )
1465 *pos = gtk_text_iter_get_offset(&iter);
1466
1467 return wxTE_HT_ON_TEXT;
1468 }
1469
1470 long wxTextCtrl::GetInsertionPoint() const
1471 {
1472 wxCHECK_MSG( m_text != NULL, 0, wxT("invalid text ctrl") );
1473
1474 if ( IsMultiLine() )
1475 {
1476 // There is no direct accessor for the cursor, but
1477 // internally, the cursor is the "mark" called
1478 // "insert" in the text view's btree structure.
1479
1480 GtkTextMark *mark = gtk_text_buffer_get_insert( m_buffer );
1481 GtkTextIter cursor;
1482 gtk_text_buffer_get_iter_at_mark( m_buffer, &cursor, mark );
1483
1484 return gtk_text_iter_get_offset( &cursor );
1485 }
1486 else
1487 {
1488 return wxTextEntry::GetInsertionPoint();
1489 }
1490 }
1491
1492 wxTextPos wxTextCtrl::GetLastPosition() const
1493 {
1494 wxCHECK_MSG( m_text != NULL, 0, wxT("invalid text ctrl") );
1495
1496 int pos = 0;
1497
1498 if ( IsMultiLine() )
1499 {
1500 GtkTextIter end;
1501 gtk_text_buffer_get_end_iter( m_buffer, &end );
1502
1503 pos = gtk_text_iter_get_offset( &end );
1504 }
1505 else // single line
1506 {
1507 pos = wxTextEntry::GetLastPosition();
1508 }
1509
1510 return (long)pos;
1511 }
1512
1513 void wxTextCtrl::Remove( long from, long to )
1514 {
1515 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1516
1517 if ( IsMultiLine() )
1518 {
1519 GtkTextIter fromi, toi;
1520 gtk_text_buffer_get_iter_at_offset( m_buffer, &fromi, from );
1521 gtk_text_buffer_get_iter_at_offset( m_buffer, &toi, to );
1522
1523 gtk_text_buffer_delete( m_buffer, &fromi, &toi );
1524 }
1525 else // single line
1526 {
1527 wxTextEntry::Remove(from, to);
1528 }
1529 }
1530
1531 void wxTextCtrl::Cut()
1532 {
1533 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1534
1535 if ( IsMultiLine() )
1536 g_signal_emit_by_name (m_text, "cut-clipboard");
1537 else
1538 wxTextEntry::Cut();
1539 }
1540
1541 void wxTextCtrl::Copy()
1542 {
1543 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1544
1545 if ( IsMultiLine() )
1546 g_signal_emit_by_name (m_text, "copy-clipboard");
1547 else
1548 wxTextEntry::Copy();
1549 }
1550
1551 void wxTextCtrl::Paste()
1552 {
1553 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1554
1555 if ( IsMultiLine() )
1556 g_signal_emit_by_name (m_text, "paste-clipboard");
1557 else
1558 wxTextEntry::Paste();
1559 }
1560
1561 // If the return values from and to are the same, there is no
1562 // selection.
1563 void wxTextCtrl::GetSelection(long* fromOut, long* toOut) const
1564 {
1565 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1566
1567 if ( !IsMultiLine() )
1568 {
1569 wxTextEntry::GetSelection(fromOut, toOut);
1570 return;
1571 }
1572
1573 gint from, to;
1574
1575 GtkTextIter ifrom, ito;
1576 if ( gtk_text_buffer_get_selection_bounds(m_buffer, &ifrom, &ito) )
1577 {
1578 from = gtk_text_iter_get_offset(&ifrom);
1579 to = gtk_text_iter_get_offset(&ito);
1580
1581 if ( from > to )
1582 {
1583 // exchange them to be compatible with wxMSW
1584 gint tmp = from;
1585 from = to;
1586 to = tmp;
1587 }
1588 }
1589 else // no selection
1590 {
1591 from =
1592 to = GetInsertionPoint();
1593 }
1594
1595 if ( fromOut )
1596 *fromOut = from;
1597 if ( toOut )
1598 *toOut = to;
1599 }
1600
1601
1602 bool wxTextCtrl::IsEditable() const
1603 {
1604 wxCHECK_MSG( m_text != NULL, false, wxT("invalid text ctrl") );
1605
1606 if ( IsMultiLine() )
1607 {
1608 return gtk_text_view_get_editable(GTK_TEXT_VIEW(m_text)) != 0;
1609 }
1610 else
1611 {
1612 return wxTextEntry::IsEditable();
1613 }
1614 }
1615
1616 bool wxTextCtrl::IsModified() const
1617 {
1618 return m_modified;
1619 }
1620
1621 void wxTextCtrl::OnChar( wxKeyEvent &key_event )
1622 {
1623 wxCHECK_RET( m_text != NULL, wxT("invalid text ctrl") );
1624
1625 if ( key_event.GetKeyCode() == WXK_RETURN )
1626 {
1627 if ( HasFlag(wxTE_PROCESS_ENTER) )
1628 {
1629 wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_windowId);
1630 event.SetEventObject(this);
1631 event.SetString(GetValue());
1632 if ( HandleWindowEvent(event) )
1633 return;
1634 }
1635 }
1636
1637 key_event.Skip();
1638 }
1639
1640 GtkWidget* wxTextCtrl::GetConnectWidget()
1641 {
1642 return GTK_WIDGET(m_text);
1643 }
1644
1645 GdkWindow *wxTextCtrl::GTKGetWindow(wxArrayGdkWindows& WXUNUSED(windows)) const
1646 {
1647 if ( IsMultiLine() )
1648 {
1649 return gtk_text_view_get_window(GTK_TEXT_VIEW(m_text),
1650 GTK_TEXT_WINDOW_TEXT );
1651 }
1652 else
1653 {
1654 #ifdef __WXGTK3__
1655 // no access to internal GdkWindows
1656 return NULL;
1657 #else
1658 return gtk_entry_get_text_window(GTK_ENTRY(m_text));
1659 #endif
1660 }
1661 }
1662
1663 // the font will change for subsequent text insertiongs
1664 bool wxTextCtrl::SetFont( const wxFont &font )
1665 {
1666 wxCHECK_MSG( m_text != NULL, false, wxT("invalid text ctrl") );
1667
1668 if ( !wxTextCtrlBase::SetFont(font) )
1669 {
1670 // font didn't change, nothing to do
1671 return false;
1672 }
1673
1674 if ( IsMultiLine() )
1675 {
1676 SetUpdateFont(true);
1677
1678 m_defaultStyle.SetFont(font);
1679
1680 ChangeFontGlobally();
1681 }
1682
1683 return true;
1684 }
1685
1686 void wxTextCtrl::ChangeFontGlobally()
1687 {
1688 // this method is very inefficient and hence should be called as rarely as
1689 // possible!
1690 //
1691 // TODO: it can be implemented much more efficiently for GTK2
1692 wxASSERT_MSG( IsMultiLine(),
1693 wxT("shouldn't be called for single line controls") );
1694
1695 wxString value = GetValue();
1696 if ( !value.empty() )
1697 {
1698 SetUpdateFont(false);
1699
1700 Clear();
1701 AppendText(value);
1702 }
1703 }
1704
1705 bool wxTextCtrl::SetForegroundColour(const wxColour& colour)
1706 {
1707 if ( !wxControl::SetForegroundColour(colour) )
1708 return false;
1709
1710 // update default fg colour too
1711 m_defaultStyle.SetTextColour(colour);
1712
1713 return true;
1714 }
1715
1716 bool wxTextCtrl::SetBackgroundColour( const wxColour &colour )
1717 {
1718 wxCHECK_MSG( m_text != NULL, false, wxT("invalid text ctrl") );
1719
1720 if ( !wxControl::SetBackgroundColour( colour ) )
1721 return false;
1722
1723 if (!m_backgroundColour.IsOk())
1724 return false;
1725
1726 // change active background color too
1727 m_defaultStyle.SetBackgroundColour( colour );
1728
1729 return true;
1730 }
1731
1732 bool wxTextCtrl::SetStyle( long start, long end, const wxTextAttr& style )
1733 {
1734 if ( IsMultiLine() )
1735 {
1736 if ( style.IsDefault() )
1737 {
1738 // nothing to do
1739 return true;
1740 }
1741
1742 gint l = gtk_text_buffer_get_char_count( m_buffer );
1743
1744 wxCHECK_MSG( start >= 0 && end <= l, false,
1745 wxT("invalid range in wxTextCtrl::SetStyle") );
1746
1747 GtkTextIter starti, endi;
1748 gtk_text_buffer_get_iter_at_offset( m_buffer, &starti, start );
1749 gtk_text_buffer_get_iter_at_offset( m_buffer, &endi, end );
1750
1751 wxGtkTextApplyTagsFromAttr( m_widget, m_buffer, style, &starti, &endi );
1752
1753 return true;
1754 }
1755 //else: single line text controls don't support styles
1756
1757 return false;
1758 }
1759
1760 bool wxTextCtrl::GetStyle(long position, wxTextAttr& style)
1761 {
1762 if ( !IsMultiLine() )
1763 {
1764 // no styles for GtkEntry
1765 return false;
1766 }
1767
1768 gint l = gtk_text_buffer_get_char_count( m_buffer );
1769
1770 wxCHECK_MSG( position >= 0 && position <= l, false,
1771 wxT("invalid range in wxTextCtrl::GetStyle") );
1772
1773 GtkTextIter positioni;
1774 gtk_text_buffer_get_iter_at_offset(m_buffer, &positioni, position);
1775
1776 // Obtain a copy of the default attributes
1777 GtkTextAttributes * const
1778 pattr = gtk_text_view_get_default_attributes(GTK_TEXT_VIEW(m_text));
1779 wxON_BLOCK_EXIT1(gtk_text_attributes_unref, pattr);
1780
1781 // And query GTK for the attributes at the given position using it as base
1782 if ( !gtk_text_iter_get_attributes(&positioni, pattr) )
1783 {
1784 style = m_defaultStyle;
1785 }
1786 else // have custom attributes
1787 {
1788 style.SetBackgroundColour(pattr->appearance.bg_color);
1789 style.SetTextColour(pattr->appearance.fg_color);
1790
1791 const wxGtkString
1792 pangoFontString(pango_font_description_to_string(pattr->font));
1793
1794 wxFont font;
1795 if ( font.SetNativeFontInfo(wxString(pangoFontString)) )
1796 style.SetFont(font);
1797
1798 // TODO: set alignment, tabs and indents
1799 }
1800
1801 return true;
1802 }
1803
1804 void wxTextCtrl::DoApplyWidgetStyle(GtkRcStyle *style)
1805 {
1806 GTKApplyStyle(m_text, style);
1807 }
1808
1809 void wxTextCtrl::OnCut(wxCommandEvent& WXUNUSED(event))
1810 {
1811 Cut();
1812 }
1813
1814 void wxTextCtrl::OnCopy(wxCommandEvent& WXUNUSED(event))
1815 {
1816 Copy();
1817 }
1818
1819 void wxTextCtrl::OnPaste(wxCommandEvent& WXUNUSED(event))
1820 {
1821 Paste();
1822 }
1823
1824 void wxTextCtrl::OnUndo(wxCommandEvent& WXUNUSED(event))
1825 {
1826 Undo();
1827 }
1828
1829 void wxTextCtrl::OnRedo(wxCommandEvent& WXUNUSED(event))
1830 {
1831 Redo();
1832 }
1833
1834 void wxTextCtrl::OnUpdateCut(wxUpdateUIEvent& event)
1835 {
1836 event.Enable( CanCut() );
1837 }
1838
1839 void wxTextCtrl::OnUpdateCopy(wxUpdateUIEvent& event)
1840 {
1841 event.Enable( CanCopy() );
1842 }
1843
1844 void wxTextCtrl::OnUpdatePaste(wxUpdateUIEvent& event)
1845 {
1846 event.Enable( CanPaste() );
1847 }
1848
1849 void wxTextCtrl::OnUpdateUndo(wxUpdateUIEvent& event)
1850 {
1851 event.Enable( CanUndo() );
1852 }
1853
1854 void wxTextCtrl::OnUpdateRedo(wxUpdateUIEvent& event)
1855 {
1856 event.Enable( CanRedo() );
1857 }
1858
1859 wxSize wxTextCtrl::DoGetBestSize() const
1860 {
1861 // FIXME should be different for multi-line controls...
1862 wxSize ret( wxControl::DoGetBestSize() );
1863 wxSize best(80, ret.y);
1864 CacheBestSize(best);
1865 return best;
1866 }
1867
1868 // ----------------------------------------------------------------------------
1869 // freeze/thaw
1870 // ----------------------------------------------------------------------------
1871
1872 void wxTextCtrl::DoFreeze()
1873 {
1874 wxCHECK_RET(m_text != NULL, wxT("invalid text ctrl"));
1875
1876 wxWindow::DoFreeze();
1877
1878 if ( HasFlag(wxTE_MULTILINE) )
1879 {
1880 GTKFreezeWidget(m_text);
1881
1882 // removing buffer dramatically speeds up insertion:
1883 g_object_ref(m_buffer);
1884 GtkTextBuffer* buf_new = gtk_text_buffer_new(NULL);
1885 gtk_text_view_set_buffer(GTK_TEXT_VIEW(m_text), buf_new);
1886 // gtk_text_view_set_buffer adds its own reference
1887 g_object_unref(buf_new);
1888 // These marks should be deleted when the buffer is changed,
1889 // but they are not (in GTK+ up to at least 3.0.1).
1890 // Otherwise these anonymous marks start to build up in the buffer,
1891 // and Freeze takes longer and longer each time it is called.
1892 if (m_anonymousMarkList)
1893 {
1894 for (GSList* item = m_anonymousMarkList; item; item = item->next)
1895 {
1896 GtkTextMark* mark = static_cast<GtkTextMark*>(item->data);
1897 if (GTK_IS_TEXT_MARK(mark) && !gtk_text_mark_get_deleted(mark))
1898 gtk_text_buffer_delete_mark(m_buffer, mark);
1899 }
1900 g_slist_free(m_anonymousMarkList);
1901 m_anonymousMarkList = NULL;
1902 }
1903 }
1904 }
1905
1906 void wxTextCtrl::DoThaw()
1907 {
1908 if ( HasFlag(wxTE_MULTILINE) )
1909 {
1910 // reattach buffer:
1911 gulong sig_id = g_signal_connect(m_buffer, "mark_set", G_CALLBACK(mark_set), &m_anonymousMarkList);
1912 gtk_text_view_set_buffer(GTK_TEXT_VIEW(m_text), m_buffer);
1913 g_object_unref(m_buffer);
1914 g_signal_handler_disconnect(m_buffer, sig_id);
1915
1916 if (m_showPositionOnThaw != NULL)
1917 {
1918 gtk_text_view_scroll_mark_onscreen(
1919 GTK_TEXT_VIEW(m_text), m_showPositionOnThaw);
1920 m_showPositionOnThaw = NULL;
1921 }
1922
1923 // and thaw the window
1924 GTKThawWidget(m_text);
1925 }
1926
1927 wxWindow::DoThaw();
1928 }
1929
1930 // ----------------------------------------------------------------------------
1931 // wxTextUrlEvent passing if style & wxTE_AUTO_URL
1932 // ----------------------------------------------------------------------------
1933
1934 // FIXME: when dragging on a link the sample gets an "Unknown event".
1935 // This might be an excessive event from us or a buggy wxMouseEvent::Moving() or
1936 // a buggy sample, or something else
1937 void wxTextCtrl::OnUrlMouseEvent(wxMouseEvent& event)
1938 {
1939 event.Skip();
1940 if( !HasFlag(wxTE_AUTO_URL) )
1941 return;
1942
1943 gint x, y;
1944 GtkTextIter start, end;
1945 GtkTextTag *tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(m_buffer),
1946 "wxUrl");
1947
1948 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(m_text), GTK_TEXT_WINDOW_WIDGET,
1949 event.GetX(), event.GetY(), &x, &y);
1950
1951 gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(m_text), &end, x, y);
1952 if (!gtk_text_iter_has_tag(&end, tag))
1953 {
1954 SetCursor(wxCursor(wxCURSOR_IBEAM));
1955 return;
1956 }
1957
1958 SetCursor(wxCursor(wxCURSOR_HAND));
1959
1960 start = end;
1961 if(!gtk_text_iter_begins_tag(&start, tag))
1962 gtk_text_iter_backward_to_tag_toggle(&start, tag);
1963 if(!gtk_text_iter_ends_tag(&end, tag))
1964 gtk_text_iter_forward_to_tag_toggle(&end, tag);
1965
1966 // Native context menu is probably not desired on an URL.
1967 // Consider making this dependent on ProcessEvent(wxTextUrlEvent) return value
1968 if(event.GetEventType() == wxEVT_RIGHT_DOWN)
1969 event.Skip(false);
1970
1971 wxTextUrlEvent url_event(m_windowId, event,
1972 gtk_text_iter_get_offset(&start),
1973 gtk_text_iter_get_offset(&end));
1974
1975 InitCommandEvent(url_event);
1976 // Is that a good idea? Seems not (pleasure with gtk_text_view_start_selection_drag)
1977 //event.Skip(!HandleWindowEvent(url_event));
1978 HandleWindowEvent(url_event);
1979 }
1980
1981 bool wxTextCtrl::GTKProcessEvent(wxEvent& event) const
1982 {
1983 bool rc = wxTextCtrlBase::GTKProcessEvent(event);
1984
1985 // GtkTextView starts a drag operation when left mouse button is pressed
1986 // and ends it when it is released and if it doesn't get the release event
1987 // the next click on a control results in an assertion failure inside
1988 // gtk_text_view_start_selection_drag() which simply *kills* the program
1989 // without anything we can do about it, so always let GTK+ have this event
1990 return rc && (IsSingleLine() || event.GetEventType() != wxEVT_LEFT_UP);
1991 }
1992
1993 // static
1994 wxVisualAttributes
1995 wxTextCtrl::GetClassDefaultAttributes(wxWindowVariant WXUNUSED(variant))
1996 {
1997 return GetDefaultAttributesFromGTKWidget(gtk_entry_new, true);
1998 }
1999
2000 #endif // wxUSE_TEXTCTRL