notepad: Updated French translation.
[wine] / programs / notepad / main.c
1 /*
2  *  Notepad
3  *
4  *  Copyright 2000 Mike McCormack <Mike_McCormack@looksmart.com.au>
5  *  Copyright 1997,98 Marcel Baur <mbaur@g26.ethz.ch>
6  *  Copyright 2002 Sylvain Petreolle <spetreolle@yahoo.fr>
7  *  Copyright 2002 Andriy Palamarchuk
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  *
23  */
24
25 #include <windows.h>
26 #include <shlwapi.h>
27 #include <stdio.h>
28
29 #include "main.h"
30 #include "dialog.h"
31 #include "notepad_res.h"
32 #include "wine/unicode.h"
33
34 NOTEPAD_GLOBALS Globals;
35 static ATOM aFINDMSGSTRING;
36 static RECT main_rect;
37
38 static const WCHAR notepad_reg_key[] = {'S','o','f','t','w','a','r','e','\\',
39                                         'M','i','c','r','o','s','o','f','t','\\','N','o','t','e','p','a','d','\0'};
40 static const WCHAR value_fWrap[]            = {'f','W','r','a','p','\0'};
41 static const WCHAR value_iPointSize[]       = {'i','P','o','i','n','t','S','i','z','e','\0'};
42 static const WCHAR value_iWindowPosDX[]     = {'i','W','i','n','d','o','w','P','o','s','D','X','\0'};
43 static const WCHAR value_iWindowPosDY[]     = {'i','W','i','n','d','o','w','P','o','s','D','Y','\0'};
44 static const WCHAR value_iWindowPosX[]      = {'i','W','i','n','d','o','w','P','o','s','X','\0'};
45 static const WCHAR value_iWindowPosY[]      = {'i','W','i','n','d','o','w','P','o','s','Y','\0'};
46 static const WCHAR value_lfCharSet[]        = {'l','f','C','h','a','r','S','e','t','\0'};
47 static const WCHAR value_lfClipPrecision[]  = {'l','f','C','l','i','p','P','r','e','c','i','s','i','o','n','\0'};
48 static const WCHAR value_lfEscapement[]     = {'l','f','E','s','c','a','p','e','m','e','n','t','\0'};
49 static const WCHAR value_lfItalic[]         = {'l','f','I','t','a','l','i','c','\0'};
50 static const WCHAR value_lfOrientation[]    = {'l','f','O','r','i','e','n','t','a','t','i','o','n','\0'};
51 static const WCHAR value_lfOutPrecision[]   = {'l','f','O','u','t','P','r','e','c','i','s','i','o','n','\0'};
52 static const WCHAR value_lfPitchAndFamily[] = {'l','f','P','i','t','c','h','A','n','d','F','a','m','i','l','y','\0'};
53 static const WCHAR value_lfQuality[]        = {'l','f','Q','u','a','l','i','t','y','\0'};
54 static const WCHAR value_lfStrikeOut[]      = {'l','f','S','t','r','i','k','e','O','u','t','\0'};
55 static const WCHAR value_lfUnderline[]      = {'l','f','U','n','d','e','r','l','i','n','e','\0'};
56 static const WCHAR value_lfWeight[]         = {'l','f','W','e','i','g','h','t','\0'};
57 static const WCHAR value_lfFaceName[]       = {'l','f','F','a','c','e','N','a','m','e','\0'};
58 static const WCHAR value_iMarginTop[]       = {'i','M','a','r','g','i','n','T','o','p','\0'};
59 static const WCHAR value_iMarginBottom[]    = {'i','M','a','r','g','i','n','B','o','t','t','o','m','\0'};
60 static const WCHAR value_iMarginLeft[]      = {'i','M','a','r','g','i','n','L','e','f','t','\0'};
61 static const WCHAR value_iMarginRight[]     = {'i','M','a','r','g','i','n','R','i','g','h','t','\0'};
62 static const WCHAR value_szHeader[]         = {'s','z','H','e','a','d','e','r','\0'};
63 static const WCHAR value_szFooter[]         = {'s','z','T','r','a','i','l','e','r','\0'};
64
65 /***********************************************************************
66  *
67  *           SetFileName
68  *
69  *  Sets Global File Name.
70  */
71 VOID SetFileName(LPCWSTR szFileName)
72 {
73     lstrcpyW(Globals.szFileName, szFileName);
74     Globals.szFileTitle[0] = 0;
75     GetFileTitleW(szFileName, Globals.szFileTitle, sizeof(Globals.szFileTitle));
76 }
77
78 /******************************************************************************
79  *      get_dpi
80  *
81  * Get the dpi from registry HKCC\Software\Fonts\LogPixels.
82  */
83 DWORD get_dpi(void)
84 {
85     static const WCHAR dpi_key_name[] = {'S','o','f','t','w','a','r','e','\\','F','o','n','t','s','\0'};
86     static const WCHAR dpi_value_name[] = {'L','o','g','P','i','x','e','l','s','\0'};
87     DWORD dpi = 96;
88     HKEY hkey;
89
90     if (RegOpenKeyW(HKEY_CURRENT_CONFIG, dpi_key_name, &hkey) == ERROR_SUCCESS)
91     {
92         DWORD type, size, new_dpi;
93
94         size = sizeof(new_dpi);
95         if(RegQueryValueExW(hkey, dpi_value_name, NULL, &type, (LPBYTE)&new_dpi, &size) == ERROR_SUCCESS)
96         {
97             if(type == REG_DWORD && new_dpi != 0)
98                 dpi = new_dpi;
99         }
100         RegCloseKey(hkey);
101     }
102     return dpi;
103 }
104
105 /***********************************************************************
106  *
107  *           NOTEPAD_SaveSettingToRegistry
108  *
109  *  Save setting to registry HKCU\Software\Microsoft\Notepad.
110  */
111 static VOID NOTEPAD_SaveSettingToRegistry(void)
112 {
113     HKEY hkey;
114     DWORD disp;
115
116     if(RegCreateKeyExW(HKEY_CURRENT_USER, notepad_reg_key, 0, NULL,
117                 REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkey, &disp) == ERROR_SUCCESS)
118     {
119         DWORD data;
120         WINDOWPLACEMENT wndpl;
121
122         wndpl.length = sizeof(WINDOWPLACEMENT);
123         GetWindowPlacement(Globals.hMainWnd, &wndpl);
124         main_rect = wndpl.rcNormalPosition;
125
126 #define SET_NOTEPAD_REG(hkey, value_name, value_data) do { DWORD data = value_data; RegSetValueExW(hkey, value_name, 0, REG_DWORD, (LPBYTE)&data, sizeof(DWORD)); }while(0)
127         SET_NOTEPAD_REG(hkey, value_fWrap,            Globals.bWrapLongLines);
128         SET_NOTEPAD_REG(hkey, value_iWindowPosX,      main_rect.left);
129         SET_NOTEPAD_REG(hkey, value_iWindowPosY,      main_rect.top);
130         SET_NOTEPAD_REG(hkey, value_iWindowPosDX,     main_rect.right - main_rect.left);
131         SET_NOTEPAD_REG(hkey, value_iWindowPosDY,     main_rect.bottom - main_rect.top);
132         SET_NOTEPAD_REG(hkey, value_lfCharSet,        Globals.lfFont.lfCharSet);
133         SET_NOTEPAD_REG(hkey, value_lfClipPrecision,  Globals.lfFont.lfClipPrecision);
134         SET_NOTEPAD_REG(hkey, value_lfEscapement,     Globals.lfFont.lfEscapement);
135         SET_NOTEPAD_REG(hkey, value_lfItalic,         Globals.lfFont.lfItalic);
136         SET_NOTEPAD_REG(hkey, value_lfOrientation,    Globals.lfFont.lfOrientation);
137         SET_NOTEPAD_REG(hkey, value_lfOutPrecision,   Globals.lfFont.lfOutPrecision);
138         SET_NOTEPAD_REG(hkey, value_lfPitchAndFamily, Globals.lfFont.lfPitchAndFamily);
139         SET_NOTEPAD_REG(hkey, value_lfQuality,        Globals.lfFont.lfQuality);
140         SET_NOTEPAD_REG(hkey, value_lfStrikeOut,      Globals.lfFont.lfStrikeOut);
141         SET_NOTEPAD_REG(hkey, value_lfUnderline,      Globals.lfFont.lfUnderline);
142         SET_NOTEPAD_REG(hkey, value_lfWeight,         Globals.lfFont.lfWeight);
143         SET_NOTEPAD_REG(hkey, value_iMarginTop,       Globals.iMarginTop);
144         SET_NOTEPAD_REG(hkey, value_iMarginBottom,    Globals.iMarginBottom);
145         SET_NOTEPAD_REG(hkey, value_iMarginLeft,      Globals.iMarginLeft);
146         SET_NOTEPAD_REG(hkey, value_iMarginRight,     Globals.iMarginRight);
147 #undef SET_NOTEPAD_REG
148
149         /* Store the current value as 10 * twips */
150         data = MulDiv(abs(Globals.lfFont.lfHeight), 720 , get_dpi());
151         RegSetValueExW(hkey, value_iPointSize, 0, REG_DWORD, (LPBYTE)&data, sizeof(DWORD));
152
153         RegSetValueExW(hkey, value_lfFaceName, 0, REG_SZ, (LPBYTE)&Globals.lfFont.lfFaceName,
154                       lstrlenW(Globals.lfFont.lfFaceName) * sizeof(Globals.lfFont.lfFaceName[0]));
155
156         RegSetValueExW(hkey, value_szHeader, 0, REG_SZ, (LPBYTE)&Globals.szHeader,
157                       lstrlenW(Globals.szHeader) * sizeof(Globals.szHeader[0]));
158
159         RegSetValueExW(hkey, value_szFooter, 0, REG_SZ, (LPBYTE)&Globals.szFooter,
160                       lstrlenW(Globals.szFooter) * sizeof(Globals.szFooter[0]));
161
162         RegCloseKey(hkey);
163     }
164 }
165
166 /***********************************************************************
167  *
168  *           NOTEPAD_LoadSettingFromRegistry
169  *
170  *  Load setting from registry HKCU\Software\Microsoft\Notepad.
171  */
172 static VOID NOTEPAD_LoadSettingFromRegistry(void)
173 {
174     static const WCHAR systemW[] = { 'S','y','s','t','e','m','\0' };
175     HKEY hkey;
176     INT base_length, dx, dy;
177
178     base_length = (GetSystemMetrics(SM_CXSCREEN) > GetSystemMetrics(SM_CYSCREEN))?
179         GetSystemMetrics(SM_CYSCREEN) : GetSystemMetrics(SM_CXSCREEN);
180
181     dx = base_length * .95;
182     dy = dx * 3 / 4;
183     SetRect( &main_rect, 0, 0, dx, dy );
184
185     Globals.bWrapLongLines  = TRUE;
186     Globals.iMarginTop = 2500;
187     Globals.iMarginBottom = 2500;
188     Globals.iMarginLeft = 2000;
189     Globals.iMarginRight = 2000;
190     
191     Globals.lfFont.lfHeight         = -12;
192     Globals.lfFont.lfWidth          = 0;
193     Globals.lfFont.lfEscapement     = 0;
194     Globals.lfFont.lfOrientation    = 0;
195     Globals.lfFont.lfWeight         = FW_REGULAR;
196     Globals.lfFont.lfItalic         = FALSE;
197     Globals.lfFont.lfUnderline      = FALSE;
198     Globals.lfFont.lfStrikeOut      = FALSE;
199     Globals.lfFont.lfCharSet        = DEFAULT_CHARSET;
200     Globals.lfFont.lfOutPrecision   = OUT_DEFAULT_PRECIS;
201     Globals.lfFont.lfClipPrecision  = CLIP_DEFAULT_PRECIS;
202     Globals.lfFont.lfQuality        = DEFAULT_QUALITY;
203     Globals.lfFont.lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE;
204     lstrcpyW(Globals.lfFont.lfFaceName, systemW);
205
206     LoadStringW(Globals.hInstance, STRING_PAGESETUP_HEADERVALUE,
207                 Globals.szHeader, ARRAY_SIZE(Globals.szHeader));
208     LoadStringW(Globals.hInstance, STRING_PAGESETUP_FOOTERVALUE,
209                 Globals.szFooter, ARRAY_SIZE(Globals.szFooter));
210
211     if(RegOpenKeyW(HKEY_CURRENT_USER, notepad_reg_key, &hkey) == ERROR_SUCCESS)
212     {
213         WORD  data_helper[MAX_PATH];
214         DWORD type, data, size;
215
216 #define QUERY_NOTEPAD_REG(hkey, value_name, ret) do { DWORD type, data; DWORD size = sizeof(DWORD); if(RegQueryValueExW(hkey, value_name, 0, &type, (LPBYTE)&data, &size) == ERROR_SUCCESS) if(type == REG_DWORD) ret = data; } while(0)
217         QUERY_NOTEPAD_REG(hkey, value_fWrap,            Globals.bWrapLongLines);
218         QUERY_NOTEPAD_REG(hkey, value_iWindowPosX,      main_rect.left);
219         QUERY_NOTEPAD_REG(hkey, value_iWindowPosY,      main_rect.top);
220         QUERY_NOTEPAD_REG(hkey, value_iWindowPosDX,     dx);
221         QUERY_NOTEPAD_REG(hkey, value_iWindowPosDY,     dy);
222         QUERY_NOTEPAD_REG(hkey, value_lfCharSet,        Globals.lfFont.lfCharSet);
223         QUERY_NOTEPAD_REG(hkey, value_lfClipPrecision,  Globals.lfFont.lfClipPrecision);
224         QUERY_NOTEPAD_REG(hkey, value_lfEscapement,     Globals.lfFont.lfEscapement);
225         QUERY_NOTEPAD_REG(hkey, value_lfItalic,         Globals.lfFont.lfItalic);
226         QUERY_NOTEPAD_REG(hkey, value_lfOrientation,    Globals.lfFont.lfOrientation);
227         QUERY_NOTEPAD_REG(hkey, value_lfOutPrecision,   Globals.lfFont.lfOutPrecision);
228         QUERY_NOTEPAD_REG(hkey, value_lfPitchAndFamily, Globals.lfFont.lfPitchAndFamily);
229         QUERY_NOTEPAD_REG(hkey, value_lfQuality,        Globals.lfFont.lfQuality);
230         QUERY_NOTEPAD_REG(hkey, value_lfStrikeOut,      Globals.lfFont.lfStrikeOut);
231         QUERY_NOTEPAD_REG(hkey, value_lfUnderline,      Globals.lfFont.lfUnderline);
232         QUERY_NOTEPAD_REG(hkey, value_lfWeight,         Globals.lfFont.lfWeight);
233         QUERY_NOTEPAD_REG(hkey, value_iMarginTop,       Globals.iMarginTop);
234         QUERY_NOTEPAD_REG(hkey, value_iMarginBottom,    Globals.iMarginBottom);
235         QUERY_NOTEPAD_REG(hkey, value_iMarginLeft,      Globals.iMarginLeft);
236         QUERY_NOTEPAD_REG(hkey, value_iMarginRight,     Globals.iMarginRight);
237 #undef QUERY_NOTEPAD_REG
238
239         main_rect.right = main_rect.left + dx;
240         main_rect.bottom = main_rect.top + dy;
241
242         size = sizeof(DWORD);
243         if(RegQueryValueExW(hkey, value_iPointSize, 0, &type, (LPBYTE)&data, &size) == ERROR_SUCCESS)
244             if(type == REG_DWORD)
245                 /* The value is stored as 10 * twips */
246                 Globals.lfFont.lfHeight = -MulDiv(abs(data), get_dpi(), 720);
247
248         size = sizeof(Globals.lfFont.lfFaceName);
249         if(RegQueryValueExW(hkey, value_lfFaceName, 0, &type, (LPBYTE)&data_helper, &size) == ERROR_SUCCESS)
250             if(type == REG_SZ)
251                 lstrcpyW(Globals.lfFont.lfFaceName, data_helper);
252
253         size = sizeof(Globals.szHeader);
254         if(RegQueryValueExW(hkey, value_szHeader, 0, &type, (LPBYTE)&data_helper, &size) == ERROR_SUCCESS)
255             if(type == REG_SZ)
256                 lstrcpyW(Globals.szHeader, data_helper);
257
258         size = sizeof(Globals.szFooter);
259         if(RegQueryValueExW(hkey, value_szFooter, 0, &type, (LPBYTE)&data_helper, &size) == ERROR_SUCCESS)
260             if(type == REG_SZ)
261                 lstrcpyW(Globals.szFooter, data_helper);
262         RegCloseKey(hkey);
263     }
264 }
265
266 /***********************************************************************
267  *
268  *           NOTEPAD_MenuCommand
269  *
270  *  All handling of main menu events
271  */
272 static int NOTEPAD_MenuCommand(WPARAM wParam)
273 {
274     switch (wParam)
275     {
276     case CMD_NEW:               DIALOG_FileNew(); break;
277     case CMD_OPEN:              DIALOG_FileOpen(); break;
278     case CMD_SAVE:              DIALOG_FileSave(); break;
279     case CMD_SAVE_AS:           DIALOG_FileSaveAs(); break;
280     case CMD_PRINT:             DIALOG_FilePrint(); break;
281     case CMD_PAGE_SETUP:        DIALOG_FilePageSetup(); break;
282     case CMD_PRINTER_SETUP:     DIALOG_FilePrinterSetup();break;
283     case CMD_EXIT:              DIALOG_FileExit(); break;
284
285     case CMD_UNDO:             DIALOG_EditUndo(); break;
286     case CMD_CUT:              DIALOG_EditCut(); break;
287     case CMD_COPY:             DIALOG_EditCopy(); break;
288     case CMD_PASTE:            DIALOG_EditPaste(); break;
289     case CMD_DELETE:           DIALOG_EditDelete(); break;
290     case CMD_SELECT_ALL:       DIALOG_EditSelectAll(); break;
291     case CMD_TIME_DATE:        DIALOG_EditTimeDate();break;
292
293     case CMD_SEARCH:           DIALOG_Search(); break;
294     case CMD_SEARCH_NEXT:      DIALOG_SearchNext(); break;
295     case CMD_REPLACE:          DIALOG_Replace(); break;
296                                
297     case CMD_WRAP:             DIALOG_EditWrap(); break;
298     case CMD_FONT:             DIALOG_SelectFont(); break;
299
300     case CMD_HELP_CONTENTS:    DIALOG_HelpContents(); break;
301     case CMD_HELP_SEARCH:      DIALOG_HelpSearch(); break;
302     case CMD_HELP_ON_HELP:     DIALOG_HelpHelp(); break;
303     case CMD_HELP_ABOUT_NOTEPAD: DIALOG_HelpAboutNotepad(); break;
304
305     default:
306         break;
307     }
308    return 0;
309 }
310
311 /***********************************************************************
312  * Data Initialization
313  */
314 static VOID NOTEPAD_InitData(VOID)
315 {
316     LPWSTR p = Globals.szFilter;
317     static const WCHAR txt_files[] = { '*','.','t','x','t',0 };
318     static const WCHAR all_files[] = { '*','.','*',0 };
319
320     LoadStringW(Globals.hInstance, STRING_TEXT_FILES_TXT, p, MAX_STRING_LEN);
321     p += lstrlenW(p) + 1;
322     lstrcpyW(p, txt_files);
323     p += lstrlenW(p) + 1;
324     LoadStringW(Globals.hInstance, STRING_ALL_FILES, p, MAX_STRING_LEN);
325     p += lstrlenW(p) + 1;
326     lstrcpyW(p, all_files);
327     p += lstrlenW(p) + 1;
328     *p = '\0';
329     Globals.hDevMode = NULL;
330     Globals.hDevNames = NULL;
331
332     CheckMenuItem(GetMenu(Globals.hMainWnd), CMD_WRAP,
333             MF_BYCOMMAND | (Globals.bWrapLongLines ? MF_CHECKED : MF_UNCHECKED));
334 }
335
336 /***********************************************************************
337  * Enable/disable items on the menu based on control state
338  */
339 static VOID NOTEPAD_InitMenuPopup(HMENU menu, int index)
340 {
341     int enable;
342
343     EnableMenuItem(menu, CMD_UNDO,
344         SendMessageW(Globals.hEdit, EM_CANUNDO, 0, 0) ? MF_ENABLED : MF_GRAYED);
345     EnableMenuItem(menu, CMD_PASTE,
346         IsClipboardFormatAvailable(CF_TEXT) ? MF_ENABLED : MF_GRAYED);
347     enable = SendMessageW(Globals.hEdit, EM_GETSEL, 0, 0);
348     enable = (HIWORD(enable) == LOWORD(enable)) ? MF_GRAYED : MF_ENABLED;
349     EnableMenuItem(menu, CMD_CUT, enable);
350     EnableMenuItem(menu, CMD_COPY, enable);
351     EnableMenuItem(menu, CMD_DELETE, enable);
352     
353     EnableMenuItem(menu, CMD_SELECT_ALL,
354         GetWindowTextLengthW(Globals.hEdit) ? MF_ENABLED : MF_GRAYED);
355 }
356
357 static LPWSTR NOTEPAD_StrRStr(LPWSTR pszSource, LPWSTR pszLast, LPWSTR pszSrch)
358 {
359     int len = lstrlenW(pszSrch);
360     pszLast--;
361     while (pszLast >= pszSource)
362     {
363         if (StrCmpNW(pszLast, pszSrch, len) == 0)
364             return pszLast;
365         pszLast--;
366     }
367     return NULL;
368 }
369
370 /***********************************************************************
371  * The user activated the Find dialog
372  */
373 void NOTEPAD_DoFind(FINDREPLACEW *fr)
374 {
375     LPWSTR content;
376     LPWSTR found;
377     int len = lstrlenW(fr->lpstrFindWhat);
378     int fileLen;
379     DWORD pos;
380
381     fileLen = GetWindowTextLengthW(Globals.hEdit) + 1;
382     content = HeapAlloc(GetProcessHeap(), 0, fileLen * sizeof(WCHAR));
383     if (!content) return;
384     GetWindowTextW(Globals.hEdit, content, fileLen);
385
386     SendMessageW(Globals.hEdit, EM_GETSEL, 0, (LPARAM)&pos);
387     switch (fr->Flags & (FR_DOWN|FR_MATCHCASE))
388     {
389         case 0:
390             found = StrRStrIW(content, content+pos-len, fr->lpstrFindWhat);
391             break;
392         case FR_DOWN:
393             found = StrStrIW(content+pos, fr->lpstrFindWhat);
394             break;
395         case FR_MATCHCASE:
396             found = NOTEPAD_StrRStr(content, content+pos-len, fr->lpstrFindWhat);
397             break;
398         case FR_DOWN|FR_MATCHCASE:
399             found = StrStrW(content+pos, fr->lpstrFindWhat);
400             break;
401         default:    /* shouldn't happen */
402             return;
403     }
404     HeapFree(GetProcessHeap(), 0, content);
405
406     if (found == NULL)
407     {
408         DIALOG_StringMsgBox(Globals.hFindReplaceDlg, STRING_NOTFOUND, fr->lpstrFindWhat,
409             MB_ICONINFORMATION|MB_OK);
410         return;
411     }
412
413     SendMessageW(Globals.hEdit, EM_SETSEL, found - content, found - content + len);
414 }
415
416 static void NOTEPAD_DoReplace(FINDREPLACEW *fr)
417 {
418     LPWSTR content;
419     int len = lstrlenW(fr->lpstrFindWhat);
420     int fileLen;
421     DWORD pos;
422     DWORD pos_start;
423
424     fileLen = GetWindowTextLengthW(Globals.hEdit) + 1;
425     content = HeapAlloc(GetProcessHeap(), 0, fileLen * sizeof(WCHAR));
426     if (!content) return;
427     GetWindowTextW(Globals.hEdit, content, fileLen);
428
429     SendMessageW(Globals.hEdit, EM_GETSEL, (WPARAM)&pos_start, (LPARAM)&pos);
430     switch (fr->Flags & (FR_DOWN|FR_MATCHCASE))
431     {
432         case FR_DOWN:
433             if ( pos-pos_start == len && StrCmpNIW(fr->lpstrFindWhat, content+pos_start, len) == 0)
434                 SendMessageW(Globals.hEdit, EM_REPLACESEL, TRUE, (LPARAM)fr->lpstrReplaceWith);
435             break;
436         case FR_DOWN|FR_MATCHCASE:
437             if ( pos-pos_start == len && StrCmpNW(fr->lpstrFindWhat, content+pos_start, len) == 0)
438                 SendMessageW(Globals.hEdit, EM_REPLACESEL, TRUE, (LPARAM)fr->lpstrReplaceWith);
439             break;
440         default:    /* shouldn't happen */
441             return;
442     }
443     HeapFree(GetProcessHeap(), 0, content);
444
445     NOTEPAD_DoFind(fr);
446 }
447
448 static void NOTEPAD_DoReplaceAll(FINDREPLACEW *fr)
449 {
450     LPWSTR content;
451     LPWSTR found;
452     int len = lstrlenW(fr->lpstrFindWhat);
453     int fileLen;
454     DWORD pos;
455
456     SendMessageW(Globals.hEdit, EM_SETSEL, 0, 0);
457     while(TRUE){
458         fileLen = GetWindowTextLengthW(Globals.hEdit) + 1;
459         content = HeapAlloc(GetProcessHeap(), 0, fileLen * sizeof(WCHAR));
460         if (!content) return;
461         GetWindowTextW(Globals.hEdit, content, fileLen);
462
463         SendMessageW(Globals.hEdit, EM_GETSEL, 0, (LPARAM)&pos);
464         switch (fr->Flags & (FR_DOWN|FR_MATCHCASE))
465         {
466             case FR_DOWN:
467                 found = StrStrIW(content+pos, fr->lpstrFindWhat);
468                 break;
469             case FR_DOWN|FR_MATCHCASE:
470                 found = StrStrW(content+pos, fr->lpstrFindWhat);
471                 break;
472             default:    /* shouldn't happen */
473                 return;
474         }
475         HeapFree(GetProcessHeap(), 0, content);
476
477         if(found == NULL)
478         {
479             SendMessageW(Globals.hEdit, EM_SETSEL, 0, 0);
480             return;
481         }
482         SendMessageW(Globals.hEdit, EM_SETSEL, found - content, found - content + len);
483         SendMessageW(Globals.hEdit, EM_REPLACESEL, TRUE, (LPARAM)fr->lpstrReplaceWith);
484     }
485 }
486
487 /***********************************************************************
488  *
489  *           NOTEPAD_WndProc
490  */
491 static LRESULT WINAPI NOTEPAD_WndProc(HWND hWnd, UINT msg, WPARAM wParam,
492                                LPARAM lParam)
493 {
494     if (msg == aFINDMSGSTRING)      /* not a constant so can't be used in switch */
495     {
496         FINDREPLACEW *fr = (FINDREPLACEW *)lParam;
497
498         if (fr->Flags & FR_DIALOGTERM)
499             Globals.hFindReplaceDlg = NULL;
500         if (fr->Flags & FR_FINDNEXT)
501         {
502             Globals.lastFind = *fr;
503             NOTEPAD_DoFind(fr);
504         }
505         if (fr->Flags & FR_REPLACE)
506         {
507             Globals.lastFind = *fr;
508             NOTEPAD_DoReplace(fr);
509         }
510         if (fr->Flags & FR_REPLACEALL)
511         {
512             Globals.lastFind = *fr;
513             NOTEPAD_DoReplaceAll(fr);
514         }
515         return 0;
516     }
517     
518     switch (msg) {
519
520     case WM_CREATE:
521     {
522         static const WCHAR editW[] = { 'e','d','i','t',0 };
523         DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_BORDER | WS_VSCROLL |
524                         ES_AUTOVSCROLL | ES_MULTILINE | ES_NOHIDESEL;
525         RECT rc;
526         GetClientRect(hWnd, &rc);
527
528         if (!Globals.bWrapLongLines) dwStyle |= WS_HSCROLL | ES_AUTOHSCROLL;
529
530         Globals.hEdit = CreateWindowExW(WS_EX_CLIENTEDGE, editW, NULL,
531                              dwStyle, 0, 0, rc.right, rc.bottom, hWnd,
532                              NULL, Globals.hInstance, NULL);
533
534         Globals.hFont = CreateFontIndirectW(&Globals.lfFont);
535         SendMessageW(Globals.hEdit, WM_SETFONT, (WPARAM)Globals.hFont, FALSE);
536         break;
537     }
538
539     case WM_COMMAND:
540         NOTEPAD_MenuCommand(LOWORD(wParam));
541         break;
542
543     case WM_DESTROYCLIPBOARD:
544         /*MessageBoxW(Globals.hMainWnd, "Empty clipboard", "Debug", MB_ICONEXCLAMATION);*/
545         break;
546
547     case WM_CLOSE:
548         if (DoCloseFile()) {
549             DestroyWindow(hWnd);
550         }
551         break;
552
553     case WM_QUERYENDSESSION:
554         if (DoCloseFile()) {
555             return 1;
556         }
557         break;
558
559     case WM_DESTROY:
560         NOTEPAD_SaveSettingToRegistry();
561
562         PostQuitMessage(0);
563         break;
564
565     case WM_SIZE:
566         SetWindowPos(Globals.hEdit, NULL, 0, 0, LOWORD(lParam), HIWORD(lParam),
567                      SWP_NOOWNERZORDER | SWP_NOZORDER);
568         break;
569
570     case WM_SETFOCUS:
571         SetFocus(Globals.hEdit);
572         break;
573
574     case WM_DROPFILES:
575     {
576         WCHAR szFileName[MAX_PATH];
577         HANDLE hDrop = (HANDLE) wParam;
578
579         DragQueryFileW(hDrop, 0, szFileName, ARRAY_SIZE(szFileName));
580         DragFinish(hDrop);
581         DoOpenFile(szFileName);
582         break;
583     }
584     
585     case WM_INITMENUPOPUP:
586         NOTEPAD_InitMenuPopup((HMENU)wParam, lParam);
587         break;
588
589     default:
590         return DefWindowProcW(hWnd, msg, wParam, lParam);
591     }
592     return 0;
593 }
594
595 static int AlertFileDoesNotExist(LPCWSTR szFileName)
596 {
597    int nResult;
598    WCHAR szMessage[MAX_STRING_LEN];
599    WCHAR szResource[MAX_STRING_LEN];
600
601    LoadStringW(Globals.hInstance, STRING_DOESNOTEXIST, szResource, ARRAY_SIZE(szResource));
602    wsprintfW(szMessage, szResource, szFileName);
603
604    LoadStringW(Globals.hInstance, STRING_ERROR, szResource, ARRAY_SIZE(szResource));
605
606    nResult = MessageBoxW(Globals.hMainWnd, szMessage, szResource,
607                          MB_ICONEXCLAMATION | MB_YESNO);
608
609    return(nResult);
610 }
611
612 static void HandleCommandLine(LPWSTR cmdline)
613 {
614     WCHAR delimiter;
615     int opt_print=0;
616     
617     /* skip white space */
618     while (*cmdline == ' ') cmdline++;
619
620     /* skip executable name */
621     delimiter = (*cmdline == '"' ? '"' : ' ');
622
623     if (*cmdline == delimiter) cmdline++;
624
625     while (*cmdline && *cmdline != delimiter) cmdline++;
626
627     if (*cmdline == delimiter) cmdline++;
628
629     while (*cmdline == ' ' || *cmdline == '-' || *cmdline == '/')
630     {
631         WCHAR option;
632
633         if (*cmdline++ == ' ') continue;
634
635         option = *cmdline;
636         if (option) cmdline++;
637         while (*cmdline == ' ') cmdline++;
638
639         switch(option)
640         {
641             case 'p':
642             case 'P':
643                 opt_print=1;
644                 break;
645         }
646     }
647
648     if (*cmdline)
649     {
650         /* file name is passed in the command line */
651         LPCWSTR file_name;
652         BOOL file_exists;
653         WCHAR buf[MAX_PATH];
654
655         if (cmdline[0] == '"')
656         {
657             WCHAR* wc;
658             cmdline++;
659             wc=cmdline;
660             /* Note: Double-quotes are not allowed in Windows filenames */
661             while (*wc && *wc != '"') wc++;
662             /* On Windows notepad ignores further arguments too */
663             *wc = 0;
664         }
665
666         if (FileExists(cmdline))
667         {
668             file_exists = TRUE;
669             file_name = cmdline;
670         }
671         else
672         {
673             static const WCHAR txtW[] = { '.','t','x','t',0 };
674
675             /* try to find file with ".txt" extension */
676             if (strchrW(PathFindFileNameW(cmdline), '.'))
677             {
678                 file_exists = FALSE;
679                 file_name = cmdline;
680             }
681             else
682             {
683                 lstrcpynW(buf, cmdline, MAX_PATH - lstrlenW(txtW) - 1);
684                 lstrcatW(buf, txtW);
685                 file_name = buf;
686                 file_exists = FileExists(buf);
687             }
688         }
689
690         if (file_exists)
691         {
692             DoOpenFile(file_name);
693             InvalidateRect(Globals.hMainWnd, NULL, FALSE);
694             if (opt_print)
695                 DIALOG_FilePrint();
696         }
697         else
698         {
699             switch (AlertFileDoesNotExist(file_name)) {
700             case IDYES:
701                 DoOpenFile(file_name);
702                 break;
703
704             case IDNO:
705                 break;
706             }
707         }
708      }
709 }
710
711 /***********************************************************************
712  *
713  *           WinMain
714  */
715 int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show)
716 {
717     MSG msg;
718     HACCEL hAccel;
719     WNDCLASSEXW class;
720     HMONITOR monitor;
721     MONITORINFO info;
722     INT x, y;
723     static const WCHAR className[] = {'N','o','t','e','p','a','d',0};
724     static const WCHAR winName[]   = {'N','o','t','e','p','a','d',0};
725
726     aFINDMSGSTRING = RegisterWindowMessageW(FINDMSGSTRINGW);
727
728     ZeroMemory(&Globals, sizeof(Globals));
729     Globals.hInstance       = hInstance;
730     NOTEPAD_LoadSettingFromRegistry();
731
732     ZeroMemory(&class, sizeof(class));
733     class.cbSize        = sizeof(class);
734     class.lpfnWndProc   = NOTEPAD_WndProc;
735     class.hInstance     = Globals.hInstance;
736     class.hIcon         = LoadIconW(Globals.hInstance, MAKEINTRESOURCEW(IDI_NOTEPAD));
737     class.hCursor       = LoadCursorW(0, (LPCWSTR)IDC_ARROW);
738     class.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
739     class.lpszMenuName  = MAKEINTRESOURCEW(MAIN_MENU);
740     class.lpszClassName = className;
741
742     if (!RegisterClassExW(&class)) return FALSE;
743
744     /* Setup windows */
745
746     monitor = MonitorFromRect( &main_rect, MONITOR_DEFAULTTOPRIMARY );
747     info.cbSize = sizeof(info);
748     GetMonitorInfoW( monitor, &info );
749
750     x = main_rect.left;
751     y = main_rect.top;
752     if (main_rect.left >= info.rcWork.right ||
753         main_rect.top >= info.rcWork.bottom ||
754         main_rect.right < info.rcWork.left ||
755         main_rect.bottom < info.rcWork.top)
756         x = y = CW_USEDEFAULT;
757
758     Globals.hMainWnd =
759         CreateWindowW(className, winName, WS_OVERLAPPEDWINDOW, x, y,
760                       main_rect.right - main_rect.left, main_rect.bottom - main_rect.top,
761                       NULL, NULL, Globals.hInstance, NULL);
762     if (!Globals.hMainWnd)
763     {
764         ShowLastError();
765         ExitProcess(1);
766     }
767
768     NOTEPAD_InitData();
769     DIALOG_FileNew();
770
771     ShowWindow(Globals.hMainWnd, show);
772     UpdateWindow(Globals.hMainWnd);
773     DragAcceptFiles(Globals.hMainWnd, TRUE);
774
775     HandleCommandLine(GetCommandLineW());
776
777     hAccel = LoadAcceleratorsW(hInstance, MAKEINTRESOURCEW(ID_ACCEL));
778
779     while (GetMessageW(&msg, 0, 0, 0))
780     {
781         if (!TranslateAcceleratorW(Globals.hMainWnd, hAccel, &msg) && !IsDialogMessageW(Globals.hFindReplaceDlg, &msg))
782         {
783             TranslateMessage(&msg);
784             DispatchMessageW(&msg);
785         }
786     }
787     return msg.wParam;
788 }