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