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