112fc1b21814de1cc1de493c7f3ee14f02e3dfc3
[wxWidgets.git] / samples / richedit / wxlwindow.cpp
1 /*-*- c++ -*-********************************************************
2 * wxLwindow.h : a scrolled Window for displaying/entering rich text*
3 * *
4 * (C) 1998, 1999 by Karsten Ballüder (karsten@phy.hw.ac.uk) *
5 * *
6 * $Id$
7 *******************************************************************/
8
9 // ============================================================================
10 // declarations
11 // ============================================================================
12
13 // ----------------------------------------------------------------------------
14 // headers
15 // ----------------------------------------------------------------------------
16
17 #ifdef __GNUG__
18 # pragma implementation "wxlwindow.h"
19 #endif
20
21 #include <wx/wxprec.h>
22
23 #ifdef __BORLANDC__
24 # pragma hdrstop
25 #endif
26
27 #include "Mpch.h"
28
29 #ifdef M_BASEDIR
30 # ifndef USE_PCH
31 # include "Mcommon.h"
32 # include "gui/wxMenuDefs.h"
33 # include "gui/wxMApp.h"
34 # endif // USE_PCH
35 # include "gui/wxlwindow.h"
36 # include "gui/wxlparser.h"
37
38 # include "MDialogs.h"
39 # include "strutil.h"
40 #else
41 # ifdef __WXMSW__
42 # include <wx/msw/private.h>
43 # endif
44
45 # include "wxlwindow.h"
46 # include "wxlparser.h"
47 #endif
48
49 #include <wx/clipbrd.h>
50 #include <wx/textctrl.h>
51 #include <wx/dataobj.h>
52
53 #ifdef WXLAYOUT_USE_CARET
54 # include <wx/caret.h>
55 #endif // WXLAYOUT_USE_CARET
56
57 #include <ctype.h>
58
59 // ----------------------------------------------------------------------------
60 // macros
61 // ----------------------------------------------------------------------------
62
63 #ifdef DEBUG
64 # define WXLO_DEBUG(x) wxLogDebug x
65 #else
66 # define WXLO_DEBUG(x)
67 #endif
68
69 // ----------------------------------------------------------------------------
70 // constants
71 // ----------------------------------------------------------------------------
72
73 /// offsets to put a nice frame around text
74 #define WXLO_XOFFSET 4
75 #define WXLO_YOFFSET 4
76
77 /// offset to the right and bottom for when to redraw scrollbars
78 #define WXLO_ROFFSET 20
79 #define WXLO_BOFFSET 20
80
81 /// scroll margins when selecting with the mouse
82 #define WXLO_SCROLLMARGIN_X 10
83 #define WXLO_SCROLLMARGIN_Y 10
84
85 /// the size of one scrollbar page in pixels
86 static const int X_SCROLL_PAGE = 10;
87 static const int Y_SCROLL_PAGE = 20;
88
89 // ----------------------------------------------------------------------------
90 // event tables
91 // ----------------------------------------------------------------------------
92
93 BEGIN_EVENT_TABLE(wxLayoutWindow,wxScrolledWindow)
94 EVT_SIZE (wxLayoutWindow::OnSize)
95
96 EVT_PAINT (wxLayoutWindow::OnPaint)
97
98 EVT_CHAR (wxLayoutWindow::OnChar)
99 EVT_KEY_UP (wxLayoutWindow::OnKeyUp)
100
101 EVT_LEFT_DOWN(wxLayoutWindow::OnLeftMouseDown)
102 EVT_LEFT_UP(wxLayoutWindow::OnLeftMouseUp)
103 EVT_RIGHT_DOWN(wxLayoutWindow::OnRightMouseClick)
104 EVT_LEFT_DCLICK(wxLayoutWindow::OnMouseDblClick)
105 EVT_MIDDLE_DOWN(wxLayoutWindow::OnMiddleMouseDown)
106 EVT_MOTION (wxLayoutWindow::OnMouseMove)
107
108 EVT_UPDATE_UI(WXLOWIN_MENU_UNDERLINE, wxLayoutWindow::OnUpdateMenuUnderline)
109 EVT_UPDATE_UI(WXLOWIN_MENU_BOLD, wxLayoutWindow::OnUpdateMenuBold)
110 EVT_UPDATE_UI(WXLOWIN_MENU_ITALICS, wxLayoutWindow::OnUpdateMenuItalic)
111 EVT_MENU_RANGE(WXLOWIN_MENU_FIRST, WXLOWIN_MENU_LAST, wxLayoutWindow::OnMenu)
112
113 EVT_SET_FOCUS(wxLayoutWindow::OnSetFocus)
114 EVT_KILL_FOCUS(wxLayoutWindow::OnKillFocus)
115
116 // EVT_IDLE(wxLayoutWindow::ResizeScrollbars)
117 END_EVENT_TABLE()
118
119 // ----------------------------------------------------------------------------
120 // function prototypes
121 // ----------------------------------------------------------------------------
122
123 /// returns TRUE if keyCode is one of arrows/home/end/page{up|down} keys
124 static bool IsDirectionKey(long keyCode);
125
126 // ============================================================================
127 // implementation
128 // ============================================================================
129
130 #ifndef wxWANTS_CHARS
131 # define wxWANTS_CHARS 0
132 #endif
133
134 // ----------------------------------------------------------------------------
135 // wxLayoutWindow
136 // ----------------------------------------------------------------------------
137
138 wxLayoutWindow::wxLayoutWindow(wxWindow *parent)
139 : wxScrolledWindow(parent, -1,
140 wxDefaultPosition, wxDefaultSize,
141 wxHSCROLL | wxVSCROLL |
142 wxBORDER |
143 wxWANTS_CHARS),
144 m_llist(NULL)
145 {
146 SetStatusBar(NULL); // don't use statusbar
147 m_Editable = false;
148 m_doSendEvents = false;
149 m_ViewStartX = 0; m_ViewStartY = 0;
150 m_DoPopupMenu = true;
151 m_PopupMenu = MakeFormatMenu();
152 m_memDC = new wxMemoryDC;
153 m_bitmap = new wxBitmap(4,4);
154 m_bitmapSize = wxPoint(4,4);
155 m_llist = new wxLayoutList();
156 m_BGbitmap = NULL;
157 m_ScrollToCursor = false;
158 #ifndef __WXMSW__
159 m_FocusFollowMode = false;
160 #endif
161 SetWrapMargin(0);
162
163 // no scrollbars initially
164 m_hasHScrollbar =
165 m_hasVScrollbar = false;
166
167 m_Selecting = false;
168
169 #ifdef WXLAYOUT_USE_CARET
170 // FIXME cursor size shouldn't be hardcoded
171 wxCaret *caret = new wxCaret(this, 2, 20);
172 SetCaret(caret);
173 m_llist->SetCaret(caret);
174 #endif // WXLAYOUT_USE_CARET
175
176 m_HaveFocus = FALSE;
177 m_HandCursor = FALSE;
178 m_CursorVisibility = -1;
179 SetCursor(wxCURSOR_IBEAM);
180 SetDirty();
181
182 // at least under Windows, this should be the default behaviour
183 m_AutoDeleteSelection = TRUE;
184 }
185
186 wxLayoutWindow::~wxLayoutWindow()
187 {
188 delete m_memDC; // deletes bitmap automatically (?)
189 delete m_bitmap;
190 delete m_llist;
191 delete m_PopupMenu;
192 SetBackgroundBitmap(NULL);
193 }
194
195 void
196 wxLayoutWindow::Clear(int family,
197 int size,
198 int style,
199 int weight,
200 int underline,
201 wxColour *fg,
202 wxColour *bg)
203 {
204 GetLayoutList()->Clear(family,size,style,weight,underline,fg,bg);
205 SetBackgroundColour(GetLayoutList()->GetDefaultStyleInfo().GetBGColour());
206 wxScrolledWindow::Clear();
207 ResizeScrollbars(true);
208 SetDirty();
209 SetModified(FALSE);
210 if ( m_Editable )
211 m_CursorVisibility = 1;
212
213 #ifdef WXLAYOUT_USE_CARET
214 if ( m_CursorVisibility == 1 )
215 GetCaret()->Show();
216 #endif // WXLAYOUT_USE_CARET
217
218 RequestUpdate((wxRect *)NULL);
219 }
220
221 void wxLayoutWindow::Refresh(bool eraseBackground, const wxRect *rect)
222 {
223 wxScrolledWindow::Refresh(eraseBackground, rect);
224 }
225
226 void
227 wxLayoutWindow::OnMouse(int eventId, wxMouseEvent& event)
228 {
229 wxClientDC dc( this );
230 PrepareDC( dc );
231 if ( eventId != WXLOWIN_MENU_MOUSEMOVE
232 #ifndef __WXMSW__
233 || m_FocusFollowMode
234 #endif
235 )
236 SetFocus();
237
238 wxPoint findPos;
239 findPos.x = dc.DeviceToLogicalX(event.GetX());
240 findPos.y = dc.DeviceToLogicalY(event.GetY());
241
242 findPos.x -= WXLO_XOFFSET;
243 findPos.y -= WXLO_YOFFSET;
244
245 if(findPos.x < 0)
246 findPos.x = 0;
247 if(findPos.y < 0)
248 findPos.y = 0;
249
250 m_ClickPosition = wxPoint(event.GetX(), event.GetY());
251
252 // Scroll the window if the mouse is at the end of it:
253 if(m_Selecting && eventId == WXLOWIN_MENU_MOUSEMOVE)
254 {
255 //WXLO_DEBUG(("selecting at : %d/%d", (int) event.GetX(), (int)event.GetY()));
256 int left, top;
257 ViewStart(&left, &top);
258 wxSize size = GetClientSize();
259 int xdelta, ydelta;
260
261 if(event.GetX() < WXLO_SCROLLMARGIN_X)
262 xdelta = -(WXLO_SCROLLMARGIN_X-event.GetX());
263 else if(event.GetX() > size.x-WXLO_SCROLLMARGIN_X)
264 xdelta = event.GetX()-size.x+WXLO_SCROLLMARGIN_X;
265 else
266 xdelta = 0;
267 if(event.GetY() < WXLO_SCROLLMARGIN_Y)
268 ydelta = -(WXLO_SCROLLMARGIN_Y-event.GetY());
269 else if(event.GetY() > size.y-WXLO_SCROLLMARGIN_Y)
270 ydelta = event.GetY()-size.y+WXLO_SCROLLMARGIN_Y;
271 else
272 ydelta = 0;
273
274 //WXLO_DEBUG(("xdelta: %d", (int) xdelta));
275 if(xdelta != 0 || ydelta != 0)
276 {
277 top += ydelta; if(top < 0) top = 0;
278 left += xdelta; if(left < 0) left = 0;
279 Scroll(left, top);
280 }
281 }
282
283 wxPoint cursorPos;
284 bool found;
285 wxLayoutObject *obj = m_llist->FindObjectScreen(dc, findPos,
286 &cursorPos, &found);
287 wxLayoutObject::UserData *u = obj ? obj->GetUserData() : NULL;
288
289 // has the mouse only been moved?
290 switch ( eventId )
291 {
292 case WXLOWIN_MENU_MOUSEMOVE:
293 {
294 // this variables is used to only erase the message in the status
295 // bar if we had put it there previously - otherwise empting status
296 // bar might be undesirable
297 static bool s_hasPutMessageInStatusBar = false;
298
299 // found is only true if we are really over an object, not just
300 // behind it
301 if(found && u && ! m_Selecting)
302 {
303 if(!m_HandCursor)
304 SetCursor(wxCURSOR_HAND);
305 m_HandCursor = TRUE;
306 if(m_StatusBar && m_StatusFieldLabel != -1)
307 {
308 const wxString &label = u->GetLabel();
309 if(label.Length())
310 {
311 m_StatusBar->SetStatusText(label,
312 m_StatusFieldLabel);
313 s_hasPutMessageInStatusBar = true;
314 }
315 }
316 }
317 else
318 {
319 if(m_HandCursor)
320 SetCursor(wxCURSOR_IBEAM);
321 m_HandCursor = FALSE;
322 if( m_StatusBar && m_StatusFieldLabel != -1 &&
323 s_hasPutMessageInStatusBar )
324 {
325 m_StatusBar->SetStatusText("", m_StatusFieldLabel);
326 }
327 }
328 }
329
330 // selecting?
331 if ( event.LeftIsDown() )
332 {
333 // m_Selecting might not be set if the button got pressed
334 // outside this window, so check for it:
335 if( m_Selecting )
336 {
337 m_llist->ContinueSelection(cursorPos, m_ClickPosition);
338 RequestUpdate(); // TODO: we don't have to redraw everything!
339 }
340 }
341
342 if ( u )
343 {
344 u->DecRef();
345 u = NULL;
346 }
347 break;
348
349 case WXLOWIN_MENU_LDOWN:
350 {
351 // always move cursor to mouse click:
352 m_llist->MoveCursorTo(cursorPos);
353
354 // clicking a mouse removes the selection
355 if ( m_llist->HasSelection() )
356 {
357 m_llist->DiscardSelection();
358 m_Selecting = false;
359 RequestUpdate(); // TODO: we don't have to redraw everything!
360 }
361
362 // Calculate where the top of the visible area is:
363 int x0, y0;
364 ViewStart(&x0,&y0);
365 int dx, dy;
366 GetScrollPixelsPerUnit(&dx, &dy);
367 x0 *= dx; y0 *= dy;
368
369 wxPoint offset(-x0+WXLO_XOFFSET, -y0+WXLO_YOFFSET);
370
371 if(m_CursorVisibility == -1)
372 m_CursorVisibility = 1;
373 #ifdef WXLAYOUT_USE_CARET
374 if ( m_CursorVisibility == 1 )
375 GetCaret()->Show();
376 #endif // WXLAYOUT_USE_CARET
377
378 if(m_CursorVisibility)
379 {
380 // draw a thick cursor for editable windows with focus
381 m_llist->DrawCursor(dc, m_HaveFocus && IsEditable(), offset);
382 }
383
384 #ifdef __WXGTK__
385 RequestUpdate(); // RequestUpdate suppresses flicker under GTK
386 #endif // wxGTK
387
388 // start selection
389 m_llist->StartSelection(wxPoint(-1, -1), m_ClickPosition);
390 m_Selecting = true;
391 }
392 break;
393
394 case WXLOWIN_MENU_LUP:
395 if ( m_Selecting )
396 {
397 m_llist->EndSelection();
398 m_Selecting = false;
399
400 RequestUpdate(); // TODO: we don't have to redraw everything!
401 }
402 break;
403
404 case WXLOWIN_MENU_MDOWN:
405 Paste(TRUE);
406 break;
407
408 case WXLOWIN_MENU_DBLCLICK:
409 // select a word under cursor
410 m_llist->MoveCursorTo(cursorPos);
411 m_llist->MoveCursorWord(-1);
412 m_llist->StartSelection();
413 m_llist->MoveCursorWord(1, false);
414 m_llist->EndSelection();
415 m_Selecting = false;
416 RequestUpdate(); // TODO: we don't have to redraw everything!
417 break;
418 }
419
420 // notify about mouse events?
421 if( m_doSendEvents )
422 {
423 // only do the menu if activated, editable and not on a clickable object
424 if(eventId == WXLOWIN_MENU_RCLICK
425 && IsEditable()
426 && (! obj || u == NULL))
427 {
428 PopupMenu(m_PopupMenu, m_ClickPosition.x, m_ClickPosition.y);
429 if(u) u->DecRef();
430 return;
431 }
432
433 // find the object at this position
434 if(obj)
435 {
436 wxCommandEvent commandEvent(wxEVT_COMMAND_MENU_SELECTED, eventId);
437 commandEvent.SetEventObject( this );
438 commandEvent.SetClientData((char *)obj);
439 GetEventHandler()->ProcessEvent(commandEvent);
440 }
441 }
442
443 if( u ) u->DecRef();
444 }
445
446 // ----------------------------------------------------------------------------
447 // keyboard handling.
448 // ----------------------------------------------------------------------------
449
450 void
451 wxLayoutWindow::OnChar(wxKeyEvent& event)
452 {
453 int keyCode = event.KeyCode();
454 bool ctrlDown = event.ControlDown();
455
456 #ifdef WXLAYOUT_DEBUG
457 if(keyCode == WXK_F1)
458 {
459 m_llist->Debug();
460 event.skip();
461 return;
462 }
463 #endif
464
465 // Force m_Selecting to be false if shift is no longer
466 // pressed. OnKeyUp() cannot catch all Shift-Up events.
467 if(m_Selecting && !event.ShiftDown())
468 {
469 m_Selecting = false;
470 m_llist->EndSelection();
471 m_llist->DiscardSelection(); //FIXME: correct?
472 }
473
474 // If we deleted the selection here, we must not execute the
475 // deletion in Delete/Backspace handling.
476 bool deletedSelection = false;
477 // pressing any non-arrow key optionally replaces the selection:
478 if(m_AutoDeleteSelection
479 && !m_Selecting
480 && m_llist->HasSelection()
481 && ! IsDirectionKey(keyCode)
482 && ! (event.AltDown() || ctrlDown)
483 )
484 {
485 m_llist->DeleteSelection();
486 deletedSelection = true;
487 SetDirty();
488 }
489
490 // <Shift>+<arrow> starts selection
491 if ( IsDirectionKey(keyCode) )
492 {
493 // just continue the old selection
494 if ( m_Selecting )
495 {
496 if( event.ShiftDown() )
497 m_llist->ContinueSelection();
498 else
499 {
500 m_llist->DiscardSelection();
501 m_Selecting = false;
502 }
503 }
504 else if( event.ShiftDown() )
505 {
506 m_Selecting = true;
507 m_llist->StartSelection();
508 }
509 }
510
511 // If needed, make cursor visible:
512 if(m_CursorVisibility == -1)
513 m_CursorVisibility = 1;
514
515 /* These two nested switches work like this:
516 The first one processes all non-editing keycodes, to move the
517 cursor, etc. It's default will process all keycodes causing
518 modifications to the buffer, but only if editing is allowed.
519 */
520 switch(keyCode)
521 {
522 case WXK_RIGHT:
523 if ( ctrlDown )
524 m_llist->MoveCursorWord(1);
525 else
526 m_llist->MoveCursorHorizontally(1);
527 break;
528 case WXK_LEFT:
529 if ( ctrlDown )
530 m_llist->MoveCursorWord(-1);
531 else
532 m_llist->MoveCursorHorizontally(-1);
533 break;
534 case WXK_UP:
535 m_llist->MoveCursorVertically(-1);
536 break;
537 case WXK_DOWN:
538 m_llist->MoveCursorVertically(1);
539 break;
540 case WXK_PRIOR:
541 m_llist->MoveCursorVertically(-Y_SCROLL_PAGE);
542 break;
543 case WXK_NEXT:
544 m_llist->MoveCursorVertically(Y_SCROLL_PAGE);
545 break;
546 case WXK_HOME:
547 if ( ctrlDown )
548 m_llist->MoveCursorTo(wxPoint(0, 0));
549 else
550 m_llist->MoveCursorToBeginOfLine();
551 break;
552 case WXK_END:
553 if ( ctrlDown )
554 m_llist->MoveCursorToEnd();
555 else
556 m_llist->MoveCursorToEndOfLine();
557 break;
558 default:
559
560 if(ctrlDown && ! IsEditable())
561 switch(keyCode)
562 {
563 case 'c':
564 // this should work even in read-only mode
565 Copy();
566 break;
567 case 's': // search
568 Find("");
569 break;
570 case 't': // search again
571 FindAgain();
572 break;
573 default:
574 ;
575 }
576 else if( IsEditable() )
577 {
578 /* First, handle control keys */
579 if(ctrlDown && ! event.AltDown())
580 {
581 if(keyCode >= 'A' && keyCode <= 'Z')
582 keyCode = tolower(keyCode);
583 switch(keyCode)
584 {
585 case WXK_INSERT:
586 Copy();
587 break;
588 case WXK_DELETE :
589 if(! deletedSelection)
590 {
591 m_llist->DeleteWord();
592 SetDirty();
593 }
594 break;
595 case 'd':
596 if(! deletedSelection) // already done
597 {
598 m_llist->Delete(1);
599 SetDirty();
600 }
601 break;
602 case 'y':
603 m_llist->DeleteLines(1);
604 SetDirty();
605 break;
606 case 'h': // like backspace
607 if(m_llist->MoveCursorHorizontally(-1))
608 {
609 m_llist->Delete(1);
610 SetDirty();
611 }
612 break;
613 case 's': // search
614 Find("");
615 break;
616 case 't': // search again
617 FindAgain();
618 break;
619 case 'u':
620 m_llist->DeleteToBeginOfLine();
621 SetDirty();
622 break;
623 case 'k':
624 m_llist->DeleteToEndOfLine();
625 SetDirty();
626 break;
627 case 'v':
628 Paste();
629 break;
630 case 'x':
631 Cut();
632 break;
633 #ifdef WXLAYOUT_DEBUG
634 case WXK_F1:
635 m_llist->SetFont(-1,-1,-1,-1,true); // underlined
636 break;
637 #endif
638 default:
639 ;
640 }
641 }
642 // ALT only:
643 else if( event.AltDown() && ! event.ControlDown() )
644 {
645 switch(keyCode)
646 {
647 case WXK_DELETE:
648 case 'd':
649 m_llist->DeleteWord();
650 SetDirty();
651 break;
652 default:
653 ;
654 }
655 }
656 // no control keys:
657 else if ( ! event.AltDown() && ! event.ControlDown())
658 {
659 switch(keyCode)
660 {
661 case WXK_INSERT:
662 if(event.ShiftDown())
663 Paste();
664 break;
665 case WXK_DELETE :
666 if(event.ShiftDown())
667 Cut();
668 else
669 if(! deletedSelection)
670 {
671 m_llist->Delete(1);
672 SetDirty();
673 }
674 break;
675 case WXK_BACK: // backspace
676 if(! deletedSelection)
677 if(m_llist->MoveCursorHorizontally(-1))
678 {
679 m_llist->Delete(1);
680 SetDirty();
681 }
682 break;
683 case WXK_RETURN:
684 if(m_WrapMargin > 0)
685 m_llist->WrapLine(m_WrapMargin);
686 m_llist->LineBreak();
687 SetDirty();
688 break;
689
690 case WXK_TAB:
691 if ( !event.ShiftDown() )
692 {
693 // TODO should be configurable
694 static const int tabSize = 8;
695
696 CoordType x = m_llist->GetCursorPos().x;
697 size_t numSpaces = tabSize - x % tabSize;
698 m_llist->Insert(wxString(' ', numSpaces));
699 SetDirty();
700 }
701 break;
702
703 default:
704 if((!(event.ControlDown() || event.AltDown()
705 //#if 0
706 ///FIXME: wxGTK reports MetaDown always
707 || event.MetaDown()
708 //#endif
709 ))
710 && (keyCode < 256 && keyCode >= 32)
711 )
712 {
713 if(m_WrapMargin > 0 && isspace(keyCode))
714 m_llist->WrapLine(m_WrapMargin);
715 m_llist->Insert((char)keyCode);
716 SetDirty();
717 }
718 break;
719 }
720 }
721 }// if(IsEditable())
722 }// first switch()
723
724 if ( m_Selecting )
725 {
726 // continue selection to the current (new) cursor position
727 m_llist->ContinueSelection();
728 }
729 ScrollToCursor();
730 // refresh the screen
731 RequestUpdate(m_llist->GetUpdateRect());
732 event.Skip();
733 }
734
735 void
736 wxLayoutWindow::OnKeyUp(wxKeyEvent& event)
737 {
738 if ( event.KeyCode() == WXK_SHIFT && m_Selecting )
739 {
740 m_llist->EndSelection();
741 m_Selecting = false;
742 }
743
744 event.Skip();
745 }
746
747
748 void
749 wxLayoutWindow::ScrollToCursor(void)
750 {
751 //is always needed to make sure we know where the cursor is
752 //if(IsDirty())
753 RequestUpdate(m_llist->GetUpdateRect());
754
755 int x0,y0,x1,y1, dx, dy;
756
757 // Calculate where the top of the visible area is:
758 ViewStart(&x0,&y0);
759 GetScrollPixelsPerUnit(&dx, &dy);
760 x0 *= dx; y0 *= dy;
761
762 WXLO_DEBUG(("ScrollToCursor: ViewStart is %d/%d", x0, y0));
763
764 // Get the size of the visible window:
765 GetClientSize(&x1, &y1);
766
767 // Make sure that the scrollbars are at a position so that the cursor is
768 // visible if we are editing
769 WXLO_DEBUG(("m_ScrollToCursor = %d", (int) m_ScrollToCursor));
770 wxPoint cc = m_llist->GetCursorScreenPos();
771
772 // the cursor should be completely visible in both directions
773 wxPoint cs(m_llist->GetCursorSize());
774 int nx = -1,
775 ny = -1;
776 if ( cc.x < x0 || cc.x >= x0 + x1 - cs.x )
777 {
778 nx = cc.x - x1/2;
779 if ( nx < 0 )
780 nx = 0;
781 }
782
783 if ( cc.y < y0 || cc.y >= y0 + y1 - cs.y )
784 {
785 ny = cc.y - y1/2;
786 if ( ny < 0)
787 ny = 0;
788 }
789
790 if ( nx != -1 || ny != -1 )
791 {
792 // set new view start
793 Scroll(nx == -1 ? -1 : (nx+dx-1)/dx, ny == -1 ? -1 : (ny+dy-1)/dy);
794 // avoid recursion
795 m_ScrollToCursor = false;
796 RequestUpdate();
797 }
798 }
799
800 void
801 wxLayoutWindow::OnPaint( wxPaintEvent &WXUNUSED(event))
802 {
803 wxRect region = GetUpdateRegion().GetBox();
804 InternalPaint(&region);
805 }
806
807 void
808 wxLayoutWindow::RequestUpdate(const wxRect *updateRect)
809 {
810 #ifdef __WXGTK__
811 // Calling Refresh() causes bad flicker under wxGTK!!!
812 InternalPaint(updateRect);
813 #else
814 // shouldn't specify the update rectangle if it doesn't include all the
815 // changed locations - otherwise, they won't be repainted at all because
816 // the system clips the display to the update rect
817 Refresh(FALSE); //, updateRect);
818 #endif
819 }
820
821 void
822 wxLayoutWindow::InternalPaint(const wxRect *updateRect)
823 {
824 wxPaintDC dc( this );
825 PrepareDC( dc );
826
827 #ifdef WXLAYOUT_USE_CARET
828 // hide the caret before drawing anything
829 GetCaret()->Hide();
830 #endif // WXLAYOUT_USE_CARET
831
832 int x0,y0,x1,y1, dx, dy;
833
834 // Calculate where the top of the visible area is:
835 ViewStart(&x0,&y0);
836 GetScrollPixelsPerUnit(&dx, &dy);
837 x0 *= dx; y0 *= dy;
838
839 // Get the size of the visible window:
840 GetClientSize(&x1,&y1);
841 wxASSERT(x1 >= 0);
842 wxASSERT(y1 >= 0);
843
844 if(updateRect)
845 {
846 WXLO_DEBUG(("Update rect: %ld,%ld / %ld,%ld",
847 updateRect->x, updateRect->y,
848 updateRect->x+updateRect->width,
849 updateRect->y+updateRect->height));
850 }
851 if(IsDirty())
852 {
853 WXLO_DEBUG(("InternalPaint, isdirty, list size: %ld,%ld",
854 (unsigned long) m_llist->GetSize().x,
855 (unsigned long) m_llist->GetSize().y));
856 // m_llist->ForceTotalLayout();
857 m_llist->Layout(dc);
858 WXLO_DEBUG(("InternalPaint, isdirty, list size after layout: %ld,%ld",
859 (unsigned long) m_llist->GetSize().x,
860 (unsigned long) m_llist->GetSize().y));
861 ResizeScrollbars();
862 ResetDirty();
863 }
864
865 /* Check whether the window has grown, if so, we need to reallocate
866 the bitmap to be larger. */
867 if(x1 > m_bitmapSize.x || y1 > m_bitmapSize.y)
868 {
869 wxASSERT(m_bitmapSize.x > 0);
870 wxASSERT(m_bitmapSize.y > 0);
871
872 m_memDC->SelectObject(wxNullBitmap);
873 delete m_bitmap;
874 m_bitmapSize = wxPoint(x1,y1);
875 m_bitmap = new wxBitmap(x1,y1);
876 m_memDC->SelectObject(*m_bitmap);
877 }
878
879 m_memDC->SetDeviceOrigin(0,0);
880 m_memDC->SetBackground(wxBrush(m_llist->GetDefaultStyleInfo().GetBGColour(),wxSOLID));
881 m_memDC->SetPen(wxPen(m_llist->GetDefaultStyleInfo().GetBGColour(),
882 0,wxTRANSPARENT));
883 m_memDC->SetLogicalFunction(wxCOPY);
884 m_memDC->Clear();
885
886 // fill the background with the background bitmap
887 if(m_BGbitmap)
888 {
889 CoordType
890 y, x,
891 w = m_BGbitmap->GetWidth(),
892 h = m_BGbitmap->GetHeight();
893 for(y = 0; y < y1; y+=h)
894 for(x = 0; x < x1; x+=w)
895 m_memDC->DrawBitmap(*m_BGbitmap, x, y);
896 m_memDC->SetBackgroundMode(wxTRANSPARENT);
897 }
898
899 // This is the important bit: we tell the list to draw itself
900 #if WXLO_DEBUG_URECT
901 if(updateRect)
902 {
903 WXLO_DEBUG(("Update rect: %ld,%ld / %ld,%ld",
904 updateRect->x, updateRect->y,
905 updateRect->x+updateRect->width,
906 updateRect->y+updateRect->height));
907 }
908 #endif
909
910 // Device origins on the memDC are suspect, we translate manually
911 // with the translate parameter of Draw().
912 wxPoint offset(-x0+WXLO_XOFFSET,-y0+WXLO_YOFFSET);
913 m_llist->Draw(*m_memDC,offset, y0, y0+y1);
914
915 // We start calculating a new update rect before drawing the
916 // cursor, so that the cursor coordinates get included in the next
917 // update rectangle (although they are drawn on the memDC, this is
918 // needed to erase it):
919 m_llist->InvalidateUpdateRect();
920 if(m_CursorVisibility != 0)
921 {
922 // draw a thick cursor for editable windows with focus
923 m_llist->DrawCursor(*m_memDC,
924 m_HaveFocus && IsEditable(),
925 offset);
926 }
927
928 // Now copy everything to the screen:
929 #if 0
930 // This somehow doesn't work, but even the following bit with the
931 // whole rect at once is still a bit broken I think.
932 wxRegionIterator ri ( GetUpdateRegion() );
933 if(ri)
934 while(ri)
935 {
936 WXLO_DEBUG(("UpdateRegion: %ld,%ld, %ld,%ld",
937 ri.GetX(),ri.GetY(),ri.GetW(),ri.GetH()));
938 dc.Blit(x0+ri.GetX(),y0+ri.GetY(),ri.GetW(),ri.GetH(),
939 m_memDC,ri.GetX(),ri.GetY(),wxCOPY,FALSE);
940 ri++;
941 }
942 else
943 #endif
944 {
945 // FIXME: Trying to copy only the changed parts, but it does not seem
946 // to work:
947 // x0 = updateRect->x; y0 = updateRect->y;
948 // if(updateRect->height < y1)
949 // y1 = updateRect->height;
950 // y1 += WXLO_YOFFSET; //FIXME might not be needed
951 dc.Blit(x0,y0,x1,y1,m_memDC,0,0,wxCOPY,FALSE);
952 }
953
954 #ifdef WXLAYOUT_USE_CARET
955 // show the caret back after everything is redrawn
956 GetCaret()->Show();
957 #endif // WXLAYOUT_USE_CARET
958
959 ResetDirty();
960
961 if ( m_StatusBar && m_StatusFieldCursor != -1 )
962 {
963 static wxPoint s_oldCursorPos(-1, -1);
964
965 wxPoint pos(m_llist->GetCursorPos());
966
967 // avoid unnecessary status bar refreshes
968 if ( pos != s_oldCursorPos )
969 {
970 s_oldCursorPos = pos;
971
972 wxString label;
973 label.Printf(_("Ln:%d Col:%d"), pos.y + 1, pos.x + 1);
974 m_StatusBar->SetStatusText(label, m_StatusFieldCursor);
975 }
976 }
977 }
978
979 void
980 wxLayoutWindow::OnSize(wxSizeEvent &event)
981 {
982 if ( m_llist )
983 ResizeScrollbars();
984
985 event.Skip();
986 }
987
988 // change the range and position of scrollbars
989 void
990 wxLayoutWindow::ResizeScrollbars(bool exact)
991 {
992
993 if(IsDirty())
994 {
995 wxClientDC dc( this );
996 PrepareDC( dc );
997 // m_llist->ForceTotalLayout();
998 m_llist->Layout(dc);
999 ResetDirty();
1000 RequestUpdate();
1001 }
1002
1003 wxPoint max = m_llist->GetSize();
1004 wxSize size = GetClientSize();
1005
1006 WXLO_DEBUG(("ResizeScrollbars: max size = (%ld, %ld)",
1007 (long int)max.x, (long int) max.y));
1008
1009 // in the absence of scrollbars we should compare with the client size
1010 if ( !m_hasHScrollbar )
1011 m_maxx = size.x;// - WXLO_ROFFSET;
1012 if ( !m_hasVScrollbar )
1013 m_maxy = size.y;// - WXLO_BOFFSET;
1014
1015 // check if the text hasn't become too big
1016 // TODO why do we set both at once? they're independent...
1017 if( max.x > m_maxx - WXLO_ROFFSET || max.y > m_maxy - WXLO_BOFFSET || exact )
1018 {
1019 // text became too large
1020 if ( !exact )
1021 {
1022 // add an extra bit to the sizes to avoid future updates
1023 max.x += WXLO_ROFFSET;
1024 max.y += WXLO_BOFFSET;
1025 }
1026
1027 ViewStart(&m_ViewStartX, &m_ViewStartY);
1028 SetScrollbars(X_SCROLL_PAGE, Y_SCROLL_PAGE,
1029 max.x / X_SCROLL_PAGE + 1, max.y / Y_SCROLL_PAGE + 1,
1030 m_ViewStartX, m_ViewStartY,
1031 true);
1032
1033 m_hasHScrollbar =
1034 m_hasVScrollbar = true;
1035
1036 m_maxx = max.x + X_SCROLL_PAGE;
1037 m_maxy = max.y + Y_SCROLL_PAGE;
1038 }
1039 #if 0
1040 //FIXME: this code is pretty broken, producing "arithmetic
1041 //exception" crashes (div by 0??)
1042 else
1043 {
1044 // check if the window hasn't become too big, thus making the scrollbars
1045 // unnecessary
1046 if ( !exact )
1047 {
1048 // add an extra bit to the sizes to avoid future updates
1049 max.x -= WXLO_ROFFSET;
1050 max.y -= WXLO_BOFFSET;
1051 }
1052
1053 if ( m_hasHScrollbar && (max.x < m_maxx) )
1054 {
1055 // remove the horizontal scrollbar
1056 SetScrollbars(0, -1, 0, -1, 0, -1, true);
1057 m_hasHScrollbar = false;
1058 }
1059
1060 if ( m_hasVScrollbar && (max.y < m_maxy) )
1061 {
1062 // remove the vertical scrollbar
1063 SetScrollbars(-1, 0, -1, 0, -1, 0, true);
1064 m_hasVScrollbar = false;
1065 }
1066 }
1067 #endif
1068 }
1069
1070 // ----------------------------------------------------------------------------
1071 // clipboard operations
1072 //
1073 // ----------------------------------------------------------------------------
1074
1075 void
1076 wxLayoutWindow::Paste(bool primary)
1077 {
1078 // Read some text
1079 if (wxTheClipboard->Open())
1080 {
1081 #if __WXGTK__
1082 if(primary)
1083 wxTheClipboard->UsePrimarySelection();
1084 #endif
1085 #if wxUSE_PRIVATE_CLIPBOARD_FORMAT
1086 wxLayoutDataObject wxldo;
1087 if (wxTheClipboard->IsSupported( wxldo.GetFormat() ))
1088 {
1089 wxTheClipboard->GetData(&wxldo);
1090 {
1091 }
1092 //FIXME: missing functionality m_llist->Insert(wxldo.GetList());
1093 }
1094 else
1095 #endif
1096 {
1097 #if 0 //RE_ENABLE FIXME!!
1098 wxTextDataObject data;
1099 if (wxTheClipboard->IsSupported( data.GetFormat() ))
1100 {
1101 wxTheClipboard->GetData(&data);
1102 wxString text = data.GetText();
1103 wxLayoutImportText( m_llist, text);
1104 SetDirty();
1105 }
1106 #endif
1107 }
1108 wxTheClipboard->Close();
1109 }
1110 }
1111
1112 bool
1113 wxLayoutWindow::Copy(bool invalidate)
1114 {
1115 // Calling GetSelection() will automatically do an EndSelection()
1116 // on the list, but we need to take a note of it, too:
1117 if(m_Selecting)
1118 {
1119 m_Selecting = false;
1120 m_llist->EndSelection();
1121 }
1122
1123 #if 0 //FIXME CLIPBOARD
1124 wxLayoutDataObject wldo;
1125 wxLayoutList *llist = m_llist->GetSelection(&wldo, invalidate);
1126 if(! llist)
1127 return FALSE;
1128 // Export selection as text:
1129 wxString text;
1130 wxLayoutExportObject *exp;
1131 wxLayoutExportStatus status(llist);
1132 while((exp = wxLayoutExport( &status, WXLO_EXPORT_AS_TEXT)) != NULL)
1133 {
1134 if(exp->type == WXLO_EXPORT_TEXT)
1135 text << *(exp->content.text);
1136 delete exp;
1137 }
1138 delete llist;
1139
1140 // The exporter always appends a newline, so we chop it off if it
1141 // is there:
1142 {
1143 size_t len = text.Length();
1144 if(len > 2 && text[len-2] == '\r') // Windows
1145 text = text.Mid(0,len-2);
1146 else if(len > 1 && text[len-1] == '\n')
1147 text = text.Mid(0,len-1);
1148 }
1149
1150
1151 if (wxTheClipboard->Open())
1152 {
1153 wxTextDataObject *data = new wxTextDataObject( text );
1154 bool rc = wxTheClipboard->SetData( data );
1155 #if wxUSE_PRIVATE_CLIPBOARD_FORMAT
1156 rc |= wxTheClipboard->AddData( &wldo );
1157 #endif
1158 wxTheClipboard->Close();
1159 return rc;
1160 }
1161 #endif //FIXME CLIPBOARD
1162
1163 return FALSE;
1164 }
1165
1166 bool
1167 wxLayoutWindow::Cut(void)
1168 {
1169 if(Copy(false)) // do not invalidate selection after copy
1170 {
1171 m_llist->DeleteSelection();
1172 SetDirty();
1173 return TRUE;
1174 }
1175 else
1176 return FALSE;
1177 }
1178
1179 // ----------------------------------------------------------------------------
1180 // searching
1181 // ----------------------------------------------------------------------------
1182
1183 #ifdef M_BASEDIR
1184 bool
1185 wxLayoutWindow::Find(const wxString &needle,
1186 wxPoint * fromWhere,
1187 const wxString &configPath)
1188 {
1189 wxPoint found;
1190
1191 if(needle.Length() == 0)
1192 {
1193 if( ! MInputBox(&m_FindString,
1194 _("Find text"),
1195 _(" Find:"),
1196 this,
1197 configPath, "")
1198 || strutil_isempty(m_FindString))
1199 return true;
1200 }
1201 else
1202 m_FindString = needle;
1203
1204 if(fromWhere == NULL)
1205 found = m_llist->FindText(m_FindString, m_llist->GetCursorPos());
1206 else
1207 found = m_llist->FindText(m_FindString, *fromWhere);
1208 if(found.x != -1)
1209 {
1210 if(fromWhere)
1211 {
1212 *fromWhere = found;
1213 fromWhere->x ++;
1214 }
1215 m_llist->MoveCursorTo(found);
1216 ScrollToCursor();
1217 RequestUpdate();
1218 return true;
1219 }
1220 return false;
1221 }
1222
1223
1224 bool
1225 wxLayoutWindow::FindAgain(void)
1226 {
1227 bool rc = Find(m_FindString);
1228 return rc;
1229 }
1230 #endif
1231
1232 // ----------------------------------------------------------------------------
1233 // popup menu stuff
1234 // ----------------------------------------------------------------------------
1235
1236 wxMenu *
1237 wxLayoutWindow::MakeFormatMenu()
1238 {
1239 wxMenu *m = new wxMenu(_("Layout Menu"));
1240
1241 m->Append(WXLOWIN_MENU_LARGER ,_("&Larger"),_("Switch to larger font."), false);
1242 m->Append(WXLOWIN_MENU_SMALLER ,_("&Smaller"),_("Switch to smaller font."), false);
1243 m->AppendSeparator();
1244 m->Append(WXLOWIN_MENU_UNDERLINE, _("&Underline"),_("Underline mode."), true);
1245 m->Append(WXLOWIN_MENU_BOLD, _("&Bold"),_("Bold mode."), true);
1246 m->Append(WXLOWIN_MENU_ITALICS, _("&Italics"),_("Italics mode."), true);
1247 m->AppendSeparator();
1248 m->Append(WXLOWIN_MENU_ROMAN ,_("&Roman"),_("Switch to roman font."), false);
1249 m->Append(WXLOWIN_MENU_TYPEWRITER,_("&Typewriter"),_("Switch to typewriter font."), false);
1250 m->Append(WXLOWIN_MENU_SANSSERIF ,_("&Sans Serif"),_("Switch to sans serif font."), false);
1251
1252 return m;
1253 }
1254
1255 void wxLayoutWindow::OnUpdateMenuUnderline(wxUpdateUIEvent& event)
1256 {
1257 event.Check(m_llist->IsFontUnderlined());
1258 }
1259
1260 void wxLayoutWindow::OnUpdateMenuBold(wxUpdateUIEvent& event)
1261 {
1262 event.Check(m_llist->IsFontBold());
1263 }
1264
1265 void wxLayoutWindow::OnUpdateMenuItalic(wxUpdateUIEvent& event)
1266 {
1267 event.Check(m_llist->IsFontItalic());
1268 }
1269
1270 void wxLayoutWindow::OnMenu(wxCommandEvent& event)
1271 {
1272 switch (event.GetId())
1273 {
1274 case WXLOWIN_MENU_LARGER:
1275 m_llist->SetFontLarger(); RequestUpdate(); break;
1276 case WXLOWIN_MENU_SMALLER:
1277 m_llist->SetFontSmaller(); RequestUpdate(); break;
1278 case WXLOWIN_MENU_UNDERLINE:
1279 m_llist->ToggleFontUnderline(); RequestUpdate(); break;
1280 case WXLOWIN_MENU_BOLD:
1281 m_llist->ToggleFontWeight(); RequestUpdate(); break;
1282 case WXLOWIN_MENU_ITALICS:
1283 m_llist->ToggleFontItalics(); RequestUpdate(); break;
1284 case WXLOWIN_MENU_ROMAN:
1285 m_llist->SetFontFamily(wxROMAN); RequestUpdate(); break;
1286 case WXLOWIN_MENU_TYPEWRITER:
1287 m_llist->SetFontFamily(wxFIXED); RequestUpdate(); break;
1288 case WXLOWIN_MENU_SANSSERIF:
1289 m_llist->SetFontFamily(wxSWISS); RequestUpdate(); break;
1290 }
1291 }
1292
1293 // ----------------------------------------------------------------------------
1294 // focus
1295 // ----------------------------------------------------------------------------
1296
1297 void
1298 wxLayoutWindow::OnSetFocus(wxFocusEvent &ev)
1299 {
1300 m_HaveFocus = true;
1301 ev.Skip();
1302 RequestUpdate(); // cursor must change
1303 }
1304
1305 void
1306 wxLayoutWindow::OnKillFocus(wxFocusEvent &ev)
1307 {
1308 m_HaveFocus = false;
1309 ev.Skip();
1310 RequestUpdate();// cursor must change
1311 }
1312
1313 // ----------------------------------------------------------------------------
1314 // private functions
1315 // ----------------------------------------------------------------------------
1316
1317 static bool IsDirectionKey(long keyCode)
1318 {
1319 switch(keyCode)
1320 {
1321 case WXK_UP:
1322 case WXK_DOWN:
1323 case WXK_RIGHT:
1324 case WXK_LEFT:
1325 case WXK_PRIOR:
1326 case WXK_NEXT:
1327 case WXK_HOME:
1328 case WXK_END:
1329 return true;
1330
1331 default:
1332 return false;
1333 }
1334 }