xref: /reactos/base/applications/wordpad/wordpad.c (revision 3dcae2ce)
1 /*
2  * Wordpad implementation
3  *
4  * Copyright 2004 by Krzysztof Foltman
5  * Copyright 2007-2008 by Alexander N. Sørnes <alex@thehandofagony.com>
6  * Copyright 2020 Katayama Hirofumi MZ <katayama.hirofumi.mz@gmail.com>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22 
23 #define WIN32_LEAN_AND_MEAN
24 
25 #include <stdio.h>
26 #include <assert.h>
27 #include <windef.h>
28 #include <winbase.h>
29 #include <wingdi.h>
30 #include <winuser.h>
31 #include <richedit.h>
32 #include <commctrl.h>
33 #include <commdlg.h>
34 #include <shellapi.h>
35 #include <shlobj.h>
36 #include <wine/unicode.h>
37 
38 #include "wordpad.h"
39 
40 #ifdef NONAMELESSUNION
41 # define U(x)  (x).u
42 # define U2(x) (x).u2
43 # define U3(x) (x).u3
44 #else
45 # define U(x)  (x)
46 # define U2(x) (x)
47 # define U3(x) (x)
48 #endif
49 
50 /* use LoadString */
51 static const WCHAR wszAppTitle[] = {'W','o','r','d','p','a','d',0};
52 
53 static const WCHAR wszMainWndClass[] = {'W','O','R','D','P','A','D','T','O','P',0};
54 
55 static const WCHAR stringFormat[] = {'%','2','d','\0'};
56 
57 const WCHAR wszPreviewWndClass[] = {'P','r','t','P','r','e','v','i','e','w',0};
58 LRESULT CALLBACK preview_proc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
59 
60 static HWND hMainWnd;
61 static HWND hEditorWnd;
62 static HWND hFindWnd;
63 static HMENU hColorPopupMenu;
64 
65 static UINT ID_FINDMSGSTRING;
66 
67 static DWORD wordWrap[2];
68 static DWORD barState[2];
69 static WPARAM fileFormat = SF_RTF;
70 
71 static WCHAR wszFileName[MAX_PATH];
72 static WCHAR wszFilter[MAX_STRING_LEN*4+6*3+5];
73 static WCHAR wszDefaultFileName[MAX_STRING_LEN];
74 static WCHAR wszSaveChanges[MAX_STRING_LEN];
75 static WCHAR units_cmW[MAX_STRING_LEN];
76 static WCHAR units_inW[MAX_STRING_LEN];
77 static WCHAR units_inchW[MAX_STRING_LEN];
78 static WCHAR units_ptW[MAX_STRING_LEN];
79 
80 static LRESULT OnSize( HWND hWnd, WPARAM wParam, LPARAM lParam );
81 
82 typedef enum
83 {
84     UNIT_CM,
85     UNIT_INCH,
86     UNIT_PT
87 } UNIT;
88 
89 typedef struct
90 {
91     int endPos;
92     BOOL wrapped;
93     WCHAR findBuffer[128];
94 } FINDREPLACE_custom;
95 
96 /* Load string resources */
97 static void DoLoadStrings(void)
98 {
99     LPWSTR p = wszFilter;
100     static const WCHAR files_rtf[] = {'*','.','r','t','f','\0'};
101     static const WCHAR files_txt[] = {'*','.','t','x','t','\0'};
102     static const WCHAR files_all[] = {'*','.','*','\0'};
103 
104     HINSTANCE hInstance = GetModuleHandleW(0);
105 
106     LoadStringW(hInstance, STRING_RICHTEXT_FILES_RTF, p, MAX_STRING_LEN);
107     p += lstrlenW(p) + 1;
108     lstrcpyW(p, files_rtf);
109     p += lstrlenW(p) + 1;
110     LoadStringW(hInstance, STRING_TEXT_FILES_TXT, p, MAX_STRING_LEN);
111     p += lstrlenW(p) + 1;
112     lstrcpyW(p, files_txt);
113     p += lstrlenW(p) + 1;
114     LoadStringW(hInstance, STRING_TEXT_FILES_UNICODE_TXT, p, MAX_STRING_LEN);
115     p += lstrlenW(p) + 1;
116     lstrcpyW(p, files_txt);
117     p += lstrlenW(p) + 1;
118     LoadStringW(hInstance, STRING_ALL_FILES, p, MAX_STRING_LEN);
119     p += lstrlenW(p) + 1;
120     lstrcpyW(p, files_all);
121     p += lstrlenW(p) + 1;
122     *p = '\0';
123 
124     p = wszDefaultFileName;
125     LoadStringW(hInstance, STRING_DEFAULT_FILENAME, p, MAX_STRING_LEN);
126 
127     p = wszSaveChanges;
128     LoadStringW(hInstance, STRING_PROMPT_SAVE_CHANGES, p, MAX_STRING_LEN);
129 
130     LoadStringW(hInstance, STRING_UNITS_CM, units_cmW, MAX_STRING_LEN);
131     LoadStringW(hInstance, STRING_UNITS_IN, units_inW, MAX_STRING_LEN);
132     LoadStringW(hInstance, STRING_UNITS_INCH, units_inchW, MAX_STRING_LEN);
133     LoadStringW(hInstance, STRING_UNITS_PT, units_ptW, MAX_STRING_LEN);
134 }
135 
136 /* Show a message box with resource strings */
137 static int MessageBoxWithResStringW(HWND hWnd, LPCWSTR lpText, LPCWSTR lpCaption, UINT uType)
138 {
139     MSGBOXPARAMSW params;
140 
141     params.cbSize             = sizeof(params);
142     params.hwndOwner          = hWnd;
143     params.hInstance          = GetModuleHandleW(0);
144     params.lpszText           = lpText;
145     params.lpszCaption        = lpCaption;
146     params.dwStyle            = uType;
147     params.lpszIcon           = NULL;
148     params.dwContextHelpId    = 0;
149     params.lpfnMsgBoxCallback = NULL;
150     params.dwLanguageId       = 0;
151     return MessageBoxIndirectW(&params);
152 }
153 
154 
155 static void AddButton(HWND hwndToolBar, int nImage, int nCommand)
156 {
157     TBBUTTON button;
158 
159     ZeroMemory(&button, sizeof(button));
160     button.iBitmap = nImage;
161     button.idCommand = nCommand;
162     button.fsState = TBSTATE_ENABLED;
163     button.fsStyle = BTNS_BUTTON;
164     button.dwData = 0;
165     button.iString = -1;
166     SendMessageW(hwndToolBar, TB_ADDBUTTONSW, 1, (LPARAM)&button);
167 }
168 
169 static void AddSeparator(HWND hwndToolBar)
170 {
171     TBBUTTON button;
172 
173     ZeroMemory(&button, sizeof(button));
174     button.iBitmap = -1;
175     button.idCommand = 0;
176     button.fsState = 0;
177     button.fsStyle = BTNS_SEP;
178     button.dwData = 0;
179     button.iString = -1;
180     SendMessageW(hwndToolBar, TB_ADDBUTTONSW, 1, (LPARAM)&button);
181 }
182 
183 static DWORD CALLBACK stream_in(DWORD_PTR cookie, LPBYTE buffer, LONG cb, LONG *pcb)
184 {
185     HANDLE hFile = (HANDLE)cookie;
186     DWORD read;
187 
188     if(!ReadFile(hFile, buffer, cb, &read, 0))
189         return 1;
190 
191     *pcb = read;
192 
193     return 0;
194 }
195 
196 static DWORD CALLBACK stream_out(DWORD_PTR cookie, LPBYTE buffer, LONG cb, LONG *pcb)
197 {
198     DWORD written;
199     int ret;
200     HANDLE hFile = (HANDLE)cookie;
201 
202     ret = WriteFile(hFile, buffer, cb, &written, 0);
203 
204     if(!ret || (cb != written))
205         return 1;
206 
207     *pcb = cb;
208 
209     return 0;
210 }
211 
212 LPWSTR file_basename(LPWSTR path)
213 {
214     LPWSTR pos = path + lstrlenW(path);
215 
216     while(pos > path)
217     {
218         if(*pos == '\\' || *pos == '/')
219         {
220             pos++;
221             break;
222         }
223         pos--;
224     }
225     return pos;
226 }
227 
228 static void set_caption(LPCWSTR wszNewFileName)
229 {
230     static const WCHAR wszSeparator[] = {' ','-',' '};
231     WCHAR *wszCaption;
232     SIZE_T length = 0;
233 
234     if(!wszNewFileName)
235         wszNewFileName = wszDefaultFileName;
236     else
237         wszNewFileName = file_basename((LPWSTR)wszNewFileName);
238 
239     wszCaption = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
240                 lstrlenW(wszNewFileName)*sizeof(WCHAR)+sizeof(wszSeparator)+sizeof(wszAppTitle));
241 
242     if(!wszCaption)
243         return;
244 
245     memcpy(wszCaption, wszNewFileName, lstrlenW(wszNewFileName)*sizeof(WCHAR));
246     length += lstrlenW(wszNewFileName);
247     memcpy(wszCaption + length, wszSeparator, sizeof(wszSeparator));
248     length += sizeof(wszSeparator) / sizeof(WCHAR);
249     memcpy(wszCaption + length, wszAppTitle, sizeof(wszAppTitle));
250 
251     SetWindowTextW(hMainWnd, wszCaption);
252 
253     HeapFree(GetProcessHeap(), 0, wszCaption);
254 }
255 
256 static BOOL validate_endptr(LPCWSTR endptr, UNIT *punit)
257 {
258     if(punit != NULL)
259         *punit = UNIT_CM;
260     if(!endptr)
261         return FALSE;
262     if(!*endptr)
263         return TRUE;
264 
265     while(*endptr == ' ')
266         endptr++;
267 
268     if(punit == NULL)
269         return *endptr == '\0';
270 
271     if(!lstrcmpW(endptr, units_cmW))
272     {
273         *punit = UNIT_CM;
274         endptr += lstrlenW(units_cmW);
275     }
276     else if (!lstrcmpW(endptr, units_inW))
277     {
278         *punit = UNIT_INCH;
279         endptr += lstrlenW(units_inW);
280     }
281     else if (!lstrcmpW(endptr, units_inchW))
282     {
283         *punit = UNIT_INCH;
284         endptr += lstrlenW(units_inchW);
285     }
286     else if (!lstrcmpW(endptr, units_ptW))
287     {
288         *punit = UNIT_PT;
289         endptr += lstrlenW(units_ptW);
290     }
291 
292     return *endptr == '\0';
293 }
294 
295 static BOOL number_from_string(LPCWSTR string, float *num, UNIT *punit)
296 {
297     double ret;
298     WCHAR *endptr;
299 
300     *num = 0;
301     errno = 0;
302     ret = wcstod(string, &endptr);
303 
304     if (punit != NULL)
305         *punit = UNIT_CM;
306     if((ret == 0 && errno != 0) || endptr == string || !validate_endptr(endptr, punit))
307     {
308         return FALSE;
309     } else
310     {
311         *num = (float)ret;
312         return TRUE;
313     }
314 }
315 
316 static void set_size(float size)
317 {
318     CHARFORMAT2W fmt;
319 
320     ZeroMemory(&fmt, sizeof(fmt));
321     fmt.cbSize = sizeof(fmt);
322     fmt.dwMask = CFM_SIZE;
323     fmt.yHeight = (int)(size * 20.0);
324     SendMessageW(hEditorWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
325 }
326 
327 static void on_sizelist_modified(HWND hwndSizeList, LPWSTR wszNewFontSize)
328 {
329     WCHAR sizeBuffer[MAX_STRING_LEN];
330     CHARFORMAT2W format;
331 
332     ZeroMemory(&format, sizeof(format));
333     format.cbSize = sizeof(format);
334     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
335 
336     wsprintfW(sizeBuffer, stringFormat, format.yHeight / 20);
337     if(lstrcmpW(sizeBuffer, wszNewFontSize))
338     {
339         float size = 0;
340         if(number_from_string(wszNewFontSize, &size, NULL)
341            && size > 0)
342         {
343             set_size(size);
344         } else
345         {
346             SetWindowTextW(hwndSizeList, sizeBuffer);
347             MessageBoxWithResStringW(hMainWnd, MAKEINTRESOURCEW(STRING_INVALID_NUMBER),
348                         wszAppTitle, MB_OK | MB_ICONINFORMATION);
349         }
350     }
351 }
352 
353 static void add_size(HWND hSizeListWnd, unsigned size)
354 {
355     WCHAR buffer[3];
356     COMBOBOXEXITEMW cbItem;
357     cbItem.mask = CBEIF_TEXT;
358     cbItem.iItem = -1;
359 
360     wsprintfW(buffer, stringFormat, size);
361     cbItem.pszText = buffer;
362     SendMessageW(hSizeListWnd, CBEM_INSERTITEMW, 0, (LPARAM)&cbItem);
363 }
364 
365 static void populate_size_list(HWND hSizeListWnd)
366 {
367     HWND hReBarWnd = GetDlgItem(hMainWnd, IDC_REBAR);
368     HWND hFontListWnd = GetDlgItem(hReBarWnd, IDC_FONTLIST);
369     COMBOBOXEXITEMW cbFontItem;
370     CHARFORMAT2W fmt;
371     HWND hListEditWnd = (HWND)SendMessageW(hSizeListWnd, CBEM_GETEDITCONTROL, 0, 0);
372     HDC hdc = GetDC(hMainWnd);
373     static const unsigned choices[] = {8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72};
374     WCHAR buffer[3];
375     size_t i;
376     DWORD fontStyle;
377 
378     ZeroMemory(&fmt, sizeof(fmt));
379     fmt.cbSize = sizeof(fmt);
380     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
381 
382     cbFontItem.mask = CBEIF_LPARAM;
383     cbFontItem.iItem = SendMessageW(hFontListWnd, CB_FINDSTRINGEXACT, -1, (LPARAM)fmt.szFaceName);
384     SendMessageW(hFontListWnd, CBEM_GETITEMW, 0, (LPARAM)&cbFontItem);
385 
386     fontStyle = (DWORD)LOWORD(cbFontItem.lParam);
387 
388     SendMessageW(hSizeListWnd, CB_RESETCONTENT, 0, 0);
389 
390     if((fontStyle & RASTER_FONTTYPE) && cbFontItem.iItem)
391     {
392         add_size(hSizeListWnd, (BYTE)MulDiv(HIWORD(cbFontItem.lParam), 72,
393                                GetDeviceCaps(hdc, LOGPIXELSY)));
394     } else
395     {
396         for(i = 0; i < sizeof(choices)/sizeof(choices[0]); i++)
397             add_size(hSizeListWnd, choices[i]);
398     }
399 
400     wsprintfW(buffer, stringFormat, fmt.yHeight / 20);
401     SendMessageW(hListEditWnd, WM_SETTEXT, 0, (LPARAM)buffer);
402 }
403 
404 static void update_size_list(void)
405 {
406     HWND hReBar = GetDlgItem(hMainWnd, IDC_REBAR);
407     HWND hwndSizeList = GetDlgItem(hReBar, IDC_SIZELIST);
408     HWND hwndSizeListEdit = (HWND)SendMessageW(hwndSizeList, CBEM_GETEDITCONTROL, 0, 0);
409     WCHAR fontSize[MAX_STRING_LEN], sizeBuffer[MAX_STRING_LEN];
410     CHARFORMAT2W fmt;
411 
412     ZeroMemory(&fmt, sizeof(fmt));
413     fmt.cbSize = sizeof(fmt);
414 
415     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
416 
417     SendMessageW(hwndSizeListEdit, WM_GETTEXT, MAX_PATH, (LPARAM)fontSize);
418     wsprintfW(sizeBuffer, stringFormat, fmt.yHeight / 20);
419 
420     if(lstrcmpW(fontSize, sizeBuffer))
421         SendMessageW(hwndSizeListEdit, WM_SETTEXT, 0, (LPARAM)sizeBuffer);
422 }
423 
424 static void update_font_list(void)
425 {
426     HWND hReBar = GetDlgItem(hMainWnd, IDC_REBAR);
427     HWND hFontList = GetDlgItem(hReBar, IDC_FONTLIST);
428     HWND hFontListEdit = (HWND)SendMessageW(hFontList, CBEM_GETEDITCONTROL, 0, 0);
429     WCHAR fontName[MAX_STRING_LEN];
430     CHARFORMAT2W fmt;
431 
432     ZeroMemory(&fmt, sizeof(fmt));
433     fmt.cbSize = sizeof(fmt);
434 
435     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
436     if (!SendMessageW(hFontListEdit, WM_GETTEXT, MAX_PATH, (LPARAM)fontName)) return;
437 
438     if(lstrcmpW(fontName, fmt.szFaceName))
439     {
440         SendMessageW(hFontListEdit, WM_SETTEXT, 0, (LPARAM)fmt.szFaceName);
441         populate_size_list(GetDlgItem(hReBar, IDC_SIZELIST));
442     } else
443     {
444         update_size_list();
445     }
446 }
447 
448 static void clear_formatting(void)
449 {
450     PARAFORMAT2 pf;
451 
452     pf.cbSize = sizeof(pf);
453     pf.dwMask = PFM_ALIGNMENT;
454     pf.wAlignment = PFA_LEFT;
455     SendMessageW(hEditorWnd, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
456 }
457 
458 static int fileformat_number(WPARAM format)
459 {
460     int number = 0;
461 
462     if(format == SF_TEXT)
463     {
464         number = 1;
465     } else if (format == (SF_TEXT | SF_UNICODE))
466     {
467         number = 2;
468     }
469     return number;
470 }
471 
472 static WPARAM fileformat_flags(int format)
473 {
474     WPARAM flags[] = { SF_RTF , SF_TEXT , SF_TEXT | SF_UNICODE };
475 
476     return flags[format];
477 }
478 
479 static void set_font(LPCWSTR wszFaceName)
480 {
481     HWND hReBarWnd = GetDlgItem(hMainWnd, IDC_REBAR);
482     HWND hSizeListWnd = GetDlgItem(hReBarWnd, IDC_SIZELIST);
483     HWND hFontListWnd = GetDlgItem(hReBarWnd, IDC_FONTLIST);
484     HWND hFontListEditWnd = (HWND)SendMessageW(hFontListWnd, CBEM_GETEDITCONTROL, 0, 0);
485     CHARFORMAT2W fmt;
486 
487     ZeroMemory(&fmt, sizeof(fmt));
488 
489     fmt.cbSize = sizeof(fmt);
490     fmt.dwMask = CFM_FACE;
491 
492     lstrcpyW(fmt.szFaceName, wszFaceName);
493 
494     SendMessageW(hEditorWnd, EM_SETCHARFORMAT,  SCF_SELECTION, (LPARAM)&fmt);
495 
496     populate_size_list(hSizeListWnd);
497 
498     SendMessageW(hFontListEditWnd, WM_SETTEXT, 0, (LPARAM)wszFaceName);
499 }
500 
501 static void set_default_font(void)
502 {
503     static const WCHAR richTextFont[] = {'T','i','m','e','s',' ','N','e','w',' ',
504                                          'R','o','m','a','n',0};
505     static const WCHAR plainTextFont[] = {'C','o','u','r','i','e','r',' ','N','e','w',0};
506     CHARFORMAT2W fmt;
507     LPCWSTR font;
508 
509     ZeroMemory(&fmt, sizeof(fmt));
510 
511     fmt.cbSize = sizeof(fmt);
512     fmt.dwMask = CFM_FACE | CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE;
513     fmt.dwEffects = 0;
514 
515     if(fileFormat & SF_RTF)
516         font = richTextFont;
517     else
518         font = plainTextFont;
519 
520     lstrcpyW(fmt.szFaceName, font);
521 
522     SendMessageW(hEditorWnd, EM_SETCHARFORMAT,  SCF_DEFAULT, (LPARAM)&fmt);
523 }
524 
525 static void on_fontlist_modified(LPWSTR wszNewFaceName)
526 {
527     CHARFORMAT2W format;
528     ZeroMemory(&format, sizeof(format));
529     format.cbSize = sizeof(format);
530     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
531 
532     if(lstrcmpW(format.szFaceName, wszNewFaceName))
533         set_font(wszNewFaceName);
534 }
535 
536 static void add_font(LPCWSTR fontName, DWORD fontType, HWND hListWnd, const NEWTEXTMETRICEXW *ntmc)
537 {
538     COMBOBOXEXITEMW cbItem;
539     WCHAR buffer[MAX_PATH];
540     int fontHeight = 0;
541 
542     cbItem.mask = CBEIF_TEXT;
543     cbItem.pszText = buffer;
544     cbItem.cchTextMax = MAX_STRING_LEN;
545     cbItem.iItem = 0;
546 
547     while(SendMessageW(hListWnd, CBEM_GETITEMW, 0, (LPARAM)&cbItem))
548     {
549         if(lstrcmpiW(cbItem.pszText, fontName) <= 0)
550             cbItem.iItem++;
551         else
552             break;
553     }
554     cbItem.pszText = HeapAlloc( GetProcessHeap(), 0, (lstrlenW(fontName) + 1)*sizeof(WCHAR) );
555     lstrcpyW( cbItem.pszText, fontName );
556 
557     cbItem.mask |= CBEIF_LPARAM;
558     if(fontType & RASTER_FONTTYPE)
559         fontHeight = ntmc->ntmTm.tmHeight - ntmc->ntmTm.tmInternalLeading;
560 
561     cbItem.lParam = MAKELONG(fontType,fontHeight);
562     SendMessageW(hListWnd, CBEM_INSERTITEMW, 0, (LPARAM)&cbItem);
563     HeapFree( GetProcessHeap(), 0, cbItem.pszText );
564 }
565 
566 static void dialog_choose_font(void)
567 {
568     CHOOSEFONTW cf;
569     LOGFONTW lf;
570     CHARFORMAT2W fmt;
571     HDC hDC = GetDC(hMainWnd);
572 
573     ZeroMemory(&cf, sizeof(cf));
574     cf.lStructSize = sizeof(cf);
575     cf.hwndOwner = hMainWnd;
576     cf.lpLogFont = &lf;
577     cf.Flags = CF_SCREENFONTS | CF_NOSCRIPTSEL | CF_INITTOLOGFONTSTRUCT | CF_EFFECTS | CF_NOVERTFONTS;
578 
579     ZeroMemory(&fmt, sizeof(fmt));
580     fmt.cbSize = sizeof(fmt);
581 
582     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
583     lstrcpyW(cf.lpLogFont->lfFaceName, fmt.szFaceName);
584     cf.lpLogFont->lfItalic = (fmt.dwEffects & CFE_ITALIC) != 0;
585     cf.lpLogFont->lfWeight = (fmt.dwEffects & CFE_BOLD) ? FW_BOLD : FW_NORMAL;
586     cf.lpLogFont->lfUnderline = (fmt.dwEffects & CFE_UNDERLINE) != 0;
587     cf.lpLogFont->lfStrikeOut = (fmt.dwEffects & CFE_STRIKEOUT) != 0;
588     cf.lpLogFont->lfHeight = -MulDiv(fmt.yHeight / 20, GetDeviceCaps(hDC, LOGPIXELSY), 72);
589     cf.rgbColors = fmt.crTextColor;
590 
591     if(ChooseFontW(&cf))
592     {
593         ZeroMemory(&fmt, sizeof(fmt));
594         fmt.cbSize = sizeof(fmt);
595         fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_SIZE | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR;
596         fmt.yHeight = cf.iPointSize * 2;
597 
598         if(cf.nFontType & BOLD_FONTTYPE)
599             fmt.dwEffects |= CFE_BOLD;
600         if(cf.nFontType & ITALIC_FONTTYPE)
601             fmt.dwEffects |= CFE_ITALIC;
602         if(cf.lpLogFont->lfUnderline)
603             fmt.dwEffects |= CFE_UNDERLINE;
604         if(cf.lpLogFont->lfStrikeOut)
605             fmt.dwEffects |= CFE_STRIKEOUT;
606 
607         fmt.crTextColor = cf.rgbColors;
608 
609         SendMessageW(hEditorWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
610         set_font(cf.lpLogFont->lfFaceName);
611     }
612 }
613 
614 
615 static int CALLBACK enum_font_proc(const LOGFONTW *lpelfe, const TEXTMETRICW *lpntme,
616                             DWORD FontType, LPARAM lParam)
617 {
618     HWND hListWnd = (HWND) lParam;
619 
620     if (lpelfe->lfFaceName[0] == '@') return 1;  /* ignore vertical fonts */
621 
622     if(SendMessageW(hListWnd, CB_FINDSTRINGEXACT, -1, (LPARAM)lpelfe->lfFaceName) == CB_ERR)
623     {
624 
625         add_font(lpelfe->lfFaceName, FontType, hListWnd, (const NEWTEXTMETRICEXW*)lpntme);
626     }
627 
628     return 1;
629 }
630 
631 static void populate_font_list(HWND hListWnd)
632 {
633     HDC hdc = GetDC(hMainWnd);
634     LOGFONTW fontinfo;
635     HWND hListEditWnd = (HWND)SendMessageW(hListWnd, CBEM_GETEDITCONTROL, 0, 0);
636     CHARFORMAT2W fmt;
637 
638     fontinfo.lfCharSet = DEFAULT_CHARSET;
639     *fontinfo.lfFaceName = '\0';
640     fontinfo.lfPitchAndFamily = 0;
641 
642     EnumFontFamiliesExW(hdc, &fontinfo, enum_font_proc,
643                         (LPARAM)hListWnd, 0);
644 
645     ZeroMemory(&fmt, sizeof(fmt));
646     fmt.cbSize = sizeof(fmt);
647     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM)&fmt);
648     SendMessageW(hListEditWnd, WM_SETTEXT, 0, (LPARAM)fmt.szFaceName);
649 }
650 
651 static void update_window(void)
652 {
653     RECT rect;
654 
655     GetClientRect(hMainWnd, &rect);
656 
657     OnSize(hMainWnd, SIZE_RESTORED, MAKELPARAM(rect.right, rect.bottom));
658 }
659 
660 static BOOL is_bar_visible(int bandId)
661 {
662     return barState[reg_formatindex(fileFormat)] & (1 << bandId);
663 }
664 
665 static void store_bar_state(int bandId, BOOL show)
666 {
667     int formatIndex = reg_formatindex(fileFormat);
668 
669     if(show)
670         barState[formatIndex] |= (1 << bandId);
671     else
672         barState[formatIndex] &= ~(1 << bandId);
673 }
674 
675 static void set_toolbar_state(int bandId, BOOL show)
676 {
677     HWND hwndReBar = GetDlgItem(hMainWnd, IDC_REBAR);
678 
679     SendMessageW(hwndReBar, RB_SHOWBAND, SendMessageW(hwndReBar, RB_IDTOINDEX, bandId, 0), show);
680 
681     if(bandId == BANDID_TOOLBAR)
682     {
683         REBARBANDINFOW rbbinfo;
684         int index = SendMessageW(hwndReBar, RB_IDTOINDEX, BANDID_FONTLIST, 0);
685 
686         rbbinfo.cbSize = REBARBANDINFOW_V6_SIZE;
687         rbbinfo.fMask = RBBIM_STYLE;
688 
689         SendMessageW(hwndReBar, RB_GETBANDINFOW, index, (LPARAM)&rbbinfo);
690 
691         if(!show)
692             rbbinfo.fStyle &= ~RBBS_BREAK;
693         else
694             rbbinfo.fStyle |= RBBS_BREAK;
695 
696         SendMessageW(hwndReBar, RB_SETBANDINFOW, index, (LPARAM)&rbbinfo);
697     }
698 
699     if(bandId == BANDID_TOOLBAR || bandId == BANDID_FORMATBAR || bandId == BANDID_RULER)
700         store_bar_state(bandId, show);
701 }
702 
703 static void set_statusbar_state(BOOL show)
704 {
705     HWND hStatusWnd = GetDlgItem(hMainWnd, IDC_STATUSBAR);
706 
707     ShowWindow(hStatusWnd, show ? SW_SHOW : SW_HIDE);
708     store_bar_state(BANDID_STATUSBAR, show);
709 }
710 
711 static void set_bar_states(void)
712 {
713     set_toolbar_state(BANDID_TOOLBAR, is_bar_visible(BANDID_TOOLBAR));
714     set_toolbar_state(BANDID_FONTLIST, is_bar_visible(BANDID_FORMATBAR));
715     set_toolbar_state(BANDID_SIZELIST, is_bar_visible(BANDID_FORMATBAR));
716     set_toolbar_state(BANDID_FORMATBAR, is_bar_visible(BANDID_FORMATBAR));
717     set_toolbar_state(BANDID_RULER, is_bar_visible(BANDID_RULER));
718     set_statusbar_state(is_bar_visible(BANDID_STATUSBAR));
719 
720     update_window();
721 }
722 
723 static void preview_exit(HWND hMainWnd)
724 {
725     HMENU hMenu = LoadMenuW(GetModuleHandleW(0), MAKEINTRESOURCEW(IDM_MAINMENU));
726     HWND hEditorWnd = GetDlgItem(hMainWnd, IDC_EDITOR);
727 
728     set_bar_states();
729     ShowWindow(hEditorWnd, TRUE);
730 
731     close_preview(hMainWnd);
732 
733     SetMenu(hMainWnd, hMenu);
734     registry_read_filelist(hMainWnd);
735 
736     update_window();
737 }
738 
739 static void set_fileformat(WPARAM format)
740 {
741     fileFormat = format;
742 
743     set_bar_states();
744     set_default_font();
745     target_device(hMainWnd, wordWrap[reg_formatindex(fileFormat)]);
746 }
747 
748 static void ShowOpenError(DWORD Code)
749 {
750     LPWSTR Message;
751 
752     switch(Code)
753     {
754         case ERROR_ACCESS_DENIED:
755             Message = MAKEINTRESOURCEW(STRING_OPEN_ACCESS_DENIED);
756             break;
757 
758         default:
759             Message = MAKEINTRESOURCEW(STRING_OPEN_FAILED);
760     }
761     MessageBoxW(hMainWnd, Message, wszAppTitle, MB_ICONEXCLAMATION | MB_OK);
762 }
763 
764 static void DoOpenFile(LPCWSTR szOpenFileName)
765 {
766     HANDLE hFile;
767     EDITSTREAM es;
768     char fileStart[5];
769     DWORD readOut;
770     WPARAM format = SF_TEXT;
771 
772     hFile = CreateFileW(szOpenFileName, GENERIC_READ, FILE_SHARE_READ, NULL,
773                         OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
774     if (hFile == INVALID_HANDLE_VALUE)
775     {
776         ShowOpenError(GetLastError());
777         return;
778     }
779 
780     ReadFile(hFile, fileStart, 5, &readOut, NULL);
781     SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
782 
783     if(readOut >= 2 && (BYTE)fileStart[0] == 0xff && (BYTE)fileStart[1] == 0xfe)
784     {
785         format = SF_TEXT | SF_UNICODE;
786         SetFilePointer(hFile, 2, NULL, FILE_BEGIN);
787     } else if(readOut >= 5)
788     {
789         static const char header[] = "{\\rtf";
790         static const BYTE STG_magic[] = { 0xd0,0xcf,0x11,0xe0 };
791 
792         if(!memcmp(header, fileStart, 5))
793             format = SF_RTF;
794         else if (!memcmp(STG_magic, fileStart, sizeof(STG_magic)))
795         {
796             CloseHandle(hFile);
797             MessageBoxWithResStringW(hMainWnd, MAKEINTRESOURCEW(STRING_OLE_STORAGE_NOT_SUPPORTED),
798                     wszAppTitle, MB_OK | MB_ICONEXCLAMATION);
799             return;
800         }
801     }
802 
803     es.dwCookie = (DWORD_PTR)hFile;
804     es.pfnCallback = stream_in;
805 
806     clear_formatting();
807     set_fileformat(format);
808     SendMessageW(hEditorWnd, EM_STREAMIN, format, (LPARAM)&es);
809 
810     CloseHandle(hFile);
811 
812     SetFocus(hEditorWnd);
813 
814     set_caption(szOpenFileName);
815     if (szOpenFileName[0])
816         SHAddToRecentDocs(SHARD_PATHW, szOpenFileName);
817 
818     lstrcpyW(wszFileName, szOpenFileName);
819     SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
820     registry_set_filelist(szOpenFileName, hMainWnd);
821     update_font_list();
822 }
823 
824 static void ShowWriteError(DWORD Code)
825 {
826     LPWSTR Message;
827 
828     switch(Code)
829     {
830         case ERROR_ACCESS_DENIED:
831             Message = MAKEINTRESOURCEW(STRING_WRITE_ACCESS_DENIED);
832             break;
833 
834         default:
835             Message = MAKEINTRESOURCEW(STRING_WRITE_FAILED);
836     }
837     MessageBoxW(hMainWnd, Message, wszAppTitle, MB_ICONEXCLAMATION | MB_OK);
838 }
839 
840 static BOOL DoSaveFile(LPCWSTR wszSaveFileName, WPARAM format)
841 {
842     HANDLE hFile;
843     EDITSTREAM stream;
844     LRESULT ret;
845 
846 #ifdef __REACTOS__
847     /* Use OPEN_ALWAYS instead of CREATE_ALWAYS in order to succeed
848      * even if the file has HIDDEN or SYSTEM attributes */
849     hFile = CreateFileW(wszSaveFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS,
850         FILE_ATTRIBUTE_NORMAL, NULL);
851 #else
852     hFile = CreateFileW(wszSaveFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
853         FILE_ATTRIBUTE_NORMAL, NULL);
854 #endif
855 
856     if(hFile == INVALID_HANDLE_VALUE)
857     {
858         ShowWriteError(GetLastError());
859         return FALSE;
860     }
861 
862     if(format == (SF_TEXT | SF_UNICODE))
863     {
864         static const BYTE unicode[] = {0xff,0xfe};
865         DWORD writeOut;
866         WriteFile(hFile, &unicode, sizeof(unicode), &writeOut, 0);
867 
868         if(writeOut != sizeof(unicode))
869         {
870             CloseHandle(hFile);
871             return FALSE;
872         }
873     }
874 
875     stream.dwCookie = (DWORD_PTR)hFile;
876     stream.pfnCallback = stream_out;
877 
878     ret = SendMessageW(hEditorWnd, EM_STREAMOUT, format, (LPARAM)&stream);
879 
880 #ifdef __REACTOS__
881     /* Truncate the file and close it */
882     SetEndOfFile(hFile);
883 #endif
884     CloseHandle(hFile);
885 
886     SetFocus(hEditorWnd);
887 
888     if(!ret)
889     {
890         GETTEXTLENGTHEX gt;
891         gt.flags = GTL_DEFAULT;
892         gt.codepage = 1200;
893 
894         if(SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0))
895             return FALSE;
896     }
897 
898     lstrcpyW(wszFileName, wszSaveFileName);
899     set_caption(wszFileName);
900     if (wszFileName[0])
901         SHAddToRecentDocs(SHARD_PATHW, wszFileName);
902 
903     SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
904     set_fileformat(format);
905 
906     return TRUE;
907 }
908 
909 static BOOL DialogSaveFile(void)
910 {
911     OPENFILENAMEW sfn;
912 
913     WCHAR wszFile[MAX_PATH] = {'\0'};
914     static const WCHAR wszDefExt[] = {'r','t','f','\0'};
915 
916     ZeroMemory(&sfn, sizeof(sfn));
917 
918     sfn.lStructSize = sizeof(sfn);
919     sfn.Flags = OFN_EXPLORER | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_ENABLESIZING;
920     sfn.hwndOwner = hMainWnd;
921     sfn.lpstrFilter = wszFilter;
922     sfn.lpstrFile = wszFile;
923     sfn.nMaxFile = MAX_PATH;
924     sfn.lpstrDefExt = wszDefExt;
925     sfn.nFilterIndex = fileformat_number(fileFormat)+1;
926 
927     while(GetSaveFileNameW(&sfn))
928     {
929         if(fileformat_flags(sfn.nFilterIndex-1) != SF_RTF)
930         {
931             if(MessageBoxWithResStringW(hMainWnd, MAKEINTRESOURCEW(STRING_SAVE_LOSEFORMATTING),
932                            wszAppTitle, MB_YESNO | MB_ICONEXCLAMATION) != IDYES)
933                 continue;
934         }
935         return DoSaveFile(sfn.lpstrFile, fileformat_flags(sfn.nFilterIndex-1));
936     }
937     return FALSE;
938 }
939 
940 static BOOL prompt_save_changes(void)
941 {
942     if(!wszFileName[0])
943     {
944         GETTEXTLENGTHEX gt;
945         gt.flags = GTL_NUMCHARS;
946         gt.codepage = 1200;
947         if(!SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0))
948             return TRUE;
949     }
950 
951     if(!SendMessageW(hEditorWnd, EM_GETMODIFY, 0, 0))
952     {
953         return TRUE;
954     } else
955     {
956         LPWSTR displayFileName;
957         WCHAR *text;
958         int ret;
959 
960         if(!wszFileName[0])
961             displayFileName = wszDefaultFileName;
962         else
963             displayFileName = file_basename(wszFileName);
964 
965         text = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
966                          (lstrlenW(displayFileName)+lstrlenW(wszSaveChanges))*sizeof(WCHAR));
967 
968         if(!text)
969             return FALSE;
970 
971         wsprintfW(text, wszSaveChanges, displayFileName);
972 
973         ret = MessageBoxW(hMainWnd, text, wszAppTitle, MB_YESNOCANCEL | MB_ICONEXCLAMATION);
974 
975         HeapFree(GetProcessHeap(), 0, text);
976 
977         switch(ret)
978         {
979             case IDNO:
980                 return TRUE;
981 
982             case IDYES:
983                 if(wszFileName[0])
984                     return DoSaveFile(wszFileName, fileFormat);
985                 return DialogSaveFile();
986 
987             default:
988                 return FALSE;
989         }
990     }
991 }
992 
993 static void DialogOpenFile(void)
994 {
995     OPENFILENAMEW ofn;
996 
997     WCHAR wszFile[MAX_PATH] = {'\0'};
998     static const WCHAR wszDefExt[] = {'r','t','f','\0'};
999 
1000     ZeroMemory(&ofn, sizeof(ofn));
1001 
1002     ofn.lStructSize = sizeof(ofn);
1003     ofn.Flags = OFN_EXPLORER | OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_ENABLESIZING;
1004     ofn.hwndOwner = hMainWnd;
1005     ofn.lpstrFilter = wszFilter;
1006     ofn.lpstrFile = wszFile;
1007     ofn.nMaxFile = MAX_PATH;
1008     ofn.lpstrDefExt = wszDefExt;
1009     ofn.nFilterIndex = fileformat_number(fileFormat)+1;
1010 
1011     if(GetOpenFileNameW(&ofn))
1012     {
1013         if(prompt_save_changes())
1014             DoOpenFile(ofn.lpstrFile);
1015     }
1016 }
1017 
1018 static void dialog_about(void)
1019 {
1020     HICON icon = LoadImageW(GetModuleHandleW(NULL), MAKEINTRESOURCEW(IDI_WORDPAD), IMAGE_ICON, 48, 48, LR_SHARED);
1021     ShellAboutW(hMainWnd, wszAppTitle, NULL, icon);
1022 }
1023 
1024 static INT_PTR CALLBACK formatopts_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
1025 {
1026     switch(message)
1027     {
1028         case WM_INITDIALOG:
1029             {
1030                 LPPROPSHEETPAGEW ps = (LPPROPSHEETPAGEW)lParam;
1031                 int wrap = -1;
1032                 char id[4];
1033                 HWND hIdWnd = GetDlgItem(hWnd, IDC_PAGEFMT_ID);
1034 
1035                 sprintf(id, "%d\n", (int)ps->lParam);
1036                 SetWindowTextA(hIdWnd, id);
1037                 if(wordWrap[ps->lParam] == ID_WORDWRAP_NONE)
1038                     wrap = IDC_PAGEFMT_WN;
1039                 else if(wordWrap[ps->lParam] == ID_WORDWRAP_WINDOW)
1040                     wrap = IDC_PAGEFMT_WW;
1041                 else if(wordWrap[ps->lParam] == ID_WORDWRAP_MARGIN)
1042                     wrap = IDC_PAGEFMT_WM;
1043 
1044                 if(wrap != -1)
1045                     CheckRadioButton(hWnd, IDC_PAGEFMT_WN,
1046                                      IDC_PAGEFMT_WM, wrap);
1047 
1048                 if(barState[ps->lParam] & (1 << BANDID_TOOLBAR))
1049                     CheckDlgButton(hWnd, IDC_PAGEFMT_TB, TRUE);
1050                 if(barState[ps->lParam] & (1 << BANDID_FORMATBAR))
1051                     CheckDlgButton(hWnd, IDC_PAGEFMT_FB, TRUE);
1052                 if(barState[ps->lParam] & (1 << BANDID_RULER))
1053                     CheckDlgButton(hWnd, IDC_PAGEFMT_RU, TRUE);
1054                 if(barState[ps->lParam] & (1 << BANDID_STATUSBAR))
1055                     CheckDlgButton(hWnd, IDC_PAGEFMT_SB, TRUE);
1056             }
1057             break;
1058 
1059         case WM_COMMAND:
1060             switch(LOWORD(wParam))
1061             {
1062                 case IDC_PAGEFMT_WN:
1063                 case IDC_PAGEFMT_WW:
1064                 case IDC_PAGEFMT_WM:
1065                     CheckRadioButton(hWnd, IDC_PAGEFMT_WN, IDC_PAGEFMT_WM,
1066                                      LOWORD(wParam));
1067                     break;
1068 
1069                 case IDC_PAGEFMT_TB:
1070                 case IDC_PAGEFMT_FB:
1071                 case IDC_PAGEFMT_RU:
1072                 case IDC_PAGEFMT_SB:
1073                     CheckDlgButton(hWnd, LOWORD(wParam),
1074                                    !IsDlgButtonChecked(hWnd, LOWORD(wParam)));
1075                     break;
1076             }
1077             break;
1078         case WM_NOTIFY:
1079             {
1080                 LPNMHDR header = (LPNMHDR)lParam;
1081                 if(header->code == PSN_APPLY)
1082                 {
1083                     HWND hIdWnd = GetDlgItem(hWnd, IDC_PAGEFMT_ID);
1084                     char sid[4];
1085                     int id;
1086 
1087                     GetWindowTextA(hIdWnd, sid, 4);
1088                     id = atoi(sid);
1089                     if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_WN))
1090                         wordWrap[id] = ID_WORDWRAP_NONE;
1091                     else if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_WW))
1092                         wordWrap[id] = ID_WORDWRAP_WINDOW;
1093                     else if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_WM))
1094                         wordWrap[id] = ID_WORDWRAP_MARGIN;
1095 
1096                     if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_TB))
1097                         barState[id] |= (1 << BANDID_TOOLBAR);
1098                     else
1099                         barState[id] &= ~(1 << BANDID_TOOLBAR);
1100 
1101                     if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_FB))
1102                         barState[id] |= (1 << BANDID_FORMATBAR);
1103                     else
1104                         barState[id] &= ~(1 << BANDID_FORMATBAR);
1105 
1106                     if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_RU))
1107                         barState[id] |= (1 << BANDID_RULER);
1108                     else
1109                         barState[id] &= ~(1 << BANDID_RULER);
1110 
1111                     if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_SB))
1112                         barState[id] |= (1 << BANDID_STATUSBAR);
1113                     else
1114                         barState[id] &= ~(1 << BANDID_STATUSBAR);
1115                 }
1116             }
1117             break;
1118     }
1119     return FALSE;
1120 }
1121 
1122 static void dialog_viewproperties(void)
1123 {
1124     PROPSHEETPAGEW psp[2];
1125     PROPSHEETHEADERW psh;
1126     size_t i;
1127     HINSTANCE hInstance = GetModuleHandleW(0);
1128     LPCPROPSHEETPAGEW ppsp = (LPCPROPSHEETPAGEW)&psp;
1129 
1130     psp[0].dwSize = sizeof(PROPSHEETPAGEW);
1131     psp[0].dwFlags = PSP_USETITLE;
1132     U(psp[0]).pszTemplate = MAKEINTRESOURCEW(IDD_FORMATOPTS);
1133     psp[0].pfnDlgProc = formatopts_proc;
1134     psp[0].hInstance = hInstance;
1135     psp[0].lParam = reg_formatindex(SF_TEXT);
1136     psp[0].pfnCallback = NULL;
1137     psp[0].pszTitle = MAKEINTRESOURCEW(STRING_VIEWPROPS_TEXT);
1138     for(i = 1; i < sizeof(psp)/sizeof(psp[0]); i++)
1139     {
1140         psp[i].dwSize = psp[0].dwSize;
1141         psp[i].dwFlags = psp[0].dwFlags;
1142         U(psp[i]).pszTemplate = U(psp[0]).pszTemplate;
1143         psp[i].pfnDlgProc = psp[0].pfnDlgProc;
1144         psp[i].hInstance = psp[0].hInstance;
1145         psp[i].lParam = reg_formatindex(SF_RTF);
1146         psp[i].pfnCallback = psp[0].pfnCallback;
1147         psp[i].pszTitle = MAKEINTRESOURCEW(STRING_VIEWPROPS_RICHTEXT);
1148     }
1149 
1150     psh.dwSize = sizeof(psh);
1151     psh.dwFlags = PSH_USEICONID | PSH_PROPSHEETPAGE | PSH_NOAPPLYNOW;
1152     psh.hwndParent = hMainWnd;
1153     psh.hInstance = hInstance;
1154     psh.pszCaption = MAKEINTRESOURCEW(STRING_VIEWPROPS_TITLE);
1155     psh.nPages = sizeof(psp)/sizeof(psp[0]);
1156     U3(psh).ppsp = ppsp;
1157     U(psh).pszIcon = MAKEINTRESOURCEW(IDI_WORDPAD);
1158 
1159     if(fileFormat & SF_RTF)
1160         U2(psh).nStartPage = 1;
1161     else
1162         U2(psh).nStartPage = 0;
1163     PropertySheetW(&psh);
1164     set_bar_states();
1165     target_device(hMainWnd, wordWrap[reg_formatindex(fileFormat)]);
1166 }
1167 
1168 static void HandleCommandLine(LPWSTR cmdline)
1169 {
1170     WCHAR delimiter;
1171     BOOL opt_print = FALSE;
1172 
1173     /* skip white space */
1174     while (*cmdline == ' ') cmdline++;
1175 
1176     /* skip executable name */
1177     delimiter = (*cmdline == '"' ? '"' : ' ');
1178 
1179     if (*cmdline == delimiter) cmdline++;
1180     while (*cmdline && *cmdline != delimiter) cmdline++;
1181     if (*cmdline == delimiter) cmdline++;
1182 
1183     while (*cmdline)
1184     {
1185         while (isspace(*cmdline)) cmdline++;
1186 
1187         if (*cmdline == '-' || *cmdline == '/')
1188         {
1189             if (!cmdline[2] || isspace(cmdline[2]))
1190             {
1191                 switch (cmdline[1])
1192                 {
1193                 case 'P':
1194                 case 'p':
1195                     opt_print = TRUE;
1196                     cmdline += 2;
1197                     continue;
1198                 }
1199             }
1200             /* a filename starting by / */
1201         }
1202         break;
1203     }
1204 
1205     if (*cmdline)
1206     {
1207         /* file name is passed on the command line */
1208         if (cmdline[0] == '"')
1209         {
1210             cmdline++;
1211             cmdline[lstrlenW(cmdline) - 1] = 0;
1212         }
1213         DoOpenFile(cmdline);
1214         InvalidateRect(hMainWnd, NULL, FALSE);
1215     }
1216 
1217     if (opt_print)
1218         MessageBoxWithResStringW(hMainWnd, MAKEINTRESOURCEW(STRING_PRINTING_NOT_IMPLEMENTED), wszAppTitle, MB_OK);
1219 }
1220 
1221 static LRESULT handle_findmsg(LPFINDREPLACEW pFr)
1222 {
1223     if(pFr->Flags & FR_DIALOGTERM)
1224     {
1225         hFindWnd = 0;
1226         pFr->Flags = FR_FINDNEXT;
1227         return 0;
1228     }
1229 
1230     if(pFr->Flags & FR_FINDNEXT || pFr->Flags & FR_REPLACE || pFr->Flags & FR_REPLACEALL)
1231     {
1232         FINDREPLACE_custom *custom_data = (FINDREPLACE_custom*)pFr->lCustData;
1233         DWORD flags;
1234         FINDTEXTEXW ft;
1235         CHARRANGE sel;
1236         LRESULT ret = -1;
1237         HMENU hMenu = GetMenu(hMainWnd);
1238         MENUITEMINFOW mi;
1239 
1240         mi.cbSize = sizeof(mi);
1241         mi.fMask = MIIM_DATA;
1242         mi.dwItemData = 1;
1243         SetMenuItemInfoW(hMenu, ID_FIND_NEXT, FALSE, &mi);
1244 
1245         /* Make sure find field is saved. */
1246         if (pFr->lpstrFindWhat != custom_data->findBuffer)
1247         {
1248             lstrcpynW(custom_data->findBuffer, pFr->lpstrFindWhat,
1249                       sizeof(custom_data->findBuffer) / sizeof(WCHAR));
1250             pFr->lpstrFindWhat = custom_data->findBuffer;
1251         }
1252 
1253         SendMessageW(hEditorWnd, EM_GETSEL, (WPARAM)&sel.cpMin, (LPARAM)&sel.cpMax);
1254         if(custom_data->endPos == -1) {
1255             custom_data->endPos = sel.cpMin;
1256             custom_data->wrapped = FALSE;
1257         }
1258 
1259         flags = FR_DOWN | (pFr->Flags & (FR_MATCHCASE | FR_WHOLEWORD));
1260         ft.lpstrText = pFr->lpstrFindWhat;
1261 
1262         /* Only replace the existing selection if it is an exact match. */
1263         if (sel.cpMin != sel.cpMax &&
1264             (pFr->Flags & FR_REPLACE || pFr->Flags & FR_REPLACEALL))
1265         {
1266             ft.chrg = sel;
1267             SendMessageW(hEditorWnd, EM_FINDTEXTEXW, flags, (LPARAM)&ft);
1268             if (ft.chrgText.cpMin == sel.cpMin && ft.chrgText.cpMax == sel.cpMax) {
1269                 SendMessageW(hEditorWnd, EM_REPLACESEL, TRUE, (LPARAM)pFr->lpstrReplaceWith);
1270                 SendMessageW(hEditorWnd, EM_GETSEL, (WPARAM)&sel.cpMin, (LPARAM)&sel.cpMax);
1271             }
1272         }
1273 
1274         /* Search from the start of the selection, but exclude the first character
1275          * from search if there is a selection. */
1276         ft.chrg.cpMin = sel.cpMin;
1277         if (sel.cpMin != sel.cpMax)
1278             ft.chrg.cpMin++;
1279 
1280         /* Search to the end, then wrap around and search from the start. */
1281         if (!custom_data->wrapped) {
1282             ft.chrg.cpMax = -1;
1283             ret = SendMessageW(hEditorWnd, EM_FINDTEXTEXW, flags, (LPARAM)&ft);
1284             if (ret == -1) {
1285                 custom_data->wrapped = TRUE;
1286                 ft.chrg.cpMin = 0;
1287             }
1288         }
1289 
1290         if (ret == -1) {
1291             ft.chrg.cpMax = custom_data->endPos + lstrlenW(pFr->lpstrFindWhat) - 1;
1292             if (ft.chrg.cpMax > ft.chrg.cpMin)
1293                 ret = SendMessageW(hEditorWnd, EM_FINDTEXTEXW, flags, (LPARAM)&ft);
1294         }
1295 
1296         if (ret == -1) {
1297             custom_data->endPos = -1;
1298             EnableWindow(hMainWnd, FALSE);
1299             MessageBoxWithResStringW(hFindWnd, MAKEINTRESOURCEW(STRING_SEARCH_FINISHED),
1300                                      wszAppTitle, MB_OK | MB_ICONASTERISK | MB_TASKMODAL);
1301             EnableWindow(hMainWnd, TRUE);
1302         } else {
1303             SendMessageW(hEditorWnd, EM_SETSEL, ft.chrgText.cpMin, ft.chrgText.cpMax);
1304             SendMessageW(hEditorWnd, EM_SCROLLCARET, 0, 0);
1305 
1306             if (pFr->Flags & FR_REPLACEALL)
1307                 return handle_findmsg(pFr);
1308         }
1309     }
1310 
1311     return 0;
1312 }
1313 
1314 static void dialog_find(LPFINDREPLACEW fr, BOOL replace)
1315 {
1316     static WCHAR selBuffer[128];
1317     static WCHAR replaceBuffer[128];
1318     static FINDREPLACE_custom custom_data;
1319     static const WCHAR endl = '\r';
1320     FINDTEXTW ft;
1321 
1322     /* Allow only one search/replace dialog to open */
1323     if(hFindWnd != NULL)
1324     {
1325         SetActiveWindow(hFindWnd);
1326         return;
1327     }
1328 
1329     ZeroMemory(fr, sizeof(FINDREPLACEW));
1330     fr->lStructSize = sizeof(FINDREPLACEW);
1331     fr->hwndOwner = hMainWnd;
1332     fr->Flags = FR_HIDEUPDOWN;
1333     /* Find field is filled with the selected text if it is non-empty
1334      * and stays within the same paragraph, otherwise the previous
1335      * find field is used. */
1336     SendMessageW(hEditorWnd, EM_GETSEL, (WPARAM)&ft.chrg.cpMin,
1337                  (LPARAM)&ft.chrg.cpMax);
1338     ft.lpstrText = &endl;
1339     if (ft.chrg.cpMin != ft.chrg.cpMax &&
1340         SendMessageW(hEditorWnd, EM_FINDTEXTW, FR_DOWN, (LPARAM)&ft) == -1)
1341     {
1342         /* Use a temporary buffer for the selected text so that the saved
1343          * find field is only overwritten when a find/replace is clicked. */
1344         GETTEXTEX gt = {sizeof(selBuffer), GT_SELECTION, 1200, NULL, NULL};
1345         SendMessageW(hEditorWnd, EM_GETTEXTEX, (WPARAM)&gt, (LPARAM)selBuffer);
1346         fr->lpstrFindWhat = selBuffer;
1347     } else {
1348         fr->lpstrFindWhat = custom_data.findBuffer;
1349     }
1350     fr->lpstrReplaceWith = replaceBuffer;
1351     custom_data.endPos = -1;
1352     custom_data.wrapped = FALSE;
1353     fr->lCustData = (LPARAM)&custom_data;
1354     fr->wFindWhatLen = sizeof(custom_data.findBuffer);
1355     fr->wReplaceWithLen = sizeof(replaceBuffer);
1356 
1357     if(replace)
1358         hFindWnd = ReplaceTextW(fr);
1359     else
1360         hFindWnd = FindTextW(fr);
1361 }
1362 
1363 static int units_to_twips(UNIT unit, float number)
1364 {
1365     int twips = 0;
1366 
1367     switch(unit)
1368     {
1369     case UNIT_CM:
1370         twips = (int)(number * 1000.0 / (float)CENTMM_PER_INCH * (float)TWIPS_PER_INCH);
1371         break;
1372 
1373     case UNIT_INCH:
1374         twips = (int)(number * (float)TWIPS_PER_INCH);
1375         break;
1376 
1377     case UNIT_PT:
1378         twips = (int)(number * (0.0138 * (float)TWIPS_PER_INCH));
1379         break;
1380     }
1381 
1382     return twips;
1383 }
1384 
1385 static void append_current_units(LPWSTR buffer)
1386 {
1387     static const WCHAR space[] = {' ', 0};
1388     lstrcatW(buffer, space);
1389     lstrcatW(buffer, units_cmW);
1390 }
1391 
1392 static void number_with_units(LPWSTR buffer, int number)
1393 {
1394     static const WCHAR fmt[] = {'%','.','2','f',' ','%','s','\0'};
1395     float converted = (float)number / (float)TWIPS_PER_INCH *(float)CENTMM_PER_INCH / 1000.0;
1396 
1397     sprintfW(buffer, fmt, converted, units_cmW);
1398 }
1399 
1400 static BOOL get_comboexlist_selection(HWND hComboEx, LPWSTR wszBuffer, UINT bufferLength)
1401 {
1402     COMBOBOXEXITEMW cbItem;
1403     COMBOBOXINFO cbInfo;
1404     HWND hCombo, hList;
1405     int idx, result;
1406 
1407     hCombo = (HWND)SendMessageW(hComboEx, CBEM_GETCOMBOCONTROL, 0, 0);
1408     if (!hCombo)
1409         return FALSE;
1410     cbInfo.cbSize = sizeof(COMBOBOXINFO);
1411     result = SendMessageW(hCombo, CB_GETCOMBOBOXINFO, 0, (LPARAM)&cbInfo);
1412     if (!result)
1413         return FALSE;
1414     hList = cbInfo.hwndList;
1415     idx = SendMessageW(hList, LB_GETCURSEL, 0, 0);
1416     if (idx < 0)
1417         return FALSE;
1418 
1419     ZeroMemory(&cbItem, sizeof(cbItem));
1420     cbItem.mask = CBEIF_TEXT;
1421     cbItem.iItem = idx;
1422     cbItem.pszText = wszBuffer;
1423     cbItem.cchTextMax = bufferLength-1;
1424     result = SendMessageW(hComboEx, CBEM_GETITEMW, 0, (LPARAM)&cbItem);
1425 
1426     return result != 0;
1427 }
1428 
1429 static INT_PTR CALLBACK datetime_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
1430 {
1431     switch(message)
1432     {
1433         case WM_INITDIALOG:
1434             {
1435                 WCHAR buffer[MAX_STRING_LEN];
1436                 SYSTEMTIME st;
1437                 HWND hListWnd = GetDlgItem(hWnd, IDC_DATETIME);
1438                 GetLocalTime(&st);
1439 
1440                 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st, 0, (LPWSTR)&buffer,
1441                                MAX_STRING_LEN);
1442                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
1443                 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, 0, (LPWSTR)&buffer,
1444                                MAX_STRING_LEN);
1445                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
1446                 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, 0, (LPWSTR)&buffer, MAX_STRING_LEN);
1447                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
1448 
1449                 SendMessageW(hListWnd, LB_SETSEL, TRUE, 0);
1450             }
1451             break;
1452 
1453         case WM_COMMAND:
1454             switch(LOWORD(wParam))
1455             {
1456                 case IDC_DATETIME:
1457                     if (HIWORD(wParam) != LBN_DBLCLK)
1458                         break;
1459                     /* Fall through */
1460 
1461                 case IDOK:
1462                     {
1463                         LRESULT index;
1464                         HWND hListWnd = GetDlgItem(hWnd, IDC_DATETIME);
1465 
1466                         index = SendMessageW(hListWnd, LB_GETCURSEL, 0, 0);
1467 
1468                         if(index != LB_ERR)
1469                         {
1470                             WCHAR buffer[MAX_STRING_LEN];
1471                             SendMessageW(hListWnd, LB_GETTEXT, index, (LPARAM)&buffer);
1472                             SendMessageW(hEditorWnd, EM_REPLACESEL, TRUE, (LPARAM)&buffer);
1473                         }
1474                     }
1475                     /* Fall through */
1476 
1477                 case IDCANCEL:
1478                     EndDialog(hWnd, wParam);
1479                     return TRUE;
1480             }
1481     }
1482     return FALSE;
1483 }
1484 
1485 static INT_PTR CALLBACK newfile_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
1486 {
1487     switch(message)
1488     {
1489         case WM_INITDIALOG:
1490             {
1491                 HINSTANCE hInstance = GetModuleHandleW(0);
1492                 WCHAR buffer[MAX_STRING_LEN];
1493                 HWND hListWnd = GetDlgItem(hWnd, IDC_NEWFILE);
1494 
1495                 LoadStringW(hInstance, STRING_NEWFILE_RICHTEXT, buffer, MAX_STRING_LEN);
1496                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
1497                 LoadStringW(hInstance, STRING_NEWFILE_TXT, buffer, MAX_STRING_LEN);
1498                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
1499                 LoadStringW(hInstance, STRING_NEWFILE_TXT_UNICODE, buffer, MAX_STRING_LEN);
1500                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
1501 
1502                 SendMessageW(hListWnd, LB_SETSEL, TRUE, 0);
1503             }
1504             break;
1505 
1506         case WM_COMMAND:
1507             switch(LOWORD(wParam))
1508             {
1509                 case IDOK:
1510                     {
1511                         LRESULT index;
1512                         HWND hListWnd = GetDlgItem(hWnd, IDC_NEWFILE);
1513                         index = SendMessageW(hListWnd, LB_GETCURSEL, 0, 0);
1514 
1515                         if(index != LB_ERR)
1516                             EndDialog(hWnd, MAKELONG(fileformat_flags(index),0));
1517                     }
1518                     return TRUE;
1519 
1520                 case IDCANCEL:
1521                     EndDialog(hWnd, MAKELONG(ID_NEWFILE_ABORT,0));
1522                     return TRUE;
1523             }
1524     }
1525     return FALSE;
1526 }
1527 
1528 static INT_PTR CALLBACK paraformat_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
1529 {
1530     static const WORD ALIGNMENT_VALUES[] = {PFA_LEFT, PFA_RIGHT, PFA_CENTER};
1531 
1532     switch(message)
1533     {
1534         case WM_INITDIALOG:
1535             {
1536                 HINSTANCE hInstance = GetModuleHandleW(0);
1537                 WCHAR buffer[MAX_STRING_LEN];
1538                 HWND hListWnd = GetDlgItem(hWnd, IDC_PARA_ALIGN);
1539                 HWND hLeftWnd = GetDlgItem(hWnd, IDC_PARA_LEFT);
1540                 HWND hRightWnd = GetDlgItem(hWnd, IDC_PARA_RIGHT);
1541                 HWND hFirstWnd = GetDlgItem(hWnd, IDC_PARA_FIRST);
1542                 PARAFORMAT2 pf;
1543                 int index = 0;
1544 
1545                 LoadStringW(hInstance, STRING_ALIGN_LEFT, buffer,
1546                             MAX_STRING_LEN);
1547                 SendMessageW(hListWnd, CB_ADDSTRING, 0, (LPARAM)buffer);
1548                 LoadStringW(hInstance, STRING_ALIGN_RIGHT, buffer,
1549                             MAX_STRING_LEN);
1550                 SendMessageW(hListWnd, CB_ADDSTRING, 0, (LPARAM)buffer);
1551                 LoadStringW(hInstance, STRING_ALIGN_CENTER, buffer,
1552                             MAX_STRING_LEN);
1553                 SendMessageW(hListWnd, CB_ADDSTRING, 0, (LPARAM)buffer);
1554 
1555                 pf.cbSize = sizeof(pf);
1556                 pf.dwMask = PFM_ALIGNMENT | PFM_OFFSET | PFM_RIGHTINDENT |
1557                             PFM_STARTINDENT;
1558                 SendMessageW(hEditorWnd, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
1559 
1560                 if(pf.wAlignment == PFA_RIGHT)
1561                     index ++;
1562                 else if(pf.wAlignment == PFA_CENTER)
1563                     index += 2;
1564 
1565                 SendMessageW(hListWnd, CB_SETCURSEL, index, 0);
1566 
1567                 number_with_units(buffer, pf.dxStartIndent + pf.dxOffset);
1568                 SetWindowTextW(hLeftWnd, buffer);
1569                 number_with_units(buffer, pf.dxRightIndent);
1570                 SetWindowTextW(hRightWnd, buffer);
1571                 number_with_units(buffer, -pf.dxOffset);
1572                 SetWindowTextW(hFirstWnd, buffer);
1573             }
1574             break;
1575 
1576         case WM_COMMAND:
1577             switch(LOWORD(wParam))
1578             {
1579                 case IDOK:
1580                     {
1581                         HWND hListWnd = GetDlgItem(hWnd, IDC_PARA_ALIGN);
1582                         HWND hLeftWnd = GetDlgItem(hWnd, IDC_PARA_LEFT);
1583                         HWND hRightWnd = GetDlgItem(hWnd, IDC_PARA_RIGHT);
1584                         HWND hFirstWnd = GetDlgItem(hWnd, IDC_PARA_FIRST);
1585                         WCHAR buffer[MAX_STRING_LEN];
1586                         int index;
1587                         float num;
1588                         int ret = 0;
1589                         PARAFORMAT pf;
1590                         UNIT unit;
1591 
1592                         index = SendMessageW(hListWnd, CB_GETCURSEL, 0, 0);
1593                         pf.wAlignment = ALIGNMENT_VALUES[index];
1594 
1595                         GetWindowTextW(hLeftWnd, buffer, MAX_STRING_LEN);
1596                         if(number_from_string(buffer, &num, &unit))
1597                             ret++;
1598                         pf.dxOffset = units_to_twips(unit, num);
1599                         GetWindowTextW(hRightWnd, buffer, MAX_STRING_LEN);
1600                         if(number_from_string(buffer, &num, &unit))
1601                             ret++;
1602                         pf.dxRightIndent = units_to_twips(unit, num);
1603                         GetWindowTextW(hFirstWnd, buffer, MAX_STRING_LEN);
1604                         if(number_from_string(buffer, &num, &unit))
1605                             ret++;
1606                         pf.dxStartIndent = units_to_twips(unit, num);
1607 
1608                         if(ret != 3)
1609                         {
1610                             MessageBoxWithResStringW(hMainWnd, MAKEINTRESOURCEW(STRING_INVALID_NUMBER),
1611                                         wszAppTitle, MB_OK | MB_ICONASTERISK);
1612                             return FALSE;
1613                         } else
1614                         {
1615                             if (pf.dxOffset + pf.dxStartIndent < 0
1616                                 && pf.dxStartIndent < 0)
1617                             {
1618                                 /* The first line is before the left edge, so
1619                                  * make sure it is at the left edge. */
1620                                 pf.dxOffset = -pf.dxStartIndent;
1621                             } else if (pf.dxOffset < 0) {
1622                                 /* The second and following lines are before
1623                                  * the left edge, so set it to be at the left
1624                                  * edge, and adjust the first line since it
1625                                  * is relative to it. */
1626                                 pf.dxStartIndent = max(pf.dxStartIndent + pf.dxOffset, 0);
1627                                 pf.dxOffset = 0;
1628                             }
1629                             /* Internally the dxStartIndent is the absolute
1630                              * offset for the first line and dxOffset is
1631                              * to it value as opposed how it is displayed with
1632                              * the first line being the relative value.
1633                              * These two lines make the adjustments. */
1634                             pf.dxStartIndent = pf.dxStartIndent + pf.dxOffset;
1635                             pf.dxOffset = pf.dxOffset - pf.dxStartIndent;
1636 
1637                             pf.cbSize = sizeof(pf);
1638                             pf.dwMask = PFM_ALIGNMENT | PFM_OFFSET | PFM_RIGHTINDENT |
1639                                         PFM_STARTINDENT;
1640                             SendMessageW(hEditorWnd, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
1641                         }
1642                     }
1643                     /* Fall through */
1644 
1645                 case IDCANCEL:
1646                     EndDialog(hWnd, wParam);
1647                     return TRUE;
1648             }
1649     }
1650     return FALSE;
1651 }
1652 
1653 static INT_PTR CALLBACK tabstops_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
1654 {
1655     switch(message)
1656     {
1657         case WM_INITDIALOG:
1658             {
1659                 HWND hTabWnd = GetDlgItem(hWnd, IDC_TABSTOPS);
1660                 PARAFORMAT pf;
1661                 WCHAR buffer[MAX_STRING_LEN];
1662                 int i;
1663 
1664                 pf.cbSize = sizeof(pf);
1665                 pf.dwMask = PFM_TABSTOPS;
1666                 SendMessageW(hEditorWnd, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
1667                 SendMessageW(hTabWnd, CB_LIMITTEXT, MAX_STRING_LEN-1, 0);
1668 
1669                 for(i = 0; i < pf.cTabCount; i++)
1670                 {
1671                     number_with_units(buffer, pf.rgxTabs[i]);
1672                     SendMessageW(hTabWnd, CB_ADDSTRING, 0, (LPARAM)&buffer);
1673                 }
1674                 SetFocus(hTabWnd);
1675             }
1676             break;
1677 
1678         case WM_COMMAND:
1679             switch(LOWORD(wParam))
1680             {
1681                 case IDC_TABSTOPS:
1682                     {
1683                         HWND hTabWnd = (HWND)lParam;
1684                         HWND hAddWnd = GetDlgItem(hWnd, ID_TAB_ADD);
1685                         HWND hDelWnd = GetDlgItem(hWnd, ID_TAB_DEL);
1686                         HWND hEmptyWnd = GetDlgItem(hWnd, ID_TAB_EMPTY);
1687 
1688                         if(GetWindowTextLengthW(hTabWnd))
1689                             EnableWindow(hAddWnd, TRUE);
1690                         else
1691                             EnableWindow(hAddWnd, FALSE);
1692 
1693                         if(SendMessageW(hTabWnd, CB_GETCOUNT, 0, 0))
1694                         {
1695                             EnableWindow(hEmptyWnd, TRUE);
1696 
1697                             if(SendMessageW(hTabWnd, CB_GETCURSEL, 0, 0) == CB_ERR)
1698                                 EnableWindow(hDelWnd, FALSE);
1699                             else
1700                                 EnableWindow(hDelWnd, TRUE);
1701                         } else
1702                         {
1703                             EnableWindow(hEmptyWnd, FALSE);
1704                         }
1705                     }
1706                     break;
1707 
1708                 case ID_TAB_ADD:
1709                     {
1710                         HWND hTabWnd = GetDlgItem(hWnd, IDC_TABSTOPS);
1711                         WCHAR buffer[MAX_STRING_LEN];
1712                         UNIT unit;
1713 
1714                         GetWindowTextW(hTabWnd, buffer, MAX_STRING_LEN);
1715                         append_current_units(buffer);
1716 
1717                         if(SendMessageW(hTabWnd, CB_FINDSTRINGEXACT, -1, (LPARAM)&buffer) == CB_ERR)
1718                         {
1719                             float number = 0;
1720                             int item_count = SendMessageW(hTabWnd, CB_GETCOUNT, 0, 0);
1721 
1722                             if(!number_from_string(buffer, &number, &unit))
1723                             {
1724                                 MessageBoxWithResStringW(hWnd, MAKEINTRESOURCEW(STRING_INVALID_NUMBER),
1725                                              wszAppTitle, MB_OK | MB_ICONINFORMATION);
1726                             } else if (item_count >= MAX_TAB_STOPS) {
1727                                 MessageBoxWithResStringW(hWnd, MAKEINTRESOURCEW(STRING_MAX_TAB_STOPS),
1728                                              wszAppTitle, MB_OK | MB_ICONINFORMATION);
1729                             } else {
1730                                 int i;
1731                                 float next_number = -1;
1732                                 int next_number_in_twips = -1;
1733                                 int insert_number = units_to_twips(unit, number);
1734 
1735                                 /* linear search for position to insert the string */
1736                                 for(i = 0; i < item_count; i++)
1737                                 {
1738                                     SendMessageW(hTabWnd, CB_GETLBTEXT, i, (LPARAM)&buffer);
1739                                     number_from_string(buffer, &next_number, &unit);
1740                                     next_number_in_twips = units_to_twips(unit, next_number);
1741                                     if (insert_number <= next_number_in_twips)
1742                                         break;
1743                                 }
1744                                 if (insert_number != next_number_in_twips)
1745                                 {
1746                                     number_with_units(buffer, insert_number);
1747                                     SendMessageW(hTabWnd, CB_INSERTSTRING, i, (LPARAM)&buffer);
1748                                     SetWindowTextW(hTabWnd, 0);
1749                                 }
1750                             }
1751                         }
1752                         SetFocus(hTabWnd);
1753                     }
1754                     break;
1755 
1756                 case ID_TAB_DEL:
1757                     {
1758                         HWND hTabWnd = GetDlgItem(hWnd, IDC_TABSTOPS);
1759                         LRESULT ret;
1760                         ret = SendMessageW(hTabWnd, CB_GETCURSEL, 0, 0);
1761                         if(ret != CB_ERR)
1762                             SendMessageW(hTabWnd, CB_DELETESTRING, ret, 0);
1763                     }
1764                     break;
1765 
1766                 case ID_TAB_EMPTY:
1767                     {
1768                         HWND hTabWnd = GetDlgItem(hWnd, IDC_TABSTOPS);
1769                         SendMessageW(hTabWnd, CB_RESETCONTENT, 0, 0);
1770                         SetFocus(hTabWnd);
1771                     }
1772                     break;
1773 
1774                 case IDOK:
1775                     {
1776                         HWND hTabWnd = GetDlgItem(hWnd, IDC_TABSTOPS);
1777                         int i;
1778                         WCHAR buffer[MAX_STRING_LEN];
1779                         PARAFORMAT pf;
1780                         float number;
1781                         UNIT unit;
1782 
1783                         pf.cbSize = sizeof(pf);
1784                         pf.dwMask = PFM_TABSTOPS;
1785 
1786                         for(i = 0; SendMessageW(hTabWnd, CB_GETLBTEXT, i,
1787                                                 (LPARAM)&buffer) != CB_ERR &&
1788                                                         i < MAX_TAB_STOPS; i++)
1789                         {
1790                             number_from_string(buffer, &number, &unit);
1791                             pf.rgxTabs[i] = units_to_twips(unit, number);
1792                         }
1793                         pf.cTabCount = i;
1794                         SendMessageW(hEditorWnd, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
1795                     }
1796                     /* Fall through */
1797                 case IDCANCEL:
1798                     EndDialog(hWnd, wParam);
1799                     return TRUE;
1800             }
1801     }
1802     return FALSE;
1803 }
1804 
1805 static LRESULT OnCreate( HWND hWnd )
1806 {
1807     HWND hToolBarWnd, hFormatBarWnd,  hReBarWnd, hFontListWnd, hSizeListWnd, hRulerWnd;
1808     HINSTANCE hInstance = GetModuleHandleW(0);
1809     HANDLE hDLL;
1810     TBADDBITMAP ab;
1811     int nStdBitmaps = 0;
1812     REBARINFO rbi;
1813     REBARBANDINFOW rbb;
1814     static const WCHAR wszRichEditDll[] = {'R','I','C','H','E','D','2','0','.','D','L','L','\0'};
1815     static const WCHAR wszRichEditText[] = {'R','i','c','h','E','d','i','t',' ','t','e','x','t','\0'};
1816 
1817     CreateStatusWindowW(CCS_NODIVIDER|WS_CHILD|WS_VISIBLE, wszRichEditText, hWnd, IDC_STATUSBAR);
1818 
1819     hReBarWnd = CreateWindowExW(WS_EX_TOOLWINDOW, REBARCLASSNAMEW, NULL,
1820       CCS_NODIVIDER|WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|RBS_VARHEIGHT|CCS_TOP,
1821       CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, hWnd, (HMENU)IDC_REBAR, hInstance, NULL);
1822 
1823     rbi.cbSize = sizeof(rbi);
1824     rbi.fMask = 0;
1825     rbi.himl = NULL;
1826     if(!SendMessageW(hReBarWnd, RB_SETBARINFO, 0, (LPARAM)&rbi))
1827         return -1;
1828 
1829     hToolBarWnd = CreateToolbarEx(hReBarWnd, CCS_NOPARENTALIGN|CCS_NOMOVEY|WS_VISIBLE|WS_CHILD|TBSTYLE_TOOLTIPS|BTNS_BUTTON,
1830       IDC_TOOLBAR,
1831       1, hInstance, IDB_TOOLBAR,
1832       NULL, 0,
1833       24, 24, 16, 16, sizeof(TBBUTTON));
1834 
1835     ab.hInst = HINST_COMMCTRL;
1836     ab.nID = IDB_STD_SMALL_COLOR;
1837     nStdBitmaps = SendMessageW(hToolBarWnd, TB_ADDBITMAP, 0, (LPARAM)&ab);
1838 
1839     AddButton(hToolBarWnd, nStdBitmaps+STD_FILENEW, ID_FILE_NEW);
1840     AddButton(hToolBarWnd, nStdBitmaps+STD_FILEOPEN, ID_FILE_OPEN);
1841     AddButton(hToolBarWnd, nStdBitmaps+STD_FILESAVE, ID_FILE_SAVE);
1842     AddSeparator(hToolBarWnd);
1843     AddButton(hToolBarWnd, nStdBitmaps+STD_PRINT, ID_PRINT_QUICK);
1844     AddButton(hToolBarWnd, nStdBitmaps+STD_PRINTPRE, ID_PREVIEW);
1845     AddSeparator(hToolBarWnd);
1846     AddButton(hToolBarWnd, nStdBitmaps+STD_FIND, ID_FIND);
1847     AddSeparator(hToolBarWnd);
1848     AddButton(hToolBarWnd, nStdBitmaps+STD_CUT, ID_EDIT_CUT);
1849     AddButton(hToolBarWnd, nStdBitmaps+STD_COPY, ID_EDIT_COPY);
1850     AddButton(hToolBarWnd, nStdBitmaps+STD_PASTE, ID_EDIT_PASTE);
1851     AddButton(hToolBarWnd, nStdBitmaps+STD_UNDO, ID_EDIT_UNDO);
1852     AddButton(hToolBarWnd, nStdBitmaps+STD_REDOW, ID_EDIT_REDO);
1853     AddSeparator(hToolBarWnd);
1854     AddButton(hToolBarWnd, 0, ID_DATETIME);
1855 
1856     SendMessageW(hToolBarWnd, TB_AUTOSIZE, 0, 0);
1857 
1858     rbb.cbSize = REBARBANDINFOW_V6_SIZE;
1859     rbb.fMask = RBBIM_SIZE | RBBIM_CHILDSIZE | RBBIM_CHILD | RBBIM_STYLE | RBBIM_ID;
1860     rbb.fStyle = RBBS_CHILDEDGE | RBBS_BREAK | RBBS_NOGRIPPER;
1861     rbb.cx = 0;
1862     rbb.hwndChild = hToolBarWnd;
1863     rbb.cxMinChild = 0;
1864     rbb.cyChild = rbb.cyMinChild = HIWORD(SendMessageW(hToolBarWnd, TB_GETBUTTONSIZE, 0, 0));
1865     rbb.wID = BANDID_TOOLBAR;
1866 
1867     SendMessageW(hReBarWnd, RB_INSERTBANDW, -1, (LPARAM)&rbb);
1868 
1869     hFontListWnd = CreateWindowExW(0, WC_COMBOBOXEXW, NULL,
1870                       WS_BORDER | WS_VISIBLE | WS_CHILD | CBS_DROPDOWN | CBS_SORT,
1871                       0, 0, 200, 150, hReBarWnd, (HMENU)IDC_FONTLIST, hInstance, NULL);
1872 
1873     rbb.hwndChild = hFontListWnd;
1874     rbb.cx = 200;
1875     rbb.wID = BANDID_FONTLIST;
1876 
1877     SendMessageW(hReBarWnd, RB_INSERTBANDW, -1, (LPARAM)&rbb);
1878 
1879     hSizeListWnd = CreateWindowExW(0, WC_COMBOBOXEXW, NULL,
1880                       WS_BORDER | WS_VISIBLE | WS_CHILD | CBS_DROPDOWN,
1881                       0, 0, 50, 150, hReBarWnd, (HMENU)IDC_SIZELIST, hInstance, NULL);
1882 
1883     rbb.hwndChild = hSizeListWnd;
1884     rbb.cx = 50;
1885     rbb.fStyle ^= RBBS_BREAK;
1886     rbb.wID = BANDID_SIZELIST;
1887 
1888     SendMessageW(hReBarWnd, RB_INSERTBANDW, -1, (LPARAM)&rbb);
1889 
1890     hFormatBarWnd = CreateToolbarEx(hReBarWnd,
1891          CCS_NOPARENTALIGN | CCS_NOMOVEY | WS_VISIBLE | TBSTYLE_TOOLTIPS | BTNS_BUTTON,
1892          IDC_FORMATBAR, 8, hInstance, IDB_FORMATBAR, NULL, 0, 16, 16, 16, 16, sizeof(TBBUTTON));
1893 
1894     AddButton(hFormatBarWnd, 0, ID_FORMAT_BOLD);
1895     AddButton(hFormatBarWnd, 1, ID_FORMAT_ITALIC);
1896     AddButton(hFormatBarWnd, 2, ID_FORMAT_UNDERLINE);
1897     AddButton(hFormatBarWnd, 3, ID_FORMAT_COLOR);
1898     AddSeparator(hFormatBarWnd);
1899     AddButton(hFormatBarWnd, 4, ID_ALIGN_LEFT);
1900     AddButton(hFormatBarWnd, 5, ID_ALIGN_CENTER);
1901     AddButton(hFormatBarWnd, 6, ID_ALIGN_RIGHT);
1902     AddSeparator(hFormatBarWnd);
1903     AddButton(hFormatBarWnd, 7, ID_BULLET);
1904 
1905     SendMessageW(hFormatBarWnd, TB_AUTOSIZE, 0, 0);
1906 
1907     rbb.hwndChild = hFormatBarWnd;
1908     rbb.wID = BANDID_FORMATBAR;
1909 
1910     SendMessageW(hReBarWnd, RB_INSERTBANDW, -1, (LPARAM)&rbb);
1911 
1912     hRulerWnd = CreateWindowExW(0, WC_STATICW, NULL, WS_VISIBLE | WS_CHILD,
1913                                 0, 0, 200, 10, hReBarWnd,  (HMENU)IDC_RULER, hInstance, NULL);
1914 
1915 
1916     rbb.hwndChild = hRulerWnd;
1917     rbb.wID = BANDID_RULER;
1918     rbb.fStyle |= RBBS_BREAK;
1919 
1920     SendMessageW(hReBarWnd, RB_INSERTBANDW, -1, (LPARAM)&rbb);
1921 
1922     hDLL = LoadLibraryW(wszRichEditDll);
1923     if(!hDLL)
1924     {
1925         MessageBoxWithResStringW(hWnd, MAKEINTRESOURCEW(STRING_LOAD_RICHED_FAILED), wszAppTitle,
1926                     MB_OK | MB_ICONEXCLAMATION);
1927         PostQuitMessage(1);
1928     }
1929 
1930     hEditorWnd = CreateWindowExW(WS_EX_CLIENTEDGE, RICHEDIT_CLASS20W, NULL,
1931       WS_CHILD|WS_VISIBLE|ES_SELECTIONBAR|ES_MULTILINE|ES_AUTOVSCROLL
1932       |ES_WANTRETURN|WS_VSCROLL|ES_NOHIDESEL|WS_HSCROLL,
1933       0, 0, 1000, 100, hWnd, (HMENU)IDC_EDITOR, hInstance, NULL);
1934 
1935     if (!hEditorWnd)
1936     {
1937         fprintf(stderr, "Error code %u\n", GetLastError());
1938         return -1;
1939     }
1940     assert(hEditorWnd);
1941 
1942     setup_richedit_olecallback(hEditorWnd);
1943     SetFocus(hEditorWnd);
1944     SendMessageW(hEditorWnd, EM_SETEVENTMASK, 0, ENM_SELCHANGE);
1945 
1946     set_default_font();
1947 
1948     populate_font_list(hFontListWnd);
1949     populate_size_list(hSizeListWnd);
1950     DoLoadStrings();
1951     SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
1952 
1953     ID_FINDMSGSTRING = RegisterWindowMessageW(FINDMSGSTRINGW);
1954 
1955     registry_read_filelist(hWnd);
1956     registry_read_formatopts_all(barState, wordWrap);
1957     registry_read_options();
1958     DragAcceptFiles(hWnd, TRUE);
1959 
1960     return 0;
1961 }
1962 
1963 static LRESULT OnUser( HWND hWnd )
1964 {
1965     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
1966     HWND hwndReBar = GetDlgItem(hWnd, IDC_REBAR);
1967     HWND hwndToolBar = GetDlgItem(hwndReBar, IDC_TOOLBAR);
1968     HWND hwndFormatBar = GetDlgItem(hwndReBar, IDC_FORMATBAR);
1969     int from, to;
1970     CHARFORMAT2W fmt;
1971     PARAFORMAT2 pf;
1972     GETTEXTLENGTHEX gt;
1973 
1974     ZeroMemory(&fmt, sizeof(fmt));
1975     fmt.cbSize = sizeof(fmt);
1976 
1977     ZeroMemory(&pf, sizeof(pf));
1978     pf.cbSize = sizeof(pf);
1979 
1980     gt.flags = GTL_NUMCHARS;
1981     gt.codepage = 1200;
1982 
1983     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_FIND,
1984                  SendMessageW(hwndEditor, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0) ? 1 : 0);
1985 
1986     SendMessageW(hwndEditor, EM_GETCHARFORMAT, TRUE, (LPARAM)&fmt);
1987 
1988     SendMessageW(hwndEditor, EM_GETSEL, (WPARAM)&from, (LPARAM)&to);
1989     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_UNDO,
1990       SendMessageW(hwndEditor, EM_CANUNDO, 0, 0));
1991     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_REDO,
1992       SendMessageW(hwndEditor, EM_CANREDO, 0, 0));
1993     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_CUT, from == to ? 0 : 1);
1994     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_COPY, from == to ? 0 : 1);
1995 
1996     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_FORMAT_BOLD, (fmt.dwMask & CFM_BOLD) &&
1997             (fmt.dwEffects & CFE_BOLD));
1998     SendMessageW(hwndFormatBar, TB_INDETERMINATE, ID_FORMAT_BOLD, !(fmt.dwMask & CFM_BOLD));
1999     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_FORMAT_ITALIC, (fmt.dwMask & CFM_ITALIC) &&
2000             (fmt.dwEffects & CFE_ITALIC));
2001     SendMessageW(hwndFormatBar, TB_INDETERMINATE, ID_FORMAT_ITALIC, !(fmt.dwMask & CFM_ITALIC));
2002     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_FORMAT_UNDERLINE, (fmt.dwMask & CFM_UNDERLINE) &&
2003             (fmt.dwEffects & CFE_UNDERLINE));
2004     SendMessageW(hwndFormatBar, TB_INDETERMINATE, ID_FORMAT_UNDERLINE, !(fmt.dwMask & CFM_UNDERLINE));
2005 
2006     SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
2007     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_ALIGN_LEFT, (pf.wAlignment == PFA_LEFT));
2008     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_ALIGN_CENTER, (pf.wAlignment == PFA_CENTER));
2009     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_ALIGN_RIGHT, (pf.wAlignment == PFA_RIGHT));
2010 
2011     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_BULLET, (pf.wNumbering & PFN_BULLET));
2012     return 0;
2013 }
2014 
2015 static LRESULT OnNotify( HWND hWnd, LPARAM lParam)
2016 {
2017     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
2018     HWND hwndReBar = GetDlgItem(hWnd, IDC_REBAR);
2019     NMHDR *pHdr = (NMHDR *)lParam;
2020     HWND hwndFontList = GetDlgItem(hwndReBar, IDC_FONTLIST);
2021     HWND hwndSizeList = GetDlgItem(hwndReBar, IDC_SIZELIST);
2022 
2023     if (pHdr->hwndFrom == hwndFontList || pHdr->hwndFrom == hwndSizeList)
2024     {
2025         if (pHdr->code == CBEN_ENDEDITW)
2026         {
2027             NMCBEENDEDITW *endEdit = (NMCBEENDEDITW *)lParam;
2028             if(pHdr->hwndFrom == hwndFontList)
2029             {
2030                 on_fontlist_modified(endEdit->szText);
2031             } else if (pHdr->hwndFrom == hwndSizeList)
2032             {
2033                 on_sizelist_modified(hwndSizeList,endEdit->szText);
2034             }
2035         }
2036         return 0;
2037     }
2038 
2039     if (pHdr->hwndFrom != hwndEditor)
2040         return 0;
2041 
2042     if (pHdr->code == EN_SELCHANGE)
2043     {
2044         SELCHANGE *pSC = (SELCHANGE *)lParam;
2045         char buf[128];
2046 
2047         update_font_list();
2048 
2049         sprintf( buf,"selection = %d..%d, line count=%ld",
2050                  pSC->chrg.cpMin, pSC->chrg.cpMax,
2051                 SendMessageW(hwndEditor, EM_GETLINECOUNT, 0, 0));
2052         SetWindowTextA(GetDlgItem(hWnd, IDC_STATUSBAR), buf);
2053         SendMessageW(hWnd, WM_USER, 0, 0);
2054         return 1;
2055     }
2056     return 0;
2057 }
2058 
2059 /* Copied from dlls/comdlg32/fontdlg.c */
2060 static const COLORREF textcolors[]=
2061 {
2062     0x00000000L,0x00000080L,0x00008000L,0x00008080L,
2063     0x00800000L,0x00800080L,0x00808000L,0x00808080L,
2064     0x00c0c0c0L,0x000000ffL,0x0000ff00L,0x0000ffffL,
2065     0x00ff0000L,0x00ff00ffL,0x00ffff00L,0x00FFFFFFL
2066 };
2067 
2068 static LRESULT OnCommand( HWND hWnd, WPARAM wParam, LPARAM lParam)
2069 {
2070     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
2071     static FINDREPLACEW findreplace;
2072 
2073     if ((HWND)lParam == hwndEditor)
2074         return 0;
2075 
2076     switch(LOWORD(wParam))
2077     {
2078 
2079     case ID_FILE_EXIT:
2080         PostMessageW(hWnd, WM_CLOSE, 0, 0);
2081         break;
2082 
2083     case ID_FILE_NEW:
2084         {
2085             HINSTANCE hInstance = GetModuleHandleW(0);
2086             int ret = DialogBoxW(hInstance, MAKEINTRESOURCEW(IDD_NEWFILE), hWnd, newfile_proc);
2087 
2088             if(ret != ID_NEWFILE_ABORT)
2089             {
2090                 if(prompt_save_changes())
2091                 {
2092                     SETTEXTEX st;
2093 
2094                     set_caption(NULL);
2095                     wszFileName[0] = '\0';
2096 
2097                     clear_formatting();
2098 
2099                     st.flags = ST_DEFAULT;
2100                     st.codepage = 1200;
2101                     SendMessageW(hEditorWnd, EM_SETTEXTEX, (WPARAM)&st, 0);
2102 
2103                     SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
2104                     set_fileformat(ret);
2105                     update_font_list();
2106                 }
2107             }
2108         }
2109         break;
2110 
2111     case ID_FILE_OPEN:
2112         DialogOpenFile();
2113         break;
2114 
2115     case ID_FILE_SAVE:
2116         if(wszFileName[0])
2117         {
2118             DoSaveFile(wszFileName, fileFormat);
2119             break;
2120         }
2121         /* Fall through */
2122 
2123     case ID_FILE_SAVEAS:
2124         DialogSaveFile();
2125         break;
2126 
2127     case ID_FILE_RECENT1:
2128     case ID_FILE_RECENT2:
2129     case ID_FILE_RECENT3:
2130     case ID_FILE_RECENT4:
2131         {
2132             HMENU hMenu = GetMenu(hWnd);
2133             MENUITEMINFOW mi;
2134 
2135             mi.cbSize = sizeof(MENUITEMINFOW);
2136             mi.fMask = MIIM_DATA;
2137             if(GetMenuItemInfoW(hMenu, LOWORD(wParam), FALSE, &mi))
2138                 DoOpenFile((LPWSTR)mi.dwItemData);
2139         }
2140         break;
2141 
2142     case ID_FIND:
2143         dialog_find(&findreplace, FALSE);
2144         break;
2145 
2146     case ID_FIND_NEXT:
2147         handle_findmsg(&findreplace);
2148         break;
2149 
2150     case ID_REPLACE:
2151         dialog_find(&findreplace, TRUE);
2152         break;
2153 
2154     case ID_FONTSETTINGS:
2155         dialog_choose_font();
2156         break;
2157 
2158     case ID_PRINT:
2159         dialog_print(hWnd, wszFileName);
2160         target_device(hMainWnd, wordWrap[reg_formatindex(fileFormat)]);
2161         break;
2162 
2163     case ID_PRINT_QUICK:
2164         print_quick(hMainWnd, wszFileName);
2165         target_device(hMainWnd, wordWrap[reg_formatindex(fileFormat)]);
2166         break;
2167 
2168     case ID_PREVIEW:
2169         {
2170             int index = reg_formatindex(fileFormat);
2171             DWORD tmp = barState[index];
2172             barState[index] = 1 << BANDID_STATUSBAR;
2173             set_bar_states();
2174             barState[index] = tmp;
2175             ShowWindow(hEditorWnd, FALSE);
2176 
2177             init_preview(hWnd, wszFileName);
2178 
2179             SetMenu(hWnd, NULL);
2180             InvalidateRect(0, 0, TRUE);
2181         }
2182         break;
2183 
2184     case ID_PRINTSETUP:
2185         dialog_printsetup(hWnd);
2186         target_device(hMainWnd, wordWrap[reg_formatindex(fileFormat)]);
2187         break;
2188 
2189     case ID_FORMAT_BOLD:
2190     case ID_FORMAT_ITALIC:
2191     case ID_FORMAT_UNDERLINE:
2192         {
2193         CHARFORMAT2W fmt;
2194         int effects = CFE_BOLD;
2195 
2196         ZeroMemory(&fmt, sizeof(fmt));
2197         fmt.cbSize = sizeof(fmt);
2198         SendMessageW(hwndEditor, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
2199 
2200         fmt.dwMask = CFM_BOLD;
2201 
2202         if (LOWORD(wParam) == ID_FORMAT_ITALIC)
2203         {
2204             effects = CFE_ITALIC;
2205             fmt.dwMask = CFM_ITALIC;
2206         } else if (LOWORD(wParam) == ID_FORMAT_UNDERLINE)
2207         {
2208             effects = CFE_UNDERLINE;
2209             fmt.dwMask = CFM_UNDERLINE;
2210         }
2211 
2212         fmt.dwEffects ^= effects;
2213 
2214         SendMessageW(hwndEditor, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
2215         break;
2216         }
2217 
2218     case ID_FORMAT_COLOR:
2219     {
2220         HWND hReBarWnd = GetDlgItem(hWnd, IDC_REBAR);
2221         HWND hFormatBarWnd = GetDlgItem(hReBarWnd, IDC_FORMATBAR);
2222         HMENU hPop;
2223         RECT itemrc;
2224         POINT pt;
2225         int mid;
2226         int itemidx = SendMessageW(hFormatBarWnd, TB_COMMANDTOINDEX, ID_FORMAT_COLOR, 0);
2227 
2228         SendMessageW(hFormatBarWnd, TB_GETITEMRECT, itemidx, (LPARAM)&itemrc);
2229         pt.x = itemrc.left;
2230         pt.y = itemrc.bottom;
2231         ClientToScreen(hFormatBarWnd, &pt);
2232         hPop = GetSubMenu(hColorPopupMenu, 0);
2233         mid = TrackPopupMenu(hPop, TPM_LEFTALIGN | TPM_TOPALIGN | TPM_LEFTBUTTON |
2234                                    TPM_RETURNCMD | TPM_NONOTIFY,
2235                              pt.x, pt.y, 0, hWnd, 0);
2236         if (mid >= ID_COLOR_FIRST && mid <= ID_COLOR_AUTOMATIC)
2237         {
2238             CHARFORMAT2W fmt;
2239 
2240             ZeroMemory(&fmt, sizeof(fmt));
2241             fmt.cbSize = sizeof(fmt);
2242             SendMessageW(hwndEditor, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
2243 
2244             fmt.dwMask = CFM_COLOR;
2245 
2246             if (mid < ID_COLOR_AUTOMATIC) {
2247                 fmt.crTextColor = textcolors[mid - ID_COLOR_FIRST];
2248                 fmt.dwEffects &= ~CFE_AUTOCOLOR;
2249             } else {
2250                 fmt.dwEffects |= CFE_AUTOCOLOR;
2251             }
2252 
2253             SendMessageW(hwndEditor, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
2254         }
2255         break;
2256     }
2257 
2258     case ID_EDIT_CUT:
2259         PostMessageW(hwndEditor, WM_CUT, 0, 0);
2260         break;
2261 
2262     case ID_EDIT_COPY:
2263         PostMessageW(hwndEditor, WM_COPY, 0, 0);
2264         break;
2265 
2266     case ID_EDIT_PASTE:
2267         PostMessageW(hwndEditor, WM_PASTE, 0, 0);
2268         break;
2269 
2270     case ID_EDIT_CLEAR:
2271         PostMessageW(hwndEditor, WM_CLEAR, 0, 0);
2272         break;
2273 
2274     case ID_EDIT_SELECTALL:
2275         {
2276         CHARRANGE range = {0, -1};
2277         SendMessageW(hwndEditor, EM_EXSETSEL, 0, (LPARAM)&range);
2278         /* SendMessage(hwndEditor, EM_SETSEL, 0, -1); */
2279         return 0;
2280         }
2281 
2282     case ID_EDIT_GETTEXT:
2283         {
2284         int nLen = GetWindowTextLengthW(hwndEditor);
2285         LPWSTR data = HeapAlloc( GetProcessHeap(), 0, (nLen+1)*sizeof(WCHAR) );
2286         TEXTRANGEW tr;
2287 
2288         GetWindowTextW(hwndEditor, data, nLen+1);
2289         MessageBoxW(NULL, data, wszAppTitle, MB_OK);
2290 
2291         HeapFree( GetProcessHeap(), 0, data);
2292         data = HeapAlloc(GetProcessHeap(), 0, (nLen+1)*sizeof(WCHAR));
2293         tr.chrg.cpMin = 0;
2294         tr.chrg.cpMax = nLen;
2295         tr.lpstrText = data;
2296         SendMessageW(hwndEditor, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
2297         MessageBoxW(NULL, data, wszAppTitle, MB_OK);
2298         HeapFree( GetProcessHeap(), 0, data );
2299 
2300         /* SendMessage(hwndEditor, EM_SETSEL, 0, -1); */
2301         return 0;
2302         }
2303 
2304     case ID_EDIT_CHARFORMAT:
2305     case ID_EDIT_DEFCHARFORMAT:
2306         {
2307         CHARFORMAT2W cf;
2308 
2309         ZeroMemory(&cf, sizeof(cf));
2310         cf.cbSize = sizeof(cf);
2311         cf.dwMask = 0;
2312         SendMessageW(hwndEditor, EM_GETCHARFORMAT,
2313                      LOWORD(wParam) == ID_EDIT_CHARFORMAT, (LPARAM)&cf);
2314         return 0;
2315         }
2316 
2317     case ID_EDIT_PARAFORMAT:
2318         {
2319         PARAFORMAT2 pf;
2320         ZeroMemory(&pf, sizeof(pf));
2321         pf.cbSize = sizeof(pf);
2322         SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
2323         return 0;
2324         }
2325 
2326     case ID_EDIT_SELECTIONINFO:
2327         {
2328         CHARRANGE range = {0, -1};
2329         char buf[128];
2330         WCHAR *data = NULL;
2331 
2332         SendMessageW(hwndEditor, EM_EXGETSEL, 0, (LPARAM)&range);
2333         data = HeapAlloc(GetProcessHeap(), 0, sizeof(*data) * (range.cpMax-range.cpMin+1));
2334         SendMessageW(hwndEditor, EM_GETSELTEXT, 0, (LPARAM)data);
2335         sprintf(buf, "Start = %d, End = %d", range.cpMin, range.cpMax);
2336         MessageBoxA(hWnd, buf, "Editor", MB_OK);
2337         MessageBoxW(hWnd, data, wszAppTitle, MB_OK);
2338         HeapFree( GetProcessHeap(), 0, data);
2339         /* SendMessage(hwndEditor, EM_SETSEL, 0, -1); */
2340         return 0;
2341         }
2342 
2343     case ID_EDIT_READONLY:
2344         {
2345         LONG nStyle = GetWindowLongW(hwndEditor, GWL_STYLE);
2346         if (nStyle & ES_READONLY)
2347             SendMessageW(hwndEditor, EM_SETREADONLY, 0, 0);
2348         else
2349             SendMessageW(hwndEditor, EM_SETREADONLY, 1, 0);
2350         return 0;
2351         }
2352 
2353     case ID_EDIT_MODIFIED:
2354         if (SendMessageW(hwndEditor, EM_GETMODIFY, 0, 0))
2355             SendMessageW(hwndEditor, EM_SETMODIFY, 0, 0);
2356         else
2357             SendMessageW(hwndEditor, EM_SETMODIFY, 1, 0);
2358         return 0;
2359 
2360     case ID_EDIT_UNDO:
2361         SendMessageW(hwndEditor, EM_UNDO, 0, 0);
2362         return 0;
2363 
2364     case ID_EDIT_REDO:
2365         SendMessageW(hwndEditor, EM_REDO, 0, 0);
2366         return 0;
2367 
2368     case ID_BULLET:
2369         {
2370             PARAFORMAT pf;
2371 
2372             pf.cbSize = sizeof(pf);
2373             pf.dwMask = PFM_NUMBERING;
2374             SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
2375 
2376             pf.dwMask |=  PFM_OFFSET;
2377 
2378             if(pf.wNumbering == PFN_BULLET)
2379             {
2380                 pf.wNumbering = 0;
2381                 pf.dxOffset = 0;
2382             } else
2383             {
2384                 pf.wNumbering = PFN_BULLET;
2385                 pf.dxOffset = 720;
2386             }
2387 
2388             SendMessageW(hwndEditor, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
2389         }
2390         break;
2391 
2392     case ID_ALIGN_LEFT:
2393     case ID_ALIGN_CENTER:
2394     case ID_ALIGN_RIGHT:
2395         {
2396         PARAFORMAT2 pf;
2397 
2398         pf.cbSize = sizeof(pf);
2399         pf.dwMask = PFM_ALIGNMENT;
2400         switch(LOWORD(wParam)) {
2401         case ID_ALIGN_LEFT: pf.wAlignment = PFA_LEFT; break;
2402         case ID_ALIGN_CENTER: pf.wAlignment = PFA_CENTER; break;
2403         case ID_ALIGN_RIGHT: pf.wAlignment = PFA_RIGHT; break;
2404         }
2405         SendMessageW(hwndEditor, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
2406         break;
2407         }
2408 
2409     case ID_BACK_1:
2410         SendMessageW(hwndEditor, EM_SETBKGNDCOLOR, 1, 0);
2411         break;
2412 
2413     case ID_BACK_2:
2414         SendMessageW(hwndEditor, EM_SETBKGNDCOLOR, 0, RGB(255,255,192));
2415         break;
2416 
2417     case ID_TOGGLE_TOOLBAR:
2418         set_toolbar_state(BANDID_TOOLBAR, !is_bar_visible(BANDID_TOOLBAR));
2419         update_window();
2420         break;
2421 
2422     case ID_TOGGLE_FORMATBAR:
2423         set_toolbar_state(BANDID_FONTLIST, !is_bar_visible(BANDID_FORMATBAR));
2424         set_toolbar_state(BANDID_SIZELIST, !is_bar_visible(BANDID_FORMATBAR));
2425         set_toolbar_state(BANDID_FORMATBAR, !is_bar_visible(BANDID_FORMATBAR));
2426         update_window();
2427         break;
2428 
2429     case ID_TOGGLE_STATUSBAR:
2430         set_statusbar_state(!is_bar_visible(BANDID_STATUSBAR));
2431         update_window();
2432         break;
2433 
2434     case ID_TOGGLE_RULER:
2435         set_toolbar_state(BANDID_RULER, !is_bar_visible(BANDID_RULER));
2436         update_window();
2437         break;
2438 
2439     case ID_DATETIME:
2440         DialogBoxW(GetModuleHandleW(0), MAKEINTRESOURCEW(IDD_DATETIME), hWnd, datetime_proc);
2441         break;
2442 
2443     case ID_PARAFORMAT:
2444         DialogBoxW(GetModuleHandleW(0), MAKEINTRESOURCEW(IDD_PARAFORMAT), hWnd, paraformat_proc);
2445         break;
2446 
2447     case ID_TABSTOPS:
2448         DialogBoxW(GetModuleHandleW(0), MAKEINTRESOURCEW(IDD_TABSTOPS), hWnd, tabstops_proc);
2449         break;
2450 
2451     case ID_ABOUT:
2452         dialog_about();
2453         break;
2454 
2455     case ID_VIEWPROPERTIES:
2456         dialog_viewproperties();
2457         break;
2458 
2459     case IDC_FONTLIST:
2460         if (HIWORD(wParam) == CBN_SELENDOK)
2461         {
2462             WCHAR buffer[LF_FACESIZE];
2463             HWND hwndFontList = (HWND)lParam;
2464             get_comboexlist_selection(hwndFontList, buffer, LF_FACESIZE);
2465             on_fontlist_modified(buffer);
2466         }
2467         break;
2468 
2469     case IDC_SIZELIST:
2470         if (HIWORD(wParam) == CBN_SELENDOK)
2471         {
2472             WCHAR buffer[MAX_STRING_LEN+1];
2473             HWND hwndSizeList = (HWND)lParam;
2474             get_comboexlist_selection(hwndSizeList, buffer, MAX_STRING_LEN+1);
2475             on_sizelist_modified(hwndSizeList, buffer);
2476         }
2477         break;
2478 
2479     default:
2480         SendMessageW(hwndEditor, WM_COMMAND, wParam, lParam);
2481         break;
2482     }
2483     return 0;
2484 }
2485 
2486 static LRESULT OnInitPopupMenu( HWND hWnd, WPARAM wParam )
2487 {
2488     HMENU hMenu = (HMENU)wParam;
2489     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
2490     HWND hwndStatus = GetDlgItem(hWnd, IDC_STATUSBAR);
2491     PARAFORMAT pf;
2492     int nAlignment = -1;
2493     int selFrom, selTo;
2494     GETTEXTLENGTHEX gt;
2495     LRESULT textLength;
2496     MENUITEMINFOW mi;
2497 
2498     SendMessageW(hEditorWnd, EM_GETSEL, (WPARAM)&selFrom, (LPARAM)&selTo);
2499     EnableMenuItem(hMenu, ID_EDIT_COPY, (selFrom == selTo) ? MF_GRAYED : MF_ENABLED);
2500     EnableMenuItem(hMenu, ID_EDIT_CUT, (selFrom == selTo) ? MF_GRAYED : MF_ENABLED);
2501 
2502     pf.cbSize = sizeof(PARAFORMAT);
2503     SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
2504     CheckMenuItem(hMenu, ID_EDIT_READONLY,
2505       (GetWindowLongW(hwndEditor, GWL_STYLE) & ES_READONLY) ? MF_CHECKED : MF_UNCHECKED);
2506     CheckMenuItem(hMenu, ID_EDIT_MODIFIED,
2507       SendMessageW(hwndEditor, EM_GETMODIFY, 0, 0) ? MF_CHECKED : MF_UNCHECKED);
2508     if (pf.dwMask & PFM_ALIGNMENT)
2509         nAlignment = pf.wAlignment;
2510     CheckMenuItem(hMenu, ID_ALIGN_LEFT, (nAlignment == PFA_LEFT) ?  MF_CHECKED : MF_UNCHECKED);
2511     CheckMenuItem(hMenu, ID_ALIGN_CENTER, (nAlignment == PFA_CENTER) ?  MF_CHECKED : MF_UNCHECKED);
2512     CheckMenuItem(hMenu, ID_ALIGN_RIGHT, (nAlignment == PFA_RIGHT) ?  MF_CHECKED : MF_UNCHECKED);
2513     CheckMenuItem(hMenu, ID_BULLET, ((pf.wNumbering == PFN_BULLET) ?  MF_CHECKED : MF_UNCHECKED));
2514     EnableMenuItem(hMenu, ID_EDIT_UNDO, SendMessageW(hwndEditor, EM_CANUNDO, 0, 0) ?
2515             MF_ENABLED : MF_GRAYED);
2516     EnableMenuItem(hMenu, ID_EDIT_REDO, SendMessageW(hwndEditor, EM_CANREDO, 0, 0) ?
2517             MF_ENABLED : MF_GRAYED);
2518 
2519     CheckMenuItem(hMenu, ID_TOGGLE_TOOLBAR, is_bar_visible(BANDID_TOOLBAR) ?
2520             MF_CHECKED : MF_UNCHECKED);
2521 
2522     CheckMenuItem(hMenu, ID_TOGGLE_FORMATBAR, is_bar_visible(BANDID_FORMATBAR) ?
2523             MF_CHECKED : MF_UNCHECKED);
2524 
2525     CheckMenuItem(hMenu, ID_TOGGLE_STATUSBAR, IsWindowVisible(hwndStatus) ?
2526             MF_CHECKED : MF_UNCHECKED);
2527 
2528     CheckMenuItem(hMenu, ID_TOGGLE_RULER, is_bar_visible(BANDID_RULER) ? MF_CHECKED : MF_UNCHECKED);
2529 
2530     gt.flags = GTL_NUMCHARS;
2531     gt.codepage = 1200;
2532     textLength = SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0);
2533     EnableMenuItem(hMenu, ID_FIND, textLength ? MF_ENABLED : MF_GRAYED);
2534 
2535     mi.cbSize = sizeof(mi);
2536     mi.fMask = MIIM_DATA;
2537 
2538     GetMenuItemInfoW(hMenu, ID_FIND_NEXT, FALSE, &mi);
2539 
2540     EnableMenuItem(hMenu, ID_FIND_NEXT, (textLength && mi.dwItemData) ?  MF_ENABLED : MF_GRAYED);
2541 
2542     EnableMenuItem(hMenu, ID_REPLACE, textLength ? MF_ENABLED : MF_GRAYED);
2543 
2544     return 0;
2545 }
2546 
2547 static LRESULT OnSize( HWND hWnd, WPARAM wParam, LPARAM lParam )
2548 {
2549     int nStatusSize = 0;
2550     RECT rc;
2551     HWND hwndEditor = preview_isactive() ? GetDlgItem(hWnd, IDC_PREVIEW) : GetDlgItem(hWnd, IDC_EDITOR);
2552     HWND hwndStatusBar = GetDlgItem(hWnd, IDC_STATUSBAR);
2553     HWND hwndReBar = GetDlgItem(hWnd, IDC_REBAR);
2554     HWND hRulerWnd = GetDlgItem(hwndReBar, IDC_RULER);
2555     int rebarHeight = 0;
2556 
2557     if (hwndStatusBar)
2558     {
2559         SendMessageW(hwndStatusBar, WM_SIZE, 0, 0);
2560         if (IsWindowVisible(hwndStatusBar))
2561         {
2562             GetClientRect(hwndStatusBar, &rc);
2563             nStatusSize = rc.bottom - rc.top;
2564         } else
2565         {
2566             nStatusSize = 0;
2567         }
2568     }
2569     if (hwndReBar)
2570     {
2571         rebarHeight = SendMessageW(hwndReBar, RB_GETBARHEIGHT, 0, 0);
2572 
2573         MoveWindow(hwndReBar, 0, 0, LOWORD(lParam), rebarHeight, TRUE);
2574     }
2575     if (hwndEditor)
2576     {
2577         GetClientRect(hWnd, &rc);
2578         MoveWindow(hwndEditor, 0, rebarHeight, rc.right, rc.bottom-nStatusSize-rebarHeight, TRUE);
2579     }
2580 
2581     redraw_ruler(hRulerWnd);
2582 
2583     return DefWindowProcW(hWnd, WM_SIZE, wParam, lParam);
2584 }
2585 
2586 static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2587 {
2588     if(msg == ID_FINDMSGSTRING)
2589         return handle_findmsg((LPFINDREPLACEW)lParam);
2590 
2591     switch(msg)
2592     {
2593     case WM_CREATE:
2594         return OnCreate( hWnd );
2595 
2596     case WM_USER:
2597         return OnUser( hWnd );
2598 
2599     case WM_NOTIFY:
2600         return OnNotify( hWnd, lParam );
2601 
2602     case WM_COMMAND:
2603         if(preview_isactive())
2604         {
2605             return preview_command( hWnd, wParam );
2606         }
2607 
2608         return OnCommand( hWnd, wParam, lParam );
2609 
2610     case WM_DESTROY:
2611         PostQuitMessage(0);
2612         break;
2613 
2614     case WM_CLOSE:
2615         if(preview_isactive())
2616         {
2617             preview_exit(hWnd);
2618         } else if(prompt_save_changes())
2619         {
2620             registry_set_options(hMainWnd);
2621             registry_set_formatopts_all(barState, wordWrap);
2622             PostQuitMessage(0);
2623         }
2624         break;
2625 
2626     case WM_ACTIVATE:
2627         if (LOWORD(wParam))
2628             SetFocus(GetDlgItem(hWnd, IDC_EDITOR));
2629         return 0;
2630 
2631     case WM_INITMENUPOPUP:
2632         return OnInitPopupMenu( hWnd, wParam );
2633 
2634     case WM_SIZE:
2635         return OnSize( hWnd, wParam, lParam );
2636 
2637     case WM_CONTEXTMENU:
2638         return DefWindowProcW(hWnd, msg, wParam, lParam);
2639 
2640     case WM_DROPFILES:
2641         {
2642             WCHAR file[MAX_PATH];
2643             DragQueryFileW((HDROP)wParam, 0, file, MAX_PATH);
2644             DragFinish((HDROP)wParam);
2645 
2646             if(prompt_save_changes())
2647                 DoOpenFile(file);
2648         }
2649         break;
2650     case WM_PAINT:
2651         if(!preview_isactive())
2652             return DefWindowProcW(hWnd, msg, wParam, lParam);
2653 
2654     default:
2655         return DefWindowProcW(hWnd, msg, wParam, lParam);
2656     }
2657 
2658     return 0;
2659 }
2660 
2661 int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hOldInstance, LPSTR szCmdParagraph, int nCmdShow)
2662 {
2663     INITCOMMONCONTROLSEX classes = {8, ICC_BAR_CLASSES|ICC_COOL_CLASSES|ICC_USEREX_CLASSES};
2664     HACCEL hAccel;
2665     WNDCLASSEXW wc;
2666     MSG msg;
2667     RECT rc;
2668     UINT_PTR hPrevRulerProc;
2669     HWND hRulerWnd;
2670     POINTL EditPoint;
2671     DWORD bMaximized;
2672     static const WCHAR wszAccelTable[] = {'M','A','I','N','A','C','C','E','L',
2673                                           'T','A','B','L','E','\0'};
2674 
2675     InitCommonControlsEx(&classes);
2676 
2677     switch (GetUserDefaultUILanguage())
2678     {
2679         case MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT):
2680             SetProcessDefaultLayout(LAYOUT_RTL);
2681             break;
2682 
2683         default:
2684             break;
2685     }
2686 
2687     hAccel = LoadAcceleratorsW(hInstance, wszAccelTable);
2688 
2689     wc.cbSize = sizeof(wc);
2690     wc.style = 0;
2691     wc.lpfnWndProc = WndProc;
2692     wc.cbClsExtra = 0;
2693     wc.cbWndExtra = 4;
2694     wc.hInstance = hInstance;
2695     wc.hIcon = LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_WORDPAD));
2696     wc.hIconSm = LoadImageW(hInstance, MAKEINTRESOURCEW(IDI_WORDPAD), IMAGE_ICON,
2697                             GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED);
2698     wc.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
2699     wc.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2700     wc.lpszMenuName = MAKEINTRESOURCEW(IDM_MAINMENU);
2701     wc.lpszClassName = wszMainWndClass;
2702     RegisterClassExW(&wc);
2703 
2704     wc.style = 0;
2705     wc.lpfnWndProc = preview_proc;
2706     wc.cbClsExtra = 0;
2707     wc.cbWndExtra = 0;
2708     wc.hInstance = hInstance;
2709     wc.hIcon = NULL;
2710     wc.hIconSm = NULL;
2711     wc.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
2712     wc.hbrBackground = NULL;
2713     wc.lpszMenuName = NULL;
2714     wc.lpszClassName = wszPreviewWndClass;
2715     RegisterClassExW(&wc);
2716 
2717     registry_read_winrect(&rc);
2718     hMainWnd = CreateWindowExW(0, wszMainWndClass, wszAppTitle, WS_CLIPCHILDREN|WS_OVERLAPPEDWINDOW,
2719       rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, NULL, NULL, hInstance, NULL);
2720     registry_read_maximized(&bMaximized);
2721     if ((nCmdShow == SW_SHOWNORMAL || nCmdShow == SW_SHOWDEFAULT)
2722 	     && bMaximized)
2723         nCmdShow = SW_SHOWMAXIMIZED;
2724     ShowWindow(hMainWnd, nCmdShow);
2725 
2726     set_caption(NULL);
2727     set_bar_states();
2728     set_fileformat(SF_RTF);
2729     hColorPopupMenu = LoadMenuW(hInstance, MAKEINTRESOURCEW(IDM_COLOR_POPUP));
2730     get_default_printer_opts();
2731     target_device(hMainWnd, wordWrap[reg_formatindex(fileFormat)]);
2732 
2733     hRulerWnd = GetDlgItem(GetDlgItem(hMainWnd, IDC_REBAR), IDC_RULER);
2734     SendMessageW(GetDlgItem(hMainWnd, IDC_EDITOR), EM_POSFROMCHAR, (WPARAM)&EditPoint, 0);
2735     hPrevRulerProc = SetWindowLongPtrW(hRulerWnd, GWLP_WNDPROC, (UINT_PTR)ruler_proc);
2736     SendMessageW(hRulerWnd, WM_USER, (WPARAM)&EditPoint, hPrevRulerProc);
2737 
2738     HandleCommandLine(GetCommandLineW());
2739 
2740     while(GetMessageW(&msg,0,0,0))
2741     {
2742         if (IsDialogMessageW(hFindWnd, &msg))
2743             continue;
2744 
2745         if (TranslateAcceleratorW(hMainWnd, hAccel, &msg))
2746             continue;
2747         TranslateMessage(&msg);
2748         DispatchMessageW(&msg);
2749         if (!PeekMessageW(&msg, 0, 0, 0, PM_NOREMOVE))
2750             SendMessageW(hMainWnd, WM_USER, 0, 0);
2751     }
2752 
2753     return 0;
2754 }
2755