mshtml: Set the SETUP_IS_CHROME_WRAPPER to FALSE as the embedded Gecko is always...
[wine] / programs / wordpad / wordpad.c
1 /*
2  * Wordpad implementation
3  *
4  * Copyright 2004 by Krzysztof Foltman
5  * Copyright 2007 by Alexander N. Sørnes <alex@thehandofagony.com>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #define WIN32_LEAN_AND_MEAN
23 #define _WIN32_IE 0x0400
24
25 #define MAX_STRING_LEN 255
26
27 #include <stdarg.h>
28 #include <ctype.h>
29 #include <stdio.h>
30 #include <assert.h>
31
32 #include <windows.h>
33 #include <richedit.h>
34 #include <commctrl.h>
35 #include <commdlg.h>
36 #include <shlobj.h>
37 #include <shellapi.h>
38 #include <math.h>
39 #include <errno.h>
40
41 #include "resource.h"
42
43 #ifdef NONAMELESSUNION
44 # define U(x)  (x).u
45 # define U2(x) (x).u2
46 # define U3(x) (x).u3
47 #else
48 # define U(x)  (x)
49 # define U2(x) (x)
50 # define U3(x) (x)
51 #endif
52
53 /* use LoadString */
54 static const WCHAR xszAppTitle[] = {'W','i','n','e',' ','W','o','r','d','p','a','d',0};
55 static const WCHAR xszMainMenu[] = {'M','A','I','N','M','E','N','U',0};
56
57 static const WCHAR wszRichEditClass[] = {'R','I','C','H','E','D','I','T','2','0','W',0};
58 static const WCHAR wszMainWndClass[] = {'W','O','R','D','P','A','D','T','O','P',0};
59 static const WCHAR wszAppTitle[] = {'W','i','n','e',' ','W','o','r','d','p','a','d',0};
60
61 static const WCHAR key_recentfiles[] = {'R','e','c','e','n','t',' ','f','i','l','e',
62                                         ' ','l','i','s','t',0};
63 static const WCHAR key_options[] = {'O','p','t','i','o','n','s',0};
64 static const WCHAR key_rtf[] = {'R','T','F',0};
65 static const WCHAR key_text[] = {'T','e','x','t',0};
66
67 static const WCHAR var_file[] = {'F','i','l','e','%','d',0};
68 static const WCHAR var_framerect[] = {'F','r','a','m','e','R','e','c','t',0};
69 static const WCHAR var_barstate0[] = {'B','a','r','S','t','a','t','e','0',0};
70 static const WCHAR var_pagemargin[] = {'P','a','g','e','M','a','r','g','i','n',0};
71
72 static const WCHAR stringFormat[] = {'%','2','d','\0'};
73
74 static HWND hMainWnd;
75 static HWND hEditorWnd;
76 static HWND hFindWnd;
77 static HMENU hPopupMenu;
78
79 static UINT ID_FINDMSGSTRING;
80
81 static WCHAR wszFilter[MAX_STRING_LEN*4+6*3+5];
82 static WCHAR wszDefaultFileName[MAX_STRING_LEN];
83 static WCHAR wszSaveChanges[MAX_STRING_LEN];
84 static WCHAR wszPrintFilter[MAX_STRING_LEN*2+6+4+1];
85 static WCHAR units_cmW[MAX_STRING_LEN];
86
87 static char units_cmA[MAX_STRING_LEN];
88
89 static LRESULT OnSize( HWND hWnd, WPARAM wParam, LPARAM lParam );
90
91 /* Load string resources */
92 static void DoLoadStrings(void)
93 {
94     LPWSTR p = wszFilter;
95     static const WCHAR files_rtf[] = {'*','.','r','t','f','\0'};
96     static const WCHAR files_txt[] = {'*','.','t','x','t','\0'};
97     static const WCHAR files_all[] = {'*','.','*','\0'};
98     static const WCHAR files_prn[] = {'*','.','P','R','N',0};
99     HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hMainWnd, GWLP_HINSTANCE);
100
101     LoadStringW(hInstance, STRING_RICHTEXT_FILES_RTF, p, MAX_STRING_LEN);
102     p += lstrlenW(p) + 1;
103     lstrcpyW(p, files_rtf);
104     p += lstrlenW(p) + 1;
105     LoadStringW(hInstance, STRING_TEXT_FILES_TXT, p, MAX_STRING_LEN);
106     p += lstrlenW(p) + 1;
107     lstrcpyW(p, files_txt);
108     p += lstrlenW(p) + 1;
109     LoadStringW(hInstance, STRING_TEXT_FILES_UNICODE_TXT, p, MAX_STRING_LEN);
110     p += lstrlenW(p) + 1;
111     lstrcpyW(p, files_txt);
112     p += lstrlenW(p) + 1;
113     LoadStringW(hInstance, STRING_ALL_FILES, p, MAX_STRING_LEN);
114     p += lstrlenW(p) + 1;
115     lstrcpyW(p, files_all);
116     p += lstrlenW(p) + 1;
117     *p = '\0';
118
119     p = wszPrintFilter;
120     LoadStringW(hInstance, STRING_PRINTER_FILES_PRN, p, MAX_STRING_LEN);
121     p += lstrlenW(p) + 1;
122     lstrcpyW(p, files_prn);
123     p += lstrlenW(p) + 1;
124     LoadStringW(hInstance, STRING_ALL_FILES, p, MAX_STRING_LEN);
125     p += lstrlenW(p) + 1;
126     lstrcpyW(p, files_all);
127     p += lstrlenW(p) + 1;
128     *p = 0;
129
130     p = wszDefaultFileName;
131     LoadStringW(hInstance, STRING_DEFAULT_FILENAME, p, MAX_STRING_LEN);
132
133     p = wszSaveChanges;
134     LoadStringW(hInstance, STRING_PROMPT_SAVE_CHANGES, p, MAX_STRING_LEN);
135
136     LoadStringA(hInstance, STRING_UNITS_CM, units_cmA, MAX_STRING_LEN);
137     LoadStringW(hInstance, STRING_UNITS_CM, units_cmW, MAX_STRING_LEN);
138 }
139
140 static void AddButton(HWND hwndToolBar, int nImage, int nCommand)
141 {
142     TBBUTTON button;
143
144     ZeroMemory(&button, sizeof(button));
145     button.iBitmap = nImage;
146     button.idCommand = nCommand;
147     button.fsState = TBSTATE_ENABLED;
148     button.fsStyle = TBSTYLE_BUTTON;
149     button.dwData = 0;
150     button.iString = -1;
151     SendMessageW(hwndToolBar, TB_ADDBUTTONSW, 1, (LPARAM)&button);
152 }
153
154 static void AddTextButton(HWND hWnd, int string, int command, int id)
155 {
156     REBARBANDINFOW rb;
157     HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hMainWnd, GWLP_HINSTANCE);
158     static const WCHAR button[] = {'B','U','T','T','O','N',0};
159     WCHAR text[MAX_STRING_LEN];
160     HWND hButton;
161     RECT rc;
162
163     LoadStringW(hInstance, string, text, MAX_STRING_LEN);
164     hButton = CreateWindowW(button, text,
165                             WS_VISIBLE | WS_CHILD, 5, 5, 100, 15,
166                             hMainWnd, (HMENU)command, hInstance, NULL);
167
168     rb.cbSize = sizeof(rb);
169     rb.fMask = RBBIM_SIZE | RBBIM_CHILDSIZE | RBBIM_STYLE | RBBIM_CHILD | RBBIM_IDEALSIZE | RBBIM_ID;
170     rb.fStyle = RBBS_NOGRIPPER | RBBS_VARIABLEHEIGHT;
171     rb.hwndChild = hButton;
172     rb.cyChild = rb.cyMinChild = 22;
173     rb.cx = rb.cxMinChild = 90;
174     rb.cxIdeal = 100;
175     rb.wID = id;
176
177     rc.bottom = 22;
178     rc.right = 90;
179
180     SendMessageW(hWnd, RB_INSERTBAND, -1, (LPARAM)&rb);
181     SetWindowPos(hButton, 0, 0, 0, 90, 22, SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER);
182 }
183
184 static void AddSeparator(HWND hwndToolBar)
185 {
186     TBBUTTON button;
187
188     ZeroMemory(&button, sizeof(button));
189     button.iBitmap = -1;
190     button.idCommand = 0;
191     button.fsState = 0;
192     button.fsStyle = TBSTYLE_SEP;
193     button.dwData = 0;
194     button.iString = -1;
195     SendMessageW(hwndToolBar, TB_ADDBUTTONSW, 1, (LPARAM)&button);
196 }
197
198 static DWORD CALLBACK stream_in(DWORD_PTR cookie, LPBYTE buffer, LONG cb, LONG *pcb)
199 {
200     HANDLE hFile = (HANDLE)cookie;
201     DWORD read;
202
203     if(!ReadFile(hFile, buffer, cb, &read, 0))
204         return 1;
205
206     *pcb = read;
207
208     return 0;
209 }
210
211 static DWORD CALLBACK stream_out(DWORD_PTR cookie, LPBYTE buffer, LONG cb, LONG *pcb)
212 {
213     DWORD written;
214     int ret;
215     HANDLE hFile = (HANDLE)cookie;
216
217     ret = WriteFile(hFile, buffer, cb, &written, 0);
218
219     if(!ret || (cb != written))
220         return 1;
221
222     *pcb = cb;
223
224     return 0;
225 }
226
227
228 static LPWSTR file_basename(LPWSTR path)
229 {
230     LPWSTR pos = path + lstrlenW(path);
231
232     while(pos > path)
233     {
234         if(*pos == '\\' || *pos == '/')
235         {
236             pos++;
237             break;
238         }
239         pos--;
240     }
241     return pos;
242 }
243
244 static WCHAR wszFileName[MAX_PATH];
245 static WPARAM fileFormat = SF_RTF;
246
247 static void set_caption(LPCWSTR wszNewFileName)
248 {
249     static const WCHAR wszSeparator[] = {' ','-',' '};
250     WCHAR *wszCaption;
251     SIZE_T length = 0;
252
253     if(!wszNewFileName)
254         wszNewFileName = wszDefaultFileName;
255     else
256         wszNewFileName = file_basename((LPWSTR)wszNewFileName);
257
258     wszCaption = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
259                 lstrlenW(wszNewFileName)*sizeof(WCHAR)+sizeof(wszSeparator)+sizeof(wszAppTitle));
260
261     if(!wszCaption)
262         return;
263
264     memcpy(wszCaption, wszNewFileName, lstrlenW(wszNewFileName)*sizeof(WCHAR));
265     length += lstrlenW(wszNewFileName);
266     memcpy(wszCaption + length, wszSeparator, sizeof(wszSeparator));
267     length += sizeof(wszSeparator) / sizeof(WCHAR);
268     memcpy(wszCaption + length, wszAppTitle, sizeof(wszAppTitle));
269
270     SetWindowTextW(hMainWnd, wszCaption);
271
272     HeapFree(GetProcessHeap(), 0, wszCaption);
273 }
274
275 static LRESULT registry_get_handle(HKEY *hKey, LPDWORD action, LPCWSTR subKey)
276 {
277     LONG ret;
278     static const WCHAR wszProgramKey[] = {'S','o','f','t','w','a','r','e','\\',
279         'M','i','c','r','o','s','o','f','t','\\',
280         'W','i','n','d','o','w','s','\\',
281         'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
282         'A','p','p','l','e','t','s','\\',
283         'W','o','r','d','p','a','d',0};
284     LPWSTR key = (LPWSTR)wszProgramKey;
285
286     if(subKey)
287     {
288         WCHAR backslash[] = {'\\',0};
289         key = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
290                         (lstrlenW(wszProgramKey)+lstrlenW(subKey)+lstrlenW(backslash)+1)
291                         *sizeof(WCHAR));
292
293         if(!key)
294             return 1;
295
296         lstrcpyW(key, wszProgramKey);
297         lstrcatW(key, backslash);
298         lstrcatW(key, subKey);
299     }
300
301     if(action)
302     {
303         ret = RegCreateKeyExW(HKEY_CURRENT_USER, key, 0, NULL, REG_OPTION_NON_VOLATILE,
304                               KEY_READ | KEY_WRITE, NULL, hKey, action);
305     } else
306     {
307         ret = RegOpenKeyExW(HKEY_CURRENT_USER, key, 0, KEY_READ | KEY_WRITE, hKey);
308     }
309
310     if(subKey)
311         HeapFree(GetProcessHeap(), 0, key);
312
313     return ret;
314 }
315
316 static RECT margins;
317
318 static void registry_set_options(void)
319 {
320     HKEY hKey;
321     DWORD action;
322
323     if(registry_get_handle(&hKey, &action, (LPWSTR)key_options) == ERROR_SUCCESS)
324     {
325         RECT rc;
326
327         GetWindowRect(hMainWnd, &rc);
328
329         RegSetValueExW(hKey, var_framerect, 0, REG_BINARY, (LPBYTE)&rc, sizeof(RECT));
330
331         RegSetValueExW(hKey, var_pagemargin, 0, REG_BINARY, (LPBYTE)&margins, sizeof(RECT));
332     }
333 }
334
335 static RECT registry_read_winrect(void)
336 {
337     HKEY hKey;
338     RECT rc;
339     DWORD size = sizeof(RECT);
340
341     ZeroMemory(&rc, sizeof(RECT));
342     if(registry_get_handle(&hKey, 0, (LPWSTR)key_options) != ERROR_SUCCESS ||
343        RegQueryValueExW(hKey, var_framerect, 0, NULL, (LPBYTE)&rc, &size) !=
344        ERROR_SUCCESS || size != sizeof(RECT))
345     {
346         rc.top = 0;
347         rc.left = 0;
348         rc.bottom = 300;
349         rc.right = 600;
350     }
351
352     RegCloseKey(hKey);
353     return rc;
354 }
355
356 static void truncate_path(LPWSTR file, LPWSTR out, LPWSTR pos1, LPWSTR pos2)
357 {
358     static const WCHAR dots[] = {'.','.','.',0};
359
360     *++pos1 = 0;
361
362     lstrcatW(out, file);
363     lstrcatW(out, dots);
364     lstrcatW(out, pos2);
365 }
366
367 static void format_filelist_filename(LPWSTR file, LPWSTR out)
368 {
369     LPWSTR pos_basename;
370     LPWSTR truncpos1, truncpos2;
371     WCHAR myDocs[MAX_STRING_LEN];
372
373     SHGetFolderPathW(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, (LPWSTR)&myDocs);
374     pos_basename = file_basename(file);
375     truncpos1 = NULL;
376     truncpos2 = NULL;
377
378     *(pos_basename-1) = 0;
379     if(!lstrcmpiW(file, myDocs) || (lstrlenW(pos_basename) > FILELIST_ENTRY_LENGTH))
380     {
381         truncpos1 = pos_basename;
382         *(pos_basename-1) = '\\';
383     } else
384     {
385         LPWSTR pos;
386         BOOL morespace = FALSE;
387
388         *(pos_basename-1) = '\\';
389
390         for(pos = file; pos < pos_basename; pos++)
391         {
392             if(*pos == '\\' || *pos == '/')
393             {
394                 if(truncpos1)
395                 {
396                     if((pos - file + lstrlenW(pos_basename)) > FILELIST_ENTRY_LENGTH)
397                         break;
398
399                     truncpos1 = pos;
400                     morespace = TRUE;
401                     break;
402                 }
403
404                 if((pos - file + lstrlenW(pos_basename)) > FILELIST_ENTRY_LENGTH)
405                     break;
406
407                 truncpos1 = pos;
408             }
409         }
410
411         if(morespace)
412         {
413             for(pos = pos_basename; pos >= truncpos1; pos--)
414             {
415                 if(*pos == '\\' || *pos == '/')
416                 {
417                     if((truncpos1 - file + lstrlenW(pos_basename) + pos_basename - pos) > FILELIST_ENTRY_LENGTH)
418                         break;
419
420                     truncpos2 = pos;
421                 }
422             }
423         }
424     }
425
426     if(truncpos1 == pos_basename)
427         lstrcatW(out, pos_basename);
428     else if(truncpos1 == truncpos2 || !truncpos2)
429         lstrcatW(out, file);
430     else
431         truncate_path(file, out, truncpos1, truncpos2 ? truncpos2 : (pos_basename-1));
432 }
433
434 static void registry_read_filelist(HWND hMainWnd)
435 {
436     HKEY hFileKey;
437
438     if(registry_get_handle(&hFileKey, 0, key_recentfiles) == ERROR_SUCCESS)
439     {
440         WCHAR itemText[MAX_PATH+3], buffer[MAX_PATH];
441         /* The menu item name is not the same as the file name, so we need to store
442            the file name here */
443         static WCHAR file1[MAX_PATH], file2[MAX_PATH], file3[MAX_PATH], file4[MAX_PATH];
444         WCHAR numFormat[] = {'&','%','d',' ',0};
445         LPWSTR pFile[] = {file1, file2, file3, file4};
446         DWORD pathSize = MAX_PATH*sizeof(WCHAR);
447         int i;
448         WCHAR key[6];
449         MENUITEMINFOW mi;
450         HMENU hMenu = GetMenu(hMainWnd);
451
452         mi.cbSize = sizeof(MENUITEMINFOW);
453         mi.fMask = MIIM_ID | MIIM_DATA | MIIM_STRING | MIIM_FTYPE;
454         mi.fType = MFT_STRING;
455         mi.dwTypeData = itemText;
456         mi.wID = ID_FILE_RECENT1;
457
458         RemoveMenu(hMenu, ID_FILE_RECENT_SEPARATOR, MF_BYCOMMAND);
459         for(i = 0; i < FILELIST_ENTRIES; i++)
460         {
461             wsprintfW(key, var_file, i+1);
462             RemoveMenu(hMenu, ID_FILE_RECENT1+i, MF_BYCOMMAND);
463             if(RegQueryValueExW(hFileKey, (LPWSTR)key, 0, NULL, (LPBYTE)pFile[i], &pathSize)
464                != ERROR_SUCCESS)
465                 break;
466
467             mi.dwItemData = (DWORD)pFile[i];
468             wsprintfW(itemText, numFormat, i+1);
469
470             lstrcpyW(buffer, pFile[i]);
471
472             format_filelist_filename(buffer, itemText);
473
474             InsertMenuItemW(hMenu, ID_FILE_EXIT, FALSE, &mi);
475             mi.wID++;
476             pathSize = MAX_PATH*sizeof(WCHAR);
477         }
478         mi.fType = MFT_SEPARATOR;
479         mi.fMask = MIIM_FTYPE | MIIM_ID;
480         InsertMenuItemW(hMenu, ID_FILE_EXIT, FALSE, &mi);
481
482         RegCloseKey(hFileKey);
483     }
484 }
485
486 static void registry_set_filelist(LPCWSTR newFile)
487 {
488     HKEY hKey;
489     DWORD action;
490
491     if(registry_get_handle(&hKey, &action, key_recentfiles) == ERROR_SUCCESS)
492     {
493         LPCWSTR pFiles[FILELIST_ENTRIES];
494         int i;
495         HMENU hMenu = GetMenu(hMainWnd);
496         MENUITEMINFOW mi;
497         WCHAR buffer[6];
498
499         mi.cbSize = sizeof(MENUITEMINFOW);
500         mi.fMask = MIIM_DATA;
501
502         for(i = 0; i < FILELIST_ENTRIES; i++)
503             pFiles[i] = NULL;
504
505         for(i = 0; GetMenuItemInfoW(hMenu, ID_FILE_RECENT1+i, FALSE, &mi); i++)
506             pFiles[i] = (LPWSTR)mi.dwItemData;
507
508         if(lstrcmpiW(newFile, pFiles[0]))
509         {
510             for(i = 0; pFiles[i] && i < FILELIST_ENTRIES; i++)
511             {
512                 if(!lstrcmpiW(pFiles[i], newFile))
513                 {
514                     int j;
515                     for(j = 0; pFiles[j] && j < i; j++)
516                     {
517                         pFiles[i-j] = pFiles[i-j-1];
518                     }
519                     pFiles[0] = NULL;
520                     break;
521                 }
522             }
523
524             if(!pFiles[0])
525             {
526                 pFiles[0] = newFile;
527             } else
528             {
529                 for(i = 0; pFiles[i] && i < FILELIST_ENTRIES-1; i++)
530                     pFiles[FILELIST_ENTRIES-1-i] = pFiles[FILELIST_ENTRIES-2-i];
531
532                 pFiles[0] = newFile;
533             }
534
535             for(i = 0; pFiles[i] && i < FILELIST_ENTRIES; i++)
536             {
537                 wsprintfW(buffer, var_file, i+1);
538                 RegSetValueExW(hKey, (LPWSTR)&buffer, 0, REG_SZ, (LPBYTE)pFiles[i],
539                                (lstrlenW(pFiles[i])+1)*sizeof(WCHAR));
540             }
541         }
542     }
543     RegCloseKey(hKey);
544     registry_read_filelist(hMainWnd);
545 }
546
547 static BOOL validate_endptr(LPCSTR endptr, BOOL units)
548 {
549     if(!endptr || !*endptr)
550         return TRUE;
551
552     while(*endptr == ' ')
553         endptr++;
554
555     if(!units)
556         return *endptr != '\0';
557
558     /* FIXME: Allow other units and convert between them */
559     if(!lstrcmpA(endptr, units_cmA))
560         endptr += 2;
561
562     return *endptr != '\0';
563 }
564
565 static BOOL number_from_string(LPCWSTR string, float *num, BOOL units)
566 {
567     double ret;
568     char buffer[MAX_STRING_LEN];
569     char *endptr = buffer;
570
571     WideCharToMultiByte(CP_ACP, 0, string, -1, buffer, MAX_STRING_LEN, NULL, NULL);
572     *num = 0;
573     errno = 0;
574     ret = strtod(buffer, &endptr);
575
576     if((ret == 0 && errno != 0) || endptr == buffer || validate_endptr(endptr, units))
577     {
578         return FALSE;
579     } else
580     {
581         *num = (float)ret;
582         return TRUE;
583     }
584 }
585
586 static void set_size(float size)
587 {
588     CHARFORMAT2W fmt;
589
590     ZeroMemory(&fmt, sizeof(fmt));
591     fmt.cbSize = sizeof(fmt);
592     fmt.dwMask = CFM_SIZE;
593     fmt.yHeight = (int)(size * 20.0);
594     SendMessageW(hEditorWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
595 }
596
597 static void add_size(HWND hSizeListWnd, unsigned size)
598 {
599     WCHAR buffer[3];
600     COMBOBOXEXITEMW cbItem;
601     cbItem.mask = CBEIF_TEXT;
602     cbItem.iItem = -1;
603
604     wsprintfW(buffer, stringFormat, size);
605     cbItem.pszText = (LPWSTR)buffer;
606     SendMessageW(hSizeListWnd, CBEM_INSERTITEMW, 0, (LPARAM)&cbItem);
607 }
608
609 static void populate_size_list(HWND hSizeListWnd)
610 {
611     HWND hReBarWnd = GetDlgItem(hMainWnd, IDC_REBAR);
612     HWND hFontListWnd = GetDlgItem(hReBarWnd, IDC_FONTLIST);
613     COMBOBOXEXITEMW cbFontItem;
614     CHARFORMAT2W fmt;
615     HWND hListEditWnd = (HWND)SendMessageW(hSizeListWnd, CBEM_GETEDITCONTROL, 0, 0);
616     HDC hdc = GetDC(hMainWnd);
617     static const unsigned choices[] = {8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72};
618     WCHAR buffer[3];
619     int i;
620     DWORD fontStyle;
621
622     ZeroMemory(&fmt, sizeof(fmt));
623     fmt.cbSize = sizeof(fmt);
624     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
625
626     cbFontItem.mask = CBEIF_LPARAM;
627     cbFontItem.iItem = SendMessageW(hFontListWnd, CB_FINDSTRINGEXACT, -1, (LPARAM)fmt.szFaceName);
628     SendMessageW(hFontListWnd, CBEM_GETITEMW, 0, (LPARAM)&cbFontItem);
629
630     fontStyle = (DWORD)LOWORD(cbFontItem.lParam);
631
632     SendMessageW(hSizeListWnd, CB_RESETCONTENT, 0, 0);
633
634     if((fontStyle & RASTER_FONTTYPE) && cbFontItem.iItem)
635     {
636         add_size(hSizeListWnd, (BYTE)MulDiv(HIWORD(cbFontItem.lParam), 72,
637                                GetDeviceCaps(hdc, LOGPIXELSY)));
638     } else
639     {
640         for(i = 0; i < sizeof(choices)/sizeof(choices[0]); i++)
641             add_size(hSizeListWnd, choices[i]);
642     }
643
644     wsprintfW(buffer, stringFormat, fmt.yHeight / 20);
645     SendMessageW(hListEditWnd, WM_SETTEXT, 0, (LPARAM)buffer);
646 }
647
648 static void update_size_list(void)
649 {
650     HWND hReBar = GetDlgItem(hMainWnd, IDC_REBAR);
651     HWND hwndSizeList = GetDlgItem(hReBar, IDC_SIZELIST);
652     HWND hwndSizeListEdit = (HWND)SendMessageW(hwndSizeList, CBEM_GETEDITCONTROL, 0, 0);
653     WCHAR fontSize[MAX_STRING_LEN], sizeBuffer[MAX_STRING_LEN];
654     CHARFORMAT2W fmt;
655
656     ZeroMemory(&fmt, sizeof(fmt));
657     fmt.cbSize = sizeof(fmt);
658
659     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
660
661     SendMessageW(hwndSizeListEdit, WM_GETTEXT, MAX_PATH, (LPARAM)fontSize);
662     wsprintfW(sizeBuffer, stringFormat, fmt.yHeight / 20);
663
664     if(lstrcmpW(fontSize, sizeBuffer))
665         SendMessageW(hwndSizeListEdit, WM_SETTEXT, 0, (LPARAM)sizeBuffer);
666 }
667
668 static void update_font_list(void)
669 {
670     HWND hReBar = GetDlgItem(hMainWnd, IDC_REBAR);
671     HWND hFontList = GetDlgItem(hReBar, IDC_FONTLIST);
672     HWND hFontListEdit = (HWND)SendMessageW(hFontList, CBEM_GETEDITCONTROL, 0, 0);
673     WCHAR fontName[MAX_STRING_LEN];
674     CHARFORMAT2W fmt;
675
676     ZeroMemory(&fmt, sizeof(fmt));
677     fmt.cbSize = sizeof(fmt);
678
679     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
680     SendMessageW(hFontListEdit, WM_GETTEXT, MAX_PATH, (LPARAM)fontName);
681
682     if(lstrcmpW(fontName, fmt.szFaceName))
683     {
684         SendMessageW(hFontListEdit, WM_SETTEXT, 0, (LPARAM)fmt.szFaceName);
685         populate_size_list(GetDlgItem(hReBar, IDC_SIZELIST));
686     } else
687     {
688         update_size_list();
689     }
690 }
691
692 static void clear_formatting(void)
693 {
694     PARAFORMAT2 pf;
695
696     pf.cbSize = sizeof(pf);
697     pf.dwMask = PFM_ALIGNMENT;
698     pf.wAlignment = PFA_LEFT;
699     SendMessageW(hEditorWnd, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
700 }
701
702 static int reg_formatindex(WPARAM format)
703 {
704     return (format & SF_TEXT) ? 1 : 0;
705 }
706
707 static int fileformat_number(WPARAM format)
708 {
709     int number = 0;
710
711     if(format == SF_TEXT)
712     {
713         number = 1;
714     } else if (format == (SF_TEXT | SF_UNICODE))
715     {
716         number = 2;
717     }
718     return number;
719 }
720
721 static WPARAM fileformat_flags(int format)
722 {
723     WPARAM flags[] = { SF_RTF , SF_TEXT , SF_TEXT | SF_UNICODE };
724
725     return flags[format];
726 }
727
728 static void set_font(LPCWSTR wszFaceName)
729 {
730     HWND hReBarWnd = GetDlgItem(hMainWnd, IDC_REBAR);
731     HWND hSizeListWnd = GetDlgItem(hReBarWnd, IDC_SIZELIST);
732     HWND hFontListWnd = GetDlgItem(hReBarWnd, IDC_FONTLIST);
733     HWND hFontListEditWnd = (HWND)SendMessageW(hFontListWnd, CBEM_GETEDITCONTROL, 0, 0);
734     CHARFORMAT2W fmt;
735
736     ZeroMemory(&fmt, sizeof(fmt));
737
738     fmt.cbSize = sizeof(fmt);
739     fmt.dwMask = CFM_FACE;
740
741     lstrcpyW(fmt.szFaceName, wszFaceName);
742
743     SendMessageW(hEditorWnd, EM_SETCHARFORMAT,  SCF_SELECTION, (LPARAM)&fmt);
744
745     populate_size_list(hSizeListWnd);
746
747     SendMessageW(hFontListEditWnd, WM_SETTEXT, 0, (LPARAM)(LPWSTR)wszFaceName);
748 }
749
750 static void set_default_font(void)
751 {
752     static const WCHAR richTextFont[] = {'T','i','m','e','s',' ','N','e','w',' ',
753                                          'R','o','m','a','n',0};
754     static const WCHAR plainTextFont[] = {'C','o','u','r','i','e','r',' ','N','e','w',0};
755     CHARFORMAT2W fmt;
756     LPCWSTR font;
757
758     ZeroMemory(&fmt, sizeof(fmt));
759
760     fmt.cbSize = sizeof(fmt);
761     fmt.dwMask = CFM_FACE | CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE;
762     fmt.dwEffects = 0;
763
764     if(fileFormat & SF_RTF)
765         font = richTextFont;
766     else
767         font = plainTextFont;
768
769     lstrcpyW(fmt.szFaceName, font);
770
771     SendMessageW(hEditorWnd, EM_SETCHARFORMAT,  SCF_DEFAULT, (LPARAM)&fmt);
772 }
773
774 static void add_font(LPWSTR fontName, DWORD fontType, HWND hListWnd, NEWTEXTMETRICEXW *ntmc)
775 {
776     COMBOBOXEXITEMW cbItem;
777     WCHAR buffer[MAX_PATH];
778     int fontHeight = 0;
779
780     cbItem.mask = CBEIF_TEXT;
781     cbItem.pszText = buffer;
782     cbItem.cchTextMax = MAX_STRING_LEN;
783     cbItem.iItem = 0;
784
785     while(SendMessageW(hListWnd, CBEM_GETITEMW, 0, (LPARAM)&cbItem))
786     {
787         if(lstrcmpiW(cbItem.pszText, fontName) <= 0)
788             cbItem.iItem++;
789         else
790             break;
791     }
792     cbItem.pszText = fontName;
793
794     cbItem.mask |= CBEIF_LPARAM;
795     if(fontType & RASTER_FONTTYPE)
796         fontHeight = ntmc->ntmTm.tmHeight - ntmc->ntmTm.tmInternalLeading;
797
798     cbItem.lParam = MAKELONG(fontType,fontHeight);
799     SendMessageW(hListWnd, CBEM_INSERTITEMW, 0, (LPARAM)&cbItem);
800 }
801
802 static void dialog_choose_font(void)
803 {
804     CHOOSEFONTW cf;
805     LOGFONTW lf;
806     CHARFORMAT2W fmt;
807     HDC hDC = GetDC(hMainWnd);
808
809     ZeroMemory(&cf, sizeof(cf));
810     cf.lStructSize = sizeof(cf);
811     cf.hwndOwner = hMainWnd;
812     cf.lpLogFont = &lf;
813     cf.Flags = CF_SCREENFONTS | CF_NOSCRIPTSEL | CF_INITTOLOGFONTSTRUCT | CF_EFFECTS;
814
815     ZeroMemory(&fmt, sizeof(fmt));
816     fmt.cbSize = sizeof(fmt);
817
818     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
819     lstrcpyW(cf.lpLogFont->lfFaceName, fmt.szFaceName);
820     cf.lpLogFont->lfItalic = (fmt.dwEffects & CFE_ITALIC) ? TRUE : FALSE;
821     cf.lpLogFont->lfWeight = (fmt.dwEffects & CFE_BOLD) ? FW_BOLD : FW_NORMAL;
822     cf.lpLogFont->lfUnderline = (fmt.dwEffects & CFE_UNDERLINE) ? TRUE : FALSE;
823     cf.lpLogFont->lfStrikeOut = (fmt.dwEffects & CFE_STRIKEOUT) ? TRUE : FALSE;
824     cf.lpLogFont->lfHeight = -MulDiv(fmt.yHeight / 20, GetDeviceCaps(hDC, LOGPIXELSY), 72);
825     cf.rgbColors = fmt.crTextColor;
826
827     if(ChooseFontW(&cf))
828     {
829         ZeroMemory(&fmt, sizeof(fmt));
830         fmt.cbSize = sizeof(fmt);
831         fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_SIZE | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR;
832         fmt.yHeight = cf.iPointSize * 2;
833
834         if(cf.nFontType & BOLD_FONTTYPE)
835             fmt.dwEffects |= CFE_BOLD;
836         if(cf.nFontType & ITALIC_FONTTYPE)
837             fmt.dwEffects |= CFE_ITALIC;
838         if(cf.lpLogFont->lfUnderline == TRUE)
839             fmt.dwEffects |= CFE_UNDERLINE;
840         if(cf.lpLogFont->lfStrikeOut == TRUE)
841             fmt.dwEffects |= CFE_STRIKEOUT;
842
843         fmt.crTextColor = cf.rgbColors;
844
845         SendMessageW(hEditorWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
846         set_font(cf.lpLogFont->lfFaceName);
847     }
848 }
849
850
851 int CALLBACK enum_font_proc(const LOGFONTW *lpelfe, const TEXTMETRICW *lpntme,
852                             DWORD FontType, LPARAM lParam)
853 {
854     HWND hListWnd = (HWND) lParam;
855
856     if(SendMessageW(hListWnd, CB_FINDSTRINGEXACT, -1, (LPARAM)lpelfe->lfFaceName) == CB_ERR)
857     {
858
859         add_font((LPWSTR)lpelfe->lfFaceName, FontType, hListWnd, (NEWTEXTMETRICEXW*)lpntme);
860     }
861
862     return 1;
863 }
864
865 static void populate_font_list(HWND hListWnd)
866 {
867     HDC hdc = GetDC(hMainWnd);
868     LOGFONTW fontinfo;
869     HWND hListEditWnd = (HWND)SendMessageW(hListWnd, CBEM_GETEDITCONTROL, 0, 0);
870     CHARFORMAT2W fmt;
871
872     fontinfo.lfCharSet = DEFAULT_CHARSET;
873     *fontinfo.lfFaceName = '\0';
874     fontinfo.lfPitchAndFamily = 0;
875
876     EnumFontFamiliesExW(hdc, &fontinfo, enum_font_proc,
877                         (LPARAM)hListWnd, 0);
878
879     ZeroMemory(&fmt, sizeof(fmt));
880     fmt.cbSize = sizeof(fmt);
881     SendMessageW(hEditorWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM)&fmt);
882     SendMessageW(hListEditWnd, WM_SETTEXT, 0, (LPARAM)fmt.szFaceName);
883 }
884
885 static void update_window(void)
886 {
887     RECT rect;
888
889     GetWindowRect(hMainWnd, &rect);
890
891     (void) OnSize(hMainWnd, SIZE_RESTORED, MAKELONG(rect.bottom, rect.right));
892 }
893
894 static DWORD barState[2];
895 static DWORD wordWrap[2];
896
897 static BOOL is_bar_visible(int bandId)
898 {
899     return barState[reg_formatindex(fileFormat)] & (1 << bandId);
900 }
901
902 static void store_bar_state(int bandId, BOOL show)
903 {
904     int formatIndex = reg_formatindex(fileFormat);
905
906     if(show)
907         barState[formatIndex] |= (1 << bandId);
908     else
909         barState[formatIndex] &= ~(1 << bandId);
910 }
911
912 static void set_toolbar_state(int bandId, BOOL show)
913 {
914     HWND hwndReBar = GetDlgItem(hMainWnd, IDC_REBAR);
915
916     SendMessageW(hwndReBar, RB_SHOWBAND, SendMessageW(hwndReBar, RB_IDTOINDEX, bandId, 0), show);
917
918     if(bandId == BANDID_TOOLBAR)
919     {
920         REBARBANDINFOW rbbinfo;
921         int index = SendMessageW(hwndReBar, RB_IDTOINDEX, BANDID_FONTLIST, 0);
922
923         rbbinfo.cbSize = sizeof(rbbinfo);
924         rbbinfo.fMask = RBBIM_STYLE;
925
926         SendMessageW(hwndReBar, RB_GETBANDINFO, index, (LPARAM)&rbbinfo);
927
928         if(!show)
929             rbbinfo.fStyle &= ~RBBS_BREAK;
930         else
931             rbbinfo.fStyle |= RBBS_BREAK;
932
933         SendMessageW(hwndReBar, RB_SETBANDINFO, index, (LPARAM)&rbbinfo);
934     }
935
936     if(bandId == BANDID_TOOLBAR || bandId == BANDID_FORMATBAR)
937         store_bar_state(bandId, show);
938 }
939
940 static void set_statusbar_state(BOOL show)
941 {
942     HWND hStatusWnd = GetDlgItem(hMainWnd, IDC_STATUSBAR);
943
944     ShowWindow(hStatusWnd, show ? SW_SHOW : SW_HIDE);
945     store_bar_state(BANDID_STATUSBAR, show);
946 }
947
948 static void set_bar_states(void)
949 {
950     set_toolbar_state(BANDID_TOOLBAR, is_bar_visible(BANDID_TOOLBAR));
951     set_toolbar_state(BANDID_FONTLIST, is_bar_visible(BANDID_FORMATBAR));
952     set_toolbar_state(BANDID_SIZELIST, is_bar_visible(BANDID_FORMATBAR));
953     set_toolbar_state(BANDID_FORMATBAR, is_bar_visible(BANDID_FORMATBAR));
954     set_statusbar_state(is_bar_visible(BANDID_STATUSBAR));
955
956     update_window();
957 }
958
959 static HGLOBAL devMode;
960 static HGLOBAL devNames;
961
962 static HDC make_dc(void)
963 {
964     if(devNames && devMode)
965     {
966         LPDEVNAMES dn = GlobalLock(devNames);
967         LPDEVMODEW dm = GlobalLock(devMode);
968         HDC ret;
969
970         ret = CreateDCW((LPWSTR)dn + dn->wDriverOffset,
971                         (LPWSTR)dn + dn->wDeviceOffset, 0, dm);
972
973         GlobalUnlock(dn);
974         GlobalUnlock(dm);
975
976         return ret;
977     } else
978     {
979         return 0;
980     }
981 }
982
983 static LONG twips_to_pixels(int twips, int dpi)
984 {
985     float ret = ((float)twips / ((float)567 * 2.54)) * (float)dpi;
986     return (LONG)ret;
987 }
988
989 static LONG devunits_to_twips(int units, int dpi)
990 {
991     float ret = ((float)units / (float)dpi) * (float)567 * 2.54;
992     return (LONG)ret;
993 }
994
995 static LONG centmm_to_twips(int mm)
996 {
997     return MulDiv(mm, 567, 1000);
998 }
999
1000 static LONG twips_to_centmm(int twips)
1001 {
1002     return MulDiv(twips, 1000, 567);
1003 }
1004
1005 static RECT get_print_rect(HDC hdc)
1006 {
1007     RECT rc;
1008     int width, height;
1009
1010     if(hdc)
1011     {
1012         int dpiY = GetDeviceCaps(hdc, LOGPIXELSY);
1013         int dpiX = GetDeviceCaps(hdc, LOGPIXELSX);
1014         width = devunits_to_twips(GetDeviceCaps(hdc, PHYSICALWIDTH), dpiX);
1015         height = devunits_to_twips(GetDeviceCaps(hdc, PHYSICALHEIGHT), dpiY);
1016     } else
1017     {
1018         width = centmm_to_twips(18500);
1019         height = centmm_to_twips(27000);
1020     }
1021
1022     rc.left = margins.left;
1023     rc.right = width - margins.right;
1024     rc.top = margins.top;
1025     rc.bottom = height - margins.bottom;
1026
1027     return rc;
1028 }
1029
1030 static void target_device(void)
1031 {
1032     HDC hdc = make_dc();
1033     int width = 0;
1034     int index = reg_formatindex(fileFormat);
1035
1036     if(wordWrap[index] == ID_WORDWRAP_MARGIN)
1037     {
1038         RECT rc = get_print_rect(hdc);
1039         width = rc.right;
1040     }
1041
1042     if(!hdc)
1043     {
1044         HDC hMaindc = GetDC(hMainWnd);
1045         hdc = CreateCompatibleDC(hMaindc);
1046         ReleaseDC(hMainWnd, hMaindc);
1047     }
1048
1049     SendMessageW(hEditorWnd, EM_SETTARGETDEVICE, (WPARAM)hdc, width);
1050
1051     DeleteDC(hdc);
1052 }
1053
1054 static void set_fileformat(WPARAM format)
1055 {
1056     HICON hIcon;
1057     HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hMainWnd, GWLP_HINSTANCE);
1058     fileFormat = format;
1059
1060     if(format & SF_TEXT)
1061         hIcon = LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_TXT));
1062     else
1063         hIcon = LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_RTF));
1064
1065     SendMessageW(hMainWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
1066
1067     set_bar_states();
1068     set_default_font();
1069     target_device();
1070 }
1071
1072 static void DoOpenFile(LPCWSTR szOpenFileName)
1073 {
1074     HANDLE hFile;
1075     EDITSTREAM es;
1076     char fileStart[5];
1077     DWORD readOut;
1078     WPARAM format = SF_TEXT;
1079
1080     hFile = CreateFileW(szOpenFileName, GENERIC_READ, FILE_SHARE_READ, NULL,
1081                         OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1082     if (hFile == INVALID_HANDLE_VALUE)
1083         return;
1084
1085     ReadFile(hFile, fileStart, 5, &readOut, NULL);
1086     SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
1087
1088     if(readOut >= 2 && (BYTE)fileStart[0] == 0xff && (BYTE)fileStart[1] == 0xfe)
1089     {
1090         format = SF_TEXT | SF_UNICODE;
1091         SetFilePointer(hFile, 2, NULL, FILE_BEGIN);
1092     } else if(readOut >= 5)
1093     {
1094         static const char header[] = "{\\rtf";
1095         if(!memcmp(header, fileStart, 5))
1096             format = SF_RTF;
1097     }
1098
1099     es.dwCookie = (DWORD_PTR)hFile;
1100     es.pfnCallback = stream_in;
1101
1102     clear_formatting();
1103     set_fileformat(format);
1104     SendMessageW(hEditorWnd, EM_STREAMIN, format, (LPARAM)&es);
1105
1106     CloseHandle(hFile);
1107
1108     SetFocus(hEditorWnd);
1109
1110     set_caption(szOpenFileName);
1111
1112     lstrcpyW(wszFileName, szOpenFileName);
1113     SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
1114     registry_set_filelist(szOpenFileName);
1115     update_font_list();
1116 }
1117
1118 static void DoSaveFile(LPCWSTR wszSaveFileName, WPARAM format)
1119 {
1120     HANDLE hFile;
1121     EDITSTREAM stream;
1122     LRESULT ret;
1123
1124     hFile = CreateFileW(wszSaveFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
1125         FILE_ATTRIBUTE_NORMAL, NULL);
1126
1127     if(hFile == INVALID_HANDLE_VALUE)
1128         return;
1129
1130     if(format == (SF_TEXT | SF_UNICODE))
1131     {
1132         static const BYTE unicode[] = {0xff,0xfe};
1133         DWORD writeOut;
1134         WriteFile(hFile, &unicode, sizeof(unicode), &writeOut, 0);
1135
1136         if(writeOut != sizeof(unicode))
1137             return;
1138     }
1139
1140     stream.dwCookie = (DWORD_PTR)hFile;
1141     stream.pfnCallback = stream_out;
1142
1143     ret = SendMessageW(hEditorWnd, EM_STREAMOUT, format, (LPARAM)&stream);
1144
1145     CloseHandle(hFile);
1146
1147     SetFocus(hEditorWnd);
1148
1149     if(!ret)
1150     {
1151         GETTEXTLENGTHEX gt;
1152         gt.flags = GTL_DEFAULT;
1153         gt.codepage = 1200;
1154
1155         if(SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0))
1156             return;
1157     }
1158
1159     lstrcpyW(wszFileName, wszSaveFileName);
1160     set_caption(wszFileName);
1161     SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
1162     set_fileformat(format);
1163 }
1164
1165 static void DialogSaveFile(void)
1166 {
1167     OPENFILENAMEW sfn;
1168
1169     WCHAR wszFile[MAX_PATH] = {'\0'};
1170     static const WCHAR wszDefExt[] = {'r','t','f','\0'};
1171
1172     ZeroMemory(&sfn, sizeof(sfn));
1173
1174     sfn.lStructSize = sizeof(sfn);
1175     sfn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT;
1176     sfn.hwndOwner = hMainWnd;
1177     sfn.lpstrFilter = wszFilter;
1178     sfn.lpstrFile = wszFile;
1179     sfn.nMaxFile = MAX_PATH;
1180     sfn.lpstrDefExt = wszDefExt;
1181     sfn.nFilterIndex = fileformat_number(fileFormat)+1;
1182
1183     while(GetSaveFileNameW(&sfn))
1184     {
1185         if(fileformat_flags(sfn.nFilterIndex-1) != SF_RTF)
1186         {
1187             if(MessageBoxW(hMainWnd, MAKEINTRESOURCEW(STRING_SAVE_LOSEFORMATTING),
1188                            wszAppTitle, MB_YESNO | MB_ICONEXCLAMATION) != IDYES)
1189             {
1190                 continue;
1191             } else
1192             {
1193                 DoSaveFile(sfn.lpstrFile, fileformat_flags(sfn.nFilterIndex-1));
1194                 break;
1195             }
1196         } else
1197         {
1198             DoSaveFile(sfn.lpstrFile, fileformat_flags(sfn.nFilterIndex-1));
1199             break;
1200         }
1201     }
1202 }
1203
1204 static BOOL prompt_save_changes(void)
1205 {
1206     if(!wszFileName[0])
1207     {
1208         GETTEXTLENGTHEX gt;
1209         gt.flags = GTL_NUMCHARS;
1210         gt.codepage = 1200;
1211         if(!SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0))
1212             return TRUE;
1213     }
1214
1215     if(!SendMessageW(hEditorWnd, EM_GETMODIFY, 0, 0))
1216     {
1217         return TRUE;
1218     } else
1219     {
1220         LPWSTR displayFileName;
1221         WCHAR *text;
1222         int ret;
1223
1224         if(!wszFileName[0])
1225             displayFileName = wszDefaultFileName;
1226         else
1227             displayFileName = file_basename(wszFileName);
1228
1229         text = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1230                          (lstrlenW(displayFileName)+lstrlenW(wszSaveChanges))*sizeof(WCHAR));
1231
1232         if(!text)
1233             return FALSE;
1234
1235         wsprintfW(text, wszSaveChanges, displayFileName);
1236
1237         ret = MessageBoxW(hMainWnd, text, wszAppTitle, MB_YESNOCANCEL | MB_ICONEXCLAMATION);
1238
1239         HeapFree(GetProcessHeap(), 0, text);
1240
1241         switch(ret)
1242         {
1243             case IDNO:
1244                 return TRUE;
1245
1246             case IDYES:
1247                 if(wszFileName[0])
1248                     DoSaveFile(wszFileName, fileFormat);
1249                 else
1250                     DialogSaveFile();
1251                 return TRUE;
1252
1253             default:
1254                 return FALSE;
1255         }
1256     }
1257 }
1258
1259 static void DialogOpenFile(void)
1260 {
1261     OPENFILENAMEW ofn;
1262
1263     WCHAR wszFile[MAX_PATH] = {'\0'};
1264     static const WCHAR wszDefExt[] = {'r','t','f','\0'};
1265
1266     ZeroMemory(&ofn, sizeof(ofn));
1267
1268     ofn.lStructSize = sizeof(ofn);
1269     ofn.Flags = OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
1270     ofn.hwndOwner = hMainWnd;
1271     ofn.lpstrFilter = wszFilter;
1272     ofn.lpstrFile = wszFile;
1273     ofn.nMaxFile = MAX_PATH;
1274     ofn.lpstrDefExt = wszDefExt;
1275     ofn.nFilterIndex = fileformat_number(fileFormat)+1;
1276
1277     if(GetOpenFileNameW(&ofn))
1278     {
1279         if(prompt_save_changes())
1280             DoOpenFile(ofn.lpstrFile);
1281     }
1282 }
1283
1284 static LPWSTR dialog_print_to_file(void)
1285 {
1286     OPENFILENAMEW ofn;
1287     static WCHAR file[MAX_PATH] = {'O','U','T','P','U','T','.','P','R','N',0};
1288     static const WCHAR defExt[] = {'P','R','N',0};
1289
1290     ZeroMemory(&ofn, sizeof(ofn));
1291
1292     ofn.lStructSize = sizeof(ofn);
1293     ofn.Flags = OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
1294     ofn.hwndOwner = hMainWnd;
1295     ofn.lpstrFilter = (LPWSTR)wszPrintFilter;
1296     ofn.lpstrFile = (LPWSTR)file;
1297     ofn.nMaxFile = MAX_PATH;
1298     ofn.lpstrDefExt = (LPWSTR)defExt;
1299
1300     if(GetSaveFileNameW(&ofn))
1301         return (LPWSTR)file;
1302     else
1303         return FALSE;
1304 }
1305
1306 static int get_num_pages(FORMATRANGE fr)
1307 {
1308     int page = 0;
1309
1310     do
1311     {
1312         page++;
1313         fr.chrg.cpMin = SendMessageW(hEditorWnd, EM_FORMATRANGE, TRUE,
1314                                      (LPARAM)&fr);
1315     }
1316     while(fr.chrg.cpMin && fr.chrg.cpMin < fr.chrg.cpMax);
1317
1318     return page;
1319 }
1320
1321 static void char_from_pagenum(FORMATRANGE *fr, int page)
1322 {
1323     int i;
1324
1325     for(i = 1; i <= page; i++)
1326     {
1327         if(i == page)
1328             break;
1329
1330         fr->chrg.cpMin = SendMessageW(hEditorWnd, EM_FORMATRANGE, TRUE, (LPARAM)fr);
1331     }
1332 }
1333
1334 static void print(LPPRINTDLGW pd)
1335 {
1336     FORMATRANGE fr;
1337     DOCINFOW di;
1338     int printedPages = 0;
1339
1340     fr.hdc = pd->hDC;
1341     fr.hdcTarget = pd->hDC;
1342
1343     fr.rc = get_print_rect(fr.hdc);
1344     fr.rcPage.left = 0;
1345     fr.rcPage.right = fr.rc.right + margins.right;
1346     fr.rcPage.top = 0;
1347     fr.rcPage.bottom = fr.rc.bottom + margins.bottom;
1348
1349     ZeroMemory(&di, sizeof(di));
1350     di.cbSize = sizeof(di);
1351     di.lpszDocName = (LPWSTR)wszFileName;
1352
1353     if(pd->Flags & PD_PRINTTOFILE)
1354     {
1355         di.lpszOutput = dialog_print_to_file();
1356         if(!di.lpszOutput)
1357             return;
1358     }
1359
1360     if(pd->Flags & PD_SELECTION)
1361     {
1362         SendMessageW(hEditorWnd, EM_EXGETSEL, 0, (LPARAM)&fr.chrg);
1363     } else
1364     {
1365         GETTEXTLENGTHEX gt;
1366         gt.flags = GTL_DEFAULT;
1367         gt.codepage = 1200;
1368         fr.chrg.cpMin = 0;
1369         fr.chrg.cpMax = SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0);
1370
1371         if(pd->Flags & PD_PAGENUMS)
1372             char_from_pagenum(&fr, pd->nToPage);
1373     }
1374
1375     StartDocW(fr.hdc, &di);
1376     do
1377     {
1378         if(StartPage(fr.hdc) <= 0)
1379             break;
1380
1381         fr.chrg.cpMin = SendMessageW(hEditorWnd, EM_FORMATRANGE, TRUE, (LPARAM)&fr);
1382
1383         if(EndPage(fr.hdc) <= 0)
1384             break;
1385
1386         printedPages++;
1387         if((pd->Flags & PD_PAGENUMS) && (printedPages > (pd->nToPage - pd->nFromPage)))
1388             break;
1389     }
1390     while(fr.chrg.cpMin && fr.chrg.cpMin < fr.chrg.cpMax);
1391
1392     EndDoc(fr.hdc);
1393     SendMessageW(hEditorWnd, EM_FORMATRANGE, FALSE, 0);
1394     target_device();
1395 }
1396
1397 static void dialog_printsetup(void)
1398 {
1399     PAGESETUPDLGW ps;
1400
1401     ZeroMemory(&ps, sizeof(ps));
1402     ps.lStructSize = sizeof(ps);
1403     ps.hwndOwner = hMainWnd;
1404     ps.Flags = PSD_INHUNDREDTHSOFMILLIMETERS | PSD_MARGINS;
1405     ps.rtMargin.left = twips_to_centmm(margins.left);
1406     ps.rtMargin.right = twips_to_centmm(margins.right);
1407     ps.rtMargin.top = twips_to_centmm(margins.top);
1408     ps.rtMargin.bottom = twips_to_centmm(margins.bottom);
1409     ps.hDevMode = devMode;
1410     ps.hDevNames = devNames;
1411
1412     if(PageSetupDlgW(&ps))
1413     {
1414         margins.left = centmm_to_twips(ps.rtMargin.left);
1415         margins.right = centmm_to_twips(ps.rtMargin.right);
1416         margins.top = centmm_to_twips(ps.rtMargin.top);
1417         margins.bottom = centmm_to_twips(ps.rtMargin.bottom);
1418         devMode = ps.hDevMode;
1419         devNames = ps.hDevNames;
1420         target_device();
1421     }
1422 }
1423
1424 static void get_default_printer_opts(void)
1425 {
1426     PRINTDLGW pd;
1427     ZeroMemory(&pd, sizeof(pd));
1428
1429     ZeroMemory(&pd, sizeof(pd));
1430     pd.lStructSize = sizeof(pd);
1431     pd.Flags = PD_RETURNDC | PD_RETURNDEFAULT;
1432     pd.hwndOwner = hMainWnd;
1433     pd.hDevMode = devMode;
1434
1435     PrintDlgW(&pd);
1436
1437     devMode = pd.hDevMode;
1438     devNames = pd.hDevNames;
1439 }
1440
1441 static void print_quick(void)
1442 {
1443     PRINTDLGW pd;
1444
1445     ZeroMemory(&pd, sizeof(pd));
1446     pd.hDC = make_dc();
1447
1448     print(&pd);
1449 }
1450
1451 static void dialog_print(void)
1452 {
1453     PRINTDLGW pd;
1454     int from = 0;
1455     int to = 0;
1456
1457     ZeroMemory(&pd, sizeof(pd));
1458     pd.lStructSize = sizeof(pd);
1459     pd.hwndOwner = hMainWnd;
1460     pd.Flags = PD_RETURNDC | PD_USEDEVMODECOPIESANDCOLLATE;
1461     pd.nMinPage = 1;
1462     pd.nMaxPage = -1;
1463     pd.hDevMode = devMode;
1464     pd.hDevNames = devNames;
1465
1466     SendMessageW(hEditorWnd, EM_GETSEL, (WPARAM)&from, (LPARAM)&to);
1467     if(from == to)
1468         pd.Flags |= PD_NOSELECTION;
1469
1470     if(PrintDlgW(&pd))
1471     {
1472         devMode = pd.hDevMode;
1473         devNames = pd.hDevNames;
1474         print(&pd);
1475     }
1476 }
1477
1478 typedef struct _previewinfo
1479 {
1480     int page;
1481     int pages;
1482     HDC hdc;
1483     HDC hdcSized;
1484     RECT window;
1485 } previewinfo, *ppreviewinfo;
1486
1487 static previewinfo preview;
1488
1489 static void preview_bar_show(BOOL show)
1490 {
1491     HWND hReBar = GetDlgItem(hMainWnd, IDC_REBAR);
1492     int i;
1493
1494     if(show)
1495     {
1496         REBARBANDINFOW rb;
1497
1498         AddTextButton(hReBar, STRING_PREVIEW_PRINT, ID_PRINT, BANDID_PREVIEW_BTN1);
1499         AddTextButton(hReBar, STRING_PREVIEW_NEXTPAGE, ID_PREVIEW_NEXTPAGE, BANDID_PREVIEW_BTN2);
1500         AddTextButton(hReBar, STRING_PREVIEW_PREVPAGE, ID_PREVIEW_PREVPAGE, BANDID_PREVIEW_BTN3);
1501         AddTextButton(hReBar, STRING_PREVIEW_CLOSE, ID_FILE_EXIT, BANDID_PREVIEW_BTN4);
1502
1503         rb.cbSize = sizeof(rb);
1504         rb.fMask = RBBIM_SIZE | RBBIM_CHILDSIZE | RBBIM_STYLE | RBBIM_CHILD | RBBIM_IDEALSIZE | RBBIM_ID;
1505         rb.fStyle = RBBS_NOGRIPPER | RBBS_VARIABLEHEIGHT;
1506         rb.cyChild = rb.cyMinChild = 22;
1507         rb.cx = rb.cxMinChild = 90;
1508         rb.cxIdeal = 100;
1509         rb.wID = BANDID_PREVIEW_BUFFER;
1510
1511         SendMessageW(hReBar, RB_INSERTBAND, -1, (LPARAM)&rb);
1512     } else
1513     {
1514         for(i = 0; i <= PREVIEW_BUTTONS; i++)
1515             SendMessageW(hReBar, RB_DELETEBAND, SendMessageW(hReBar, RB_IDTOINDEX, BANDID_PREVIEW_BTN1+i, 0), 0);
1516     }
1517 }
1518
1519 static void preview_exit(void)
1520 {
1521     HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hMainWnd, GWLP_HINSTANCE);
1522     HMENU hMenu = LoadMenuW(hInstance, xszMainMenu);
1523
1524     set_bar_states();
1525     preview.window.right = 0;
1526     preview.window.bottom = 0;
1527     preview.page = 0;
1528     preview.pages = 0;
1529     ShowWindow(hEditorWnd, TRUE);
1530
1531     preview_bar_show(FALSE);
1532
1533     SetMenu(hMainWnd, hMenu);
1534     registry_read_filelist(hMainWnd);
1535
1536     update_window();
1537 }
1538
1539 static LRESULT print_preview(void)
1540 {
1541     FORMATRANGE fr;
1542     GETTEXTLENGTHEX gt;
1543     HDC hdc;
1544     RECT window, background;
1545     HBITMAP hBitmapCapture, hBitmapScaled;
1546     int bmWidth, bmHeight, bmNewWidth, bmNewHeight;
1547     float ratioWidth, ratioHeight, ratio;
1548     int xOffset, yOffset;
1549     int barheight;
1550     HWND hReBar = GetDlgItem(hMainWnd, IDC_REBAR);
1551     PAINTSTRUCT ps;
1552
1553     hdc = BeginPaint(hMainWnd, &ps);
1554     GetClientRect(hMainWnd, &window);
1555
1556     fr.hdcTarget = make_dc();
1557     fr.rc = get_print_rect(fr.hdcTarget);
1558     fr.rcPage.left = 0;
1559     fr.rcPage.top = 0;
1560     fr.rcPage.bottom = fr.rc.bottom + margins.bottom;
1561     fr.rcPage.right = fr.rc.right + margins.right;
1562
1563     bmWidth = twips_to_pixels(fr.rcPage.right, GetDeviceCaps(hdc, LOGPIXELSX));
1564     bmHeight = twips_to_pixels(fr.rcPage.bottom, GetDeviceCaps(hdc, LOGPIXELSY));
1565
1566     hBitmapCapture = CreateCompatibleBitmap(hdc, bmWidth, bmHeight);
1567
1568     if(!preview.hdc)
1569     {
1570         RECT paper;
1571
1572         preview.hdc = CreateCompatibleDC(hdc);
1573         fr.hdc = preview.hdc;
1574         gt.flags = GTL_DEFAULT;
1575         gt.codepage = 1200;
1576         fr.chrg.cpMin = 0;
1577         fr.chrg.cpMax = SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0);
1578
1579         paper.left = 0;
1580         paper.right = bmWidth;
1581         paper.top = 0;
1582         paper.bottom = bmHeight;
1583
1584         if(!preview.pages)
1585             preview.pages = get_num_pages(fr);
1586
1587         SelectObject(preview.hdc, hBitmapCapture);
1588
1589         char_from_pagenum(&fr, preview.page);
1590
1591         FillRect(preview.hdc, &paper, GetStockObject(WHITE_BRUSH));
1592         SendMessageW(hEditorWnd, EM_FORMATRANGE, TRUE, (LPARAM)&fr);
1593         SendMessageW(hEditorWnd, EM_FORMATRANGE, FALSE, 0);
1594
1595         EnableWindow(GetDlgItem(hReBar, ID_PREVIEW_PREVPAGE), preview.page > 1);
1596         EnableWindow(GetDlgItem(hReBar, ID_PREVIEW_NEXTPAGE), preview.page < preview.pages);
1597     }
1598
1599     barheight = SendMessageW(hReBar, RB_GETBARHEIGHT, 0, 0);
1600     ratioWidth = ((float)window.right - 20.0) / (float)bmHeight;
1601     ratioHeight = ((float)window.bottom - 20.0 - (float)barheight) / (float)bmHeight;
1602
1603     if(ratioWidth > ratioHeight)
1604         ratio = ratioHeight;
1605     else
1606         ratio = ratioWidth;
1607
1608     bmNewWidth = (int)((float)bmWidth * ratio);
1609     bmNewHeight = (int)((float)bmHeight * ratio);
1610     hBitmapScaled = CreateCompatibleBitmap(hdc, bmNewWidth, bmNewHeight);
1611
1612     xOffset = ((window.right - bmNewWidth) / 2);
1613     yOffset = ((window.bottom - bmNewHeight + barheight) / 2);
1614
1615     if(window.right != preview.window.right || window.bottom != preview.window.bottom)
1616     {
1617         DeleteDC(preview.hdcSized),
1618         preview.hdcSized = CreateCompatibleDC(hdc);
1619         SelectObject(preview.hdcSized, hBitmapScaled);
1620
1621         StretchBlt(preview.hdcSized, 0, 0, bmNewWidth, bmNewHeight, preview.hdc, 0, 0, bmWidth, bmHeight, SRCCOPY);
1622     }
1623
1624     window.top = barheight;
1625     FillRect(hdc, &window, GetStockObject(GRAY_BRUSH));
1626
1627     SelectObject(hdc, hBitmapScaled);
1628
1629     background.left = xOffset - 2;
1630     background.right = xOffset + bmNewWidth + 2;
1631     background.top = yOffset - 2;
1632     background.bottom = yOffset + bmNewHeight + 2;
1633
1634     FillRect(hdc, &background, GetStockObject(BLACK_BRUSH));
1635
1636     BitBlt(hdc, xOffset, yOffset, bmNewWidth, bmNewHeight, preview.hdcSized, 0, 0, SRCCOPY);
1637
1638     DeleteDC(fr.hdcTarget);
1639     preview.window = window;
1640
1641     EndPaint(hMainWnd, &ps);
1642
1643     return 0;
1644 }
1645
1646 static LRESULT preview_command(HWND hWnd, WPARAM wParam, LPARAM lParam)
1647 {
1648     switch(LOWORD(wParam))
1649     {
1650         case ID_FILE_EXIT:
1651             PostMessageW(hMainWnd, WM_CLOSE, 0, 0);
1652             break;
1653
1654         case ID_PREVIEW_NEXTPAGE:
1655         case ID_PREVIEW_PREVPAGE:
1656             {
1657                 HWND hReBar = GetDlgItem(hMainWnd, IDC_REBAR);
1658                 RECT rc;
1659
1660                 if(LOWORD(wParam) == ID_PREVIEW_NEXTPAGE)
1661                     preview.page++;
1662                 else
1663                     preview.page--;
1664
1665                 preview.hdc = 0;
1666                 preview.window.right = 0;
1667
1668                 GetClientRect(hMainWnd, &rc);
1669                 rc.top += SendMessageW(hReBar, RB_GETBARHEIGHT, 0, 0);
1670                 InvalidateRect(hMainWnd, &rc, TRUE);
1671             }
1672             break;
1673
1674         case ID_PRINT:
1675             dialog_print();
1676             preview_exit();
1677             break;
1678     }
1679
1680     return 0;
1681 }
1682
1683
1684 static void dialog_about(void)
1685 {
1686     HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hMainWnd, GWLP_HINSTANCE);
1687     HICON icon = LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_WORDPAD));
1688     ShellAboutW(hMainWnd, wszAppTitle, 0, icon);
1689 }
1690
1691 static INT_PTR CALLBACK formatopts_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
1692 {
1693     switch(message)
1694     {
1695         case WM_INITDIALOG:
1696             {
1697                 LPPROPSHEETPAGEW ps = (LPPROPSHEETPAGEW)lParam;
1698                 int wrap = -1;
1699                 char id[4];
1700                 HWND hIdWnd = GetDlgItem(hWnd, IDC_PAGEFMT_ID);
1701
1702                 sprintf(id, "%d\n", (int)ps->lParam);
1703                 SetWindowTextA(hIdWnd, id);
1704                 if(wordWrap[ps->lParam] == ID_WORDWRAP_WINDOW)
1705                     wrap = IDC_PAGEFMT_WW;
1706                 else if(wordWrap[ps->lParam] == ID_WORDWRAP_MARGIN)
1707                     wrap = IDC_PAGEFMT_WM;
1708
1709                 if(wrap != -1)
1710                     CheckRadioButton(hWnd, IDC_PAGEFMT_WW,
1711                                      IDC_PAGEFMT_WM, wrap);
1712
1713                 if(barState[ps->lParam] & (1 << BANDID_TOOLBAR))
1714                     CheckDlgButton(hWnd, IDC_PAGEFMT_TB, TRUE);
1715                 if(barState[ps->lParam] & (1 << BANDID_FORMATBAR))
1716                     CheckDlgButton(hWnd, IDC_PAGEFMT_FB, TRUE);
1717                 if(barState[ps->lParam] & (BANDID_STATUSBAR))
1718                     CheckDlgButton(hWnd, IDC_PAGEFMT_SB, TRUE);
1719             }
1720             break;
1721
1722         case WM_COMMAND:
1723             switch(LOWORD(wParam))
1724             {
1725                 case IDC_PAGEFMT_WW:
1726                 case IDC_PAGEFMT_WM:
1727                     CheckRadioButton(hWnd, IDC_PAGEFMT_WW, IDC_PAGEFMT_WM,
1728                                      LOWORD(wParam));
1729                     break;
1730
1731                 case IDC_PAGEFMT_TB:
1732                 case IDC_PAGEFMT_FB:
1733                 case IDC_PAGEFMT_SB:
1734                     CheckDlgButton(hWnd, LOWORD(wParam),
1735                                    !IsDlgButtonChecked(hWnd, LOWORD(wParam)));
1736                     break;
1737             }
1738             break;
1739         case WM_NOTIFY:
1740             {
1741                 LPNMHDR header = (LPNMHDR)lParam;
1742                 if(header->code == PSN_APPLY)
1743                 {
1744                     HWND hIdWnd = GetDlgItem(hWnd, IDC_PAGEFMT_ID);
1745                     char sid[4];
1746                     int id;
1747
1748                     GetWindowTextA(hIdWnd, sid, 4);
1749                     id = atoi(sid);
1750                     if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_WW))
1751                         wordWrap[id] = ID_WORDWRAP_WINDOW;
1752                     else if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_WM))
1753                         wordWrap[id] = ID_WORDWRAP_MARGIN;
1754
1755                     if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_TB))
1756                         barState[id] |= (1 << BANDID_TOOLBAR);
1757                     else
1758                         barState[id] &= ~(1 << BANDID_TOOLBAR);
1759
1760                     if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_FB))
1761                         barState[id] |= (1 << BANDID_FORMATBAR);
1762                     else
1763                         barState[id] &= ~(1 << BANDID_FORMATBAR);
1764
1765                     if(IsDlgButtonChecked(hWnd, IDC_PAGEFMT_SB))
1766                         barState[id] |= (1 << BANDID_STATUSBAR);
1767                     else
1768                         barState[id] &= ~(1 << BANDID_STATUSBAR);
1769                 }
1770             }
1771             break;
1772     }
1773     return FALSE;
1774 }
1775
1776 static void dialog_viewproperties(void)
1777 {
1778     PROPSHEETPAGEW psp[2];
1779     PROPSHEETHEADERW psh;
1780     int i;
1781     HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hMainWnd, GWLP_HINSTANCE);
1782     LPCPROPSHEETPAGEW ppsp = (LPCPROPSHEETPAGEW)&psp;
1783
1784     psp[0].dwSize = sizeof(PROPSHEETPAGEW);
1785     psp[0].dwFlags = PSP_USETITLE;
1786     U(psp[0]).pszTemplate = MAKEINTRESOURCEW(IDD_FORMATOPTS);
1787     psp[0].pfnDlgProc = formatopts_proc;
1788     psp[0].hInstance = hInstance;
1789     psp[0].lParam = reg_formatindex(SF_TEXT);
1790     psp[0].pfnCallback = NULL;
1791     psp[0].pszTitle = MAKEINTRESOURCEW(STRING_VIEWPROPS_TEXT);
1792     for(i = 1; i < sizeof(psp)/sizeof(psp[0]); i++)
1793     {
1794         psp[i].dwSize = psp[0].dwSize;
1795         psp[i].dwFlags = psp[0].dwFlags;
1796         U(psp[i]).pszTemplate = U(psp[0]).pszTemplate;
1797         psp[i].pfnDlgProc = psp[0].pfnDlgProc;
1798         psp[i].hInstance = psp[0].hInstance;
1799         psp[i].lParam = reg_formatindex(SF_RTF);
1800         psp[i].pfnCallback = psp[0].pfnCallback;
1801         psp[i].pszTitle = MAKEINTRESOURCEW(STRING_VIEWPROPS_RICHTEXT);
1802     }
1803
1804     psh.dwSize = sizeof(psh);
1805     psh.dwFlags = PSH_USEICONID | PSH_PROPSHEETPAGE | PSH_NOAPPLYNOW;
1806     psh.hwndParent = hMainWnd;
1807     psh.hInstance = hInstance;
1808     psh.pszCaption = MAKEINTRESOURCEW(STRING_VIEWPROPS_TITLE);
1809     psh.nPages = sizeof(psp)/sizeof(psp[0]);
1810     U3(psh).ppsp = ppsp;
1811     U(psh).pszIcon = MAKEINTRESOURCEW(IDI_WORDPAD);
1812
1813     if(fileFormat & SF_RTF)
1814         U2(psh).nStartPage = 1;
1815     else
1816         U2(psh).nStartPage = 0;
1817     PropertySheetW(&psh);
1818     set_bar_states();
1819     target_device();
1820 }
1821
1822 static void HandleCommandLine(LPWSTR cmdline)
1823 {
1824     WCHAR delimiter;
1825     int opt_print = 0;
1826
1827     /* skip white space */
1828     while (*cmdline == ' ') cmdline++;
1829
1830     /* skip executable name */
1831     delimiter = (*cmdline == '"' ? '"' : ' ');
1832
1833     if (*cmdline == delimiter) cmdline++;
1834     while (*cmdline && *cmdline != delimiter) cmdline++;
1835     if (*cmdline == delimiter) cmdline++;
1836
1837     while (*cmdline == ' ' || *cmdline == '-' || *cmdline == '/')
1838     {
1839         WCHAR option;
1840
1841         if (*cmdline++ == ' ') continue;
1842
1843         option = *cmdline;
1844         if (option) cmdline++;
1845         while (*cmdline == ' ') cmdline++;
1846
1847         switch (option)
1848         {
1849             case 'p':
1850             case 'P':
1851                 opt_print = 1;
1852                 break;
1853         }
1854     }
1855
1856     if (*cmdline)
1857     {
1858         /* file name is passed on the command line */
1859         if (cmdline[0] == '"')
1860         {
1861             cmdline++;
1862             cmdline[lstrlenW(cmdline) - 1] = 0;
1863         }
1864         DoOpenFile(cmdline);
1865         InvalidateRect(hMainWnd, NULL, FALSE);
1866     }
1867
1868     if (opt_print)
1869         MessageBox(hMainWnd, "Printing not implemented", "WordPad", MB_OK);
1870 }
1871
1872 static LRESULT handle_findmsg(LPFINDREPLACEW pFr)
1873 {
1874     if(pFr->Flags & FR_DIALOGTERM)
1875     {
1876         hFindWnd = 0;
1877         pFr->Flags = FR_FINDNEXT;
1878         return 0;
1879     }
1880
1881     if(pFr->Flags & FR_FINDNEXT || pFr->Flags & FR_REPLACE || pFr->Flags & FR_REPLACEALL)
1882     {
1883         DWORD flags = FR_DOWN;
1884         FINDTEXTW ft;
1885         static CHARRANGE cr;
1886         LRESULT end, ret;
1887         GETTEXTLENGTHEX gt;
1888         LRESULT length;
1889         int startPos;
1890         HMENU hMenu = GetMenu(hMainWnd);
1891         MENUITEMINFOW mi;
1892
1893         mi.cbSize = sizeof(mi);
1894         mi.fMask = MIIM_DATA;
1895         mi.dwItemData = 1;
1896         SetMenuItemInfoW(hMenu, ID_FIND_NEXT, FALSE, &mi);
1897
1898         gt.flags = GTL_NUMCHARS;
1899         gt.codepage = 1200;
1900
1901         length = SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0);
1902
1903         if(pFr->lCustData == -1)
1904         {
1905             SendMessageW(hEditorWnd, EM_GETSEL, (WPARAM)&startPos, (LPARAM)&end);
1906             cr.cpMin = startPos;
1907             pFr->lCustData = startPos;
1908             cr.cpMax = length;
1909             if(cr.cpMin == length)
1910                 cr.cpMin = 0;
1911         } else
1912         {
1913             startPos = pFr->lCustData;
1914         }
1915
1916         if(cr.cpMax > length)
1917         {
1918             startPos = 0;
1919             cr.cpMin = 0;
1920             cr.cpMax = length;
1921         }
1922
1923         ft.chrg = cr;
1924         ft.lpstrText = pFr->lpstrFindWhat;
1925
1926         if(pFr->Flags & FR_MATCHCASE)
1927             flags |= FR_MATCHCASE;
1928         if(pFr->Flags & FR_WHOLEWORD)
1929             flags |= FR_WHOLEWORD;
1930
1931         ret = SendMessageW(hEditorWnd, EM_FINDTEXTW, (WPARAM)flags, (LPARAM)&ft);
1932
1933         if(ret == -1)
1934         {
1935             if(cr.cpMax == length && cr.cpMax != startPos)
1936             {
1937                 ft.chrg.cpMin = cr.cpMin = 0;
1938                 ft.chrg.cpMax = cr.cpMax = startPos;
1939
1940                 ret = SendMessageW(hEditorWnd, EM_FINDTEXTW, (WPARAM)flags, (LPARAM)&ft);
1941             }
1942         }
1943
1944         if(ret == -1)
1945         {
1946             pFr->lCustData = -1;
1947             MessageBoxW(hMainWnd, MAKEINTRESOURCEW(STRING_SEARCH_FINISHED), wszAppTitle,
1948                         MB_OK | MB_ICONASTERISK);
1949         } else
1950         {
1951             end = ret + lstrlenW(pFr->lpstrFindWhat);
1952             cr.cpMin = end;
1953             SendMessageW(hEditorWnd, EM_SETSEL, (WPARAM)ret, (LPARAM)end);
1954             SendMessageW(hEditorWnd, EM_SCROLLCARET, 0, 0);
1955
1956             if(pFr->Flags & FR_REPLACE || pFr->Flags & FR_REPLACEALL)
1957                 SendMessageW(hEditorWnd, EM_REPLACESEL, TRUE, (LPARAM)pFr->lpstrReplaceWith);
1958
1959             if(pFr->Flags & FR_REPLACEALL)
1960                 handle_findmsg(pFr);
1961         }
1962     }
1963
1964     return 0;
1965 }
1966
1967 static void dialog_find(LPFINDREPLACEW fr, BOOL replace)
1968 {
1969     static WCHAR findBuffer[MAX_STRING_LEN];
1970
1971     ZeroMemory(fr, sizeof(FINDREPLACEW));
1972     fr->lStructSize = sizeof(FINDREPLACEW);
1973     fr->hwndOwner = hMainWnd;
1974     fr->Flags = FR_HIDEUPDOWN;
1975     fr->lpstrFindWhat = findBuffer;
1976     fr->lCustData = -1;
1977     fr->wFindWhatLen = MAX_STRING_LEN*sizeof(WCHAR);
1978
1979     if(replace)
1980         hFindWnd = ReplaceTextW(fr);
1981     else
1982         hFindWnd = FindTextW(fr);
1983 }
1984
1985 static void registry_read_options(void)
1986 {
1987     HKEY hKey;
1988     DWORD size = sizeof(RECT);
1989
1990     if(registry_get_handle(&hKey, 0, key_options) != ERROR_SUCCESS ||
1991        RegQueryValueExW(hKey, var_pagemargin, 0, NULL, (LPBYTE)&margins,
1992                         &size) != ERROR_SUCCESS || size != sizeof(RECT))
1993     {
1994         margins.top = 1417;
1995         margins.bottom = 1417;
1996         margins.left = 1757;
1997         margins.right = 1757;
1998     }
1999
2000     RegCloseKey(hKey);
2001 }
2002
2003 static void registry_read_formatopts(int index, LPCWSTR key)
2004 {
2005     HKEY hKey;
2006     DWORD action = 0;
2007     BOOL fetched = FALSE;
2008     barState[index] = 0;
2009     wordWrap[index] = 0;
2010
2011     if(registry_get_handle(&hKey, &action, key) != ERROR_SUCCESS)
2012         return;
2013
2014     if(action == REG_OPENED_EXISTING_KEY)
2015     {
2016         DWORD size = sizeof(DWORD);
2017
2018         if(RegQueryValueExW(hKey, var_barstate0, 0, NULL, (LPBYTE)&barState[index],
2019                          &size) == ERROR_SUCCESS)
2020             fetched = TRUE;
2021     }
2022
2023     if(!fetched)
2024         barState[index] = (1 << BANDID_TOOLBAR) | (1 << BANDID_FORMATBAR) | (1 << BANDID_RULER) | (1 << BANDID_STATUSBAR);
2025
2026     if(index == reg_formatindex(SF_RTF))
2027         wordWrap[index] = ID_WORDWRAP_WINDOW;
2028     else if(index == reg_formatindex(SF_TEXT))
2029         wordWrap[index] = ID_WORDWRAP_WINDOW; /* FIXME: should be ID_WORDWRAP_NONE once we support it */
2030
2031     RegCloseKey(hKey);
2032 }
2033
2034 static void registry_read_formatopts_all(void)
2035 {
2036     registry_read_formatopts(reg_formatindex(SF_RTF), key_rtf);
2037     registry_read_formatopts(reg_formatindex(SF_TEXT), key_text);
2038 }
2039
2040 static void registry_set_formatopts(int index, LPCWSTR key)
2041 {
2042     HKEY hKey;
2043     DWORD action = 0;
2044
2045     if(registry_get_handle(&hKey, &action, key) == ERROR_SUCCESS)
2046     {
2047         RegSetValueExW(hKey, var_barstate0, 0, REG_DWORD, (LPBYTE)&barState[index],
2048                        sizeof(DWORD));
2049
2050         RegCloseKey(hKey);
2051     }
2052 }
2053
2054 static void registry_set_formatopts_all(void)
2055 {
2056     registry_set_formatopts(reg_formatindex(SF_RTF), key_rtf);
2057     registry_set_formatopts(reg_formatindex(SF_TEXT), key_text);
2058 }
2059
2060 static int current_units_to_twips(float number)
2061 {
2062     int twips = (int)(number * 567);
2063     return twips;
2064 }
2065
2066 static void append_current_units(LPWSTR buffer)
2067 {
2068     static const WCHAR space[] = {' '};
2069     lstrcatW(buffer, space);
2070     lstrcatW(buffer, units_cmW);
2071 }
2072
2073 static void number_with_units(LPWSTR buffer, int number)
2074 {
2075     float converted = (float)number / 567;
2076     char string[MAX_STRING_LEN];
2077
2078     sprintf(string, "%.2f ", converted);
2079     lstrcatA(string, units_cmA);
2080     MultiByteToWideChar(CP_ACP, 0, string, -1, buffer, MAX_STRING_LEN);
2081 }
2082
2083 BOOL CALLBACK datetime_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
2084 {
2085     switch(message)
2086     {
2087         case WM_INITDIALOG:
2088             {
2089                 WCHAR buffer[MAX_STRING_LEN];
2090                 SYSTEMTIME st;
2091                 HWND hListWnd = GetDlgItem(hWnd, IDC_DATETIME);
2092                 GetLocalTime(&st);
2093
2094                 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st, 0, (LPWSTR)&buffer,
2095                                MAX_STRING_LEN);
2096                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
2097                 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, 0, (LPWSTR)&buffer,
2098                                MAX_STRING_LEN);
2099                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
2100                 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, 0, (LPWSTR)&buffer, MAX_STRING_LEN);
2101                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
2102
2103                 SendMessageW(hListWnd, LB_SETSEL, TRUE, 0);
2104             }
2105             break;
2106
2107         case WM_COMMAND:
2108             switch(LOWORD(wParam))
2109             {
2110                 case IDOK:
2111                     {
2112                         LRESULT index;
2113                         HWND hListWnd = GetDlgItem(hWnd, IDC_DATETIME);
2114
2115                         index = SendMessageW(hListWnd, LB_GETCURSEL, 0, 0);
2116
2117                         if(index != LB_ERR)
2118                         {
2119                             WCHAR buffer[MAX_STRING_LEN];
2120                             SendMessageW(hListWnd, LB_GETTEXT, index, (LPARAM)&buffer);
2121                             SendMessageW(hEditorWnd, EM_REPLACESEL, TRUE, (LPARAM)&buffer);
2122                         }
2123                     }
2124                     /* Fall through */
2125
2126                 case IDCANCEL:
2127                     EndDialog(hWnd, wParam);
2128                     return TRUE;
2129             }
2130     }
2131     return FALSE;
2132 }
2133
2134 BOOL CALLBACK newfile_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
2135 {
2136     switch(message)
2137     {
2138         case WM_INITDIALOG:
2139             {
2140                 HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hMainWnd, GWLP_HINSTANCE);
2141                 WCHAR buffer[MAX_STRING_LEN];
2142                 HWND hListWnd = GetDlgItem(hWnd, IDC_NEWFILE);
2143
2144                 LoadStringW(hInstance, STRING_NEWFILE_RICHTEXT, (LPWSTR)buffer, MAX_STRING_LEN);
2145                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
2146                 LoadStringW(hInstance, STRING_NEWFILE_TXT, (LPWSTR)buffer, MAX_STRING_LEN);
2147                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
2148                 LoadStringW(hInstance, STRING_NEWFILE_TXT_UNICODE, (LPWSTR)buffer, MAX_STRING_LEN);
2149                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
2150
2151                 SendMessageW(hListWnd, LB_SETSEL, TRUE, 0);
2152             }
2153             break;
2154
2155         case WM_COMMAND:
2156             switch(LOWORD(wParam))
2157             {
2158                 case IDOK:
2159                     {
2160                         LRESULT index;
2161                         HWND hListWnd = GetDlgItem(hWnd, IDC_NEWFILE);
2162                         index = SendMessageW(hListWnd, LB_GETCURSEL, 0, 0);
2163
2164                         if(index != LB_ERR)
2165                             EndDialog(hWnd, MAKELONG(fileformat_flags(index),0));
2166                     }
2167                     return TRUE;
2168
2169                 case IDCANCEL:
2170                     EndDialog(hWnd, MAKELONG(ID_NEWFILE_ABORT,0));
2171                     return TRUE;
2172             }
2173     }
2174     return FALSE;
2175 }
2176
2177 static INT_PTR CALLBACK paraformat_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
2178 {
2179     switch(message)
2180     {
2181         case WM_INITDIALOG:
2182             {
2183                 HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hMainWnd,
2184                                                                   GWLP_HINSTANCE);
2185                 WCHAR buffer[MAX_STRING_LEN];
2186                 HWND hListWnd = GetDlgItem(hWnd, IDC_PARA_ALIGN);
2187                 HWND hLeftWnd = GetDlgItem(hWnd, IDC_PARA_LEFT);
2188                 HWND hRightWnd = GetDlgItem(hWnd, IDC_PARA_RIGHT);
2189                 HWND hFirstWnd = GetDlgItem(hWnd, IDC_PARA_FIRST);
2190                 PARAFORMAT2 pf;
2191                 int index = 0;
2192
2193                 LoadStringW(hInstance, STRING_ALIGN_LEFT, buffer,
2194                             MAX_STRING_LEN);
2195                 SendMessageW(hListWnd, CB_ADDSTRING, 0, (LPARAM)buffer);
2196                 LoadStringW(hInstance, STRING_ALIGN_RIGHT, buffer,
2197                             MAX_STRING_LEN);
2198                 SendMessageW(hListWnd, CB_ADDSTRING, 0, (LPARAM)buffer);
2199                 LoadStringW(hInstance, STRING_ALIGN_CENTER, buffer,
2200                             MAX_STRING_LEN);
2201                 SendMessageW(hListWnd, CB_ADDSTRING, 0, (LPARAM)buffer);
2202
2203                 pf.cbSize = sizeof(pf);
2204                 pf.dwMask = PFM_ALIGNMENT | PFM_OFFSET | PFM_RIGHTINDENT |
2205                             PFM_OFFSETINDENT;
2206                 SendMessageW(hEditorWnd, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
2207
2208                 if(pf.wAlignment == PFA_RIGHT)
2209                     index ++;
2210                 else if(pf.wAlignment == PFA_CENTER)
2211                     index += 2;
2212
2213                 SendMessageW(hListWnd, CB_SETCURSEL, index, 0);
2214
2215                 number_with_units(buffer, pf.dxOffset);
2216                 SetWindowTextW(hLeftWnd, buffer);
2217                 number_with_units(buffer, pf.dxRightIndent);
2218                 SetWindowTextW(hRightWnd, buffer);
2219                 number_with_units(buffer, pf.dxStartIndent - pf.dxOffset);
2220                 SetWindowTextW(hFirstWnd, buffer);
2221             }
2222             break;
2223
2224         case WM_COMMAND:
2225             switch(LOWORD(wParam))
2226             {
2227                 case IDOK:
2228                     {
2229                         HWND hLeftWnd = GetDlgItem(hWnd, IDC_PARA_LEFT);
2230                         HWND hRightWnd = GetDlgItem(hWnd, IDC_PARA_RIGHT);
2231                         HWND hFirstWnd = GetDlgItem(hWnd, IDC_PARA_FIRST);
2232                         WCHAR buffer[MAX_STRING_LEN];
2233                         float num;
2234                         int ret = 0;
2235                         PARAFORMAT pf;
2236
2237                         GetWindowTextW(hLeftWnd, buffer, MAX_STRING_LEN);
2238                         if(number_from_string(buffer, &num, TRUE))
2239                             ret++;
2240                         pf.dxOffset = current_units_to_twips(num);
2241                         GetWindowTextW(hRightWnd, buffer, MAX_STRING_LEN);
2242                         if(number_from_string(buffer, &num, TRUE))
2243                             ret++;
2244                         pf.dxRightIndent = current_units_to_twips(num);
2245                         GetWindowTextW(hFirstWnd, buffer, MAX_STRING_LEN);
2246                         if(number_from_string(buffer, &num, TRUE))
2247                             ret++;
2248                         pf.dxStartIndent = current_units_to_twips(num);
2249
2250                         if(ret != 3)
2251                         {
2252                             MessageBoxW(hMainWnd, MAKEINTRESOURCEW(STRING_INVALID_NUMBER),
2253                                         wszAppTitle, MB_OK | MB_ICONASTERISK);
2254                             return FALSE;
2255                         } else
2256                         {
2257                             pf.dxStartIndent = pf.dxStartIndent + pf.dxOffset;
2258                             pf.cbSize = sizeof(pf);
2259                             pf.dwMask = PFM_OFFSET | PFM_OFFSETINDENT | PFM_RIGHTINDENT;
2260                             SendMessageW(hEditorWnd, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
2261                         }
2262                     }
2263                     /* Fall through */
2264
2265                 case IDCANCEL:
2266                     EndDialog(hWnd, wParam);
2267                     return TRUE;
2268             }
2269     }
2270     return FALSE;
2271 }
2272
2273 static INT_PTR CALLBACK tabstops_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
2274 {
2275     switch(message)
2276     {
2277         case WM_INITDIALOG:
2278             {
2279                 HWND hTabWnd = GetDlgItem(hWnd, IDC_TABSTOPS);
2280                 PARAFORMAT pf;
2281                 WCHAR buffer[MAX_STRING_LEN];
2282                 int i;
2283
2284                 pf.cbSize = sizeof(pf);
2285                 pf.dwMask = PFM_TABSTOPS;
2286                 SendMessageW(hEditorWnd, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
2287                 SendMessageW(hTabWnd, CB_LIMITTEXT, MAX_STRING_LEN-1, 0);
2288
2289                 for(i = 0; i < pf.cTabCount; i++)
2290                 {
2291                     number_with_units(buffer, pf.rgxTabs[i]);
2292                     SendMessageW(hTabWnd, CB_ADDSTRING, 0, (LPARAM)&buffer);
2293                 }
2294                 SetFocus(hTabWnd);
2295             }
2296             break;
2297
2298         case WM_COMMAND:
2299             switch(LOWORD(wParam))
2300             {
2301                 case IDC_TABSTOPS:
2302                     {
2303                         HWND hTabWnd = (HWND)lParam;
2304                         HWND hAddWnd = GetDlgItem(hWnd, ID_TAB_ADD);
2305                         HWND hDelWnd = GetDlgItem(hWnd, ID_TAB_DEL);
2306                         HWND hEmptyWnd = GetDlgItem(hWnd, ID_TAB_EMPTY);
2307
2308                         if(GetWindowTextLengthW(hTabWnd))
2309                             EnableWindow(hAddWnd, TRUE);
2310                         else
2311                             EnableWindow(hAddWnd, FALSE);
2312
2313                         if(SendMessageW(hTabWnd, CB_GETCOUNT, 0, 0))
2314                         {
2315                             EnableWindow(hEmptyWnd, TRUE);
2316
2317                             if(SendMessageW(hTabWnd, CB_GETCURSEL, 0, 0) == CB_ERR)
2318                                 EnableWindow(hDelWnd, FALSE);
2319                             else
2320                                 EnableWindow(hDelWnd, TRUE);
2321                         } else
2322                         {
2323                             EnableWindow(hEmptyWnd, FALSE);
2324                         }
2325                     }
2326                     break;
2327
2328                 case ID_TAB_ADD:
2329                     {
2330                         HWND hTabWnd = GetDlgItem(hWnd, IDC_TABSTOPS);
2331                         WCHAR buffer[MAX_STRING_LEN];
2332
2333                         GetWindowTextW(hTabWnd, buffer, MAX_STRING_LEN);
2334                         append_current_units(buffer);
2335
2336                         if(SendMessageW(hTabWnd, CB_FINDSTRINGEXACT, -1, (LPARAM)&buffer) == CB_ERR)
2337                         {
2338                             float number = 0;
2339
2340                             if(!number_from_string(buffer, &number, TRUE))
2341                             {
2342                                 MessageBoxW(hWnd, MAKEINTRESOURCEW(STRING_INVALID_NUMBER),
2343                                              wszAppTitle, MB_OK | MB_ICONINFORMATION);
2344                             } else
2345                             {
2346                                 SendMessageW(hTabWnd, CB_ADDSTRING, 0, (LPARAM)&buffer);
2347                                 SetWindowTextW(hTabWnd, 0);
2348                             }
2349                         }
2350                         SetFocus(hTabWnd);
2351                     }
2352                     break;
2353
2354                 case ID_TAB_DEL:
2355                     {
2356                         HWND hTabWnd = GetDlgItem(hWnd, IDC_TABSTOPS);
2357                         LRESULT ret;
2358                         ret = SendMessageW(hTabWnd, CB_GETCURSEL, 0, 0);
2359                         if(ret != CB_ERR)
2360                             SendMessageW(hTabWnd, CB_DELETESTRING, ret, 0);
2361                     }
2362                     break;
2363
2364                 case ID_TAB_EMPTY:
2365                     {
2366                         HWND hTabWnd = GetDlgItem(hWnd, IDC_TABSTOPS);
2367                         SendMessageW(hTabWnd, CB_RESETCONTENT, 0, 0);
2368                         SetFocus(hTabWnd);
2369                     }
2370                     break;
2371
2372                 case IDOK:
2373                     {
2374                         HWND hTabWnd = GetDlgItem(hWnd, IDC_TABSTOPS);
2375                         int i;
2376                         WCHAR buffer[MAX_STRING_LEN];
2377                         PARAFORMAT pf;
2378                         float number;
2379
2380                         pf.cbSize = sizeof(pf);
2381                         pf.dwMask = PFM_TABSTOPS;
2382
2383                         for(i = 0; SendMessageW(hTabWnd, CB_GETLBTEXT, i,
2384                                                 (LPARAM)&buffer) != CB_ERR &&
2385                                                         i < MAX_TAB_STOPS; i++)
2386                         {
2387                             number_from_string(buffer, &number, TRUE);
2388                             pf.rgxTabs[i] = current_units_to_twips(number);
2389                         }
2390                         pf.cTabCount = i;
2391                         SendMessageW(hEditorWnd, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
2392                     }
2393                     /* Fall through */
2394                 case IDCANCEL:
2395                     EndDialog(hWnd, wParam);
2396                     return TRUE;
2397             }
2398     }
2399     return FALSE;
2400 }
2401
2402 static int context_menu(LPARAM lParam)
2403 {
2404     int x = (int)(short)LOWORD(lParam);
2405     int y = (int)(short)HIWORD(lParam);
2406     HMENU hPop = GetSubMenu(hPopupMenu, 0);
2407
2408     if(x == -1)
2409     {
2410         int from = 0, to = 0;
2411         POINTL pt;
2412         SendMessageW(hEditorWnd, EM_GETSEL, (WPARAM)&from, (LPARAM)&to);
2413         SendMessageW(hEditorWnd, EM_POSFROMCHAR, (WPARAM)&pt, (LPARAM)to);
2414         ClientToScreen(hEditorWnd, (POINT*)&pt);
2415         x = pt.x;
2416         y = pt.y;
2417     }
2418
2419     TrackPopupMenu(hPop, TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2420                    x, y, 0, hMainWnd, 0);
2421
2422     return 0;
2423 }
2424
2425 static LRESULT OnCreate( HWND hWnd, WPARAM wParam, LPARAM lParam)
2426 {
2427     HWND hToolBarWnd, hFormatBarWnd,  hReBarWnd, hFontListWnd, hSizeListWnd;
2428     HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE);
2429     HANDLE hDLL;
2430     TBADDBITMAP ab;
2431     int nStdBitmaps = 0;
2432     REBARINFO rbi;
2433     REBARBANDINFOW rbb;
2434     static const WCHAR wszRichEditDll[] = {'R','I','C','H','E','D','2','0','.','D','L','L','\0'};
2435     static const WCHAR wszRichEditText[] = {'R','i','c','h','E','d','i','t',' ','t','e','x','t','\0'};
2436
2437     CreateStatusWindowW(CCS_NODIVIDER|WS_CHILD|WS_VISIBLE, wszRichEditText, hWnd, IDC_STATUSBAR);
2438
2439     hReBarWnd = CreateWindowExW(WS_EX_TOOLWINDOW, REBARCLASSNAMEW, NULL,
2440       CCS_NODIVIDER|WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|RBS_VARHEIGHT|CCS_TOP,
2441       CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, hWnd, (HMENU)IDC_REBAR, hInstance, NULL);
2442
2443     rbi.cbSize = sizeof(rbi);
2444     rbi.fMask = 0;
2445     rbi.himl = NULL;
2446     if(!SendMessageW(hReBarWnd, RB_SETBARINFO, 0, (LPARAM)&rbi))
2447         return -1;
2448
2449     hToolBarWnd = CreateToolbarEx(hReBarWnd, CCS_NOPARENTALIGN|CCS_NOMOVEY|WS_VISIBLE|WS_CHILD|TBSTYLE_TOOLTIPS|TBSTYLE_BUTTON,
2450       IDC_TOOLBAR,
2451       1, hInstance, IDB_TOOLBAR,
2452       NULL, 0,
2453       24, 24, 16, 16, sizeof(TBBUTTON));
2454
2455     ab.hInst = HINST_COMMCTRL;
2456     ab.nID = IDB_STD_SMALL_COLOR;
2457     nStdBitmaps = SendMessageW(hToolBarWnd, TB_ADDBITMAP, 0, (LPARAM)&ab);
2458
2459     AddButton(hToolBarWnd, nStdBitmaps+STD_FILENEW, ID_FILE_NEW);
2460     AddButton(hToolBarWnd, nStdBitmaps+STD_FILEOPEN, ID_FILE_OPEN);
2461     AddButton(hToolBarWnd, nStdBitmaps+STD_FILESAVE, ID_FILE_SAVE);
2462     AddSeparator(hToolBarWnd);
2463     AddButton(hToolBarWnd, nStdBitmaps+STD_PRINT, ID_PRINT_QUICK);
2464     AddButton(hToolBarWnd, nStdBitmaps+STD_PRINTPRE, ID_PREVIEW);
2465     AddSeparator(hToolBarWnd);
2466     AddButton(hToolBarWnd, nStdBitmaps+STD_FIND, ID_FIND);
2467     AddSeparator(hToolBarWnd);
2468     AddButton(hToolBarWnd, nStdBitmaps+STD_CUT, ID_EDIT_CUT);
2469     AddButton(hToolBarWnd, nStdBitmaps+STD_COPY, ID_EDIT_COPY);
2470     AddButton(hToolBarWnd, nStdBitmaps+STD_PASTE, ID_EDIT_PASTE);
2471     AddButton(hToolBarWnd, nStdBitmaps+STD_UNDO, ID_EDIT_UNDO);
2472     AddButton(hToolBarWnd, nStdBitmaps+STD_REDOW, ID_EDIT_REDO);
2473     AddSeparator(hToolBarWnd);
2474     AddButton(hToolBarWnd, 0, ID_DATETIME);
2475
2476     SendMessageW(hToolBarWnd, TB_AUTOSIZE, 0, 0);
2477
2478     rbb.cbSize = sizeof(rbb);
2479     rbb.fMask = RBBIM_SIZE | RBBIM_CHILDSIZE | RBBIM_CHILD | RBBIM_STYLE | RBBIM_ID;
2480     rbb.fStyle = RBBS_CHILDEDGE | RBBS_BREAK | RBBS_NOGRIPPER;
2481     rbb.cx = 0;
2482     rbb.hwndChild = hToolBarWnd;
2483     rbb.cxMinChild = 0;
2484     rbb.cyChild = rbb.cyMinChild = HIWORD(SendMessageW(hToolBarWnd, TB_GETBUTTONSIZE, 0, 0));
2485     rbb.wID = BANDID_TOOLBAR;
2486
2487     SendMessageW(hReBarWnd, RB_INSERTBAND, -1, (LPARAM)&rbb);
2488
2489     hFontListWnd = CreateWindowExW(0, WC_COMBOBOXEXW, NULL,
2490                       WS_BORDER | WS_VISIBLE | WS_CHILD | CBS_DROPDOWN | CBS_SORT,
2491                       0, 0, 200, 150, hReBarWnd, (HMENU)IDC_FONTLIST, hInstance, NULL);
2492
2493     rbb.hwndChild = hFontListWnd;
2494     rbb.cx = 200;
2495     rbb.wID = BANDID_FONTLIST;
2496
2497     SendMessageW(hReBarWnd, RB_INSERTBAND, -1, (LPARAM)&rbb);
2498
2499     hSizeListWnd = CreateWindowExW(0, WC_COMBOBOXEXW, NULL,
2500                       WS_BORDER | WS_VISIBLE | WS_CHILD | CBS_DROPDOWN,
2501                       0, 0, 50, 150, hReBarWnd, (HMENU)IDC_SIZELIST, hInstance, NULL);
2502
2503     rbb.hwndChild = hSizeListWnd;
2504     rbb.cx = 50;
2505     rbb.fStyle ^= RBBS_BREAK;
2506     rbb.wID = BANDID_SIZELIST;
2507
2508     SendMessageW(hReBarWnd, RB_INSERTBAND, -1, (LPARAM)&rbb);
2509
2510     hFormatBarWnd = CreateToolbarEx(hReBarWnd,
2511          CCS_NOPARENTALIGN | CCS_NOMOVEY | WS_VISIBLE | TBSTYLE_TOOLTIPS | TBSTYLE_BUTTON,
2512          IDC_FORMATBAR, 7, hInstance, IDB_FORMATBAR, NULL, 0, 16, 16, 16, 16, sizeof(TBBUTTON));
2513
2514     AddButton(hFormatBarWnd, 0, ID_FORMAT_BOLD);
2515     AddButton(hFormatBarWnd, 1, ID_FORMAT_ITALIC);
2516     AddButton(hFormatBarWnd, 2, ID_FORMAT_UNDERLINE);
2517     AddSeparator(hFormatBarWnd);
2518     AddButton(hFormatBarWnd, 3, ID_ALIGN_LEFT);
2519     AddButton(hFormatBarWnd, 4, ID_ALIGN_CENTER);
2520     AddButton(hFormatBarWnd, 5, ID_ALIGN_RIGHT);
2521     AddSeparator(hFormatBarWnd);
2522     AddButton(hFormatBarWnd, 6, ID_BULLET);
2523
2524     SendMessageW(hFormatBarWnd, TB_AUTOSIZE, 0, 0);
2525
2526     rbb.hwndChild = hFormatBarWnd;
2527     rbb.wID = BANDID_FORMATBAR;
2528
2529     SendMessageW(hReBarWnd, RB_INSERTBAND, -1, (LPARAM)&rbb);
2530
2531     hDLL = LoadLibraryW(wszRichEditDll);
2532     if(!hDLL)
2533     {
2534         MessageBoxW(hWnd, MAKEINTRESOURCEW(STRING_LOAD_RICHED_FAILED), wszAppTitle,
2535                     MB_OK | MB_ICONEXCLAMATION);
2536         PostQuitMessage(1);
2537     }
2538
2539     hEditorWnd = CreateWindowExW(WS_EX_CLIENTEDGE, wszRichEditClass, NULL,
2540       WS_CHILD|WS_VISIBLE|ECO_SELECTIONBAR|ES_MULTILINE|ES_AUTOVSCROLL|ES_WANTRETURN|WS_VSCROLL,
2541       0, 0, 1000, 100, hWnd, (HMENU)IDC_EDITOR, hInstance, NULL);
2542
2543     if (!hEditorWnd)
2544     {
2545         fprintf(stderr, "Error code %u\n", GetLastError());
2546         return -1;
2547     }
2548     assert(hEditorWnd);
2549
2550     SetFocus(hEditorWnd);
2551     SendMessageW(hEditorWnd, EM_SETEVENTMASK, 0, ENM_SELCHANGE);
2552
2553     set_default_font();
2554
2555     populate_font_list(hFontListWnd);
2556     populate_size_list(hSizeListWnd);
2557     DoLoadStrings();
2558     SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
2559
2560     ID_FINDMSGSTRING = RegisterWindowMessageW(FINDMSGSTRINGW);
2561
2562     registry_read_filelist(hWnd);
2563     registry_read_formatopts_all();
2564     registry_read_options();
2565     DragAcceptFiles(hWnd, TRUE);
2566
2567     return 0;
2568 }
2569
2570 static LRESULT OnUser( HWND hWnd, WPARAM wParam, LPARAM lParam)
2571 {
2572     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
2573     HWND hwndReBar = GetDlgItem(hWnd, IDC_REBAR);
2574     HWND hwndToolBar = GetDlgItem(hwndReBar, IDC_TOOLBAR);
2575     HWND hwndFormatBar = GetDlgItem(hwndReBar, IDC_FORMATBAR);
2576     int from, to;
2577     CHARFORMAT2W fmt;
2578     PARAFORMAT2 pf;
2579     GETTEXTLENGTHEX gt;
2580
2581     ZeroMemory(&fmt, sizeof(fmt));
2582     fmt.cbSize = sizeof(fmt);
2583
2584     ZeroMemory(&pf, sizeof(pf));
2585     pf.cbSize = sizeof(pf);
2586
2587     gt.flags = GTL_NUMCHARS;
2588     gt.codepage = 1200;
2589
2590     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_FIND,
2591                  SendMessageW(hwndEditor, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0) ? 1 : 0);
2592
2593     SendMessageW(hwndEditor, EM_GETCHARFORMAT, TRUE, (LPARAM)&fmt);
2594
2595     SendMessageW(hwndEditor, EM_GETSEL, (WPARAM)&from, (LPARAM)&to);
2596     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_UNDO,
2597       SendMessageW(hwndEditor, EM_CANUNDO, 0, 0));
2598     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_REDO,
2599       SendMessageW(hwndEditor, EM_CANREDO, 0, 0));
2600     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_CUT, from == to ? 0 : 1);
2601     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_COPY, from == to ? 0 : 1);
2602
2603     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_FORMAT_BOLD, (fmt.dwMask & CFM_BOLD) &&
2604             (fmt.dwEffects & CFE_BOLD));
2605     SendMessageW(hwndFormatBar, TB_INDETERMINATE, ID_FORMAT_BOLD, !(fmt.dwMask & CFM_BOLD));
2606     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_FORMAT_ITALIC, (fmt.dwMask & CFM_ITALIC) &&
2607             (fmt.dwEffects & CFE_ITALIC));
2608     SendMessageW(hwndFormatBar, TB_INDETERMINATE, ID_FORMAT_ITALIC, !(fmt.dwMask & CFM_ITALIC));
2609     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_FORMAT_UNDERLINE, (fmt.dwMask & CFM_UNDERLINE) &&
2610             (fmt.dwEffects & CFE_UNDERLINE));
2611     SendMessageW(hwndFormatBar, TB_INDETERMINATE, ID_FORMAT_UNDERLINE, !(fmt.dwMask & CFM_UNDERLINE));
2612
2613     SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
2614     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_ALIGN_LEFT, (pf.wAlignment == PFA_LEFT));
2615     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_ALIGN_CENTER, (pf.wAlignment == PFA_CENTER));
2616     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_ALIGN_RIGHT, (pf.wAlignment == PFA_RIGHT));
2617
2618     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_BULLET, (pf.wNumbering & PFN_BULLET));
2619     return 0;
2620 }
2621
2622 static LRESULT OnNotify( HWND hWnd, WPARAM wParam, LPARAM lParam)
2623 {
2624     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
2625     HWND hwndReBar = GetDlgItem(hWnd, IDC_REBAR);
2626     NMHDR *pHdr = (NMHDR *)lParam;
2627     HWND hwndFontList = GetDlgItem(hwndReBar, IDC_FONTLIST);
2628     HWND hwndSizeList = GetDlgItem(hwndReBar, IDC_SIZELIST);
2629     WCHAR sizeBuffer[MAX_PATH];
2630
2631     if (pHdr->hwndFrom == hwndFontList || pHdr->hwndFrom == hwndSizeList)
2632     {
2633         if (pHdr->code == CBEN_ENDEDITW)
2634         {
2635             CHARFORMAT2W format;
2636             NMCBEENDEDIT *endEdit = (NMCBEENDEDIT *)lParam;
2637
2638             ZeroMemory(&format, sizeof(format));
2639             format.cbSize = sizeof(format);
2640             SendMessageW(hwndEditor, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
2641
2642             if(pHdr->hwndFrom == hwndFontList)
2643             {
2644                 if(lstrcmpW(format.szFaceName, (LPWSTR)endEdit->szText))
2645                     set_font((LPCWSTR) endEdit->szText);
2646             } else if (pHdr->hwndFrom == hwndSizeList)
2647             {
2648                 wsprintfW(sizeBuffer, stringFormat, format.yHeight / 20);
2649                 if(lstrcmpW(sizeBuffer, (LPWSTR)endEdit->szText))
2650                 {
2651                     float size = 0;
2652                     if(number_from_string((LPWSTR)endEdit->szText, &size, FALSE))
2653                     {
2654                         set_size(size);
2655                     } else
2656                     {
2657                         SetWindowTextW(hwndSizeList, sizeBuffer);
2658                         MessageBoxW(hMainWnd, MAKEINTRESOURCEW(STRING_INVALID_NUMBER), wszAppTitle, MB_OK | MB_ICONINFORMATION);
2659                     }
2660                 }
2661             }
2662         }
2663         return 0;
2664     }
2665
2666     if (pHdr->hwndFrom != hwndEditor)
2667         return 0;
2668
2669     if (pHdr->code == EN_SELCHANGE)
2670     {
2671         SELCHANGE *pSC = (SELCHANGE *)lParam;
2672         char buf[128];
2673
2674         update_font_list();
2675
2676         sprintf( buf,"selection = %d..%d, line count=%ld",
2677                  pSC->chrg.cpMin, pSC->chrg.cpMax,
2678         SendMessage(hwndEditor, EM_GETLINECOUNT, 0, 0));
2679         SetWindowText(GetDlgItem(hWnd, IDC_STATUSBAR), buf);
2680         SendMessage(hWnd, WM_USER, 0, 0);
2681         return 1;
2682     }
2683     return 0;
2684 }
2685
2686 static LRESULT OnCommand( HWND hWnd, WPARAM wParam, LPARAM lParam)
2687 {
2688     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
2689     static FINDREPLACEW findreplace;
2690
2691     if ((HWND)lParam == hwndEditor)
2692         return 0;
2693
2694     switch(LOWORD(wParam))
2695     {
2696
2697     case ID_FILE_EXIT:
2698         PostMessageW(hWnd, WM_CLOSE, 0, 0);
2699         break;
2700
2701     case ID_FILE_NEW:
2702         {
2703             HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE);
2704             int ret = DialogBox(hInstance, MAKEINTRESOURCE(IDD_NEWFILE), hWnd,
2705                                 (DLGPROC)newfile_proc);
2706
2707             if(ret != ID_NEWFILE_ABORT)
2708             {
2709                 if(prompt_save_changes())
2710                 {
2711                     SETTEXTEX st;
2712
2713                     set_caption(NULL);
2714                     wszFileName[0] = '\0';
2715
2716                     clear_formatting();
2717
2718                     st.flags = ST_DEFAULT;
2719                     st.codepage = 1200;
2720                     SendMessageW(hEditorWnd, EM_SETTEXTEX, (WPARAM)&st, 0);
2721
2722                     SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
2723                     set_fileformat(ret);
2724                     update_font_list();
2725                 }
2726             }
2727         }
2728         break;
2729
2730     case ID_FILE_OPEN:
2731         DialogOpenFile();
2732         break;
2733
2734     case ID_FILE_SAVE:
2735         if(wszFileName[0])
2736         {
2737             DoSaveFile(wszFileName, fileFormat);
2738             break;
2739         }
2740         /* Fall through */
2741
2742     case ID_FILE_SAVEAS:
2743         DialogSaveFile();
2744         break;
2745
2746     case ID_FILE_RECENT1:
2747     case ID_FILE_RECENT2:
2748     case ID_FILE_RECENT3:
2749     case ID_FILE_RECENT4:
2750         {
2751             HMENU hMenu = GetMenu(hWnd);
2752             MENUITEMINFOW mi;
2753
2754             mi.cbSize = sizeof(MENUITEMINFOW);
2755             mi.fMask = MIIM_DATA;
2756             if(GetMenuItemInfoW(hMenu, LOWORD(wParam), FALSE, &mi))
2757                 DoOpenFile((LPWSTR)mi.dwItemData);
2758         }
2759         break;
2760
2761     case ID_FIND:
2762         dialog_find(&findreplace, FALSE);
2763         break;
2764
2765     case ID_FIND_NEXT:
2766         handle_findmsg(&findreplace);
2767         break;
2768
2769     case ID_REPLACE:
2770         dialog_find(&findreplace, TRUE);
2771         break;
2772
2773     case ID_FONTSETTINGS:
2774         dialog_choose_font();
2775         break;
2776
2777     case ID_PRINT:
2778         dialog_print();
2779         break;
2780
2781     case ID_PRINT_QUICK:
2782         print_quick();
2783         break;
2784
2785     case ID_PREVIEW:
2786         {
2787             int index = reg_formatindex(fileFormat);
2788             DWORD tmp = barState[index];
2789             barState[index] = 0;
2790             set_bar_states();
2791             barState[index] = tmp;
2792             ShowWindow(hEditorWnd, FALSE);
2793             preview_bar_show(TRUE);
2794
2795             preview.page = 1;
2796             preview.hdc = 0;
2797             SetMenu(hWnd, NULL);
2798             InvalidateRect(0, 0, TRUE);
2799         }
2800         break;
2801
2802     case ID_PRINTSETUP:
2803         dialog_printsetup();
2804         break;
2805
2806     case ID_FORMAT_BOLD:
2807     case ID_FORMAT_ITALIC:
2808     case ID_FORMAT_UNDERLINE:
2809         {
2810         CHARFORMAT2W fmt;
2811         int effects = CFE_BOLD;
2812
2813         ZeroMemory(&fmt, sizeof(fmt));
2814         fmt.cbSize = sizeof(fmt);
2815         SendMessageW(hwndEditor, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
2816
2817         fmt.dwMask = CFM_BOLD;
2818
2819         if (LOWORD(wParam) == ID_FORMAT_ITALIC)
2820         {
2821             effects = CFE_ITALIC;
2822             fmt.dwMask = CFM_ITALIC;
2823         } else if (LOWORD(wParam) == ID_FORMAT_UNDERLINE)
2824         {
2825             effects = CFE_UNDERLINE;
2826             fmt.dwMask = CFM_UNDERLINE;
2827         }
2828
2829         fmt.dwEffects ^= effects;
2830
2831         SendMessageW(hwndEditor, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
2832         break;
2833         }
2834
2835     case ID_EDIT_CUT:
2836         PostMessageW(hwndEditor, WM_CUT, 0, 0);
2837         break;
2838
2839     case ID_EDIT_COPY:
2840         PostMessageW(hwndEditor, WM_COPY, 0, 0);
2841         break;
2842
2843     case ID_EDIT_PASTE:
2844         PostMessageW(hwndEditor, WM_PASTE, 0, 0);
2845         break;
2846
2847     case ID_EDIT_CLEAR:
2848         PostMessageW(hwndEditor, WM_CLEAR, 0, 0);
2849         break;
2850
2851     case ID_EDIT_SELECTALL:
2852         {
2853         CHARRANGE range = {0, -1};
2854         SendMessageW(hwndEditor, EM_EXSETSEL, 0, (LPARAM)&range);
2855         /* SendMessage(hwndEditor, EM_SETSEL, 0, -1); */
2856         return 0;
2857         }
2858
2859     case ID_EDIT_GETTEXT:
2860         {
2861         int nLen = GetWindowTextLengthW(hwndEditor);
2862         LPWSTR data = HeapAlloc( GetProcessHeap(), 0, (nLen+1)*sizeof(WCHAR) );
2863         TEXTRANGEW tr;
2864
2865         GetWindowTextW(hwndEditor, data, nLen+1);
2866         MessageBoxW(NULL, data, xszAppTitle, MB_OK);
2867
2868         HeapFree( GetProcessHeap(), 0, data);
2869         data = HeapAlloc(GetProcessHeap(), 0, (nLen+1)*sizeof(WCHAR));
2870         tr.chrg.cpMin = 0;
2871         tr.chrg.cpMax = nLen;
2872         tr.lpstrText = data;
2873         SendMessage (hwndEditor, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
2874         MessageBoxW(NULL, data, xszAppTitle, MB_OK);
2875         HeapFree( GetProcessHeap(), 0, data );
2876
2877         /* SendMessage(hwndEditor, EM_SETSEL, 0, -1); */
2878         return 0;
2879         }
2880
2881     case ID_EDIT_CHARFORMAT:
2882     case ID_EDIT_DEFCHARFORMAT:
2883         {
2884         CHARFORMAT2W cf;
2885         LRESULT i;
2886         ZeroMemory(&cf, sizeof(cf));
2887         cf.cbSize = sizeof(cf);
2888         cf.dwMask = 0;
2889         i = SendMessageW(hwndEditor, EM_GETCHARFORMAT,
2890                         LOWORD(wParam) == ID_EDIT_CHARFORMAT, (LPARAM)&cf);
2891         return 0;
2892         }
2893
2894     case ID_EDIT_PARAFORMAT:
2895         {
2896         PARAFORMAT2 pf;
2897         ZeroMemory(&pf, sizeof(pf));
2898         pf.cbSize = sizeof(pf);
2899         SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
2900         return 0;
2901         }
2902
2903     case ID_EDIT_SELECTIONINFO:
2904         {
2905         CHARRANGE range = {0, -1};
2906         char buf[128];
2907         WCHAR *data = NULL;
2908
2909         SendMessage(hwndEditor, EM_EXGETSEL, 0, (LPARAM)&range);
2910         data = HeapAlloc(GetProcessHeap(), 0, sizeof(*data) * (range.cpMax-range.cpMin+1));
2911         SendMessage(hwndEditor, EM_GETSELTEXT, 0, (LPARAM)data);
2912         sprintf(buf, "Start = %d, End = %d", range.cpMin, range.cpMax);
2913         MessageBoxA(hWnd, buf, "Editor", MB_OK);
2914         MessageBoxW(hWnd, data, xszAppTitle, MB_OK);
2915         HeapFree( GetProcessHeap(), 0, data);
2916         /* SendMessage(hwndEditor, EM_SETSEL, 0, -1); */
2917         return 0;
2918         }
2919
2920     case ID_EDIT_READONLY:
2921         {
2922         long nStyle = GetWindowLong(hwndEditor, GWL_STYLE);
2923         if (nStyle & ES_READONLY)
2924             SendMessageW(hwndEditor, EM_SETREADONLY, 0, 0);
2925         else
2926             SendMessageW(hwndEditor, EM_SETREADONLY, 1, 0);
2927         return 0;
2928         }
2929
2930     case ID_EDIT_MODIFIED:
2931         if (SendMessageW(hwndEditor, EM_GETMODIFY, 0, 0))
2932             SendMessageW(hwndEditor, EM_SETMODIFY, 0, 0);
2933         else
2934             SendMessageW(hwndEditor, EM_SETMODIFY, 1, 0);
2935         return 0;
2936
2937     case ID_EDIT_UNDO:
2938         SendMessageW(hwndEditor, EM_UNDO, 0, 0);
2939         return 0;
2940
2941     case ID_EDIT_REDO:
2942         SendMessageW(hwndEditor, EM_REDO, 0, 0);
2943         return 0;
2944
2945     case ID_BULLET:
2946         {
2947             PARAFORMAT pf;
2948
2949             pf.cbSize = sizeof(pf);
2950             pf.dwMask = PFM_NUMBERING;
2951             SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
2952
2953             pf.dwMask |=  PFM_OFFSET;
2954
2955             if(pf.wNumbering == PFN_BULLET)
2956             {
2957                 pf.wNumbering = 0;
2958                 pf.dxOffset = 0;
2959             } else
2960             {
2961                 pf.wNumbering = PFN_BULLET;
2962                 pf.dxOffset = 720;
2963             }
2964
2965             SendMessageW(hwndEditor, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
2966         }
2967         break;
2968
2969     case ID_ALIGN_LEFT:
2970     case ID_ALIGN_CENTER:
2971     case ID_ALIGN_RIGHT:
2972         {
2973         PARAFORMAT2 pf;
2974
2975         pf.cbSize = sizeof(pf);
2976         pf.dwMask = PFM_ALIGNMENT;
2977         switch(LOWORD(wParam)) {
2978         case ID_ALIGN_LEFT: pf.wAlignment = PFA_LEFT; break;
2979         case ID_ALIGN_CENTER: pf.wAlignment = PFA_CENTER; break;
2980         case ID_ALIGN_RIGHT: pf.wAlignment = PFA_RIGHT; break;
2981         }
2982         SendMessageW(hwndEditor, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
2983         break;
2984         }
2985
2986     case ID_BACK_1:
2987         SendMessageW(hwndEditor, EM_SETBKGNDCOLOR, 1, 0);
2988         break;
2989
2990     case ID_BACK_2:
2991         SendMessageW(hwndEditor, EM_SETBKGNDCOLOR, 0, RGB(255,255,192));
2992         break;
2993
2994     case ID_TOGGLE_TOOLBAR:
2995         set_toolbar_state(BANDID_TOOLBAR, !is_bar_visible(BANDID_TOOLBAR));
2996         update_window();
2997         break;
2998
2999     case ID_TOGGLE_FORMATBAR:
3000         set_toolbar_state(BANDID_FONTLIST, !is_bar_visible(BANDID_FORMATBAR));
3001         set_toolbar_state(BANDID_SIZELIST, !is_bar_visible(BANDID_FORMATBAR));
3002         set_toolbar_state(BANDID_FORMATBAR, !is_bar_visible(BANDID_FORMATBAR));
3003         update_window();
3004         break;
3005
3006     case ID_TOGGLE_STATUSBAR:
3007         set_statusbar_state(!is_bar_visible(BANDID_STATUSBAR));
3008         update_window();
3009         break;
3010
3011     case ID_DATETIME:
3012         {
3013         HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE);
3014         DialogBoxW(hInstance, MAKEINTRESOURCEW(IDD_DATETIME), hWnd, (DLGPROC)datetime_proc);
3015         break;
3016         }
3017
3018     case ID_PARAFORMAT:
3019         {
3020             HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE);
3021             DialogBoxW(hInstance, MAKEINTRESOURCEW(IDD_PARAFORMAT), hWnd,
3022                        paraformat_proc);
3023         }
3024         break;
3025
3026     case ID_TABSTOPS:
3027         {
3028             HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE);
3029             DialogBoxW(hInstance, MAKEINTRESOURCEW(IDD_TABSTOPS), hWnd, tabstops_proc);
3030         }
3031         break;
3032
3033     case ID_ABOUT:
3034         dialog_about();
3035         break;
3036
3037     case ID_VIEWPROPERTIES:
3038         dialog_viewproperties();
3039         break;
3040
3041     default:
3042         SendMessageW(hwndEditor, WM_COMMAND, wParam, lParam);
3043         break;
3044     }
3045     return 0;
3046 }
3047
3048 static LRESULT OnInitPopupMenu( HWND hWnd, WPARAM wParam, LPARAM lParam )
3049 {
3050     HMENU hMenu = (HMENU)wParam;
3051     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
3052     HWND hwndStatus = GetDlgItem(hWnd, IDC_STATUSBAR);
3053     PARAFORMAT pf;
3054     int nAlignment = -1;
3055     int selFrom, selTo;
3056     GETTEXTLENGTHEX gt;
3057     LRESULT textLength;
3058     MENUITEMINFOW mi;
3059
3060     SendMessageW(hEditorWnd, EM_GETSEL, (WPARAM)&selFrom, (LPARAM)&selTo);
3061     EnableMenuItem(hMenu, ID_EDIT_COPY, MF_BYCOMMAND|(selFrom == selTo) ? MF_GRAYED : MF_ENABLED);
3062     EnableMenuItem(hMenu, ID_EDIT_CUT, MF_BYCOMMAND|(selFrom == selTo) ? MF_GRAYED : MF_ENABLED);
3063
3064     pf.cbSize = sizeof(PARAFORMAT);
3065     SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
3066     CheckMenuItem(hMenu, ID_EDIT_READONLY,
3067       MF_BYCOMMAND|(GetWindowLong(hwndEditor, GWL_STYLE)&ES_READONLY ? MF_CHECKED : MF_UNCHECKED));
3068     CheckMenuItem(hMenu, ID_EDIT_MODIFIED,
3069       MF_BYCOMMAND|(SendMessage(hwndEditor, EM_GETMODIFY, 0, 0) ? MF_CHECKED : MF_UNCHECKED));
3070     if (pf.dwMask & PFM_ALIGNMENT)
3071         nAlignment = pf.wAlignment;
3072     CheckMenuItem(hMenu, ID_ALIGN_LEFT, MF_BYCOMMAND|(nAlignment == PFA_LEFT) ?
3073             MF_CHECKED : MF_UNCHECKED);
3074     CheckMenuItem(hMenu, ID_ALIGN_CENTER, MF_BYCOMMAND|(nAlignment == PFA_CENTER) ?
3075             MF_CHECKED : MF_UNCHECKED);
3076     CheckMenuItem(hMenu, ID_ALIGN_RIGHT, MF_BYCOMMAND|(nAlignment == PFA_RIGHT) ?
3077             MF_CHECKED : MF_UNCHECKED);
3078     CheckMenuItem(hMenu, ID_BULLET, MF_BYCOMMAND | ((pf.wNumbering == PFN_BULLET) ?
3079             MF_CHECKED : MF_UNCHECKED));
3080     EnableMenuItem(hMenu, ID_EDIT_UNDO, MF_BYCOMMAND|(SendMessageW(hwndEditor, EM_CANUNDO, 0, 0)) ?
3081             MF_ENABLED : MF_GRAYED);
3082     EnableMenuItem(hMenu, ID_EDIT_REDO, MF_BYCOMMAND|(SendMessageW(hwndEditor, EM_CANREDO, 0, 0)) ?
3083             MF_ENABLED : MF_GRAYED);
3084
3085     CheckMenuItem(hMenu, ID_TOGGLE_TOOLBAR, MF_BYCOMMAND|(is_bar_visible(BANDID_TOOLBAR)) ?
3086             MF_CHECKED : MF_UNCHECKED);
3087
3088     CheckMenuItem(hMenu, ID_TOGGLE_FORMATBAR, MF_BYCOMMAND|(is_bar_visible(BANDID_FORMATBAR)) ?
3089             MF_CHECKED : MF_UNCHECKED);
3090
3091     CheckMenuItem(hMenu, ID_TOGGLE_STATUSBAR, MF_BYCOMMAND|IsWindowVisible(hwndStatus) ?
3092             MF_CHECKED : MF_UNCHECKED);
3093
3094     gt.flags = GTL_NUMCHARS;
3095     gt.codepage = 1200;
3096     textLength = SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0);
3097     EnableMenuItem(hMenu, ID_FIND, MF_BYCOMMAND|(textLength ? MF_ENABLED : MF_GRAYED));
3098
3099     mi.cbSize = sizeof(mi);
3100     mi.fMask = MIIM_DATA;
3101
3102     GetMenuItemInfoW(hMenu, ID_FIND_NEXT, FALSE, &mi);
3103
3104     EnableMenuItem(hMenu, ID_FIND_NEXT, MF_BYCOMMAND|((textLength && mi.dwItemData) ?
3105                    MF_ENABLED : MF_GRAYED));
3106
3107     EnableMenuItem(hMenu, ID_REPLACE, MF_BYCOMMAND|(textLength ? MF_ENABLED : MF_GRAYED));
3108
3109     return 0;
3110 }
3111
3112 static LRESULT OnSize( HWND hWnd, WPARAM wParam, LPARAM lParam )
3113 {
3114     int nStatusSize = 0;
3115     RECT rc;
3116     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
3117     HWND hwndStatusBar = GetDlgItem(hWnd, IDC_STATUSBAR);
3118     HWND hwndReBar = GetDlgItem(hWnd, IDC_REBAR);
3119     int rebarHeight = 0;
3120     int rebarRows = 2;
3121
3122     if (hwndStatusBar)
3123     {
3124         SendMessageW(hwndStatusBar, WM_SIZE, 0, 0);
3125         if (IsWindowVisible(hwndStatusBar))
3126         {
3127             GetClientRect(hwndStatusBar, &rc);
3128             nStatusSize = rc.bottom - rc.top;
3129         } else
3130         {
3131             nStatusSize = 0;
3132         }
3133     }
3134     if (hwndReBar)
3135     {
3136         if(!is_bar_visible(BANDID_TOOLBAR))
3137             rebarRows--;
3138
3139         if(!is_bar_visible(BANDID_FORMATBAR))
3140             rebarRows--;
3141
3142         rebarHeight = rebarRows ? SendMessageW(hwndReBar, RB_GETBARHEIGHT, 0, 0) : 0;
3143
3144         MoveWindow(hwndReBar, 0, 0, LOWORD(lParam), rebarHeight, TRUE);
3145     }
3146     if (hwndEditor)
3147     {
3148         GetClientRect(hWnd, &rc);
3149         MoveWindow(hwndEditor, 0, rebarHeight, rc.right, rc.bottom-nStatusSize-rebarHeight, TRUE);
3150     }
3151
3152     return DefWindowProcW(hWnd, WM_SIZE, wParam, lParam);
3153 }
3154
3155 static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3156 {
3157     if(msg == ID_FINDMSGSTRING)
3158         return handle_findmsg((LPFINDREPLACEW)lParam);
3159
3160     switch(msg)
3161     {
3162     case WM_CREATE:
3163         return OnCreate( hWnd, wParam, lParam );
3164
3165     case WM_USER:
3166         return OnUser( hWnd, wParam, lParam );
3167
3168     case WM_NOTIFY:
3169         return OnNotify( hWnd, wParam, lParam );
3170
3171     case WM_COMMAND:
3172         if(preview.page)
3173             return preview_command( hWnd, wParam, lParam );
3174         else
3175             return OnCommand( hWnd, wParam, lParam );
3176
3177     case WM_DESTROY:
3178         PostQuitMessage(0);
3179         break;
3180
3181     case WM_CLOSE:
3182         if(preview.page)
3183         {
3184             preview_exit();
3185         } else if(prompt_save_changes())
3186         {
3187             registry_set_options();
3188             registry_set_formatopts_all();
3189             PostQuitMessage(0);
3190         }
3191         break;
3192
3193     case WM_ACTIVATE:
3194         if (LOWORD(wParam))
3195             SetFocus(GetDlgItem(hWnd, IDC_EDITOR));
3196         return 0;
3197
3198     case WM_INITMENUPOPUP:
3199         return OnInitPopupMenu( hWnd, wParam, lParam );
3200
3201     case WM_SIZE:
3202         return OnSize( hWnd, wParam, lParam );
3203
3204     case WM_CONTEXTMENU:
3205         if((HWND)wParam == hEditorWnd)
3206             return context_menu(lParam);
3207         else
3208             return DefWindowProcW(hWnd, msg, wParam, lParam);
3209
3210     case WM_DROPFILES:
3211         {
3212             WCHAR file[MAX_PATH];
3213             DragQueryFileW((HDROP)wParam, 0, file, MAX_PATH);
3214             DragFinish((HDROP)wParam);
3215
3216             if(prompt_save_changes())
3217                 DoOpenFile(file);
3218         }
3219         break;
3220     case WM_PAINT:
3221         if(preview.page)
3222             return print_preview();
3223         else
3224             return DefWindowProcW(hWnd, msg, wParam, lParam);
3225
3226     default:
3227         return DefWindowProcW(hWnd, msg, wParam, lParam);
3228     }
3229
3230     return 0;
3231 }
3232
3233 int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hOldInstance, LPSTR szCmdParagraph, int res)
3234 {
3235     INITCOMMONCONTROLSEX classes = {8, ICC_BAR_CLASSES|ICC_COOL_CLASSES|ICC_USEREX_CLASSES};
3236     HACCEL hAccel;
3237     WNDCLASSW wc;
3238     MSG msg;
3239     RECT rc;
3240     static const WCHAR wszAccelTable[] = {'M','A','I','N','A','C','C','E','L',
3241                                           'T','A','B','L','E','\0'};
3242
3243     InitCommonControlsEx(&classes);
3244
3245     hAccel = LoadAcceleratorsW(hInstance, wszAccelTable);
3246
3247     wc.style = CS_HREDRAW | CS_VREDRAW;
3248     wc.lpfnWndProc = WndProc;
3249     wc.cbClsExtra = 0;
3250     wc.cbWndExtra = 4;
3251     wc.hInstance = hInstance;
3252     wc.hIcon = LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_WORDPAD));
3253     wc.hCursor = LoadCursor(NULL, IDC_IBEAM);
3254     wc.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3255     wc.lpszMenuName = xszMainMenu;
3256     wc.lpszClassName = wszMainWndClass;
3257     RegisterClassW(&wc);
3258
3259     rc = registry_read_winrect();
3260     hMainWnd = CreateWindowExW(0, wszMainWndClass, wszAppTitle, WS_CLIPCHILDREN|WS_OVERLAPPEDWINDOW,
3261       rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, NULL, NULL, hInstance, NULL);
3262     ShowWindow(hMainWnd, SW_SHOWDEFAULT);
3263
3264     set_caption(NULL);
3265     set_bar_states();
3266     set_fileformat(SF_RTF);
3267     hPopupMenu = LoadMenuW(hInstance, MAKEINTRESOURCEW(IDM_POPUP));
3268     get_default_printer_opts();
3269     target_device();
3270
3271     HandleCommandLine(GetCommandLineW());
3272
3273     while(GetMessageW(&msg,0,0,0))
3274     {
3275         if (IsDialogMessage(hFindWnd, &msg))
3276             continue;
3277
3278         if (TranslateAcceleratorW(hMainWnd, hAccel, &msg))
3279             continue;
3280         TranslateMessage(&msg);
3281         DispatchMessageW(&msg);
3282         if (!PeekMessageW(&msg, 0, 0, 0, PM_NOREMOVE))
3283             SendMessageW(hMainWnd, WM_USER, 0, 0);
3284     }
3285
3286     return 0;
3287 }