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