wordpad: Handle different formats on open/save.
[wine] / programs / wordpad / wordpad.c
1 /*
2  * Wordpad implementation
3  *
4  * Copyright 2004 by Krzysztof Foltman
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #define WIN32_LEAN_AND_MEAN
22 #define _WIN32_IE 0x0400
23
24 #define MAX_STRING_LEN 255
25
26 #include <stdarg.h>
27 #include <ctype.h>
28 #include <stdio.h>
29 #include <assert.h>
30
31 #include <windows.h>
32 #include <richedit.h>
33 #include <commctrl.h>
34 #include <commdlg.h>
35 #include <shlobj.h>
36
37 #include "resource.h"
38
39 /* use LoadString */
40 static const WCHAR xszAppTitle[] = {'W','i','n','e',' ','W','o','r','d','p','a','d',0};
41 static const WCHAR xszMainMenu[] = {'M','A','I','N','M','E','N','U',0};
42
43 static const WCHAR wszRichEditClass[] = {'R','I','C','H','E','D','I','T','2','0','W',0};
44 static const WCHAR wszMainWndClass[] = {'W','O','R','D','P','A','D','T','O','P',0};
45 static const WCHAR wszAppTitle[] = {'W','i','n','e',' ','W','o','r','d','p','a','d',0};
46
47 static const WCHAR key_recentfiles[] = {'R','e','c','e','n','t',' ','f','i','l','e',
48                                         ' ','l','i','s','t',0};
49
50 static const WCHAR var_file[] = {'F','i','l','e','%','d',0};
51
52 static HWND hMainWnd;
53 static HWND hEditorWnd;
54 static HWND hFindWnd;
55
56 static UINT ID_FINDMSGSTRING;
57
58 static WCHAR wszFilter[MAX_STRING_LEN*4+6*3+5];
59 static WCHAR wszDefaultFileName[MAX_STRING_LEN];
60 static WCHAR wszSaveChanges[MAX_STRING_LEN];
61
62 static LRESULT OnSize( HWND hWnd, WPARAM wParam, LPARAM lParam );
63
64 /* Load string resources */
65 static void DoLoadStrings(void)
66 {
67     LPWSTR p = wszFilter;
68     static const WCHAR files_rtf[] = {'*','.','r','t','f','\0'};
69     static const WCHAR files_txt[] = {'*','.','t','x','t','\0'};
70     static const WCHAR files_all[] = {'*','.','*','\0'};
71     HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hMainWnd, GWLP_HINSTANCE);
72
73     LoadStringW(hInstance, STRING_RICHTEXT_FILES_RTF, p, MAX_STRING_LEN);
74     p += lstrlenW(p) + 1;
75     lstrcpyW(p, files_rtf);
76     p += lstrlenW(p) + 1;
77     LoadStringW(hInstance, STRING_TEXT_FILES_TXT, p, MAX_STRING_LEN);
78     p += lstrlenW(p) + 1;
79     lstrcpyW(p, files_txt);
80     p += lstrlenW(p) + 1;
81     LoadStringW(hInstance, STRING_TEXT_FILES_UNICODE_TXT, p, MAX_STRING_LEN);
82     p += lstrlenW(p) + 1;
83     lstrcpyW(p, files_txt);
84     p += lstrlenW(p) + 1;
85     LoadStringW(hInstance, STRING_ALL_FILES, p, MAX_STRING_LEN);
86     p += lstrlenW(p) + 1;
87     lstrcpyW(p, files_all);
88     p += lstrlenW(p) + 1;
89     *p = '\0';
90
91     p = wszDefaultFileName;
92     LoadStringW(hInstance, STRING_DEFAULT_FILENAME, p, MAX_STRING_LEN);
93
94     p = wszSaveChanges;
95     LoadStringW(hInstance, STRING_PROMPT_SAVE_CHANGES, p, MAX_STRING_LEN);
96 }
97
98 static void AddButton(HWND hwndToolBar, int nImage, int nCommand)
99 {
100     TBBUTTON button;
101
102     ZeroMemory(&button, sizeof(button));
103     button.iBitmap = nImage;
104     button.idCommand = nCommand;
105     button.fsState = TBSTATE_ENABLED;
106     button.fsStyle = TBSTYLE_BUTTON;
107     button.dwData = 0;
108     button.iString = -1;
109     SendMessageW(hwndToolBar, TB_ADDBUTTONSW, 1, (LPARAM)&button);
110 }
111
112 static void AddSeparator(HWND hwndToolBar)
113 {
114     TBBUTTON button;
115
116     ZeroMemory(&button, sizeof(button));
117     button.iBitmap = -1;
118     button.idCommand = 0;
119     button.fsState = 0;
120     button.fsStyle = TBSTYLE_SEP;
121     button.dwData = 0;
122     button.iString = -1;
123     SendMessageW(hwndToolBar, TB_ADDBUTTONSW, 1, (LPARAM)&button);
124 }
125
126 static DWORD CALLBACK stream_in(DWORD_PTR cookie, LPBYTE buffer, LONG cb, LONG *pcb)
127 {
128     HANDLE hFile = (HANDLE)cookie;
129     DWORD read;
130
131     if(!ReadFile(hFile, buffer, cb, &read, 0))
132         return 1;
133
134     *pcb = read;
135
136     return 0;
137 }
138
139 static DWORD CALLBACK stream_out(DWORD_PTR cookie, LPBYTE buffer, LONG cb, LONG *pcb)
140 {
141     DWORD written;
142     int ret;
143     HANDLE hFile = (HANDLE)cookie;
144
145     ret = WriteFile(hFile, buffer, cb, &written, 0);
146
147     if(!ret || (cb != written))
148         return 1;
149
150     *pcb = cb;
151
152     return 0;
153 }
154
155 static LPWSTR file_basename(LPWSTR path)
156 {
157     LPWSTR pos = path + lstrlenW(path);
158
159     while(pos > path)
160     {
161         if(*pos == '\\' || *pos == '/')
162         {
163             pos++;
164             break;
165         }
166         pos--;
167     }
168     return pos;
169 }
170
171 static WCHAR wszFileName[MAX_PATH];
172 static WPARAM fileFormat = SF_RTF;
173
174 static void set_caption(LPCWSTR wszNewFileName)
175 {
176     static const WCHAR wszSeparator[] = {' ','-',' '};
177     WCHAR *wszCaption;
178     SIZE_T length = 0;
179
180     if(!wszNewFileName)
181         wszNewFileName = wszDefaultFileName;
182
183     wszCaption = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
184                 lstrlenW(wszNewFileName)*sizeof(WCHAR)+sizeof(wszSeparator)+sizeof(wszAppTitle));
185
186     if(!wszCaption)
187         return;
188
189     memcpy(wszCaption, wszNewFileName, lstrlenW(wszNewFileName)*sizeof(WCHAR));
190     length += lstrlenW(wszNewFileName);
191     memcpy(wszCaption + length, wszSeparator, sizeof(wszSeparator));
192     length += sizeof(wszSeparator) / sizeof(WCHAR);
193     memcpy(wszCaption + length, wszAppTitle, sizeof(wszAppTitle));
194
195     SetWindowTextW(hMainWnd, wszCaption);
196
197     HeapFree(GetProcessHeap(), 0, wszCaption);
198 }
199
200 static LRESULT registry_get_handle(HKEY *hKey, LPDWORD action, LPCWSTR subKey)
201 {
202     LONG ret;
203     static const WCHAR wszProgramKey[] = {'S','o','f','t','w','a','r','e','\\',
204         'M','i','c','r','o','s','o','f','t','\\',
205         'W','i','n','d','o','w','s','\\',
206         'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
207         'A','p','p','l','e','t','s','\\',
208         'W','o','r','d','p','a','d',0};
209     LPWSTR key = (LPWSTR)wszProgramKey;
210
211     if(subKey)
212     {
213         WCHAR backslash[] = {'\\',0};
214         key = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
215                         (lstrlenW(wszProgramKey)+lstrlenW(subKey)+lstrlenW(backslash)+1)
216                         *sizeof(WCHAR));
217
218         if(!key)
219             return 1;
220
221         lstrcpyW(key, wszProgramKey);
222         lstrcatW(key, backslash);
223         lstrcatW(key, subKey);
224     }
225
226     if(action)
227     {
228         ret = RegCreateKeyExW(HKEY_CURRENT_USER, key, 0, NULL, REG_OPTION_NON_VOLATILE,
229                               KEY_READ | KEY_WRITE, NULL, hKey, action);
230     } else
231     {
232         ret = RegOpenKeyExW(HKEY_CURRENT_USER, key, 0, KEY_READ | KEY_WRITE, hKey);
233     }
234
235     if(subKey)
236         HeapFree(GetProcessHeap(), 0, key);
237
238     return ret;
239 }
240
241 static void truncate_path(LPWSTR file, LPWSTR out, LPWSTR pos1, LPWSTR pos2)
242 {
243     static const WCHAR dots[] = {'.','.','.',0};
244
245     *++pos1 = 0;
246
247     lstrcatW(out, file);
248     lstrcatW(out, dots);
249     lstrcatW(out, pos2);
250 }
251
252 static void format_filelist_filename(LPWSTR file, LPWSTR out)
253 {
254     LPWSTR pos_basename;
255     LPWSTR truncpos1, truncpos2;
256     WCHAR myDocs[MAX_STRING_LEN];
257
258     SHGetFolderPathW(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, (LPWSTR)&myDocs);
259     pos_basename = file_basename(file);
260     truncpos1 = NULL;
261     truncpos2 = NULL;
262
263     *(pos_basename-1) = 0;
264     if(!lstrcmpiW(file, myDocs) || (lstrlenW(pos_basename) > FILELIST_ENTRY_LENGTH))
265     {
266         truncpos1 = pos_basename;
267         *(pos_basename-1) = '\\';
268     } else
269     {
270         LPWSTR pos;
271         BOOL morespace = FALSE;
272
273         *(pos_basename-1) = '\\';
274
275         for(pos = file; pos < pos_basename; pos++)
276         {
277             if(*pos == '\\' || *pos == '/')
278             {
279                 if(truncpos1)
280                 {
281                     if((pos - file + lstrlenW(pos_basename)) > FILELIST_ENTRY_LENGTH)
282                         break;
283
284                     truncpos1 = pos;
285                     morespace = TRUE;
286                     break;
287                 }
288
289                 if((pos - file + lstrlenW(pos_basename)) > FILELIST_ENTRY_LENGTH)
290                     break;
291
292                 truncpos1 = pos;
293             }
294         }
295
296         if(morespace)
297         {
298             for(pos = pos_basename; pos >= truncpos1; pos--)
299             {
300                 if(*pos == '\\' || *pos == '/')
301                 {
302                     if((truncpos1 - file + lstrlenW(pos_basename) + pos_basename - pos) > FILELIST_ENTRY_LENGTH)
303                         break;
304
305                     truncpos2 = pos;
306                 }
307             }
308         }
309     }
310
311     if(truncpos1 == pos_basename)
312         lstrcatW(out, pos_basename);
313     else if(truncpos1 == truncpos2 || !truncpos2)
314         lstrcatW(out, file);
315     else
316         truncate_path(file, out, truncpos1, truncpos2 ? truncpos2 : (pos_basename-1));
317 }
318
319 static void registry_read_filelist(HWND hMainWnd)
320 {
321     HKEY hFileKey;
322
323     if(registry_get_handle(&hFileKey, 0, key_recentfiles) == ERROR_SUCCESS)
324     {
325         WCHAR itemText[MAX_PATH+3], buffer[MAX_PATH];
326         /* The menu item name is not the same as the file name, so we need to store
327            the file name here */
328         static WCHAR file1[MAX_PATH], file2[MAX_PATH], file3[MAX_PATH], file4[MAX_PATH];
329         WCHAR numFormat[] = {'&','%','d',' ',0};
330         LPWSTR pFile[] = {file1, file2, file3, file4};
331         DWORD pathSize = MAX_PATH*sizeof(WCHAR);
332         int i;
333         WCHAR key[6];
334         MENUITEMINFOW mi;
335         HMENU hMenu = GetMenu(hMainWnd);
336
337         mi.cbSize = sizeof(MENUITEMINFOW);
338         mi.fMask = MIIM_ID | MIIM_DATA | MIIM_STRING | MIIM_FTYPE;
339         mi.fType = MFT_STRING;
340         mi.dwTypeData = itemText;
341         mi.wID = ID_FILE_RECENT1;
342
343         RemoveMenu(hMenu, ID_FILE_RECENT_SEPARATOR, MF_BYCOMMAND);
344         for(i = 0; i < FILELIST_ENTRIES; i++)
345         {
346             wsprintfW(key, var_file, i+1);
347             RemoveMenu(hMenu, ID_FILE_RECENT1+i, MF_BYCOMMAND);
348             if(RegQueryValueExW(hFileKey, (LPWSTR)key, 0, NULL, (LPBYTE)pFile[i], &pathSize)
349                != ERROR_SUCCESS)
350                 break;
351
352             mi.dwItemData = (DWORD)pFile[i];
353             wsprintfW(itemText, numFormat, i+1);
354
355             lstrcpyW(buffer, pFile[i]);
356
357             format_filelist_filename(buffer, itemText);
358
359             InsertMenuItemW(hMenu, ID_FILE_EXIT, FALSE, &mi);
360             mi.wID++;
361             pathSize = MAX_PATH*sizeof(WCHAR);
362         }
363         mi.fType = MFT_SEPARATOR;
364         mi.fMask = MIIM_FTYPE | MIIM_ID;
365         InsertMenuItemW(hMenu, ID_FILE_EXIT, FALSE, &mi);
366
367         RegCloseKey(hFileKey);
368     }
369 }
370
371 static void registry_set_filelist(LPCWSTR newFile)
372 {
373     HKEY hKey;
374     DWORD action;
375
376     if(registry_get_handle(&hKey, &action, key_recentfiles) == ERROR_SUCCESS)
377     {
378         LPCWSTR pFiles[FILELIST_ENTRIES];
379         int i;
380         HMENU hMenu = GetMenu(hMainWnd);
381         MENUITEMINFOW mi;
382         WCHAR buffer[6];
383
384         mi.cbSize = sizeof(MENUITEMINFOW);
385         mi.fMask = MIIM_DATA;
386
387         for(i = 0; i < FILELIST_ENTRIES; i++)
388             pFiles[i] = NULL;
389
390         for(i = 0; GetMenuItemInfoW(hMenu, ID_FILE_RECENT1+i, FALSE, &mi); i++)
391             pFiles[i] = (LPWSTR)mi.dwItemData;
392
393         if(lstrcmpiW(newFile, pFiles[0]))
394         {
395             for(i = 0; pFiles[i] && i < FILELIST_ENTRIES; i++)
396             {
397                 if(!lstrcmpiW(pFiles[i], newFile))
398                 {
399                     int j;
400                     for(j = 0; pFiles[j] && j < i; j++)
401                     {
402                         pFiles[i-j] = pFiles[i-j-1];
403                     }
404                     pFiles[0] = NULL;
405                     break;
406                 }
407             }
408
409             if(!pFiles[0])
410             {
411                 pFiles[0] = newFile;
412             } else
413             {
414                 for(i = 0; pFiles[i] && i < FILELIST_ENTRIES-1; i++)
415                     pFiles[FILELIST_ENTRIES-1-i] = pFiles[FILELIST_ENTRIES-2-i];
416
417                 pFiles[0] = newFile;
418             }
419
420             for(i = 0; pFiles[i] && i < FILELIST_ENTRIES; i++)
421             {
422                 wsprintfW(buffer, var_file, i+1);
423                 RegSetValueExW(hKey, (LPWSTR)&buffer, 0, REG_SZ, (LPBYTE)pFiles[i],
424                                (lstrlenW(pFiles[i])+1)*sizeof(WCHAR));
425             }
426         }
427     }
428     RegCloseKey(hKey);
429     registry_read_filelist(hMainWnd);
430 }
431
432 static int fileformat_number(WPARAM format)
433 {
434     int number = 0;
435
436     if(format == SF_TEXT)
437     {
438         number = 1;
439     } else if (format == (SF_TEXT | SF_UNICODE))
440     {
441         number = 2;
442     }
443     return number;
444 }
445
446 static WPARAM fileformat_flags(int format)
447 {
448     WPARAM flags[] = { SF_RTF , SF_TEXT , SF_TEXT | SF_UNICODE };
449
450     return flags[format];
451 }
452
453 static void set_fileformat(WPARAM format)
454 {
455     fileFormat = format;
456 }
457
458 static void DoOpenFile(LPCWSTR szOpenFileName)
459 {
460     HANDLE hFile;
461     EDITSTREAM es;
462     char fileStart[5];
463     DWORD readOut;
464     WPARAM format = SF_TEXT;
465
466     hFile = CreateFileW(szOpenFileName, GENERIC_READ, FILE_SHARE_READ, NULL,
467                         OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
468     if (hFile == INVALID_HANDLE_VALUE)
469         return;
470
471     ReadFile(hFile, fileStart, 5, &readOut, NULL);
472     SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
473
474     if(readOut >= 2 && (BYTE)fileStart[0] == 0xff && (BYTE)fileStart[1] == 0xfe)
475     {
476         format = SF_TEXT | SF_UNICODE;
477         SetFilePointer(hFile, 2, NULL, FILE_BEGIN);
478     } else if(readOut >= 5)
479     {
480         static const char header[] = "{\\rtf";
481         if(!memcmp(header, fileStart, 5))
482             format = SF_RTF;
483     }
484
485     es.dwCookie = (DWORD_PTR)hFile;
486     es.pfnCallback = stream_in;
487
488     SendMessageW(hEditorWnd, EM_STREAMIN, format, (LPARAM)&es);
489
490     CloseHandle(hFile);
491
492     SetFocus(hEditorWnd);
493
494     set_caption(szOpenFileName);
495
496     lstrcpyW(wszFileName, szOpenFileName);
497     SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
498     registry_set_filelist(szOpenFileName);
499     set_fileformat(format);
500 }
501
502 static void DoSaveFile(LPCWSTR wszSaveFileName, WPARAM format)
503 {
504     HANDLE hFile;
505     EDITSTREAM stream;
506     LRESULT ret;
507
508     hFile = CreateFileW(wszSaveFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
509         FILE_ATTRIBUTE_NORMAL, NULL);
510
511     if(hFile == INVALID_HANDLE_VALUE)
512         return;
513
514     if(format == (SF_TEXT | SF_UNICODE))
515     {
516         static const BYTE unicode[] = {0xff,0xfe};
517         DWORD writeOut;
518         WriteFile(hFile, &unicode, sizeof(unicode), &writeOut, 0);
519
520         if(writeOut != sizeof(unicode))
521             return;
522     }
523
524     stream.dwCookie = (DWORD_PTR)hFile;
525     stream.pfnCallback = stream_out;
526
527     ret = SendMessageW(hEditorWnd, EM_STREAMOUT, format, (LPARAM)&stream);
528
529     CloseHandle(hFile);
530
531     SetFocus(hEditorWnd);
532
533     if(!ret)
534     {
535         GETTEXTLENGTHEX gt;
536         gt.flags = GTL_DEFAULT;
537         gt.codepage = 1200;
538
539         if(SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0))
540             return;
541     }
542
543     lstrcpyW(wszFileName, wszSaveFileName);
544     set_caption(wszFileName);
545     SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
546     set_fileformat(format);
547 }
548
549 static void DialogSaveFile(void)
550 {
551     OPENFILENAMEW sfn;
552
553     WCHAR wszFile[MAX_PATH] = {'\0'};
554     static const WCHAR wszDefExt[] = {'r','t','f','\0'};
555
556     ZeroMemory(&sfn, sizeof(sfn));
557
558     sfn.lStructSize = sizeof(sfn);
559     sfn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT;
560     sfn.hwndOwner = hMainWnd;
561     sfn.lpstrFilter = wszFilter;
562     sfn.lpstrFile = wszFile;
563     sfn.nMaxFile = MAX_PATH;
564     sfn.lpstrDefExt = wszDefExt;
565     sfn.nFilterIndex = fileformat_number(fileFormat)+1;
566
567     while(GetSaveFileNameW(&sfn))
568     {
569         if(fileformat_flags(sfn.nFilterIndex-1) != SF_RTF)
570         {
571             if(MessageBoxW(hMainWnd, MAKEINTRESOURCEW(STRING_SAVE_LOSEFORMATTING),
572                            wszAppTitle, MB_YESNO | MB_ICONEXCLAMATION) != IDYES)
573             {
574                 continue;
575             } else
576             {
577                 DoSaveFile(sfn.lpstrFile, fileformat_flags(sfn.nFilterIndex-1));
578                 break;
579             }
580         } else
581         {
582             DoSaveFile(sfn.lpstrFile, fileformat_flags(sfn.nFilterIndex-1));
583             break;
584         }
585     }
586 }
587
588 static BOOL prompt_save_changes(void)
589 {
590     if(!wszFileName[0])
591     {
592         GETTEXTLENGTHEX gt;
593         gt.flags = GTL_NUMCHARS;
594         gt.codepage = 1200;
595         if(!SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0))
596             return TRUE;
597     }
598
599     if(!SendMessageW(hEditorWnd, EM_GETMODIFY, 0, 0))
600     {
601         return TRUE;
602     } else
603     {
604         LPWSTR displayFileName;
605         WCHAR *text;
606         int ret;
607
608         if(!wszFileName[0])
609             displayFileName = wszDefaultFileName;
610         else
611             displayFileName = wszFileName;
612
613         text = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
614                          (lstrlenW(displayFileName)+lstrlenW(wszSaveChanges))*sizeof(WCHAR));
615
616         if(!text)
617             return FALSE;
618
619         wsprintfW(text, wszSaveChanges, displayFileName);
620
621         ret = MessageBoxW(hMainWnd, text, wszAppTitle, MB_YESNOCANCEL | MB_ICONEXCLAMATION);
622
623         HeapFree(GetProcessHeap(), 0, text);
624
625         switch(ret)
626         {
627             case IDNO:
628                 return TRUE;
629
630             case IDYES:
631                 if(wszFileName[0])
632                     DoSaveFile(wszFileName, fileFormat);
633                 else
634                     DialogSaveFile();
635                 return TRUE;
636
637             default:
638                 return FALSE;
639         }
640     }
641 }
642
643 static void DialogOpenFile(void)
644 {
645     OPENFILENAMEW ofn;
646
647     WCHAR wszFile[MAX_PATH] = {'\0'};
648     static const WCHAR wszDefExt[] = {'r','t','f','\0'};
649
650     ZeroMemory(&ofn, sizeof(ofn));
651
652     ofn.lStructSize = sizeof(ofn);
653     ofn.Flags = OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
654     ofn.hwndOwner = hMainWnd;
655     ofn.lpstrFilter = wszFilter;
656     ofn.lpstrFile = wszFile;
657     ofn.nMaxFile = MAX_PATH;
658     ofn.lpstrDefExt = wszDefExt;
659     ofn.nFilterIndex = fileformat_number(fileFormat)+1;
660
661     if(GetOpenFileNameW(&ofn))
662     {
663         if(prompt_save_changes())
664             DoOpenFile(ofn.lpstrFile);
665     }
666 }
667
668 static void HandleCommandLine(LPWSTR cmdline)
669 {
670     WCHAR delimiter;
671     int opt_print = 0;
672
673     /* skip white space */
674     while (*cmdline == ' ') cmdline++;
675
676     /* skip executable name */
677     delimiter = (*cmdline == '"' ? '"' : ' ');
678
679     if (*cmdline == delimiter) cmdline++;
680     while (*cmdline && *cmdline != delimiter) cmdline++;
681     if (*cmdline == delimiter) cmdline++;
682
683     while (*cmdline == ' ' || *cmdline == '-' || *cmdline == '/')
684     {
685         WCHAR option;
686
687         if (*cmdline++ == ' ') continue;
688
689         option = *cmdline;
690         if (option) cmdline++;
691         while (*cmdline == ' ') cmdline++;
692
693         switch (option)
694         {
695             case 'p':
696             case 'P':
697                 opt_print = 1;
698                 break;
699         }
700     }
701
702     if (*cmdline)
703     {
704         /* file name is passed on the command line */
705         if (cmdline[0] == '"')
706         {
707             cmdline++;
708             cmdline[lstrlenW(cmdline) - 1] = 0;
709         }
710         DoOpenFile(cmdline);
711         InvalidateRect(hMainWnd, NULL, FALSE);
712     }
713
714     if (opt_print)
715         MessageBox(hMainWnd, "Printing not implemented", "WordPad", MB_OK);
716 }
717
718 static LRESULT handle_findmsg(LPFINDREPLACEW pFr)
719 {
720     if(pFr->Flags & FR_DIALOGTERM)
721     {
722         hFindWnd = 0;
723         pFr->Flags = FR_FINDNEXT;
724         return 0;
725     } else if(pFr->Flags & FR_FINDNEXT)
726     {
727         DWORD flags = FR_DOWN;
728         FINDTEXTW ft;
729         static CHARRANGE cr;
730         LRESULT end, ret;
731         GETTEXTLENGTHEX gt;
732         LRESULT length;
733         int startPos;
734         HMENU hMenu = GetMenu(hMainWnd);
735         MENUITEMINFOW mi;
736
737         mi.cbSize = sizeof(mi);
738         mi.fMask = MIIM_DATA;
739         mi.dwItemData = 1;
740         SetMenuItemInfoW(hMenu, ID_FIND_NEXT, FALSE, &mi);
741
742         gt.flags = GTL_NUMCHARS;
743         gt.codepage = 1200;
744
745         length = SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0);
746
747         if(pFr->lCustData == -1)
748         {
749             SendMessageW(hEditorWnd, EM_GETSEL, (WPARAM)&startPos, (LPARAM)&end);
750             cr.cpMin = startPos;
751             pFr->lCustData = startPos;
752             cr.cpMax = length;
753             if(cr.cpMin == length)
754                 cr.cpMin = 0;
755         } else
756         {
757             startPos = pFr->lCustData;
758         }
759
760         if(cr.cpMax > length)
761         {
762             startPos = 0;
763             cr.cpMin = 0;
764             cr.cpMax = length;
765         }
766
767         ft.chrg = cr;
768         ft.lpstrText = pFr->lpstrFindWhat;
769
770         if(pFr->Flags & FR_MATCHCASE)
771             flags |= FR_MATCHCASE;
772         if(pFr->Flags & FR_WHOLEWORD)
773             flags |= FR_WHOLEWORD;
774
775         ret = SendMessageW(hEditorWnd, EM_FINDTEXTW, (WPARAM)flags, (LPARAM)&ft);
776
777         if(ret == -1)
778         {
779             if(cr.cpMax == length && cr.cpMax != startPos)
780             {
781                 ft.chrg.cpMin = cr.cpMin = 0;
782                 ft.chrg.cpMax = cr.cpMax = startPos;
783
784                 ret = SendMessageW(hEditorWnd, EM_FINDTEXTW, (WPARAM)flags, (LPARAM)&ft);
785             }
786         }
787
788         if(ret == -1)
789         {
790             pFr->lCustData = -1;
791             MessageBoxW(hMainWnd, MAKEINTRESOURCEW(STRING_SEARCH_FINISHED), wszAppTitle,
792                         MB_OK | MB_ICONASTERISK);
793         } else
794         {
795             end = ret + lstrlenW(pFr->lpstrFindWhat);
796             cr.cpMin = end;
797             SendMessageW(hEditorWnd, EM_SETSEL, (WPARAM)ret, (LPARAM)end);
798             SendMessageW(hEditorWnd, EM_SCROLLCARET, 0, 0);
799         }
800     }
801
802     return 0;
803 }
804
805 static void dialog_find(LPFINDREPLACEW fr)
806 {
807     static WCHAR findBuffer[MAX_STRING_LEN];
808
809     ZeroMemory(fr, sizeof(FINDREPLACEW));
810     fr->lStructSize = sizeof(FINDREPLACEW);
811     fr->hwndOwner = hMainWnd;
812     fr->Flags = FR_HIDEUPDOWN;
813     fr->lpstrFindWhat = findBuffer;
814     fr->lCustData = -1;
815     fr->wFindWhatLen = MAX_STRING_LEN*sizeof(WCHAR);
816
817     hFindWnd = FindTextW(fr);
818 }
819
820
821 static void DoDefaultFont(void)
822 {
823     static const WCHAR szFaceName[] = {'T','i','m','e','s',' ','N','e','w',' ','R','o','m','a','n',0};
824     CHARFORMAT2W fmt;
825
826     ZeroMemory(&fmt, sizeof(fmt));
827
828     fmt.cbSize = sizeof(fmt);
829     fmt.dwMask = CFM_FACE | CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE;
830     fmt.dwEffects = 0;
831
832     lstrcpyW(fmt.szFaceName, szFaceName);
833
834     SendMessageW(hEditorWnd, EM_SETCHARFORMAT,  SCF_DEFAULT, (LPARAM)&fmt);
835 }
836
837 static void update_window(void)
838 {
839     RECT rect;
840
841     GetWindowRect(hMainWnd, &rect);
842
843     (void) OnSize(hMainWnd, SIZE_RESTORED, MAKELONG(rect.bottom, rect.right));
844 }
845
846 static void toggle_toolbar(int bandId)
847 {
848     HWND hwndReBar = GetDlgItem(hMainWnd, IDC_REBAR);
849     REBARBANDINFOW rbbinfo;
850     BOOL hide = TRUE;
851
852     if(!hwndReBar)
853         return;
854
855     rbbinfo.cbSize = sizeof(rbbinfo);
856     rbbinfo.fMask = RBBIM_STYLE | RBBIM_SIZE;
857
858     SendMessageW(hwndReBar, RB_GETBANDINFO, bandId, (LPARAM)&rbbinfo);
859
860     if(rbbinfo.fStyle & RBBS_HIDDEN)
861         hide = FALSE;
862
863     SendMessageW(hwndReBar, RB_SHOWBAND, bandId, hide ? 0 : 1);
864
865     if(bandId == BANDID_TOOLBAR)
866     {
867         rbbinfo.fMask ^= RBBIM_SIZE;
868
869         SendMessageW(hwndReBar, RB_GETBANDINFO, BANDID_FORMATBAR, (LPARAM)&rbbinfo);
870
871         if(hide)
872             rbbinfo.fStyle ^= RBBS_BREAK;
873         else
874             rbbinfo.fStyle |= RBBS_BREAK;
875
876         SendMessageW(hwndReBar, RB_SETBANDINFO, BANDID_FORMATBAR, (LPARAM)&rbbinfo);
877     }
878 }
879
880 BOOL CALLBACK datetime_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
881 {
882     switch(message)
883     {
884         case WM_INITDIALOG:
885             {
886                 WCHAR buffer[MAX_STRING_LEN];
887                 SYSTEMTIME st;
888                 HWND hListWnd = GetDlgItem(hWnd, IDC_DATETIME);
889                 GetLocalTime(&st);
890
891                 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &st, 0, (LPWSTR)&buffer,
892                                MAX_STRING_LEN);
893                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
894                 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, 0, (LPWSTR)&buffer,
895                                MAX_STRING_LEN);
896                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
897                 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, 0, (LPWSTR)&buffer, MAX_STRING_LEN);
898                 SendMessageW(hListWnd, LB_ADDSTRING, 0, (LPARAM)&buffer);
899
900                 SendMessageW(hListWnd, LB_SETSEL, TRUE, 0);
901             }
902             break;
903
904         case WM_COMMAND:
905             switch(LOWORD(wParam))
906             {
907                 case IDOK:
908                     {
909                         LRESULT index;
910                         HWND hListWnd = GetDlgItem(hWnd, IDC_DATETIME);
911
912                         index = SendMessageW(hListWnd, LB_GETCURSEL, 0, 0);
913
914                         if(index != LB_ERR)
915                         {
916                             WCHAR buffer[MAX_STRING_LEN];
917                             SendMessageW(hListWnd, LB_GETTEXT, index, (LPARAM)&buffer);
918                             SendMessageW(hEditorWnd, EM_REPLACESEL, TRUE, (LPARAM)&buffer);
919                         }
920                     }
921                     /* Fall through */
922
923                 case IDCANCEL:
924                     EndDialog(hWnd, wParam);
925                     return TRUE;
926             }
927     }
928     return FALSE;
929 }
930
931 static LRESULT OnCreate( HWND hWnd, WPARAM wParam, LPARAM lParam)
932 {
933     HWND hToolBarWnd, hFormatBarWnd,  hReBarWnd;
934     HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE);
935     HANDLE hDLL;
936     TBADDBITMAP ab;
937     int nStdBitmaps = 0;
938     REBARINFO rbi;
939     REBARBANDINFOW rbb;
940     static const WCHAR wszRichEditDll[] = {'R','I','C','H','E','D','2','0','.','D','L','L','\0'};
941     static const WCHAR wszRichEditText[] = {'R','i','c','h','E','d','i','t',' ','t','e','x','t','\0'};
942
943     CreateStatusWindowW(CCS_NODIVIDER|WS_CHILD|WS_VISIBLE, wszRichEditText, hWnd, IDC_STATUSBAR);
944
945     hReBarWnd = CreateWindowExW(WS_EX_TOOLWINDOW, REBARCLASSNAMEW, NULL,
946       CCS_NODIVIDER|WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|RBS_VARHEIGHT|CCS_TOP,
947       CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, hWnd, (HMENU)IDC_REBAR, hInstance, NULL);
948
949     rbi.cbSize = sizeof(rbi);
950     rbi.fMask = 0;
951     rbi.himl = NULL;
952     if(!SendMessageW(hReBarWnd, RB_SETBARINFO, 0, (LPARAM)&rbi))
953         return -1;
954
955     hToolBarWnd = CreateToolbarEx(hReBarWnd, CCS_NOPARENTALIGN|CCS_NOMOVEY|WS_VISIBLE|WS_CHILD|TBSTYLE_TOOLTIPS|TBSTYLE_BUTTON,
956       IDC_TOOLBAR,
957       1, hInstance, IDB_TOOLBAR,
958       NULL, 0,
959       24, 24, 16, 16, sizeof(TBBUTTON));
960
961     ab.hInst = HINST_COMMCTRL;
962     ab.nID = IDB_STD_SMALL_COLOR;
963     nStdBitmaps = SendMessageW(hToolBarWnd, TB_ADDBITMAP, 0, (LPARAM)&ab);
964
965     AddButton(hToolBarWnd, nStdBitmaps+STD_FILENEW, ID_FILE_NEW);
966     AddButton(hToolBarWnd, nStdBitmaps+STD_FILEOPEN, ID_FILE_OPEN);
967     AddButton(hToolBarWnd, nStdBitmaps+STD_FILESAVE, ID_FILE_SAVE);
968     AddSeparator(hToolBarWnd);
969     AddButton(hToolBarWnd, nStdBitmaps+STD_PRINT, ID_PRINT);
970     AddButton(hToolBarWnd, nStdBitmaps+STD_PRINTPRE, ID_PREVIEW);
971     AddSeparator(hToolBarWnd);
972     AddButton(hToolBarWnd, nStdBitmaps+STD_FIND, ID_FIND);
973     AddSeparator(hToolBarWnd);
974     AddButton(hToolBarWnd, nStdBitmaps+STD_CUT, ID_EDIT_CUT);
975     AddButton(hToolBarWnd, nStdBitmaps+STD_COPY, ID_EDIT_COPY);
976     AddButton(hToolBarWnd, nStdBitmaps+STD_PASTE, ID_EDIT_PASTE);
977     AddButton(hToolBarWnd, nStdBitmaps+STD_UNDO, ID_EDIT_UNDO);
978     AddButton(hToolBarWnd, nStdBitmaps+STD_REDOW, ID_EDIT_REDO);
979     AddSeparator(hToolBarWnd);
980     AddButton(hToolBarWnd, 0, ID_DATETIME);
981
982     SendMessageW(hToolBarWnd, TB_AUTOSIZE, 0, 0);
983
984     rbb.cbSize = sizeof(rbb);
985     rbb.fMask = RBBIM_SIZE | RBBIM_CHILDSIZE | RBBIM_CHILD | RBBIM_STYLE;
986     rbb.fStyle = RBBS_CHILDEDGE | RBBS_BREAK | RBBS_NOGRIPPER;
987     rbb.cx = 0;
988     rbb.hwndChild = hToolBarWnd;
989     rbb.cxMinChild = 0;
990     rbb.cyChild = rbb.cyMinChild = HIWORD(SendMessageW(hToolBarWnd, TB_GETBUTTONSIZE, 0, 0));
991
992     SendMessageW(hReBarWnd, RB_INSERTBAND, BANDID_TOOLBAR, (LPARAM)&rbb);
993
994     hFormatBarWnd = CreateToolbarEx(hReBarWnd,
995          CCS_NOPARENTALIGN | CCS_NOMOVEY | WS_VISIBLE | TBSTYLE_TOOLTIPS | TBSTYLE_BUTTON,
996          IDC_FORMATBAR, 7, hInstance, IDB_FORMATBAR, NULL, 0, 16, 16, 16, 16, sizeof(TBBUTTON));
997
998     AddButton(hFormatBarWnd, 0, ID_FORMAT_BOLD);
999     AddButton(hFormatBarWnd, 1, ID_FORMAT_ITALIC);
1000     AddButton(hFormatBarWnd, 2, ID_FORMAT_UNDERLINE);
1001     AddSeparator(hFormatBarWnd);
1002     AddButton(hFormatBarWnd, 3, ID_ALIGN_LEFT);
1003     AddButton(hFormatBarWnd, 4, ID_ALIGN_CENTER);
1004     AddButton(hFormatBarWnd, 5, ID_ALIGN_RIGHT);
1005     AddSeparator(hFormatBarWnd);
1006     AddButton(hFormatBarWnd, 6, ID_BULLET);
1007
1008     SendMessageW(hFormatBarWnd, TB_AUTOSIZE, 0, 0);
1009
1010     rbb.hwndChild = hFormatBarWnd;
1011
1012     SendMessageW(hReBarWnd, RB_INSERTBAND, BANDID_FORMATBAR, (LPARAM)&rbb);
1013
1014     hDLL = LoadLibraryW(wszRichEditDll);
1015     if(!hDLL)
1016     {
1017         MessageBoxW(hWnd, MAKEINTRESOURCEW(STRING_LOAD_RICHED_FAILED), wszAppTitle,
1018                     MB_OK | MB_ICONEXCLAMATION);
1019         PostQuitMessage(1);
1020     }
1021
1022     hEditorWnd = CreateWindowExW(WS_EX_CLIENTEDGE, wszRichEditClass, NULL,
1023       WS_CHILD|WS_VISIBLE|ES_MULTILINE|ES_AUTOVSCROLL|ES_WANTRETURN|WS_VSCROLL,
1024       0, 0, 1000, 100, hWnd, (HMENU)IDC_EDITOR, hInstance, NULL);
1025
1026     if (!hEditorWnd)
1027     {
1028         fprintf(stderr, "Error code %u\n", GetLastError());
1029         return -1;
1030     }
1031     assert(hEditorWnd);
1032
1033     SetFocus(hEditorWnd);
1034     SendMessageW(hEditorWnd, EM_SETEVENTMASK, 0, ENM_SELCHANGE);
1035
1036     DoDefaultFont();
1037
1038     DoLoadStrings();
1039     SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
1040
1041     ID_FINDMSGSTRING = RegisterWindowMessageW(FINDMSGSTRINGW);
1042
1043     registry_read_filelist(hWnd);
1044
1045     return 0;
1046 }
1047
1048 static LRESULT OnUser( HWND hWnd, WPARAM wParam, LPARAM lParam)
1049 {
1050     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
1051     HWND hwndReBar = GetDlgItem(hWnd, IDC_REBAR);
1052     HWND hwndToolBar = GetDlgItem(hwndReBar, IDC_TOOLBAR);
1053     HWND hwndFormatBar = GetDlgItem(hwndReBar, IDC_FORMATBAR);
1054     int from, to;
1055     CHARFORMAT2W fmt;
1056     PARAFORMAT2 pf;
1057     GETTEXTLENGTHEX gt;
1058
1059     ZeroMemory(&fmt, sizeof(fmt));
1060     fmt.cbSize = sizeof(fmt);
1061
1062     ZeroMemory(&pf, sizeof(pf));
1063     pf.cbSize = sizeof(pf);
1064
1065     gt.flags = GTL_NUMCHARS;
1066     gt.codepage = 1200;
1067
1068     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_FIND,
1069                  SendMessageW(hwndEditor, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0) ? 1 : 0);
1070
1071     SendMessageW(hwndEditor, EM_GETCHARFORMAT, TRUE, (LPARAM)&fmt);
1072
1073     SendMessageW(hwndEditor, EM_GETSEL, (WPARAM)&from, (LPARAM)&to);
1074     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_UNDO,
1075       SendMessageW(hwndEditor, EM_CANUNDO, 0, 0));
1076     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_REDO,
1077       SendMessageW(hwndEditor, EM_CANREDO, 0, 0));
1078     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_CUT, from == to ? 0 : 1);
1079     SendMessageW(hwndToolBar, TB_ENABLEBUTTON, ID_EDIT_COPY, from == to ? 0 : 1);
1080
1081     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_FORMAT_BOLD, (fmt.dwMask & CFM_BOLD) &&
1082             (fmt.dwEffects & CFE_BOLD));
1083     SendMessageW(hwndFormatBar, TB_INDETERMINATE, ID_FORMAT_BOLD, !(fmt.dwMask & CFM_BOLD));
1084     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_FORMAT_ITALIC, (fmt.dwMask & CFM_ITALIC) &&
1085             (fmt.dwEffects & CFE_ITALIC));
1086     SendMessageW(hwndFormatBar, TB_INDETERMINATE, ID_FORMAT_ITALIC, !(fmt.dwMask & CFM_ITALIC));
1087     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_FORMAT_UNDERLINE, (fmt.dwMask & CFM_UNDERLINE) &&
1088             (fmt.dwEffects & CFE_UNDERLINE));
1089     SendMessageW(hwndFormatBar, TB_INDETERMINATE, ID_FORMAT_UNDERLINE, !(fmt.dwMask & CFM_UNDERLINE));
1090
1091     SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
1092     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_ALIGN_LEFT, (pf.wAlignment == PFA_LEFT));
1093     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_ALIGN_CENTER, (pf.wAlignment == PFA_CENTER));
1094     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_ALIGN_RIGHT, (pf.wAlignment == PFA_RIGHT));
1095
1096     SendMessageW(hwndFormatBar, TB_CHECKBUTTON, ID_BULLET, (pf.wNumbering & PFN_BULLET));
1097     return 0;
1098 }
1099
1100 static LRESULT OnNotify( HWND hWnd, WPARAM wParam, LPARAM lParam)
1101 {
1102     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
1103     NMHDR *pHdr = (NMHDR *)lParam;
1104
1105     if (pHdr->hwndFrom != hwndEditor)
1106         return 0;
1107
1108     if (pHdr->code == EN_SELCHANGE)
1109     {
1110         SELCHANGE *pSC = (SELCHANGE *)lParam;
1111         char buf[128];
1112
1113         sprintf( buf,"selection = %d..%d, line count=%ld",
1114                  pSC->chrg.cpMin, pSC->chrg.cpMax,
1115         SendMessage(hwndEditor, EM_GETLINECOUNT, 0, 0));
1116         SetWindowText(GetDlgItem(hWnd, IDC_STATUSBAR), buf);
1117         SendMessage(hWnd, WM_USER, 0, 0);
1118         return 1;
1119     }
1120     return 0;
1121 }
1122
1123 static LRESULT OnCommand( HWND hWnd, WPARAM wParam, LPARAM lParam)
1124 {
1125     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
1126     HWND hwndStatus = GetDlgItem(hWnd, IDC_STATUSBAR);
1127     static FINDREPLACEW findreplace;
1128
1129     if ((HWND)lParam == hwndEditor)
1130         return 0;
1131
1132     switch(LOWORD(wParam))
1133     {
1134
1135     case ID_FILE_EXIT:
1136         PostMessageW(hWnd, WM_CLOSE, 0, 0);
1137         break;
1138
1139     case ID_FILE_NEW:
1140         if(prompt_save_changes())
1141         {
1142             set_caption(NULL);
1143             wszFileName[0] = '\0';
1144             SetWindowTextW(hwndEditor, wszFileName);
1145             SendMessageW(hEditorWnd, EM_SETMODIFY, FALSE, 0);
1146             fileFormat = SF_RTF;
1147         }
1148         break;
1149
1150     case ID_FILE_OPEN:
1151         DialogOpenFile();
1152         break;
1153
1154     case ID_FILE_SAVE:
1155         if(wszFileName[0])
1156         {
1157             DoSaveFile(wszFileName, fileFormat);
1158             break;
1159         }
1160         /* Fall through */
1161
1162     case ID_FILE_SAVEAS:
1163         DialogSaveFile();
1164         break;
1165
1166     case ID_FILE_RECENT1:
1167     case ID_FILE_RECENT2:
1168     case ID_FILE_RECENT3:
1169     case ID_FILE_RECENT4:
1170         {
1171             HMENU hMenu = GetMenu(hWnd);
1172             MENUITEMINFOW mi;
1173
1174             mi.cbSize = sizeof(MENUITEMINFOW);
1175             mi.fMask = MIIM_DATA;
1176             if(GetMenuItemInfoW(hMenu, LOWORD(wParam), FALSE, &mi))
1177                 DoOpenFile((LPWSTR)mi.dwItemData);
1178         }
1179         break;
1180
1181     case ID_FIND:
1182         dialog_find(&findreplace);
1183         break;
1184
1185     case ID_FIND_NEXT:
1186         handle_findmsg(&findreplace);
1187         break;
1188
1189     case ID_PRINT:
1190     case ID_PREVIEW:
1191         {
1192             static const WCHAR wszNotImplemented[] = {'N','o','t',' ',
1193                                                       'i','m','p','l','e','m','e','n','t','e','d','\0'};
1194             MessageBoxW(hWnd, wszNotImplemented, wszAppTitle, MB_OK);
1195         }
1196         break;
1197
1198     case ID_FORMAT_BOLD:
1199     case ID_FORMAT_ITALIC:
1200     case ID_FORMAT_UNDERLINE:
1201         {
1202         CHARFORMAT2W fmt;
1203         int mask = CFM_BOLD;
1204         if (LOWORD(wParam) == ID_FORMAT_ITALIC) mask = CFM_ITALIC;
1205         if (LOWORD(wParam) == ID_FORMAT_UNDERLINE) mask = CFM_UNDERLINE;
1206
1207         ZeroMemory(&fmt, sizeof(fmt));
1208         fmt.cbSize = sizeof(fmt);
1209         SendMessageW(hwndEditor, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
1210         if (!(fmt.dwMask&mask))
1211             fmt.dwEffects |= mask;
1212         else
1213             fmt.dwEffects ^= mask;
1214         fmt.dwMask = mask;
1215         SendMessageW(hwndEditor, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&fmt);
1216         break;
1217         }
1218
1219     case ID_EDIT_CUT:
1220         PostMessageW(hwndEditor, WM_CUT, 0, 0);
1221         break;
1222
1223     case ID_EDIT_COPY:
1224         PostMessageW(hwndEditor, WM_COPY, 0, 0);
1225         break;
1226
1227     case ID_EDIT_PASTE:
1228         PostMessageW(hwndEditor, WM_PASTE, 0, 0);
1229         break;
1230
1231     case ID_EDIT_CLEAR:
1232         PostMessageW(hwndEditor, WM_CLEAR, 0, 0);
1233         break;
1234
1235     case ID_EDIT_SELECTALL:
1236         {
1237         CHARRANGE range = {0, -1};
1238         SendMessageW(hwndEditor, EM_EXSETSEL, 0, (LPARAM)&range);
1239         /* SendMessage(hwndEditor, EM_SETSEL, 0, -1); */
1240         return 0;
1241         }
1242
1243     case ID_EDIT_GETTEXT:
1244         {
1245         int nLen = GetWindowTextLengthW(hwndEditor);
1246         LPWSTR data = HeapAlloc( GetProcessHeap(), 0, (nLen+1)*sizeof(WCHAR) );
1247         TEXTRANGEW tr;
1248
1249         GetWindowTextW(hwndEditor, data, nLen+1);
1250         MessageBoxW(NULL, data, xszAppTitle, MB_OK);
1251
1252         HeapFree( GetProcessHeap(), 0, data);
1253         data = HeapAlloc(GetProcessHeap(), 0, (nLen+1)*sizeof(WCHAR));
1254         tr.chrg.cpMin = 0;
1255         tr.chrg.cpMax = nLen;
1256         tr.lpstrText = data;
1257         SendMessage (hwndEditor, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1258         MessageBoxW(NULL, data, xszAppTitle, MB_OK);
1259         HeapFree( GetProcessHeap(), 0, data );
1260
1261         /* SendMessage(hwndEditor, EM_SETSEL, 0, -1); */
1262         return 0;
1263         }
1264
1265     case ID_EDIT_CHARFORMAT:
1266     case ID_EDIT_DEFCHARFORMAT:
1267         {
1268         CHARFORMAT2W cf;
1269         LRESULT i;
1270         ZeroMemory(&cf, sizeof(cf));
1271         cf.cbSize = sizeof(cf);
1272         cf.dwMask = 0;
1273         i = SendMessageW(hwndEditor, EM_GETCHARFORMAT,
1274                         LOWORD(wParam) == ID_EDIT_CHARFORMAT, (LPARAM)&cf);
1275         return 0;
1276         }
1277
1278     case ID_EDIT_PARAFORMAT:
1279         {
1280         PARAFORMAT2 pf;
1281         ZeroMemory(&pf, sizeof(pf));
1282         pf.cbSize = sizeof(pf);
1283         SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
1284         return 0;
1285         }
1286
1287     case ID_EDIT_SELECTIONINFO:
1288         {
1289         CHARRANGE range = {0, -1};
1290         char buf[128];
1291         WCHAR *data = NULL;
1292
1293         SendMessage(hwndEditor, EM_EXGETSEL, 0, (LPARAM)&range);
1294         data = HeapAlloc(GetProcessHeap(), 0, sizeof(*data) * (range.cpMax-range.cpMin+1));
1295         SendMessage(hwndEditor, EM_GETSELTEXT, 0, (LPARAM)data);
1296         sprintf(buf, "Start = %d, End = %d", range.cpMin, range.cpMax);
1297         MessageBoxA(hWnd, buf, "Editor", MB_OK);
1298         MessageBoxW(hWnd, data, xszAppTitle, MB_OK);
1299         HeapFree( GetProcessHeap(), 0, data);
1300         /* SendMessage(hwndEditor, EM_SETSEL, 0, -1); */
1301         return 0;
1302         }
1303
1304     case ID_EDIT_READONLY:
1305         {
1306         long nStyle = GetWindowLong(hwndEditor, GWL_STYLE);
1307         if (nStyle & ES_READONLY)
1308             SendMessageW(hwndEditor, EM_SETREADONLY, 0, 0);
1309         else
1310             SendMessageW(hwndEditor, EM_SETREADONLY, 1, 0);
1311         return 0;
1312         }
1313
1314     case ID_EDIT_MODIFIED:
1315         if (SendMessageW(hwndEditor, EM_GETMODIFY, 0, 0))
1316             SendMessageW(hwndEditor, EM_SETMODIFY, 0, 0);
1317         else
1318             SendMessageW(hwndEditor, EM_SETMODIFY, 1, 0);
1319         return 0;
1320
1321     case ID_EDIT_UNDO:
1322         SendMessageW(hwndEditor, EM_UNDO, 0, 0);
1323         return 0;
1324
1325     case ID_EDIT_REDO:
1326         SendMessageW(hwndEditor, EM_REDO, 0, 0);
1327         return 0;
1328
1329     case ID_BULLET:
1330         {
1331             PARAFORMAT pf;
1332
1333             pf.cbSize = sizeof(pf);
1334             pf.dwMask = PFM_NUMBERING;
1335             SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
1336
1337             pf.dwMask |=  PFM_OFFSET;
1338
1339             if(pf.wNumbering == PFN_BULLET)
1340             {
1341                 pf.wNumbering = 0;
1342                 pf.dxOffset = 0;
1343             } else
1344             {
1345                 pf.wNumbering = PFN_BULLET;
1346                 pf.dxOffset = 720;
1347             }
1348
1349             SendMessageW(hwndEditor, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
1350         }
1351         break;
1352
1353     case ID_ALIGN_LEFT:
1354     case ID_ALIGN_CENTER:
1355     case ID_ALIGN_RIGHT:
1356         {
1357         PARAFORMAT2 pf;
1358
1359         pf.cbSize = sizeof(pf);
1360         pf.dwMask = PFM_ALIGNMENT;
1361         switch(LOWORD(wParam)) {
1362         case ID_ALIGN_LEFT: pf.wAlignment = PFA_LEFT; break;
1363         case ID_ALIGN_CENTER: pf.wAlignment = PFA_CENTER; break;
1364         case ID_ALIGN_RIGHT: pf.wAlignment = PFA_RIGHT; break;
1365         }
1366         SendMessageW(hwndEditor, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
1367         break;
1368         }
1369
1370     case ID_BACK_1:
1371         SendMessageW(hwndEditor, EM_SETBKGNDCOLOR, 1, 0);
1372         break;
1373
1374     case ID_BACK_2:
1375         SendMessageW(hwndEditor, EM_SETBKGNDCOLOR, 0, RGB(255,255,192));
1376         break;
1377
1378     case ID_TOGGLE_TOOLBAR:
1379         toggle_toolbar(BANDID_TOOLBAR);
1380         update_window();
1381         break;
1382
1383     case ID_TOGGLE_FORMATBAR:
1384         toggle_toolbar(BANDID_FORMATBAR);
1385         update_window();
1386         break;
1387
1388     case ID_TOGGLE_STATUSBAR:
1389         ShowWindow(hwndStatus, IsWindowVisible(hwndStatus) ? SW_HIDE : SW_SHOW);
1390         update_window();
1391         break;
1392
1393     case ID_DATETIME:
1394         {
1395         HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE);
1396         DialogBoxW(hInstance, MAKEINTRESOURCEW(IDD_DATETIME), hWnd, (DLGPROC)datetime_proc);
1397         break;
1398         }
1399
1400     default:
1401         SendMessageW(hwndEditor, WM_COMMAND, wParam, lParam);
1402         break;
1403     }
1404     return 0;
1405 }
1406
1407 static LRESULT OnInitPopupMenu( HWND hWnd, WPARAM wParam, LPARAM lParam )
1408 {
1409     HMENU hMenu = (HMENU)wParam;
1410     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
1411     HWND hwndReBar = GetDlgItem(hWnd, IDC_REBAR);
1412     HWND hwndStatus = GetDlgItem(hWnd, IDC_STATUSBAR);
1413     PARAFORMAT pf;
1414     int nAlignment = -1;
1415     REBARBANDINFOW rbbinfo;
1416     int selFrom, selTo;
1417     GETTEXTLENGTHEX gt;
1418     LRESULT textLength;
1419     MENUITEMINFOW mi;
1420
1421     SendMessageW(hEditorWnd, EM_GETSEL, (WPARAM)&selFrom, (LPARAM)&selTo);
1422     EnableMenuItem(hMenu, ID_EDIT_COPY, MF_BYCOMMAND|(selFrom == selTo) ? MF_GRAYED : MF_ENABLED);
1423     EnableMenuItem(hMenu, ID_EDIT_CUT, MF_BYCOMMAND|(selFrom == selTo) ? MF_GRAYED : MF_ENABLED);
1424
1425     pf.cbSize = sizeof(PARAFORMAT);
1426     SendMessageW(hwndEditor, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
1427     CheckMenuItem(hMenu, ID_EDIT_READONLY,
1428       MF_BYCOMMAND|(GetWindowLong(hwndEditor, GWL_STYLE)&ES_READONLY ? MF_CHECKED : MF_UNCHECKED));
1429     CheckMenuItem(hMenu, ID_EDIT_MODIFIED,
1430       MF_BYCOMMAND|(SendMessage(hwndEditor, EM_GETMODIFY, 0, 0) ? MF_CHECKED : MF_UNCHECKED));
1431     if (pf.dwMask & PFM_ALIGNMENT)
1432         nAlignment = pf.wAlignment;
1433     CheckMenuItem(hMenu, ID_ALIGN_LEFT, MF_BYCOMMAND|(nAlignment == PFA_LEFT) ?
1434             MF_CHECKED : MF_UNCHECKED);
1435     CheckMenuItem(hMenu, ID_ALIGN_CENTER, MF_BYCOMMAND|(nAlignment == PFA_CENTER) ?
1436             MF_CHECKED : MF_UNCHECKED);
1437     CheckMenuItem(hMenu, ID_ALIGN_RIGHT, MF_BYCOMMAND|(nAlignment == PFA_RIGHT) ?
1438             MF_CHECKED : MF_UNCHECKED);
1439     CheckMenuItem(hMenu, ID_BULLET, MF_BYCOMMAND | ((pf.wNumbering == PFN_BULLET) ?
1440             MF_CHECKED : MF_UNCHECKED));
1441     EnableMenuItem(hMenu, ID_EDIT_UNDO, MF_BYCOMMAND|(SendMessageW(hwndEditor, EM_CANUNDO, 0, 0)) ?
1442             MF_ENABLED : MF_GRAYED);
1443     EnableMenuItem(hMenu, ID_EDIT_REDO, MF_BYCOMMAND|(SendMessageW(hwndEditor, EM_CANREDO, 0, 0)) ?
1444             MF_ENABLED : MF_GRAYED);
1445
1446     rbbinfo.cbSize = sizeof(rbbinfo);
1447     rbbinfo.fMask = RBBIM_STYLE;
1448     SendMessageW(hwndReBar, RB_GETBANDINFO, BANDID_TOOLBAR, (LPARAM)&rbbinfo);
1449
1450     CheckMenuItem(hMenu, ID_TOGGLE_TOOLBAR, MF_BYCOMMAND|(rbbinfo.fStyle & RBBS_HIDDEN) ?
1451             MF_UNCHECKED : MF_CHECKED);
1452
1453     SendMessageW(hwndReBar, RB_GETBANDINFO, BANDID_FORMATBAR, (LPARAM)&rbbinfo);
1454
1455     CheckMenuItem(hMenu, ID_TOGGLE_FORMATBAR, MF_BYCOMMAND|(rbbinfo.fStyle & RBBS_HIDDEN) ?
1456             MF_UNCHECKED : MF_CHECKED);
1457
1458     CheckMenuItem(hMenu, ID_TOGGLE_STATUSBAR, MF_BYCOMMAND|IsWindowVisible(hwndStatus) ?
1459             MF_CHECKED : MF_UNCHECKED);
1460
1461     gt.flags = GTL_NUMCHARS;
1462     gt.codepage = 1200;
1463     textLength = SendMessageW(hEditorWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gt, 0);
1464     EnableMenuItem(hMenu, ID_FIND, MF_BYCOMMAND|(textLength ? MF_ENABLED : MF_GRAYED));
1465
1466     mi.cbSize = sizeof(mi);
1467     mi.fMask = MIIM_DATA;
1468
1469     GetMenuItemInfoW(hMenu, ID_FIND_NEXT, FALSE, &mi);
1470
1471     EnableMenuItem(hMenu, ID_FIND_NEXT, MF_BYCOMMAND|((textLength && mi.dwItemData) ?
1472                    MF_ENABLED : MF_GRAYED));
1473     return 0;
1474 }
1475
1476 static LRESULT OnSize( HWND hWnd, WPARAM wParam, LPARAM lParam )
1477 {
1478     int nStatusSize = 0;
1479     RECT rc;
1480     HWND hwndEditor = GetDlgItem(hWnd, IDC_EDITOR);
1481     HWND hwndStatusBar = GetDlgItem(hWnd, IDC_STATUSBAR);
1482     HWND hwndReBar = GetDlgItem(hWnd, IDC_REBAR);
1483     int rebarHeight = 0;
1484     REBARBANDINFOW rbbinfo;
1485     int rebarRows = 2;
1486
1487     if (hwndStatusBar)
1488     {
1489         SendMessageW(hwndStatusBar, WM_SIZE, 0, 0);
1490         if (IsWindowVisible(hwndStatusBar))
1491         {
1492             GetClientRect(hwndStatusBar, &rc);
1493             nStatusSize = rc.bottom - rc.top;
1494         } else
1495         {
1496             nStatusSize = 0;
1497         }
1498     }
1499     if (hwndReBar)
1500     {
1501         rbbinfo.cbSize = sizeof(rbbinfo);
1502         rbbinfo.fMask = RBBIM_STYLE;
1503
1504         SendMessageW(hwndReBar, RB_GETBANDINFO, BANDID_TOOLBAR, (LPARAM)&rbbinfo);
1505         if(rbbinfo.fStyle & RBBS_HIDDEN)
1506             rebarRows--;
1507
1508         SendMessageW(hwndReBar, RB_GETBANDINFO, BANDID_FORMATBAR, (LPARAM)&rbbinfo);
1509         if(rbbinfo.fStyle & RBBS_HIDDEN)
1510             rebarRows--;
1511
1512         rebarHeight = rebarRows ? SendMessageW(hwndReBar, RB_GETBARHEIGHT, 0, 0) : 0;
1513
1514         rc.top = rc.left = 0;
1515         rc.bottom = rebarHeight;
1516         rc.right = LOWORD(lParam);
1517         SendMessageW(hwndReBar, RB_SIZETORECT, 0, (LPARAM)&rc);
1518     }
1519     if (hwndEditor)
1520     {
1521         GetClientRect(hWnd, &rc);
1522         MoveWindow(hwndEditor, 0, rebarHeight, rc.right, rc.bottom-nStatusSize-rebarHeight, TRUE);
1523     }
1524
1525     return DefWindowProcW(hWnd, WM_SIZE, wParam, lParam);
1526 }
1527
1528 static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1529 {
1530     if(msg == ID_FINDMSGSTRING)
1531         return handle_findmsg((LPFINDREPLACEW)lParam);
1532
1533     switch(msg)
1534     {
1535     case WM_CREATE:
1536         return OnCreate( hWnd, wParam, lParam );
1537
1538     case WM_USER:
1539         return OnUser( hWnd, wParam, lParam );
1540
1541     case WM_NOTIFY:
1542         return OnNotify( hWnd, wParam, lParam );
1543
1544     case WM_COMMAND:
1545         return OnCommand( hWnd, wParam, lParam );
1546
1547     case WM_DESTROY:
1548         PostQuitMessage(0);
1549         break;
1550
1551     case WM_CLOSE:
1552         if(prompt_save_changes())
1553             PostQuitMessage(0);
1554         break;
1555
1556     case WM_ACTIVATE:
1557         if (LOWORD(wParam))
1558             SetFocus(GetDlgItem(hWnd, IDC_EDITOR));
1559         return 0;
1560
1561     case WM_INITMENUPOPUP:
1562         return OnInitPopupMenu( hWnd, wParam, lParam );
1563
1564     case WM_SIZE:
1565         return OnSize( hWnd, wParam, lParam );
1566
1567     default:
1568         return DefWindowProcW(hWnd, msg, wParam, lParam);
1569     }
1570
1571     return 0;
1572 }
1573
1574 int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hOldInstance, LPSTR szCmdParagraph, int res)
1575 {
1576     INITCOMMONCONTROLSEX classes = {8, ICC_BAR_CLASSES|ICC_COOL_CLASSES};
1577     HACCEL hAccel;
1578     WNDCLASSW wc;
1579     MSG msg;
1580     static const WCHAR wszAccelTable[] = {'M','A','I','N','A','C','C','E','L',
1581                                           'T','A','B','L','E','\0'};
1582
1583     InitCommonControlsEx(&classes);
1584
1585     hAccel = LoadAcceleratorsW(hInstance, wszAccelTable);
1586
1587     wc.style = CS_HREDRAW | CS_VREDRAW;
1588     wc.lpfnWndProc = WndProc;
1589     wc.cbClsExtra = 0;
1590     wc.cbWndExtra = 4;
1591     wc.hInstance = hInstance;
1592     wc.hIcon = LoadIconW(hInstance, MAKEINTRESOURCEW(IDI_WORDPAD));
1593     wc.hCursor = LoadCursor(NULL, IDC_IBEAM);
1594     wc.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1595     wc.lpszMenuName = xszMainMenu;
1596     wc.lpszClassName = wszMainWndClass;
1597     RegisterClassW(&wc);
1598
1599     hMainWnd = CreateWindowExW(0, wszMainWndClass, wszAppTitle, WS_OVERLAPPEDWINDOW,
1600       CW_USEDEFAULT, CW_USEDEFAULT, 680, 260, NULL, NULL, hInstance, NULL);
1601     ShowWindow(hMainWnd, SW_SHOWDEFAULT);
1602
1603     set_caption(NULL);
1604
1605     HandleCommandLine(GetCommandLineW());
1606
1607     while(GetMessageW(&msg,0,0,0))
1608     {
1609         if (IsDialogMessage(hFindWnd, &msg))
1610             continue;
1611
1612         if (TranslateAcceleratorW(hMainWnd, hAccel, &msg))
1613             continue;
1614         TranslateMessage(&msg);
1615         DispatchMessageW(&msg);
1616         if (!PeekMessageW(&msg, 0, 0, 0, PM_NOREMOVE))
1617             SendMessageW(hMainWnd, WM_USER, 0, 0);
1618     }
1619
1620     return 0;
1621 }