opengl32: Avoid generating a wrapper for internal functions when we can call the...
[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   ME_InternalDeleteText(editor, ME_GetCursorOfs(editor, nCursor), nChars);
370 }
371
372 static ME_DisplayItem *
373 ME_InternalInsertTextFromCursor(ME_TextEditor *editor, int nCursor,
374                                 const WCHAR *str, int len, ME_Style *style,
375                                 int flags)
376 {
377   ME_Cursor *p = &editor->pCursors[nCursor];
378
379   editor->bCaretAtEnd = FALSE;
380   
381   assert(p->pRun->type == diRun);
382   
383   return ME_InsertRunAtCursor(editor, p, style, str, len, flags);
384 }
385
386
387 /* FIXME this is temporary, just to have something to test how bad graphics handler is */
388 void ME_InsertGraphicsFromCursor(ME_TextEditor *editor, int nCursor)
389 {
390   ME_Style *pStyle = ME_GetInsertStyle(editor, nCursor);
391   WCHAR space = ' ';
392   
393   /* FIXME no no no */
394   if (ME_IsSelection(editor))
395     ME_DeleteSelection(editor);
396
397   ME_InternalInsertTextFromCursor(editor, nCursor, &space, 1, pStyle,
398                                   MERF_GRAPHICS);
399   ME_SendSelChange(editor);
400 }
401
402
403 void
404 ME_InsertTableCellFromCursor(ME_TextEditor *editor, int nCursor)
405 {
406   WCHAR tab = '\t';
407   ME_DisplayItem *p, *run;
408   ME_Style *pStyle = ME_GetInsertStyle(editor, nCursor);
409   
410   p = ME_InternalInsertTextFromCursor(editor, nCursor, &tab, 1, pStyle,
411                                       MERF_CELL);
412   run = p;
413   while ((run = ME_FindItemBack(run, diRunOrParagraph))->type == diRun)
414   {
415     if (run->member.run.nFlags & MERF_CELL)
416     {
417       assert(run->member.run.pCell->next);
418       p->member.run.pCell = run->member.run.pCell->next;
419       return;
420     }
421   }
422   assert(run->type == diParagraph);
423   assert(run->member.para.bTable);
424   assert(run->member.para.pCells);
425   p->member.run.pCell = run->member.para.pCells;
426 }
427
428
429 void ME_InsertTextFromCursor(ME_TextEditor *editor, int nCursor, 
430   const WCHAR *str, int len, ME_Style *style)
431 {
432   const WCHAR *pos;
433   ME_Cursor *p = NULL;
434   /* FIXME: is this too slow? */
435   /* Didn't affect performance for WM_SETTEXT (around 50sec/30K) */
436   int freeSpace = editor->nTextLimit - ME_GetTextLength(editor);
437
438   assert(style);
439
440   /* FIXME really HERE ? */
441   if (ME_IsSelection(editor))
442     ME_DeleteSelection(editor);
443
444   assert(nCursor>=0 && nCursor<editor->nCursors);
445   if (len == -1)
446     len = lstrlenW(str);
447   len = min(len, freeSpace);
448   while (len)
449   {
450     pos = str;
451     /* FIXME this sucks - no respect for unicode (what else can be a line separator in unicode?) */
452     while(pos-str < len && *pos != '\r' && *pos != '\n' && *pos != '\t')
453       pos++;
454     if (pos-str < len && *pos == '\t') { /* handle tabs */
455       WCHAR tab = '\t';
456
457       if (pos!=str)
458         ME_InternalInsertTextFromCursor(editor, nCursor, str, pos-str, style, 0);
459     
460       ME_InternalInsertTextFromCursor(editor, nCursor, &tab, 1, style, MERF_TAB);
461  
462       pos++;
463       if(pos-str <= len) {
464         len -= pos - str;
465         str = pos;
466         continue;
467       }
468     }
469     if (pos-str < len) {   /* handle EOLs */
470       ME_DisplayItem *tp, *end_run;
471       ME_Style *tmp_style;
472       if (pos!=str)
473         ME_InternalInsertTextFromCursor(editor, nCursor, str, pos-str, style, 0);
474       p = &editor->pCursors[nCursor];
475       if (p->nOffset) {
476         ME_SplitRunSimple(editor, p->pRun, p->nOffset);
477         p = &editor->pCursors[nCursor];
478       }
479       tmp_style = ME_GetInsertStyle(editor, nCursor);
480       /* ME_SplitParagraph increases style refcount */
481       tp = ME_SplitParagraph(editor, p->pRun, p->pRun->member.run.style);
482       p->pRun = ME_FindItemFwd(tp, diRun);
483       end_run = ME_FindItemBack(tp, diRun);
484       ME_ReleaseStyle(end_run->member.run.style);
485       end_run->member.run.style = tmp_style;
486       p->nOffset = 0;
487       if(pos-str < len && *pos =='\r')
488         pos++;
489       if(pos-str < len && *pos =='\n')
490         pos++;
491       if(pos-str <= len) {
492         len -= pos - str;
493         str = pos;
494         continue;
495       }
496     }
497     ME_InternalInsertTextFromCursor(editor, nCursor, str, len, style, 0);
498     len = 0;
499   }
500 }
501
502
503 static BOOL
504 ME_MoveCursorChars(ME_TextEditor *editor, ME_Cursor *pCursor, int nRelOfs)
505 {
506   ME_DisplayItem *pRun = pCursor->pRun;
507   
508   if (nRelOfs == -1)
509   {
510     if (!pCursor->nOffset)
511     {
512       do {
513         pRun = ME_FindItemBack(pRun, diRunOrParagraph);
514         assert(pRun);
515         switch (pRun->type)
516         {
517           case diRun:
518             break;
519           case diParagraph:
520             if (pRun->member.para.prev_para->type == diTextStart)
521               return FALSE;
522             pRun = ME_FindItemBack(pRun, diRunOrParagraph);
523             /* every paragraph ought to have at least one run */
524             assert(pRun && pRun->type == diRun);
525             assert(pRun->member.run.nFlags & MERF_ENDPARA);
526             break;
527           default:
528             assert(pRun->type != diRun && pRun->type != diParagraph);
529             return FALSE;
530         }
531       } while (RUN_IS_HIDDEN(&pRun->member.run));
532       pCursor->pRun = pRun;
533       if (pRun->member.run.nFlags & MERF_ENDPARA)
534         pCursor->nOffset = 0;
535       else
536         pCursor->nOffset = pRun->member.run.strText->nLen;
537     }
538     
539     if (pCursor->nOffset)
540       pCursor->nOffset = ME_StrRelPos2(pCursor->pRun->member.run.strText, pCursor->nOffset, nRelOfs);
541     return TRUE;
542   }
543   else
544   {
545     if (!(pRun->member.run.nFlags & MERF_ENDPARA))
546     {
547       int new_ofs = ME_StrRelPos2(pRun->member.run.strText, pCursor->nOffset, nRelOfs);
548     
549       if (new_ofs < pRun->member.run.strText->nLen)
550       {
551         pCursor->nOffset = new_ofs;
552         return TRUE;
553       }
554     }
555     do {
556       pRun = ME_FindItemFwd(pRun, diRun);
557     } while (pRun && RUN_IS_HIDDEN(&pRun->member.run));
558     if (pRun)
559     {
560       pCursor->pRun = pRun;
561       pCursor->nOffset = 0;
562       return TRUE;
563     }
564   }
565   return FALSE;
566 }
567
568
569 static BOOL
570 ME_MoveCursorWords(ME_TextEditor *editor, ME_Cursor *cursor, int nRelOfs)
571 {
572   ME_DisplayItem *pRun = cursor->pRun, *pOtherRun;
573   int nOffset = cursor->nOffset;
574   
575   if (nRelOfs == -1)
576   {
577     /* Backward movement */
578     while (TRUE)
579     {
580       nOffset = ME_CallWordBreakProc(editor, pRun->member.run.strText,
581                                      nOffset, WB_MOVEWORDLEFT);
582        if (nOffset)
583         break;
584       pOtherRun = ME_FindItemBack(pRun, diRunOrParagraph);
585       if (pOtherRun->type == diRun)
586       {
587         if (ME_CallWordBreakProc(editor, pOtherRun->member.run.strText,
588                                  pOtherRun->member.run.strText->nLen - 1,
589                                  WB_ISDELIMITER)
590             && !(pRun->member.run.nFlags & MERF_ENDPARA)
591             && !(cursor->pRun == pRun && cursor->nOffset == 0)
592             && !ME_CallWordBreakProc(editor, pRun->member.run.strText, 0,
593                                      WB_ISDELIMITER))
594           break;
595         pRun = pOtherRun;
596         nOffset = pOtherRun->member.run.strText->nLen;
597       }
598       else if (pOtherRun->type == diParagraph)
599       {
600         if (cursor->pRun == pRun && cursor->nOffset == 0)
601         {
602           /* Paragraph breaks are treated as separate words */
603           if (pOtherRun->member.para.prev_para->type == diTextStart)
604             return FALSE;
605           pRun = ME_FindItemBack(pOtherRun, diRunOrParagraph);
606         }
607         break;
608       }
609     }
610   }
611   else
612   {
613     /* Forward movement */
614     BOOL last_delim = FALSE;
615     
616     while (TRUE)
617     {
618       if (last_delim && !ME_CallWordBreakProc(editor, pRun->member.run.strText,
619                                               nOffset, WB_ISDELIMITER))
620         break;
621       nOffset = ME_CallWordBreakProc(editor, pRun->member.run.strText,
622                                      nOffset, WB_MOVEWORDRIGHT);
623       if (nOffset < pRun->member.run.strText->nLen)
624         break;
625       pOtherRun = ME_FindItemFwd(pRun, diRunOrParagraphOrEnd);
626       if (pOtherRun->type == diRun)
627       {
628         last_delim = ME_CallWordBreakProc(editor, pRun->member.run.strText,
629                                           nOffset - 1, WB_ISDELIMITER);
630         pRun = pOtherRun;
631         nOffset = 0;
632       }
633       else if (pOtherRun->type == diParagraph)
634       {
635         if (cursor->pRun == pRun)
636           pRun = ME_FindItemFwd(pOtherRun, diRun);
637         nOffset = 0;
638         break;
639       }
640       else /* diTextEnd */
641       {
642         if (cursor->pRun == pRun)
643           return FALSE;
644         nOffset = 0;
645         break;
646       }
647     }
648   }
649   cursor->pRun = pRun;
650   cursor->nOffset = nOffset;
651   return TRUE;
652 }
653
654
655 void
656 ME_SelectWord(ME_TextEditor *editor)
657 {
658   if (!(editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA))
659     ME_MoveCursorWords(editor, &editor->pCursors[0], -1);
660   ME_MoveCursorWords(editor, &editor->pCursors[1], +1);
661   ME_InvalidateSelection(editor);
662   ME_SendSelChange(editor);
663 }
664
665
666 int ME_GetCursorOfs(ME_TextEditor *editor, int nCursor)
667 {
668   ME_Cursor *pCursor = &editor->pCursors[nCursor];
669   
670   return ME_GetParagraph(pCursor->pRun)->member.para.nCharOfs
671     + pCursor->pRun->member.run.nCharOfs + pCursor->nOffset;
672 }
673
674 int ME_FindPixelPos(ME_TextEditor *editor, int x, int y, ME_Cursor *result, BOOL *is_eol)
675 {
676   ME_DisplayItem *p = editor->pBuffer->pFirst->member.para.next_para;
677   int rx = 0;
678   
679   if (is_eol)
680     *is_eol = 0;
681
682   while(p != editor->pBuffer->pLast)
683   {
684     if (p->type == diParagraph)
685     {
686       int ry = y - p->member.para.nYPos;
687       if (ry < 0)
688       {
689         result->pRun = ME_FindItemFwd(p, diRun);
690         result->nOffset = 0;
691         return 0;
692       }
693       if (ry >= p->member.para.nHeight)
694       {
695         p = p->member.para.next_para;
696         continue;
697       }
698       p = ME_FindItemFwd(p, diStartRow);
699       y = ry;
700       continue;
701     }
702     if (p->type == diStartRow)
703     {
704       int ry = y - p->member.row.nYPos;
705       if (ry < 0)
706         return 0;
707       if (ry >= p->member.row.nHeight)
708       {
709         p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
710         if (p->type != diStartRow)
711           return 0;
712         continue;
713       }
714       p = ME_FindItemFwd(p, diRun);
715       continue;
716     }
717     if (p->type == diRun)
718     {
719       ME_DisplayItem *pp;
720       rx = x - p->member.run.pt.x;
721       if (rx < 0)
722         rx = 0;
723       if (rx >= p->member.run.nWidth) /* not this run yet... find next item */
724       {
725         pp = p;
726         do {
727           p = p->next;
728           if (p->type == diRun)
729           {
730             rx = x - p->member.run.pt.x;
731             goto continue_search;
732           }
733           if (p->type == diStartRow)
734           {
735             p = ME_FindItemFwd(p, diRun);
736             if (is_eol)
737               *is_eol = 1;
738             rx = 0; /* FIXME not sure */
739             goto found_here;
740           }
741           if (p->type == diParagraph || p->type == diTextEnd)
742           {
743             rx = 0; /* FIXME not sure */
744             p = pp;
745             goto found_here;
746           }
747         } while(1);
748         continue;
749       }
750     found_here:
751       if (p->member.run.nFlags & MERF_ENDPARA)
752         rx = 0;
753       result->pRun = p;
754       result->nOffset = ME_CharFromPointCursor(editor, rx, &p->member.run);
755       if (editor->pCursors[0].nOffset == p->member.run.strText->nLen && rx)
756       {
757         result->pRun = ME_FindItemFwd(editor->pCursors[0].pRun, diRun);
758         result->nOffset = 0;
759       }
760       return 1;
761     }
762     assert(0);
763   continue_search:
764     ;
765   }
766   result->pRun = ME_FindItemBack(p, diRun);
767   result->nOffset = 0;
768   assert(result->pRun->member.run.nFlags & MERF_ENDPARA);
769   return 0;
770 }
771
772
773 int
774 ME_CharFromPos(ME_TextEditor *editor, int x, int y)
775 {
776   ME_Cursor cursor;
777   RECT rc;
778
779   GetClientRect(editor->hWnd, &rc);
780   if (x < 0 || y < 0 || x >= rc.right || y >= rc.bottom)
781     return -1;
782   y += ME_GetYScrollPos(editor);
783   ME_FindPixelPos(editor, x, y, &cursor, NULL);
784   return (ME_GetParagraph(cursor.pRun)->member.para.nCharOfs
785           + cursor.pRun->member.run.nCharOfs + cursor.nOffset);
786 }
787
788
789 void ME_LButtonDown(ME_TextEditor *editor, int x, int y)
790 {
791   ME_Cursor tmp_cursor;
792   int is_selection = 0;
793   
794   editor->nUDArrowX = -1;
795   
796   y += ME_GetYScrollPos(editor);
797
798   tmp_cursor = editor->pCursors[0];
799   is_selection = ME_IsSelection(editor);
800
801   ME_FindPixelPos(editor, x, y, &editor->pCursors[0], &editor->bCaretAtEnd);
802   
803   if (GetKeyState(VK_SHIFT)>=0)
804   {
805     editor->pCursors[1] = editor->pCursors[0];
806   }
807   else
808   {
809     if (!is_selection) {
810       editor->pCursors[1] = tmp_cursor;
811       is_selection = 1;
812     }
813   }
814   ME_InvalidateSelection(editor);
815   HideCaret(editor->hWnd);
816   ME_MoveCaret(editor);
817   ShowCaret(editor->hWnd);
818   ME_ClearTempStyle(editor);
819   ME_SendSelChange(editor);
820 }
821
822 void ME_MouseMove(ME_TextEditor *editor, int x, int y)
823 {
824   ME_Cursor tmp_cursor;
825   
826   y += ME_GetYScrollPos(editor);
827
828   tmp_cursor = editor->pCursors[0];
829   /* FIXME: do something with the return value of ME_FindPixelPos */
830   ME_FindPixelPos(editor, x, y, &tmp_cursor, &editor->bCaretAtEnd);
831   
832   if (tmp_cursor.pRun == editor->pCursors[0].pRun && 
833       tmp_cursor.nOffset == editor->pCursors[0].nOffset)
834     return;
835   
836   ME_InvalidateSelection(editor);
837   editor->pCursors[0] = tmp_cursor;
838   HideCaret(editor->hWnd);
839   ME_MoveCaret(editor);
840   ME_InvalidateSelection(editor);
841   ShowCaret(editor->hWnd);
842   ME_SendSelChange(editor);
843 }
844
845 static ME_DisplayItem *ME_FindRunInRow(ME_TextEditor *editor, ME_DisplayItem *pRow, 
846                                 int x, int *pOffset, int *pbCaretAtEnd)
847 {
848   ME_DisplayItem *pNext, *pLastRun;
849   pNext = ME_FindItemFwd(pRow, diRunOrStartRow);
850   assert(pNext->type == diRun);
851   pLastRun = pNext;
852   *pbCaretAtEnd = FALSE;
853   do {
854     int run_x = pNext->member.run.pt.x;
855     int width = pNext->member.run.nWidth;
856     if (x < run_x)
857     {
858       if (pOffset) *pOffset = 0;
859       return pNext;
860     }
861     if (x >= run_x && x < run_x+width)
862     {
863       int ch = ME_CharFromPointCursor(editor, x-run_x, &pNext->member.run);
864       ME_String *s = pNext->member.run.strText;
865       if (ch < s->nLen) {
866         if (pOffset)
867           *pOffset = ch;
868         return pNext;          
869       }
870     }
871     pLastRun = pNext;
872     pNext = ME_FindItemFwd(pNext, diRunOrStartRow);
873   } while(pNext && pNext->type == diRun);
874   
875   if ((pLastRun->member.run.nFlags & MERF_ENDPARA) == 0)
876   {
877     pNext = ME_FindItemFwd(pNext, diRun);
878     if (pbCaretAtEnd) *pbCaretAtEnd = 1;
879     if (pOffset) *pOffset = 0;
880     return pNext;
881   } else {
882     if (pbCaretAtEnd) *pbCaretAtEnd = 0;
883     if (pOffset) *pOffset = 0;
884     return pLastRun;
885   }
886 }
887
888 static int ME_GetXForArrow(ME_TextEditor *editor, ME_Cursor *pCursor)
889 {
890   ME_DisplayItem *pRun = pCursor->pRun;
891   int x;
892
893   if (editor->nUDArrowX != -1)
894     x = editor->nUDArrowX;
895   else {
896     if (editor->bCaretAtEnd)
897     {
898       pRun = ME_FindItemBack(pRun, diRun);
899       assert(pRun);
900       x = pRun->member.run.pt.x + pRun->member.run.nWidth;
901     }
902     else {
903       x = pRun->member.run.pt.x;
904       x += ME_PointFromChar(editor, &pRun->member.run, pCursor->nOffset);
905     }
906     editor->nUDArrowX = x;
907   }
908   return x;
909 }
910
911
912 static void
913 ME_MoveCursorLines(ME_TextEditor *editor, ME_Cursor *pCursor, int nRelOfs)
914 {
915   ME_DisplayItem *pRun = pCursor->pRun;
916   ME_DisplayItem *pItem;
917   int x = ME_GetXForArrow(editor, pCursor);
918
919   if (editor->bCaretAtEnd && !pCursor->nOffset)
920     pRun = ME_FindItemBack(pRun, diRun);
921   if (!pRun)
922     return;
923   if (nRelOfs == -1)
924   {
925     /* start of this row */
926     pItem = ME_FindItemBack(pRun, diStartRow);
927     assert(pItem);
928     /* start of the previous row */
929     pItem = ME_FindItemBack(pItem, diStartRow);
930   }
931   else
932   {
933     /* start of the next row */
934     pItem = ME_FindItemFwd(pRun, diStartRow);
935     /* FIXME If diParagraph is before diStartRow, wrap the next paragraph?
936     */
937   }
938   if (!pItem)
939   {
940     /* row not found - ignore */
941     return;
942   }
943   pCursor->pRun = ME_FindRunInRow(editor, pItem, x, &pCursor->nOffset, &editor->bCaretAtEnd);
944   assert(pCursor->pRun);
945   assert(pCursor->pRun->type == diRun);
946 }
947
948
949 static void ME_ArrowPageUp(ME_TextEditor *editor, ME_Cursor *pCursor)
950 {
951   ME_DisplayItem *pRun = pCursor->pRun;
952   ME_DisplayItem *pLast, *p;
953   int x, y, ys, yd, yp, yprev;
954   ME_Cursor tmp_curs = *pCursor;
955   
956   x = ME_GetXForArrow(editor, pCursor);
957   if (!pCursor->nOffset && editor->bCaretAtEnd)
958     pRun = ME_FindItemBack(pRun, diRun);
959   
960   p = ME_FindItemBack(pRun, diStartRowOrParagraph);
961   assert(p->type == diStartRow);
962   yp = ME_FindItemBack(p, diParagraph)->member.para.nYPos;
963   yprev = ys = y = yp + p->member.row.nYPos;
964   yd = y - editor->sizeWindow.cy;
965   pLast = p;
966   
967   do {
968     p = ME_FindItemBack(p, diStartRowOrParagraph);
969     if (!p)
970       break;
971     if (p->type == diParagraph) { /* crossing paragraphs */
972       if (p->member.para.prev_para == NULL)
973         break;
974       yp = p->member.para.prev_para->member.para.nYPos;
975       continue;
976     }
977     y = yp + p->member.row.nYPos;
978     if (y < yd)
979       break;
980     pLast = p;
981     yprev = y;
982   } while(1);
983   
984   pCursor->pRun = ME_FindRunInRow(editor, pLast, x, &pCursor->nOffset, &editor->bCaretAtEnd);
985   ME_UpdateSelection(editor, &tmp_curs);
986   if (yprev < editor->sizeWindow.cy)
987   {
988     ME_EnsureVisible(editor, ME_FindItemFwd(editor->pBuffer->pFirst, diRun));
989     ME_Repaint(editor);
990   }
991   else 
992   {
993     ME_ScrollUp(editor, ys-yprev);
994   }
995   assert(pCursor->pRun);
996   assert(pCursor->pRun->type == diRun);
997 }
998
999 /* FIXME: in the original RICHEDIT, PageDown always scrolls by the same amount 
1000    of pixels, even if it makes the scroll bar position exceed its normal maximum.
1001    In such a situation, clicking the scrollbar restores its position back to the
1002    normal range (ie. sets it to (doclength-screenheight)). */
1003
1004 static void ME_ArrowPageDown(ME_TextEditor *editor, ME_Cursor *pCursor)
1005 {
1006   ME_DisplayItem *pRun = pCursor->pRun;
1007   ME_DisplayItem *pLast, *p;
1008   int x, y, ys, yd, yp, yprev;
1009   ME_Cursor tmp_curs = *pCursor;
1010   
1011   x = ME_GetXForArrow(editor, pCursor);
1012   if (!pCursor->nOffset && editor->bCaretAtEnd)
1013     pRun = ME_FindItemBack(pRun, diRun);
1014   
1015   p = ME_FindItemBack(pRun, diStartRowOrParagraph);
1016   assert(p->type == diStartRow);
1017   yp = ME_FindItemBack(p, diParagraph)->member.para.nYPos;
1018   yprev = ys = y = yp + p->member.row.nYPos;
1019   yd = y + editor->sizeWindow.cy;
1020   pLast = p;
1021   
1022   do {
1023     p = ME_FindItemFwd(p, diStartRowOrParagraph);
1024     if (!p)
1025       break;
1026     if (p->type == diParagraph) {
1027       yp = p->member.para.nYPos;
1028       continue;
1029     }
1030     y = yp + p->member.row.nYPos;
1031     if (y >= yd)
1032       break;
1033     pLast = p;
1034     yprev = y;
1035   } while(1);
1036   
1037   pCursor->pRun = ME_FindRunInRow(editor, pLast, x, &pCursor->nOffset, &editor->bCaretAtEnd);
1038   ME_UpdateSelection(editor, &tmp_curs);
1039   if (yprev >= editor->nTotalLength-editor->sizeWindow.cy)
1040   {
1041     ME_EnsureVisible(editor, ME_FindItemBack(editor->pBuffer->pLast, diRun));
1042     ME_Repaint(editor);
1043   }
1044   else 
1045   {
1046     ME_ScrollUp(editor,ys-yprev);
1047   }
1048   assert(pCursor->pRun);
1049   assert(pCursor->pRun->type == diRun);
1050 }
1051
1052 static void ME_ArrowHome(ME_TextEditor *editor, ME_Cursor *pCursor)
1053 {
1054   ME_DisplayItem *pRow = ME_FindItemBack(pCursor->pRun, diStartRow);
1055   /* bCaretAtEnd doesn't make sense if the cursor isn't set at the
1056   first character of the next row */
1057   assert(!editor->bCaretAtEnd || !pCursor->nOffset);
1058   ME_WrapMarkedParagraphs(editor);
1059   if (pRow) {
1060     ME_DisplayItem *pRun;
1061     if (editor->bCaretAtEnd && !pCursor->nOffset) {
1062       pRow = ME_FindItemBack(pRow, diStartRow);
1063       if (!pRow)
1064         return;
1065     }
1066     pRun = ME_FindItemFwd(pRow, diRun);
1067     if (pRun) {
1068       pCursor->pRun = pRun;
1069       pCursor->nOffset = 0;
1070     }
1071   }
1072   editor->bCaretAtEnd = FALSE;
1073 }
1074
1075 static void ME_ArrowCtrlHome(ME_TextEditor *editor, ME_Cursor *pCursor)
1076 {
1077   ME_DisplayItem *pRow = ME_FindItemBack(pCursor->pRun, diTextStart);
1078   if (pRow) {
1079     ME_DisplayItem *pRun = ME_FindItemFwd(pRow, diRun);
1080     if (pRun) {
1081       pCursor->pRun = pRun;
1082       pCursor->nOffset = 0;
1083     }
1084   }
1085 }
1086
1087 static void ME_ArrowEnd(ME_TextEditor *editor, ME_Cursor *pCursor)
1088 {
1089   ME_DisplayItem *pRow;
1090   
1091   if (editor->bCaretAtEnd && !pCursor->nOffset)
1092     return;
1093   
1094   pRow = ME_FindItemFwd(pCursor->pRun, diStartRowOrParagraphOrEnd);
1095   assert(pRow);
1096   if (pRow->type == diStartRow) {
1097     /* FIXME WTF was I thinking about here ? */
1098     ME_DisplayItem *pRun = ME_FindItemFwd(pRow, diRun);
1099     assert(pRun);
1100     pCursor->pRun = pRun;
1101     pCursor->nOffset = 0;
1102     editor->bCaretAtEnd = 1;
1103     return;
1104   }
1105   pCursor->pRun = ME_FindItemBack(pRow, diRun);
1106   assert(pCursor->pRun && pCursor->pRun->member.run.nFlags & MERF_ENDPARA);
1107   pCursor->nOffset = 0;
1108   editor->bCaretAtEnd = FALSE;
1109 }
1110       
1111 static void ME_ArrowCtrlEnd(ME_TextEditor *editor, ME_Cursor *pCursor)
1112 {
1113   ME_DisplayItem *p = ME_FindItemFwd(pCursor->pRun, diTextEnd);
1114   assert(p);
1115   p = ME_FindItemBack(p, diRun);
1116   assert(p);
1117   assert(p->member.run.nFlags & MERF_ENDPARA);
1118   pCursor->pRun = p;
1119   pCursor->nOffset = 0;
1120   editor->bCaretAtEnd = FALSE;
1121 }
1122
1123 BOOL ME_IsSelection(ME_TextEditor *editor)
1124 {
1125   return memcmp(&editor->pCursors[0], &editor->pCursors[1], sizeof(ME_Cursor))!=0;
1126 }
1127
1128 static int ME_GetSelCursor(ME_TextEditor *editor, int dir)
1129 {
1130   int cdir = ME_GetCursorOfs(editor, 0) - ME_GetCursorOfs(editor, 1);
1131   
1132   if (cdir*dir>0)
1133     return 0;
1134   else
1135     return 1;
1136 }
1137       
1138 BOOL ME_UpdateSelection(ME_TextEditor *editor, ME_Cursor *pTempCursor)
1139 {
1140   ME_Cursor old_anchor = editor->pCursors[1];
1141   
1142   if (GetKeyState(VK_SHIFT)>=0) /* cancelling selection */
1143   {
1144     /* any selection was present ? if so, it's no more, repaint ! */
1145     editor->pCursors[1] = editor->pCursors[0];
1146     if (memcmp(pTempCursor, &old_anchor, sizeof(ME_Cursor))) {
1147       return TRUE;
1148     }
1149     return FALSE;
1150   }
1151   else
1152   {
1153     if (!memcmp(pTempCursor, &editor->pCursors[1], sizeof(ME_Cursor))) /* starting selection */
1154     {
1155       editor->pCursors[1] = *pTempCursor;
1156       return TRUE;
1157     }
1158   }
1159
1160   ME_Repaint(editor);
1161   return TRUE;
1162 }
1163
1164 void ME_DeleteSelection(ME_TextEditor *editor)
1165 {
1166   int from, to;
1167   ME_GetSelection(editor, &from, &to);
1168   ME_DeleteTextAtCursor(editor, ME_GetSelCursor(editor,-1), to-from);
1169 }
1170
1171 ME_Style *ME_GetSelectionInsertStyle(ME_TextEditor *editor)
1172 {
1173   ME_Style *style;
1174   int from, to;
1175   ME_Cursor c;
1176   
1177   ME_GetSelection(editor, &from, &to);
1178   ME_CursorFromCharOfs(editor, from, &c);
1179   if (from != to) {
1180     style = c.pRun->member.run.style;
1181     ME_AddRefStyle(style); /* ME_GetInsertStyle has already done that */
1182   }
1183   else
1184     style = ME_GetInsertStyle(editor, 0);
1185   return style;
1186 }
1187
1188 void ME_SendSelChange(ME_TextEditor *editor)
1189 {
1190   SELCHANGE sc;
1191
1192   ME_ClearTempStyle(editor);
1193   
1194   if (!(editor->nEventMask & ENM_SELCHANGE))
1195     return;
1196   
1197   sc.nmhdr.hwndFrom = editor->hWnd;
1198   sc.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1199   sc.nmhdr.code = EN_SELCHANGE;
1200   SendMessageW(editor->hWnd, EM_EXGETSEL, 0, (LPARAM)&sc.chrg);
1201   sc.seltyp = SEL_EMPTY;
1202   if (sc.chrg.cpMin != sc.chrg.cpMax)
1203     sc.seltyp |= SEL_TEXT;
1204   if (sc.chrg.cpMin < sc.chrg.cpMax+1) /* wth were RICHEDIT authors thinking ? */
1205     sc.seltyp |= SEL_MULTICHAR;
1206   SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, sc.nmhdr.idFrom, (LPARAM)&sc);
1207 }
1208
1209
1210 BOOL
1211 ME_ArrowKey(ME_TextEditor *editor, int nVKey, BOOL extend, BOOL ctrl)
1212 {
1213   int nCursor = 0;
1214   ME_Cursor *p = &editor->pCursors[nCursor];
1215   ME_Cursor tmp_curs = *p;
1216   BOOL success = FALSE;
1217   
1218   ME_CheckCharOffsets(editor);
1219   editor->nUDArrowX = -1;
1220   switch(nVKey) {
1221     case VK_LEFT:
1222       editor->bCaretAtEnd = 0;
1223       if (ctrl)
1224         success = ME_MoveCursorWords(editor, &tmp_curs, -1);
1225       else
1226         success = ME_MoveCursorChars(editor, &tmp_curs, -1);
1227       break;
1228     case VK_RIGHT:
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_UP:
1236       ME_MoveCursorLines(editor, &tmp_curs, -1);
1237       break;
1238     case VK_DOWN:
1239       ME_MoveCursorLines(editor, &tmp_curs, +1);
1240       break;
1241     case VK_PRIOR:
1242       ME_ArrowPageUp(editor, &tmp_curs);
1243       break;
1244     case VK_NEXT:
1245       ME_ArrowPageDown(editor, &tmp_curs);
1246       break;
1247     case VK_HOME: {
1248       if (ctrl)
1249         ME_ArrowCtrlHome(editor, &tmp_curs);
1250       else
1251         ME_ArrowHome(editor, &tmp_curs);
1252       editor->bCaretAtEnd = 0;
1253       break;
1254     }
1255     case VK_END: 
1256       if (ctrl)
1257         ME_ArrowCtrlEnd(editor, &tmp_curs);
1258       else
1259         ME_ArrowEnd(editor, &tmp_curs);
1260       break;
1261   }
1262   
1263   if (!extend)
1264     editor->pCursors[1] = tmp_curs;
1265   *p = tmp_curs;
1266   
1267   ME_InvalidateSelection(editor);
1268   ME_Repaint(editor);
1269   HideCaret(editor->hWnd);
1270   ME_EnsureVisible(editor, tmp_curs.pRun); 
1271   ME_ShowCaret(editor);
1272   ME_SendSelChange(editor);
1273   return success;
1274 }