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