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