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