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