mcicda: Exclude unused headers.
[wine] / dlls / riched20 / caret.c
1 /*
2  * RichEdit - Caret and selection functions.
3  *
4  * Copyright 2004 by Krzysztof Foltman
5  * Copyright 2005 by Phil Krylov
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22
23 #include "editor.h"
24
25 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
26
27 static BOOL
28 ME_MoveCursorChars(ME_TextEditor *editor, ME_Cursor *pCursor, int nRelOfs);
29
30
31 void ME_GetSelection(ME_TextEditor *editor, int *from, int *to)
32 {
33   *from = ME_GetCursorOfs(editor, 0);
34   *to =   ME_GetCursorOfs(editor, 1);
35   
36   if (*from > *to)
37   {
38     int tmp = *from;
39     *from = *to;
40     *to = tmp;    
41   }
42 }
43
44 int ME_GetTextLength(ME_TextEditor *editor)
45 {
46   return ME_CharOfsFromRunOfs(editor, ME_FindItemBack(editor->pBuffer->pLast, diRun), 0);   
47 }
48
49
50 int ME_GetTextLengthEx(ME_TextEditor *editor, GETTEXTLENGTHEX *how)
51 {
52   int length;
53   
54   if (how->flags & GTL_PRECISE && how->flags & GTL_CLOSE)
55     return E_INVALIDARG;
56   if (how->flags & GTL_NUMCHARS && how->flags & GTL_NUMBYTES)
57     return E_INVALIDARG;
58   
59   length = ME_GetTextLength(editor);
60   
61   if (how->flags & GTL_USECRLF)
62     length += editor->nParagraphs;
63   
64   if (how->flags & GTL_NUMBYTES)
65   {
66     CPINFO cpinfo;
67     
68     if (how->codepage == 1200)
69       return length * 2;
70     if (how->flags & GTL_PRECISE)
71       FIXME("GTL_PRECISE flag unsupported. Using GTL_CLOSE\n");
72     if (GetCPInfo(how->codepage, &cpinfo))
73       return length * cpinfo.MaxCharSize;
74     ERR("Invalid codepage %u\n", how->codepage);
75     return E_INVALIDARG;
76   }
77   return length; 
78 }
79
80
81 int ME_SetSelection(ME_TextEditor *editor, int from, int to)
82 {
83   int selectionEnd = 0;
84   const int len = ME_GetTextLength(editor);
85
86   /* all negative values are effectively the same */
87   if (from < 0)
88     from = -1;
89   if (to < 0)
90     to = -1;
91
92   /* select all */
93   if (from == 0 && to == -1)
94   {
95     editor->pCursors[1].pRun = ME_FindItemFwd(editor->pBuffer->pFirst, diRun);
96     editor->pCursors[1].nOffset = 0; 
97     editor->pCursors[0].pRun = ME_FindItemBack(editor->pBuffer->pLast, diRun); 
98     editor->pCursors[0].nOffset = 0;
99     ME_InvalidateSelection(editor);
100     ME_ClearTempStyle(editor);
101     return len + 1;
102   }
103
104   /* if both values are equal and also out of bound, that means to */
105   /* put the selection at the end of the text */
106   if ((from == to) && (to < 0 || to > len))
107   {
108     selectionEnd = 1;
109   }
110   else
111   {
112     /* if from is negative and to is positive then selection is */
113     /* deselected and caret moved to end of the current selection */
114     if (from < 0)
115     {
116       int start, end;
117       ME_GetSelection(editor, &start, &end);
118       editor->pCursors[1] = editor->pCursors[0];
119       ME_Repaint(editor);
120       ME_ClearTempStyle(editor);
121       return end;
122     }
123
124     /* adjust to if it's a negative value */
125     if (to < 0)
126       to = len + 1;
127
128     /* flip from and to if they are reversed */
129     if (from>to)
130     {
131       int tmp = from;
132       from = to;
133       to = tmp;
134     }
135
136     /* after fiddling with the values, we find from > len && to > len */
137     if (from > len)
138       selectionEnd = 1;
139     /* special case with to too big */
140     else if (to > len)
141       to = len + 1;
142   }
143
144   if (selectionEnd)
145   {
146     editor->pCursors[1].pRun = editor->pCursors[0].pRun = ME_FindItemBack(editor->pBuffer->pLast, diRun);
147     editor->pCursors[1].nOffset = editor->pCursors[0].nOffset = 0;
148     ME_InvalidateSelection(editor);
149     ME_ClearTempStyle(editor);
150     return len;
151   }
152
153   ME_RunOfsFromCharOfs(editor, from, &editor->pCursors[1].pRun, &editor->pCursors[1].nOffset);
154   ME_RunOfsFromCharOfs(editor, to, &editor->pCursors[0].pRun, &editor->pCursors[0].nOffset);
155   return to;
156 }
157
158
159 void
160 ME_GetCursorCoordinates(ME_TextEditor *editor, ME_Cursor *pCursor,
161                         int *x, int *y, int *height)
162 {
163   ME_DisplayItem *pCursorRun = pCursor->pRun;
164   ME_DisplayItem *pSizeRun = pCursor->pRun;
165
166   assert(!pCursor->nOffset || !editor->bCaretAtEnd);
167   assert(height && x && y);
168   assert(!(ME_GetParagraph(pCursorRun)->member.para.nFlags & MEPF_REWRAP));
169   assert(pCursor->pRun);
170   assert(pCursor->pRun->type == diRun);
171   
172   if (pCursorRun->type == diRun) {
173     ME_DisplayItem *row = ME_FindItemBack(pCursorRun, diStartRowOrParagraph);
174
175     if (row) {
176       HDC hDC = GetDC(editor->hWnd);
177       ME_Context c;
178       ME_DisplayItem *run = pCursorRun;
179       ME_DisplayItem *para = NULL;
180       SIZE sz = {0, 0};
181     
182       ME_InitContext(&c, editor, hDC);
183       
184       if (!pCursor->nOffset && !editor->bCaretAtEnd)
185       {
186         ME_DisplayItem *prev = ME_FindItemBack(pCursorRun, diRunOrStartRow);
187         assert(prev);
188         if (prev->type == diRun)
189           pSizeRun = prev;
190       }
191       assert(row->type == diStartRow); /* paragraph -> run without start row ?*/
192       para = ME_FindItemBack(row, diParagraph);
193       assert(para);
194       assert(para->type == diParagraph);
195       if (editor->bCaretAtEnd && !pCursor->nOffset && 
196           run == ME_FindItemFwd(row, diRun))
197       {
198         ME_DisplayItem *tmp = ME_FindItemBack(row, diRunOrParagraph);
199         assert(tmp);
200         if (tmp->type == diRun)
201         {
202           row = ME_FindItemBack(tmp, diStartRow);
203           pSizeRun = run = tmp;
204           assert(run);
205           assert(run->type == diRun);
206           sz = ME_GetRunSize(&c, &para->member.para, &run->member.run, ME_StrLen(run->member.run.strText));
207         }
208       }
209       if (pCursor->nOffset && !(run->member.run.nFlags & MERF_SKIPPED)) {
210         sz = ME_GetRunSize(&c, &para->member.para, &run->member.run, pCursor->nOffset);
211       }
212
213       *height = pSizeRun->member.run.nAscent + pSizeRun->member.run.nDescent;
214       *x = run->member.run.pt.x + sz.cx;
215       *y = para->member.para.nYPos + row->member.row.nBaseline + pSizeRun->member.run.pt.y - pSizeRun->member.run.nAscent - ME_GetYScrollPos(editor);
216       
217       ME_DestroyContext(&c);
218       ReleaseDC(editor->hWnd, hDC);
219       return;
220     }
221   }
222   *height = 10; /* FIXME use global font */
223   *x = 0;
224   *y = 0;
225 }
226
227
228 void
229 ME_MoveCaret(ME_TextEditor *editor)
230 {
231   int x, y, height;
232
233   ME_WrapMarkedParagraphs(editor);
234   ME_GetCursorCoordinates(editor, &editor->pCursors[0], &x, &y, &height);
235   CreateCaret(editor->hWnd, NULL, 0, height);
236   SetCaretPos(x, y);
237 }
238
239
240 void ME_ShowCaret(ME_TextEditor *ed)
241 {
242   ME_MoveCaret(ed);
243   ShowCaret(ed->hWnd);
244 }
245
246 void ME_HideCaret(ME_TextEditor *ed)
247 {
248   HideCaret(ed->hWnd);
249   DestroyCaret();
250 }
251
252 void ME_InternalDeleteText(ME_TextEditor *editor, int nOfs, 
253   int nChars)
254 {
255   ME_Cursor c;
256   int shift = 0;
257   
258   while(nChars > 0)
259   {
260     ME_Run *run;
261     ME_CursorFromCharOfs(editor, nOfs, &c);
262     run = &c.pRun->member.run;
263     if (run->nFlags & MERF_ENDPARA) {
264       if (!ME_FindItemFwd(c.pRun, diParagraph))
265       {
266         return;
267       }
268       ME_JoinParagraphs(editor, ME_GetParagraph(c.pRun));
269       /* ME_SkipAndPropagateCharOffset(p->pRun, shift); */
270       ME_CheckCharOffsets(editor);
271       nChars--;
272       if (editor->bEmulateVersion10 && nChars)
273         nChars--;
274       continue;
275     }
276     else
277     {
278       ME_Cursor cursor;
279       int nIntendedChars = nChars;
280       int nCharsToDelete = nChars;
281       int i;
282       int loc = c.nOffset;
283       
284       ME_FindItemBack(c.pRun, diParagraph)->member.para.nFlags |= MEPF_REWRAP;
285       
286       cursor = c;
287       ME_StrRelPos(run->strText, loc, &nChars);
288       /* nChars is the number of characters that should be deleted from the
289          FOLLOWING runs (these AFTER cursor.pRun)
290          nCharsToDelete is a number of chars to delete from THIS run */
291       nCharsToDelete -= nChars;
292       shift -= nCharsToDelete;
293       TRACE("Deleting %d (intended %d-remaning %d) chars at %d in '%s' (%d)\n", 
294         nCharsToDelete, nIntendedChars, nChars, c.nOffset, 
295         debugstr_w(run->strText->szData), run->strText->nLen);
296
297       if (!c.nOffset && ME_StrVLen(run->strText) == nCharsToDelete)
298       {
299         /* undo = reinsert whole run */
300         /* nOfs is a character offset (from the start of the document
301            to the current (deleted) run */
302         ME_UndoItem *pUndo = ME_AddUndoItem(editor, diUndoInsertRun, c.pRun);
303         if (pUndo)
304           pUndo->di.member.run.nCharOfs = nOfs;
305       }
306       else
307       {
308         /* undo = reinsert partial run */
309         ME_UndoItem *pUndo = ME_AddUndoItem(editor, diUndoInsertRun, c.pRun);
310         if (pUndo) {
311           ME_DestroyString(pUndo->di.member.run.strText);
312           pUndo->di.member.run.nCharOfs = nOfs;
313           pUndo->di.member.run.strText = ME_MakeStringN(run->strText->szData+c.nOffset, nCharsToDelete);
314         }
315       }
316       TRACE("Post deletion string: %s (%d)\n", debugstr_w(run->strText->szData), run->strText->nLen);
317       TRACE("Shift value: %d\n", shift);
318       ME_StrDeleteV(run->strText, c.nOffset, nCharsToDelete);
319       
320       /* update cursors (including c) */
321       for (i=-1; i<editor->nCursors; i++) {
322         ME_Cursor *pThisCur = editor->pCursors + i; 
323         if (i == -1) pThisCur = &c;
324         if (pThisCur->pRun == cursor.pRun) {
325           if (pThisCur->nOffset > cursor.nOffset) {
326             if (pThisCur->nOffset-cursor.nOffset < nCharsToDelete)
327               pThisCur->nOffset = cursor.nOffset;
328             else
329               pThisCur->nOffset -= nCharsToDelete;
330             assert(pThisCur->nOffset >= 0);
331             assert(pThisCur->nOffset <= ME_StrVLen(run->strText));
332           }
333           if (pThisCur->nOffset == ME_StrVLen(run->strText))
334           {
335             pThisCur->pRun = ME_FindItemFwd(pThisCur->pRun, diRunOrParagraphOrEnd);
336             assert(pThisCur->pRun->type == diRun);
337             pThisCur->nOffset = 0;
338           }
339         }
340       }
341       
342       /* c = updated data now */
343       
344       if (c.pRun == cursor.pRun)
345         ME_SkipAndPropagateCharOffset(c.pRun, shift);
346       else
347         ME_PropagateCharOffset(c.pRun, shift);
348
349       if (!ME_StrVLen(cursor.pRun->member.run.strText))
350       {
351         TRACE("Removing useless run\n");
352         ME_Remove(cursor.pRun);
353         ME_DestroyDisplayItem(cursor.pRun);
354       }
355       
356       shift = 0;
357       /*
358       ME_CheckCharOffsets(editor);
359       */
360       continue;
361     }
362   }
363 }
364
365 void ME_DeleteTextAtCursor(ME_TextEditor *editor, int nCursor, 
366   int nChars)
367 {  
368   assert(nCursor>=0 && nCursor<editor->nCursors);
369   /* text operations set modified state */
370   editor->nModifyStep = 1;
371   ME_InternalDeleteText(editor, ME_GetCursorOfs(editor, nCursor), nChars);
372 }
373
374 static ME_DisplayItem *
375 ME_InternalInsertTextFromCursor(ME_TextEditor *editor, int nCursor,
376                                 const WCHAR *str, int len, ME_Style *style,
377                                 int flags)
378 {
379   ME_Cursor *p = &editor->pCursors[nCursor];
380
381   editor->bCaretAtEnd = FALSE;
382   
383   assert(p->pRun->type == diRun);
384   
385   return ME_InsertRunAtCursor(editor, p, style, str, len, flags);
386 }
387
388
389 /* FIXME this is temporary, just to have something to test how bad graphics handler is */
390 void ME_InsertGraphicsFromCursor(ME_TextEditor *editor, int nCursor)
391 {
392   ME_Style *pStyle = ME_GetInsertStyle(editor, nCursor);
393   WCHAR space = ' ';
394   
395   /* FIXME no no no */
396   if (ME_IsSelection(editor))
397     ME_DeleteSelection(editor);
398
399   ME_InternalInsertTextFromCursor(editor, nCursor, &space, 1, pStyle,
400                                   MERF_GRAPHICS);
401   ME_SendSelChange(editor);
402 }
403
404
405 void
406 ME_InsertTableCellFromCursor(ME_TextEditor *editor, int nCursor)
407 {
408   WCHAR tab = '\t';
409   ME_DisplayItem *p, *run;
410   ME_Style *pStyle = ME_GetInsertStyle(editor, nCursor);
411   
412   p = ME_InternalInsertTextFromCursor(editor, nCursor, &tab, 1, pStyle,
413                                       MERF_CELL);
414   run = p;
415   while ((run = ME_FindItemBack(run, diRunOrParagraph))->type == diRun)
416   {
417     if (run->member.run.nFlags & MERF_CELL)
418     {
419       assert(run->member.run.pCell->next);
420       p->member.run.pCell = run->member.run.pCell->next;
421       return;
422     }
423   }
424   assert(run->type == diParagraph);
425   assert(run->member.para.bTable);
426   assert(run->member.para.pCells);
427   p->member.run.pCell = run->member.para.pCells;
428 }
429
430
431 void ME_InsertTextFromCursor(ME_TextEditor *editor, int nCursor, 
432   const WCHAR *str, int len, ME_Style *style)
433 {
434   const WCHAR *pos;
435   ME_Cursor *p = NULL;
436   int freeSpace;
437
438   /* FIXME really HERE ? */
439   if (ME_IsSelection(editor))
440     ME_DeleteSelection(editor);
441
442   /* FIXME: is this too slow? */
443   /* Didn't affect performance for WM_SETTEXT (around 50sec/30K) */
444   freeSpace = editor->nTextLimit - ME_GetTextLength(editor);
445
446   /* text operations set modified state */
447   editor->nModifyStep = 1;
448
449   assert(style);
450
451   assert(nCursor>=0 && nCursor<editor->nCursors);
452   if (len == -1)
453     len = lstrlenW(str);
454   len = min(len, freeSpace);
455   while (len)
456   {
457     pos = str;
458     /* FIXME this sucks - no respect for unicode (what else can be a line separator in unicode?) */
459     while(pos-str < len && *pos != '\r' && *pos != '\n' && *pos != '\t')
460       pos++;
461     if (pos-str < len && *pos == '\t') { /* handle tabs */
462       WCHAR tab = '\t';
463
464       if (pos!=str)
465         ME_InternalInsertTextFromCursor(editor, nCursor, str, pos-str, style, 0);
466     
467       ME_InternalInsertTextFromCursor(editor, nCursor, &tab, 1, style, MERF_TAB);
468  
469       pos++;
470       if(pos-str <= len) {
471         len -= pos - str;
472         str = pos;
473         continue;
474       }
475     }
476     if (pos-str < len) {   /* handle EOLs */
477       ME_DisplayItem *tp, *end_run;
478       ME_Style *tmp_style;
479       if (pos!=str)
480         ME_InternalInsertTextFromCursor(editor, nCursor, str, pos-str, style, 0);
481       p = &editor->pCursors[nCursor];
482       if (p->nOffset) {
483         ME_SplitRunSimple(editor, p->pRun, p->nOffset);
484         p = &editor->pCursors[nCursor];
485       }
486       tmp_style = ME_GetInsertStyle(editor, nCursor);
487       /* ME_SplitParagraph increases style refcount */
488       tp = ME_SplitParagraph(editor, p->pRun, p->pRun->member.run.style);
489       p->pRun = ME_FindItemFwd(tp, diRun);
490       end_run = ME_FindItemBack(tp, diRun);
491       ME_ReleaseStyle(end_run->member.run.style);
492       end_run->member.run.style = tmp_style;
493       p->nOffset = 0;
494       if(pos-str < len && *pos =='\r')
495         pos++;
496       if(pos-str < len && *pos =='\n')
497         pos++;
498       if(pos-str <= len) {
499         len -= pos - str;
500         str = pos;
501         continue;
502       }
503     }
504     ME_InternalInsertTextFromCursor(editor, nCursor, str, len, style, 0);
505     len = 0;
506   }
507 }
508
509
510 static BOOL
511 ME_MoveCursorChars(ME_TextEditor *editor, ME_Cursor *pCursor, int nRelOfs)
512 {
513   ME_DisplayItem *pRun = pCursor->pRun;
514   
515   if (nRelOfs == -1)
516   {
517     if (!pCursor->nOffset)
518     {
519       do {
520         pRun = ME_FindItemBack(pRun, diRunOrParagraph);
521         assert(pRun);
522         switch (pRun->type)
523         {
524           case diRun:
525             break;
526           case diParagraph:
527             if (pRun->member.para.prev_para->type == diTextStart)
528               return FALSE;
529             pRun = ME_FindItemBack(pRun, diRunOrParagraph);
530             /* every paragraph ought to have at least one run */
531             assert(pRun && pRun->type == diRun);
532             assert(pRun->member.run.nFlags & MERF_ENDPARA);
533             break;
534           default:
535             assert(pRun->type != diRun && pRun->type != diParagraph);
536             return FALSE;
537         }
538       } while (RUN_IS_HIDDEN(&pRun->member.run));
539       pCursor->pRun = pRun;
540       if (pRun->member.run.nFlags & MERF_ENDPARA)
541         pCursor->nOffset = 0;
542       else
543         pCursor->nOffset = pRun->member.run.strText->nLen;
544     }
545     
546     if (pCursor->nOffset)
547       pCursor->nOffset = ME_StrRelPos2(pCursor->pRun->member.run.strText, pCursor->nOffset, nRelOfs);
548     return TRUE;
549   }
550   else
551   {
552     if (!(pRun->member.run.nFlags & MERF_ENDPARA))
553     {
554       int new_ofs = ME_StrRelPos2(pRun->member.run.strText, pCursor->nOffset, nRelOfs);
555     
556       if (new_ofs < pRun->member.run.strText->nLen)
557       {
558         pCursor->nOffset = new_ofs;
559         return TRUE;
560       }
561     }
562     do {
563       pRun = ME_FindItemFwd(pRun, diRun);
564     } while (pRun && RUN_IS_HIDDEN(&pRun->member.run));
565     if (pRun)
566     {
567       pCursor->pRun = pRun;
568       pCursor->nOffset = 0;
569       return TRUE;
570     }
571   }
572   return FALSE;
573 }
574
575
576 static BOOL
577 ME_MoveCursorWords(ME_TextEditor *editor, ME_Cursor *cursor, int nRelOfs)
578 {
579   ME_DisplayItem *pRun = cursor->pRun, *pOtherRun;
580   int nOffset = cursor->nOffset;
581   
582   if (nRelOfs == -1)
583   {
584     /* Backward movement */
585     while (TRUE)
586     {
587       nOffset = ME_CallWordBreakProc(editor, pRun->member.run.strText,
588                                      nOffset, WB_MOVEWORDLEFT);
589        if (nOffset)
590         break;
591       pOtherRun = ME_FindItemBack(pRun, diRunOrParagraph);
592       if (pOtherRun->type == diRun)
593       {
594         if (ME_CallWordBreakProc(editor, pOtherRun->member.run.strText,
595                                  pOtherRun->member.run.strText->nLen - 1,
596                                  WB_ISDELIMITER)
597             && !(pRun->member.run.nFlags & MERF_ENDPARA)
598             && !(cursor->pRun == pRun && cursor->nOffset == 0)
599             && !ME_CallWordBreakProc(editor, pRun->member.run.strText, 0,
600                                      WB_ISDELIMITER))
601           break;
602         pRun = pOtherRun;
603         nOffset = pOtherRun->member.run.strText->nLen;
604       }
605       else if (pOtherRun->type == diParagraph)
606       {
607         if (cursor->pRun == pRun && cursor->nOffset == 0)
608         {
609           /* Paragraph breaks are treated as separate words */
610           if (pOtherRun->member.para.prev_para->type == diTextStart)
611             return FALSE;
612           pRun = ME_FindItemBack(pOtherRun, diRunOrParagraph);
613         }
614         break;
615       }
616     }
617   }
618   else
619   {
620     /* Forward movement */
621     BOOL last_delim = FALSE;
622     
623     while (TRUE)
624     {
625       if (last_delim && !ME_CallWordBreakProc(editor, pRun->member.run.strText,
626                                               nOffset, WB_ISDELIMITER))
627         break;
628       nOffset = ME_CallWordBreakProc(editor, pRun->member.run.strText,
629                                      nOffset, WB_MOVEWORDRIGHT);
630       if (nOffset < pRun->member.run.strText->nLen)
631         break;
632       pOtherRun = ME_FindItemFwd(pRun, diRunOrParagraphOrEnd);
633       if (pOtherRun->type == diRun)
634       {
635         last_delim = ME_CallWordBreakProc(editor, pRun->member.run.strText,
636                                           nOffset - 1, WB_ISDELIMITER);
637         pRun = pOtherRun;
638         nOffset = 0;
639       }
640       else if (pOtherRun->type == diParagraph)
641       {
642         if (cursor->pRun == pRun)
643           pRun = ME_FindItemFwd(pOtherRun, diRun);
644         nOffset = 0;
645         break;
646       }
647       else /* diTextEnd */
648       {
649         if (cursor->pRun == pRun)
650           return FALSE;
651         nOffset = 0;
652         break;
653       }
654     }
655   }
656   cursor->pRun = pRun;
657   cursor->nOffset = nOffset;
658   return TRUE;
659 }
660
661
662 void
663 ME_SelectWord(ME_TextEditor *editor)
664 {
665   if (!(editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA))
666     ME_MoveCursorWords(editor, &editor->pCursors[0], -1);
667   ME_MoveCursorWords(editor, &editor->pCursors[1], +1);
668   ME_InvalidateSelection(editor);
669   ME_SendSelChange(editor);
670 }
671
672
673 int ME_GetCursorOfs(ME_TextEditor *editor, int nCursor)
674 {
675   ME_Cursor *pCursor = &editor->pCursors[nCursor];
676   
677   return ME_GetParagraph(pCursor->pRun)->member.para.nCharOfs
678     + pCursor->pRun->member.run.nCharOfs + pCursor->nOffset;
679 }
680
681 int ME_FindPixelPos(ME_TextEditor *editor, int x, int y, ME_Cursor *result, BOOL *is_eol)
682 {
683   ME_DisplayItem *p = editor->pBuffer->pFirst->member.para.next_para;
684   int rx = 0;
685   
686   if (is_eol)
687     *is_eol = 0;
688
689   while(p != editor->pBuffer->pLast)
690   {
691     if (p->type == diParagraph)
692     {
693       int ry = y - p->member.para.nYPos;
694       if (ry < 0)
695       {
696         result->pRun = ME_FindItemFwd(p, diRun);
697         result->nOffset = 0;
698         return 0;
699       }
700       if (ry >= p->member.para.nHeight)
701       {
702         p = p->member.para.next_para;
703         continue;
704       }
705       p = ME_FindItemFwd(p, diStartRow);
706       y = ry;
707       continue;
708     }
709     if (p->type == diStartRow)
710     {
711       int ry = y - p->member.row.nYPos;
712       if (ry < 0)
713         return 0;
714       if (ry >= p->member.row.nHeight)
715       {
716         p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
717         if (p->type != diStartRow)
718           return 0;
719         continue;
720       }
721       p = ME_FindItemFwd(p, diRun);
722       continue;
723     }
724     if (p->type == diRun)
725     {
726       ME_DisplayItem *pp;
727       rx = x - p->member.run.pt.x;
728       if (rx < 0)
729         rx = 0;
730       if (rx >= p->member.run.nWidth) /* not this run yet... find next item */
731       {
732         pp = p;
733         do {
734           p = p->next;
735           if (p->type == diRun)
736           {
737             rx = x - p->member.run.pt.x;
738             goto continue_search;
739           }
740           if (p->type == diStartRow)
741           {
742             p = ME_FindItemFwd(p, diRun);
743             if (is_eol)
744               *is_eol = 1;
745             rx = 0; /* FIXME not sure */
746             goto found_here;
747           }
748           if (p->type == diParagraph || p->type == diTextEnd)
749           {
750             rx = 0; /* FIXME not sure */
751             p = pp;
752             goto found_here;
753           }
754         } while(1);
755         continue;
756       }
757     found_here:
758       if (p->member.run.nFlags & MERF_ENDPARA)
759         rx = 0;
760       result->pRun = p;
761       result->nOffset = ME_CharFromPointCursor(editor, rx, &p->member.run);
762       if (editor->pCursors[0].nOffset == p->member.run.strText->nLen && rx)
763       {
764         result->pRun = ME_FindItemFwd(editor->pCursors[0].pRun, diRun);
765         result->nOffset = 0;
766       }
767       return 1;
768     }
769     assert(0);
770   continue_search:
771     ;
772   }
773   result->pRun = ME_FindItemBack(p, diRun);
774   result->nOffset = 0;
775   assert(result->pRun->member.run.nFlags & MERF_ENDPARA);
776   return 0;
777 }
778
779
780 int
781 ME_CharFromPos(ME_TextEditor *editor, int x, int y)
782 {
783   ME_Cursor cursor;
784   RECT rc;
785
786   GetClientRect(editor->hWnd, &rc);
787   if (x < 0 || y < 0 || x >= rc.right || y >= rc.bottom)
788     return -1;
789   y += ME_GetYScrollPos(editor);
790   ME_FindPixelPos(editor, x, y, &cursor, NULL);
791   return (ME_GetParagraph(cursor.pRun)->member.para.nCharOfs
792           + cursor.pRun->member.run.nCharOfs + cursor.nOffset);
793 }
794
795
796 void ME_LButtonDown(ME_TextEditor *editor, int x, int y)
797 {
798   ME_Cursor tmp_cursor;
799   int is_selection = 0;
800   
801   editor->nUDArrowX = -1;
802   
803   y += ME_GetYScrollPos(editor);
804
805   tmp_cursor = editor->pCursors[0];
806   is_selection = ME_IsSelection(editor);
807
808   ME_FindPixelPos(editor, x, y, &editor->pCursors[0], &editor->bCaretAtEnd);
809   
810   if (GetKeyState(VK_SHIFT)>=0)
811   {
812     editor->pCursors[1] = editor->pCursors[0];
813   }
814   else
815   {
816     if (!is_selection) {
817       editor->pCursors[1] = tmp_cursor;
818       is_selection = 1;
819     }
820   }
821   ME_InvalidateSelection(editor);
822   HideCaret(editor->hWnd);
823   ME_MoveCaret(editor);
824   ShowCaret(editor->hWnd);
825   ME_ClearTempStyle(editor);
826   ME_SendSelChange(editor);
827 }
828
829 void ME_MouseMove(ME_TextEditor *editor, int x, int y)
830 {
831   ME_Cursor tmp_cursor;
832   
833   y += ME_GetYScrollPos(editor);
834
835   tmp_cursor = editor->pCursors[0];
836   /* FIXME: do something with the return value of ME_FindPixelPos */
837   ME_FindPixelPos(editor, x, y, &tmp_cursor, &editor->bCaretAtEnd);
838   
839   if (tmp_cursor.pRun == editor->pCursors[0].pRun && 
840       tmp_cursor.nOffset == editor->pCursors[0].nOffset)
841     return;
842   
843   ME_InvalidateSelection(editor);
844   editor->pCursors[0] = tmp_cursor;
845   HideCaret(editor->hWnd);
846   ME_MoveCaret(editor);
847   ME_InvalidateSelection(editor);
848   ShowCaret(editor->hWnd);
849   ME_SendSelChange(editor);
850 }
851
852 static ME_DisplayItem *ME_FindRunInRow(ME_TextEditor *editor, ME_DisplayItem *pRow, 
853                                 int x, int *pOffset, int *pbCaretAtEnd)
854 {
855   ME_DisplayItem *pNext, *pLastRun;
856   pNext = ME_FindItemFwd(pRow, diRunOrStartRow);
857   assert(pNext->type == diRun);
858   pLastRun = pNext;
859   *pbCaretAtEnd = FALSE;
860   do {
861     int run_x = pNext->member.run.pt.x;
862     int width = pNext->member.run.nWidth;
863     if (x < run_x)
864     {
865       if (pOffset) *pOffset = 0;
866       return pNext;
867     }
868     if (x >= run_x && x < run_x+width)
869     {
870       int ch = ME_CharFromPointCursor(editor, x-run_x, &pNext->member.run);
871       ME_String *s = pNext->member.run.strText;
872       if (ch < s->nLen) {
873         if (pOffset)
874           *pOffset = ch;
875         return pNext;          
876       }
877     }
878     pLastRun = pNext;
879     pNext = ME_FindItemFwd(pNext, diRunOrStartRow);
880   } while(pNext && pNext->type == diRun);
881   
882   if ((pLastRun->member.run.nFlags & MERF_ENDPARA) == 0)
883   {
884     pNext = ME_FindItemFwd(pNext, diRun);
885     if (pbCaretAtEnd) *pbCaretAtEnd = 1;
886     if (pOffset) *pOffset = 0;
887     return pNext;
888   } else {
889     if (pbCaretAtEnd) *pbCaretAtEnd = 0;
890     if (pOffset) *pOffset = 0;
891     return pLastRun;
892   }
893 }
894
895 static int ME_GetXForArrow(ME_TextEditor *editor, ME_Cursor *pCursor)
896 {
897   ME_DisplayItem *pRun = pCursor->pRun;
898   int x;
899
900   if (editor->nUDArrowX != -1)
901     x = editor->nUDArrowX;
902   else {
903     if (editor->bCaretAtEnd)
904     {
905       pRun = ME_FindItemBack(pRun, diRun);
906       assert(pRun);
907       x = pRun->member.run.pt.x + pRun->member.run.nWidth;
908     }
909     else {
910       x = pRun->member.run.pt.x;
911       x += ME_PointFromChar(editor, &pRun->member.run, pCursor->nOffset);
912     }
913     editor->nUDArrowX = x;
914   }
915   return x;
916 }
917
918
919 static void
920 ME_MoveCursorLines(ME_TextEditor *editor, ME_Cursor *pCursor, int nRelOfs)
921 {
922   ME_DisplayItem *pRun = pCursor->pRun;
923   ME_DisplayItem *pItem;
924   int x = ME_GetXForArrow(editor, pCursor);
925
926   if (editor->bCaretAtEnd && !pCursor->nOffset)
927     pRun = ME_FindItemBack(pRun, diRun);
928   if (!pRun)
929     return;
930   if (nRelOfs == -1)
931   {
932     /* start of this row */
933     pItem = ME_FindItemBack(pRun, diStartRow);
934     assert(pItem);
935     /* start of the previous row */
936     pItem = ME_FindItemBack(pItem, diStartRow);
937   }
938   else
939   {
940     /* start of the next row */
941     pItem = ME_FindItemFwd(pRun, diStartRow);
942     /* FIXME If diParagraph is before diStartRow, wrap the next paragraph?
943     */
944   }
945   if (!pItem)
946   {
947     /* row not found - ignore */
948     return;
949   }
950   pCursor->pRun = ME_FindRunInRow(editor, pItem, x, &pCursor->nOffset, &editor->bCaretAtEnd);
951   assert(pCursor->pRun);
952   assert(pCursor->pRun->type == diRun);
953 }
954
955
956 static void ME_ArrowPageUp(ME_TextEditor *editor, ME_Cursor *pCursor)
957 {
958   ME_DisplayItem *pRun = pCursor->pRun;
959   ME_DisplayItem *pLast, *p;
960   int x, y, ys, yd, yp, yprev;
961   ME_Cursor tmp_curs = *pCursor;
962   
963   x = ME_GetXForArrow(editor, pCursor);
964   if (!pCursor->nOffset && editor->bCaretAtEnd)
965     pRun = ME_FindItemBack(pRun, diRun);
966   
967   p = ME_FindItemBack(pRun, diStartRowOrParagraph);
968   assert(p->type == diStartRow);
969   yp = ME_FindItemBack(p, diParagraph)->member.para.nYPos;
970   yprev = ys = y = yp + p->member.row.nYPos;
971   yd = y - editor->sizeWindow.cy;
972   pLast = p;
973   
974   do {
975     p = ME_FindItemBack(p, diStartRowOrParagraph);
976     if (!p)
977       break;
978     if (p->type == diParagraph) { /* crossing paragraphs */
979       if (p->member.para.prev_para == NULL)
980         break;
981       yp = p->member.para.prev_para->member.para.nYPos;
982       continue;
983     }
984     y = yp + p->member.row.nYPos;
985     if (y < yd)
986       break;
987     pLast = p;
988     yprev = y;
989   } while(1);
990   
991   pCursor->pRun = ME_FindRunInRow(editor, pLast, x, &pCursor->nOffset, &editor->bCaretAtEnd);
992   ME_UpdateSelection(editor, &tmp_curs);
993   if (yprev < editor->sizeWindow.cy)
994   {
995     ME_EnsureVisible(editor, ME_FindItemFwd(editor->pBuffer->pFirst, diRun));
996     ME_Repaint(editor);
997   }
998   else 
999   {
1000     ME_ScrollUp(editor, ys-yprev);
1001   }
1002   assert(pCursor->pRun);
1003   assert(pCursor->pRun->type == diRun);
1004 }
1005
1006 /* FIXME: in the original RICHEDIT, PageDown always scrolls by the same amount 
1007    of pixels, even if it makes the scroll bar position exceed its normal maximum.
1008    In such a situation, clicking the scrollbar restores its position back to the
1009    normal range (ie. sets it to (doclength-screenheight)). */
1010
1011 static void ME_ArrowPageDown(ME_TextEditor *editor, ME_Cursor *pCursor)
1012 {
1013   ME_DisplayItem *pRun = pCursor->pRun;
1014   ME_DisplayItem *pLast, *p;
1015   int x, y, ys, yd, yp, yprev;
1016   ME_Cursor tmp_curs = *pCursor;
1017   
1018   x = ME_GetXForArrow(editor, pCursor);
1019   if (!pCursor->nOffset && editor->bCaretAtEnd)
1020     pRun = ME_FindItemBack(pRun, diRun);
1021   
1022   p = ME_FindItemBack(pRun, diStartRowOrParagraph);
1023   assert(p->type == diStartRow);
1024   yp = ME_FindItemBack(p, diParagraph)->member.para.nYPos;
1025   yprev = ys = y = yp + p->member.row.nYPos;
1026   yd = y + editor->sizeWindow.cy;
1027   pLast = p;
1028   
1029   do {
1030     p = ME_FindItemFwd(p, diStartRowOrParagraph);
1031     if (!p)
1032       break;
1033     if (p->type == diParagraph) {
1034       yp = p->member.para.nYPos;
1035       continue;
1036     }
1037     y = yp + p->member.row.nYPos;
1038     if (y >= yd)
1039       break;
1040     pLast = p;
1041     yprev = y;
1042   } while(1);
1043   
1044   pCursor->pRun = ME_FindRunInRow(editor, pLast, x, &pCursor->nOffset, &editor->bCaretAtEnd);
1045   ME_UpdateSelection(editor, &tmp_curs);
1046   if (yprev >= editor->nTotalLength-editor->sizeWindow.cy)
1047   {
1048     ME_EnsureVisible(editor, ME_FindItemBack(editor->pBuffer->pLast, diRun));
1049     ME_Repaint(editor);
1050   }
1051   else 
1052   {
1053     ME_ScrollUp(editor,ys-yprev);
1054   }
1055   assert(pCursor->pRun);
1056   assert(pCursor->pRun->type == diRun);
1057 }
1058
1059 static void ME_ArrowHome(ME_TextEditor *editor, ME_Cursor *pCursor)
1060 {
1061   ME_DisplayItem *pRow = ME_FindItemBack(pCursor->pRun, diStartRow);
1062   /* bCaretAtEnd doesn't make sense if the cursor isn't set at the
1063   first character of the next row */
1064   assert(!editor->bCaretAtEnd || !pCursor->nOffset);
1065   ME_WrapMarkedParagraphs(editor);
1066   if (pRow) {
1067     ME_DisplayItem *pRun;
1068     if (editor->bCaretAtEnd && !pCursor->nOffset) {
1069       pRow = ME_FindItemBack(pRow, diStartRow);
1070       if (!pRow)
1071         return;
1072     }
1073     pRun = ME_FindItemFwd(pRow, diRun);
1074     if (pRun) {
1075       pCursor->pRun = pRun;
1076       pCursor->nOffset = 0;
1077     }
1078   }
1079   editor->bCaretAtEnd = FALSE;
1080 }
1081
1082 static void ME_ArrowCtrlHome(ME_TextEditor *editor, ME_Cursor *pCursor)
1083 {
1084   ME_DisplayItem *pRow = ME_FindItemBack(pCursor->pRun, diTextStart);
1085   if (pRow) {
1086     ME_DisplayItem *pRun = ME_FindItemFwd(pRow, diRun);
1087     if (pRun) {
1088       pCursor->pRun = pRun;
1089       pCursor->nOffset = 0;
1090     }
1091   }
1092 }
1093
1094 static void ME_ArrowEnd(ME_TextEditor *editor, ME_Cursor *pCursor)
1095 {
1096   ME_DisplayItem *pRow;
1097   
1098   if (editor->bCaretAtEnd && !pCursor->nOffset)
1099     return;
1100   
1101   pRow = ME_FindItemFwd(pCursor->pRun, diStartRowOrParagraphOrEnd);
1102   assert(pRow);
1103   if (pRow->type == diStartRow) {
1104     /* FIXME WTF was I thinking about here ? */
1105     ME_DisplayItem *pRun = ME_FindItemFwd(pRow, diRun);
1106     assert(pRun);
1107     pCursor->pRun = pRun;
1108     pCursor->nOffset = 0;
1109     editor->bCaretAtEnd = 1;
1110     return;
1111   }
1112   pCursor->pRun = ME_FindItemBack(pRow, diRun);
1113   assert(pCursor->pRun && pCursor->pRun->member.run.nFlags & MERF_ENDPARA);
1114   pCursor->nOffset = 0;
1115   editor->bCaretAtEnd = FALSE;
1116 }
1117       
1118 static void ME_ArrowCtrlEnd(ME_TextEditor *editor, ME_Cursor *pCursor)
1119 {
1120   ME_DisplayItem *p = ME_FindItemFwd(pCursor->pRun, diTextEnd);
1121   assert(p);
1122   p = ME_FindItemBack(p, diRun);
1123   assert(p);
1124   assert(p->member.run.nFlags & MERF_ENDPARA);
1125   pCursor->pRun = p;
1126   pCursor->nOffset = 0;
1127   editor->bCaretAtEnd = FALSE;
1128 }
1129
1130 BOOL ME_IsSelection(ME_TextEditor *editor)
1131 {
1132   return memcmp(&editor->pCursors[0], &editor->pCursors[1], sizeof(ME_Cursor))!=0;
1133 }
1134
1135 static int ME_GetSelCursor(ME_TextEditor *editor, int dir)
1136 {
1137   int cdir = ME_GetCursorOfs(editor, 0) - ME_GetCursorOfs(editor, 1);
1138   
1139   if (cdir*dir>0)
1140     return 0;
1141   else
1142     return 1;
1143 }
1144       
1145 BOOL ME_UpdateSelection(ME_TextEditor *editor, ME_Cursor *pTempCursor)
1146 {
1147   ME_Cursor old_anchor = editor->pCursors[1];
1148   
1149   if (GetKeyState(VK_SHIFT)>=0) /* cancelling selection */
1150   {
1151     /* any selection was present ? if so, it's no more, repaint ! */
1152     editor->pCursors[1] = editor->pCursors[0];
1153     if (memcmp(pTempCursor, &old_anchor, sizeof(ME_Cursor))) {
1154       return TRUE;
1155     }
1156     return FALSE;
1157   }
1158   else
1159   {
1160     if (!memcmp(pTempCursor, &editor->pCursors[1], sizeof(ME_Cursor))) /* starting selection */
1161     {
1162       editor->pCursors[1] = *pTempCursor;
1163       return TRUE;
1164     }
1165   }
1166
1167   ME_Repaint(editor);
1168   return TRUE;
1169 }
1170
1171 void ME_DeleteSelection(ME_TextEditor *editor)
1172 {
1173   int from, to;
1174   ME_GetSelection(editor, &from, &to);
1175   ME_DeleteTextAtCursor(editor, ME_GetSelCursor(editor,-1), to-from);
1176 }
1177
1178 ME_Style *ME_GetSelectionInsertStyle(ME_TextEditor *editor)
1179 {
1180   ME_Style *style;
1181   int from, to;
1182   ME_Cursor c;
1183   
1184   ME_GetSelection(editor, &from, &to);
1185   ME_CursorFromCharOfs(editor, from, &c);
1186   if (from != to) {
1187     style = c.pRun->member.run.style;
1188     ME_AddRefStyle(style); /* ME_GetInsertStyle has already done that */
1189   }
1190   else
1191     style = ME_GetInsertStyle(editor, 0);
1192   return style;
1193 }
1194
1195 void ME_SendSelChange(ME_TextEditor *editor)
1196 {
1197   SELCHANGE sc;
1198
1199   ME_ClearTempStyle(editor);
1200   
1201   if (!(editor->nEventMask & ENM_SELCHANGE))
1202     return;
1203   
1204   sc.nmhdr.hwndFrom = editor->hWnd;
1205   sc.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1206   sc.nmhdr.code = EN_SELCHANGE;
1207   SendMessageW(editor->hWnd, EM_EXGETSEL, 0, (LPARAM)&sc.chrg);
1208   sc.seltyp = SEL_EMPTY;
1209   if (sc.chrg.cpMin != sc.chrg.cpMax)
1210     sc.seltyp |= SEL_TEXT;
1211   if (sc.chrg.cpMin < sc.chrg.cpMax+1) /* wth were RICHEDIT authors thinking ? */
1212     sc.seltyp |= SEL_MULTICHAR;
1213   SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, sc.nmhdr.idFrom, (LPARAM)&sc);
1214 }
1215
1216
1217 BOOL
1218 ME_ArrowKey(ME_TextEditor *editor, int nVKey, BOOL extend, BOOL ctrl)
1219 {
1220   int nCursor = 0;
1221   ME_Cursor *p = &editor->pCursors[nCursor];
1222   ME_Cursor tmp_curs = *p;
1223   BOOL success = FALSE;
1224   
1225   ME_CheckCharOffsets(editor);
1226   editor->nUDArrowX = -1;
1227   switch(nVKey) {
1228     case VK_LEFT:
1229       editor->bCaretAtEnd = 0;
1230       if (ctrl)
1231         success = ME_MoveCursorWords(editor, &tmp_curs, -1);
1232       else
1233         success = ME_MoveCursorChars(editor, &tmp_curs, -1);
1234       break;
1235     case VK_RIGHT:
1236       editor->bCaretAtEnd = 0;
1237       if (ctrl)
1238         success = ME_MoveCursorWords(editor, &tmp_curs, +1);
1239       else
1240         success = ME_MoveCursorChars(editor, &tmp_curs, +1);
1241       break;
1242     case VK_UP:
1243       ME_MoveCursorLines(editor, &tmp_curs, -1);
1244       break;
1245     case VK_DOWN:
1246       ME_MoveCursorLines(editor, &tmp_curs, +1);
1247       break;
1248     case VK_PRIOR:
1249       ME_ArrowPageUp(editor, &tmp_curs);
1250       break;
1251     case VK_NEXT:
1252       ME_ArrowPageDown(editor, &tmp_curs);
1253       break;
1254     case VK_HOME: {
1255       if (ctrl)
1256         ME_ArrowCtrlHome(editor, &tmp_curs);
1257       else
1258         ME_ArrowHome(editor, &tmp_curs);
1259       editor->bCaretAtEnd = 0;
1260       break;
1261     }
1262     case VK_END: 
1263       if (ctrl)
1264         ME_ArrowCtrlEnd(editor, &tmp_curs);
1265       else
1266         ME_ArrowEnd(editor, &tmp_curs);
1267       break;
1268   }
1269   
1270   if (!extend)
1271     editor->pCursors[1] = tmp_curs;
1272   *p = tmp_curs;
1273   
1274   ME_InvalidateSelection(editor);
1275   ME_Repaint(editor);
1276   HideCaret(editor->hWnd);
1277   ME_EnsureVisible(editor, tmp_curs.pRun); 
1278   ME_ShowCaret(editor);
1279   ME_SendSelChange(editor);
1280   return success;
1281 }