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