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