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