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