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