xref: /haiku/src/apps/stylededit/StyledEditWindow.cpp (revision 5b5da451b3b1e4432b2c52c26a2f592dceba136f)
1 /*
2  * Copyright 2002-2020, Haiku, Inc. All Rights Reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Mattias Sundblad
7  *		Andrew Bachmann
8  *		Philippe Saint-Pierre
9  *		Jonas Sundström
10  *		Ryan Leavengood
11  *		Vlad Slepukhin
12  *		Sarzhuk Zharski
13  *		Pascal R. G. Abresch
14  */
15 
16 
17 #include "ColorMenuItem.h"
18 #include "Constants.h"
19 #include "FindWindow.h"
20 #include "ReplaceWindow.h"
21 #include "StatusView.h"
22 #include "StyledEditApp.h"
23 #include "StyledEditView.h"
24 #include "StyledEditWindow.h"
25 
26 #include <Alert.h>
27 #include <Autolock.h>
28 #include <Catalog.h>
29 #include <CharacterSet.h>
30 #include <CharacterSetRoster.h>
31 #include <Clipboard.h>
32 #include <Debug.h>
33 #include <File.h>
34 #include <FilePanel.h>
35 #include <fs_attr.h>
36 #include <LayoutBuilder.h>
37 #include <Locale.h>
38 #include <Menu.h>
39 #include <MenuBar.h>
40 #include <MenuItem.h>
41 #include <NodeMonitor.h>
42 #include <Path.h>
43 #include <PrintJob.h>
44 #include <RecentItems.h>
45 #include <Rect.h>
46 #include <Roster.h>
47 #include <Screen.h>
48 #include <ScrollView.h>
49 #include <TextControl.h>
50 #include <TextView.h>
51 #include <TranslationUtils.h>
52 #include <UnicodeChar.h>
53 #include <UTF8.h>
54 #include <Volume.h>
55 
56 
57 using namespace BPrivate;
58 
59 
60 const float kLineViewWidth = 30.0;
61 const char* kInfoAttributeName = "StyledEdit-info";
62 
63 
64 #undef B_TRANSLATION_CONTEXT
65 #define B_TRANSLATION_CONTEXT "StyledEditWindow"
66 
67 
68 // This is a temporary solution for building BString with printf like format.
69 // will be removed in the future.
70 static void
71 bs_printf(BString* string, const char* format, ...)
72 {
73 	va_list ap;
74 	va_start(ap, format);
75 	char* buf;
76 	vasprintf(&buf, format, ap);
77 	string->SetTo(buf);
78 	free(buf);
79 	va_end(ap);
80 }
81 
82 
83 // #pragma mark -
84 
85 
86 StyledEditWindow::StyledEditWindow(BRect frame, int32 id, uint32 encoding)
87 	:
88 	BWindow(frame, "untitled", B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS
89 		| B_AUTO_UPDATE_SIZE_LIMITS),
90 	fFindWindow(NULL),
91 	fReplaceWindow(NULL)
92 {
93 	_InitWindow(encoding);
94 	BString unTitled(B_TRANSLATE("Untitled "));
95 	unTitled << id;
96 	SetTitle(unTitled.String());
97 	fSaveItem->SetEnabled(true);
98 		// allow saving empty files
99 	Show();
100 }
101 
102 
103 StyledEditWindow::StyledEditWindow(BRect frame, entry_ref* ref, uint32 encoding)
104 	:
105 	BWindow(frame, "untitled", B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS
106 		| B_AUTO_UPDATE_SIZE_LIMITS),
107 	fFindWindow(NULL),
108 	fReplaceWindow(NULL)
109 {
110 	_InitWindow(encoding);
111 	OpenFile(ref);
112 	Show();
113 }
114 
115 
116 StyledEditWindow::~StyledEditWindow()
117 {
118 	delete fSaveMessage;
119 	delete fPrintSettings;
120 	delete fSavePanel;
121 }
122 
123 
124 void
125 StyledEditWindow::Quit()
126 {
127 	_SwitchNodeMonitor(false);
128 
129 	_SaveAttrs();
130 	if (StyledEditApp* app = dynamic_cast<StyledEditApp*>(be_app))
131 		app->CloseDocument();
132 	BWindow::Quit();
133 }
134 
135 
136 #undef B_TRANSLATION_CONTEXT
137 #define B_TRANSLATION_CONTEXT "QuitAlert"
138 
139 
140 bool
141 StyledEditWindow::QuitRequested()
142 {
143 	if (fClean)
144 		return true;
145 
146 	if (fTextView->TextLength() == 0 && fSaveMessage == NULL)
147 		return true;
148 
149 	BString alertText;
150 	bs_printf(&alertText,
151 		B_TRANSLATE("Save changes to the document \"%s\"? "), Title());
152 
153 	int32 index = _ShowAlert(alertText, B_TRANSLATE("Cancel"),
154 		B_TRANSLATE("Don't save"), B_TRANSLATE("Save"),	B_WARNING_ALERT);
155 
156 	if (index == 0)
157 		return false;	// "cancel": dont save, dont close the window
158 
159 	if (index == 1)
160 		return true;	// "don't save": just close the window
161 
162 	if (!fSaveMessage) {
163 		SaveAs(new BMessage(SAVE_THEN_QUIT));
164 		return false;
165 	}
166 
167 	return Save() == B_OK;
168 }
169 
170 
171 void
172 StyledEditWindow::MessageReceived(BMessage* message)
173 {
174 	if (message->WasDropped()) {
175 		entry_ref ref;
176 		if (message->FindRef("refs", 0, &ref)==B_OK) {
177 			message->what = B_REFS_RECEIVED;
178 			be_app->PostMessage(message);
179 		}
180 	}
181 
182 	switch (message->what) {
183 		case MENU_NEW:
184 			 // this is because of the layout menu change,
185 			 // it is too early to connect to a different looper there
186 			 // so either have to redirect it here, or change the invocation
187 			be_app->PostMessage(message);
188 			break;
189 		// File menu
190 		case MENU_SAVE:
191 			if (!fSaveMessage)
192 				SaveAs();
193 			else
194 				Save(fSaveMessage);
195 			break;
196 
197 		case MENU_SAVEAS:
198 			SaveAs();
199 			break;
200 
201 		case B_SAVE_REQUESTED:
202 			Save(message);
203 			break;
204 
205 		case SAVE_THEN_QUIT:
206 			if (Save(message) == B_OK)
207 				Quit();
208 			break;
209 
210 		case MENU_RELOAD:
211 			_ReloadDocument(message);
212 			break;
213 
214 		case MENU_CLOSE:
215 			if (QuitRequested())
216 				Quit();
217 			break;
218 
219 		case MENU_PAGESETUP:
220 			PageSetup(fTextView->Window()->Title());
221 			break;
222 		case MENU_PRINT:
223 			Print(fTextView->Window()->Title());
224 			break;
225 		case MENU_QUIT:
226 			be_app->PostMessage(B_QUIT_REQUESTED);
227 			break;
228 
229 		// Edit menu
230 
231 		case B_UNDO:
232 			ASSERT(fCanUndo || fCanRedo);
233 			ASSERT(!(fCanUndo && fCanRedo));
234 			if (fCanUndo)
235 				fUndoFlag = true;
236 			if (fCanRedo)
237 				fRedoFlag = true;
238 
239 			fTextView->Undo(be_clipboard);
240 			break;
241 		case B_CUT:
242 		case B_COPY:
243 		case B_PASTE:
244 		case B_SELECT_ALL:
245 			fTextView->MessageReceived(message);
246 			break;
247 		case MENU_CLEAR:
248 			fTextView->Clear();
249 			break;
250 		case MENU_FIND:
251 		{
252 			if (fFindWindow == NULL) {
253 				BRect findWindowFrame(Frame());
254 				findWindowFrame.InsetBy(
255 					(findWindowFrame.Width() - 400) / 2,
256 					(findWindowFrame.Height() - 235) / 2);
257 
258 				fFindWindow = new FindWindow(findWindowFrame, this,
259 					&fStringToFind, fCaseSensitive, fWrapAround, fBackSearch);
260 				fFindWindow->Show();
261 
262 			} else if (fFindWindow->IsHidden())
263 				fFindWindow->Show();
264 			else
265 				fFindWindow->Activate();
266 			break;
267 		}
268 		case MSG_FIND_WINDOW_QUIT:
269 		{
270 			fFindWindow = NULL;
271 			Activate();
272 				// In case any 'always on top' application tries to make its
273 				// window active after fFindWindow is closed.
274 			break;
275 		}
276 		case MSG_REPLACE_WINDOW_QUIT:
277 		{
278 			fReplaceWindow = NULL;
279 			Activate();
280 			break;
281 		}
282 		case MSG_SEARCH:
283 			message->FindString("findtext", &fStringToFind);
284 			fFindAgainItem->SetEnabled(true);
285 			message->FindBool("casesens", &fCaseSensitive);
286 			message->FindBool("wrap", &fWrapAround);
287 			message->FindBool("backsearch", &fBackSearch);
288 
289 			_Search(fStringToFind, fCaseSensitive, fWrapAround, fBackSearch);
290 			Activate();
291 			break;
292 		case MENU_FIND_AGAIN:
293 			_Search(fStringToFind, fCaseSensitive, fWrapAround, fBackSearch);
294 			break;
295 		case MENU_FIND_SELECTION:
296 			_FindSelection();
297 			break;
298 		case MENU_REPLACE:
299 		{
300 			if (fReplaceWindow == NULL) {
301 				BRect replaceWindowFrame(Frame());
302 				replaceWindowFrame.InsetBy(
303 					(replaceWindowFrame.Width() - 400) / 2,
304 					(replaceWindowFrame.Height() - 284) / 2);
305 
306 				fReplaceWindow = new ReplaceWindow(replaceWindowFrame, this,
307 					&fStringToFind, &fReplaceString, fCaseSensitive,
308 					fWrapAround, fBackSearch);
309 				fReplaceWindow->Show();
310 
311 			} else if (fReplaceWindow->IsHidden())
312 				fReplaceWindow->Show();
313 			else
314 				fReplaceWindow->Activate();
315 			break;
316 		}
317 		case MSG_REPLACE:
318 		{
319 			message->FindBool("casesens", &fCaseSensitive);
320 			message->FindBool("wrap", &fWrapAround);
321 			message->FindBool("backsearch", &fBackSearch);
322 
323 			message->FindString("FindText", &fStringToFind);
324 			message->FindString("ReplaceText", &fReplaceString);
325 
326 			fFindAgainItem->SetEnabled(true);
327 			fReplaceSameItem->SetEnabled(true);
328 
329 			_Replace(fStringToFind, fReplaceString, fCaseSensitive, fWrapAround,
330 				fBackSearch);
331 			Activate();
332 			break;
333 		}
334 		case MENU_REPLACE_SAME:
335 			_Replace(fStringToFind, fReplaceString, fCaseSensitive, fWrapAround,
336 				fBackSearch);
337 			break;
338 
339 		case MSG_REPLACE_ALL:
340 		{
341 			message->FindBool("casesens", &fCaseSensitive);
342 			message->FindString("FindText", &fStringToFind);
343 			message->FindString("ReplaceText", &fReplaceString);
344 
345 			bool allWindows;
346 			message->FindBool("allwindows", &allWindows);
347 
348 			fFindAgainItem->SetEnabled(true);
349 			fReplaceSameItem->SetEnabled(true);
350 
351 			if (allWindows)
352 				SearchAllWindows(fStringToFind, fReplaceString, fCaseSensitive);
353 			else
354 				_ReplaceAll(fStringToFind, fReplaceString, fCaseSensitive);
355 			Activate();
356 			break;
357 		}
358 
359 		case B_NODE_MONITOR:
360 			_HandleNodeMonitorEvent(message);
361 			break;
362 
363 		// Font menu
364 
365 		case FONT_SIZE:
366 		{
367 			float fontSize;
368 			if (message->FindFloat("size", &fontSize) == B_OK)
369 				_SetFontSize(fontSize);
370 			break;
371 		}
372 		case FONT_FAMILY:
373 		{
374 			const char* fontFamily = NULL;
375 			const char* fontStyle = NULL;
376 			void* ptr;
377 			if (message->FindPointer("source", &ptr) == B_OK) {
378 				BMenuItem* item = static_cast<BMenuItem*>(ptr);
379 				fontFamily = item->Label();
380 			}
381 
382 			BFont font;
383 			font.SetFamilyAndStyle(fontFamily, fontStyle);
384 			fItalicItem->SetMarked((font.Face() & B_ITALIC_FACE) != 0);
385 			fBoldItem->SetMarked((font.Face() & B_BOLD_FACE) != 0);
386 			fUnderlineItem->SetMarked((font.Face() & B_UNDERSCORE_FACE) != 0);
387 
388 			_SetFontStyle(fontFamily, fontStyle);
389 			break;
390 		}
391 		case FONT_STYLE:
392 		{
393 			const char* fontFamily = NULL;
394 			const char* fontStyle = NULL;
395 			void* ptr;
396 			if (message->FindPointer("source", &ptr) == B_OK) {
397 				BMenuItem* item = static_cast<BMenuItem*>(ptr);
398 				fontStyle = item->Label();
399 				BMenu* menu = item->Menu();
400 				if (menu != NULL) {
401 					BMenuItem* super_item = menu->Superitem();
402 					if (super_item != NULL)
403 						fontFamily = super_item->Label();
404 				}
405 			}
406 
407 			BFont font;
408 			font.SetFamilyAndStyle(fontFamily, fontStyle);
409 			fItalicItem->SetMarked((font.Face() & B_ITALIC_FACE) != 0);
410 			fBoldItem->SetMarked((font.Face() & B_BOLD_FACE) != 0);
411 			fUnderlineItem->SetMarked((font.Face() & B_UNDERSCORE_FACE) != 0);
412 
413 			_SetFontStyle(fontFamily, fontStyle);
414 			break;
415 		}
416 		case kMsgSetFontUp:
417 		{
418 			uint32 sameProperties;
419 			BFont font;
420 
421 			fTextView->GetFontAndColor(&font, &sameProperties);
422 			//GetFont seems to return a constant size for font.Size(),
423 			//thus not used here (maybe that is a bug)
424 			int32 cur_size = (int32)font.Size();
425 
426 			for (unsigned int a = 0;
427 				a < sizeof(fontSizes)/sizeof(fontSizes[0]); a++) {
428 				if (fontSizes[a] > cur_size) {
429 					_SetFontSize(fontSizes[a]);
430 					break;
431 				}
432 			}
433 			break;
434 		}
435 		case kMsgSetFontDown:
436 		{
437 			uint32 sameProperties;
438 			BFont font;
439 
440 			fTextView->GetFontAndColor(&font, &sameProperties);
441 			int32 cur_size = (int32)font.Size();
442 
443 			for (unsigned int a = 1;
444 				a < sizeof(fontSizes)/sizeof(fontSizes[0]); a++) {
445 				if (fontSizes[a] >= cur_size) {
446 					_SetFontSize(fontSizes[a-1]);
447 					break;
448 				}
449 			}
450 			break;
451 		}
452 		case kMsgSetItalic:
453 		{
454 			uint32 sameProperties;
455 			BFont font;
456 			fTextView->GetFontAndColor(&font, &sameProperties);
457 
458 			if (fItalicItem->IsMarked())
459 				font.SetFace(B_REGULAR_FACE);
460 			fItalicItem->SetMarked(!fItalicItem->IsMarked());
461 
462 			font_family family;
463 			font_style style;
464 			font.GetFamilyAndStyle(&family, &style);
465 
466 			_SetFontStyle(family, style);
467 			break;
468 		}
469 		case kMsgSetBold:
470 		{
471 			uint32 sameProperties;
472 			BFont font;
473 			fTextView->GetFontAndColor(&font, &sameProperties);
474 
475 			if (fBoldItem->IsMarked())
476 				font.SetFace(B_REGULAR_FACE);
477 			fBoldItem->SetMarked(!fBoldItem->IsMarked());
478 
479 			font_family family;
480 			font_style style;
481 			font.GetFamilyAndStyle(&family, &style);
482 
483 			_SetFontStyle(family, style);
484 			break;
485 		}
486 		case kMsgSetUnderline:
487 		{
488 			uint32 sameProperties;
489 			BFont font;
490 			fTextView->GetFontAndColor(&font, &sameProperties);
491 
492 			if (fUnderlineItem->IsMarked())
493 				font.SetFace(B_REGULAR_FACE);
494 			fUnderlineItem->SetMarked(!fUnderlineItem->IsMarked());
495 
496 			font_family family;
497 			font_style style;
498 			font.GetFamilyAndStyle(&family, &style);
499 
500 			_SetFontStyle(family, style);
501 			break;
502 		}
503 		case FONT_COLOR:
504 		{
505 			ssize_t colorLength;
506 			rgb_color* color;
507 			if (message->FindData("color", B_RGB_COLOR_TYPE,
508 					(const void**)&color, &colorLength) == B_OK
509 				&& colorLength == sizeof(rgb_color)) {
510 				/*
511 				 * TODO: Ideally, when selecting the default color,
512 				 * you wouldn't naively apply it; it shouldn't lose its nature.
513 				 * When reloaded with a different default color, it should
514 				 * reflect that different choice.
515 				 */
516 				_SetFontColor(color);
517 			}
518 			break;
519 		}
520 
521 		// Document menu
522 
523 		case ALIGN_LEFT:
524 			fTextView->SetAlignment(B_ALIGN_LEFT);
525 			_UpdateCleanUndoRedoSaveRevert();
526 			break;
527 		case ALIGN_CENTER:
528 			fTextView->SetAlignment(B_ALIGN_CENTER);
529 			_UpdateCleanUndoRedoSaveRevert();
530 			break;
531 		case ALIGN_RIGHT:
532 			fTextView->SetAlignment(B_ALIGN_RIGHT);
533 			_UpdateCleanUndoRedoSaveRevert();
534 			break;
535 		case WRAP_LINES:
536 		{
537 			// update wrap setting
538 			if (fTextView->DoesWordWrap()) {
539 				fTextView->SetWordWrap(false);
540 				fWrapItem->SetMarked(false);
541 			} else {
542 				fTextView->SetWordWrap(true);
543 				fWrapItem->SetMarked(true);
544 			}
545 
546 			// update buttons
547 			_UpdateCleanUndoRedoSaveRevert();
548 			break;
549 		}
550 		case SHOW_STATISTICS:
551 			_ShowStatistics();
552 			break;
553 		case ENABLE_ITEMS:
554 			fCutItem->SetEnabled(true);
555 			fCopyItem->SetEnabled(true);
556 			break;
557 		case DISABLE_ITEMS:
558 			fCutItem->SetEnabled(false);
559 			fCopyItem->SetEnabled(false);
560 			break;
561 		case TEXT_CHANGED:
562 			if (fUndoFlag) {
563 				if (fUndoCleans) {
564 					// we cleaned!
565 					fClean = true;
566 					fUndoCleans = false;
567 				} else if (fClean) {
568 					// if we were clean
569 					// then a redo will make us clean again
570 					fRedoCleans = true;
571 					fClean = false;
572 				}
573 				// set mode
574 				fCanUndo = false;
575 				fCanRedo = true;
576 				fUndoItem->SetLabel(B_TRANSLATE("Redo typing"));
577 				fUndoItem->SetEnabled(true);
578 				fUndoFlag = false;
579 			} else {
580 				if (fRedoFlag && fRedoCleans) {
581 					// we cleaned!
582 					fClean = true;
583 					fRedoCleans = false;
584 				} else if (fClean) {
585 					// if we were clean
586 					// then an undo will make us clean again
587 					fUndoCleans = true;
588 					fClean = false;
589 				} else {
590 					// no more cleaning from undo now...
591 					fUndoCleans = false;
592 				}
593 				// set mode
594 				fCanUndo = true;
595 				fCanRedo = false;
596 				fUndoItem->SetLabel(B_TRANSLATE("Undo typing"));
597 				fUndoItem->SetEnabled(true);
598 				fRedoFlag = false;
599 			}
600 			if (fClean) {
601 				fSaveItem->SetEnabled(fSaveMessage == NULL);
602 			} else {
603 				fSaveItem->SetEnabled(true);
604 			}
605 			fReloadItem->SetEnabled(fSaveMessage != NULL);
606 			fEncodingItem->SetEnabled(fSaveMessage != NULL);
607 			break;
608 
609 		case SAVE_AS_ENCODING:
610 			void* ptr;
611 			if (message->FindPointer("source", &ptr) == B_OK
612 				&& fSavePanelEncodingMenu != NULL) {
613 				fTextView->SetEncoding(
614 					(uint32)fSavePanelEncodingMenu->IndexOf((BMenuItem*)ptr));
615 			}
616 			break;
617 
618 		case UPDATE_STATUS:
619 		{
620 			message->AddBool("modified", !fClean);
621 			bool readOnly = !fTextView->IsEditable();
622 			message->AddBool("readOnly", readOnly);
623 			if (readOnly) {
624 				BVolume volume(fNodeRef.device);
625 				message->AddBool("canUnlock", !volume.IsReadOnly());
626 			}
627 			fStatusView->SetStatus(message);
628 			break;
629 		}
630 
631 		case UPDATE_STATUS_REF:
632 		{
633 			entry_ref ref;
634 			const char* name;
635 
636 			if (fSaveMessage != NULL
637 				&& fSaveMessage->FindRef("directory", &ref) == B_OK
638 				&& fSaveMessage->FindString("name", &name) == B_OK) {
639 
640 				BDirectory dir(&ref);
641 				status_t status = dir.InitCheck();
642 				BEntry entry;
643 				if (status == B_OK)
644 					status = entry.SetTo(&dir, name);
645 				if (status == B_OK)
646 					status = entry.GetRef(&ref);
647 			}
648 			fStatusView->SetRef(ref);
649 			break;
650 		}
651 
652 		case UNLOCK_FILE:
653 		{
654 			status_t status = _UnlockFile();
655 			if (status != B_OK) {
656 				BString text;
657 				bs_printf(&text,
658 					B_TRANSLATE("Unable to unlock file\n\t%s"),
659 					strerror(status));
660 				_ShowAlert(text, B_TRANSLATE("OK"), "", "", B_STOP_ALERT);
661 			}
662 			PostMessage(UPDATE_STATUS);
663 			break;
664 		}
665 
666 		case UPDATE_LINE_SELECTION:
667 		{
668 			int32 line;
669 			if (message->FindInt32("be:line", &line) == B_OK) {
670 				fTextView->GoToLine(line);
671 				fTextView->ScrollToSelection();
672 			}
673 
674 			int32 start, length;
675 			if (message->FindInt32("be:selection_offset", &start) == B_OK) {
676 				if (message->FindInt32("be:selection_length", &length) != B_OK)
677 					length = 0;
678 
679 				fTextView->Select(start, start + length);
680 				fTextView->ScrollToOffset(start);
681 			}
682 			break;
683 		}
684 		default:
685 			BWindow::MessageReceived(message);
686 			break;
687 	}
688 }
689 
690 
691 void
692 StyledEditWindow::MenusBeginning()
693 {
694 	// update the font menu
695 	// unselect the old values
696 	if (fCurrentFontItem != NULL) {
697 		fCurrentFontItem->SetMarked(false);
698 		BMenu* menu = fCurrentFontItem->Submenu();
699 		if (menu != NULL) {
700 			BMenuItem* item = menu->FindMarked();
701 			if (item != NULL)
702 				item->SetMarked(false);
703 		}
704 	}
705 
706 	if (fCurrentStyleItem != NULL) {
707 		fCurrentStyleItem->SetMarked(false);
708 	}
709 
710 	BMenuItem* oldColorItem = fFontColorMenu->FindMarked();
711 	if (oldColorItem != NULL)
712 		oldColorItem->SetMarked(false);
713 
714 	BMenuItem* oldSizeItem = fFontSizeMenu->FindMarked();
715 	if (oldSizeItem != NULL)
716 		oldSizeItem->SetMarked(false);
717 
718 	// find the current font, color, size
719 	BFont font;
720 	uint32 sameProperties;
721 	rgb_color color = ui_color(B_DOCUMENT_TEXT_COLOR);
722 	bool sameColor;
723 	fTextView->GetFontAndColor(&font, &sameProperties, &color, &sameColor);
724 	color.alpha = 255;
725 
726 	if (sameColor) {
727 		if (fDefaultFontColorItem->Color() == color)
728 			fDefaultFontColorItem->SetMarked(true);
729 		else {
730 			for (int i = 0; i < fFontColorMenu->CountItems(); i++) {
731 				ColorMenuItem* item = dynamic_cast<ColorMenuItem*>
732 					(fFontColorMenu->ItemAt(i));
733 				if (item != NULL && item->Color() == color) {
734 					item->SetMarked(true);
735 					break;
736 				}
737 			}
738 		}
739 	}
740 
741 	if (sameProperties & B_FONT_SIZE) {
742 		if ((int)font.Size() == font.Size()) {
743 			// select the current font size
744 			char fontSizeStr[16];
745 			snprintf(fontSizeStr, 15, "%i", (int)font.Size());
746 			BMenuItem* item = fFontSizeMenu->FindItem(fontSizeStr);
747 			if (item != NULL)
748 				item->SetMarked(true);
749 		}
750 	}
751 
752 	font_family family;
753 	font_style style;
754 	font.GetFamilyAndStyle(&family, &style);
755 
756 	fCurrentFontItem = fFontMenu->FindItem(family);
757 
758 	if (fCurrentFontItem != NULL) {
759 		fCurrentFontItem->SetMarked(true);
760 		BMenu* menu = fCurrentFontItem->Submenu();
761 		if (menu != NULL) {
762 			BMenuItem* item = menu->FindItem(style);
763 			fCurrentStyleItem = item;
764 			if (fCurrentStyleItem != NULL)
765 				item->SetMarked(true);
766 		}
767 	}
768 
769 	fBoldItem->SetMarked((font.Face() & B_BOLD_FACE) != 0);
770 	fItalicItem->SetMarked((font.Face() & B_ITALIC_FACE) != 0);
771 	fUnderlineItem->SetMarked((font.Face() & B_UNDERSCORE_FACE) != 0);
772 
773 	switch (fTextView->Alignment()) {
774 		case B_ALIGN_LEFT:
775 		default:
776 			fAlignLeft->SetMarked(true);
777 			break;
778 		case B_ALIGN_CENTER:
779 			fAlignCenter->SetMarked(true);
780 			break;
781 		case B_ALIGN_RIGHT:
782 			fAlignRight->SetMarked(true);
783 			break;
784 	}
785 
786 	// text encoding
787 	const BCharacterSet* charset
788 		= BCharacterSetRoster::GetCharacterSetByFontID(fTextView->GetEncoding());
789 	BMenu* encodingMenu = fEncodingItem->Submenu();
790 	if (charset != NULL && encodingMenu != NULL) {
791 		const char* mime = charset->GetMIMEName();
792 		BString name(charset->GetPrintName());
793 		if (mime)
794 			name << " (" << mime << ")";
795 
796 		BMenuItem* item = encodingMenu->FindItem(name);
797 		if (item != NULL)
798 			item->SetMarked(true);
799 	}
800 }
801 
802 
803 #undef B_TRANSLATION_CONTEXT
804 #define B_TRANSLATION_CONTEXT "SaveAlert"
805 
806 
807 status_t
808 StyledEditWindow::Save(BMessage* message)
809 {
810 	_NodeMonitorSuspender nodeMonitorSuspender(this);
811 
812 	if (!message)
813 		message = fSaveMessage;
814 
815 	if (!message)
816 		return B_ERROR;
817 
818 	entry_ref dirRef;
819 	const char* name;
820 	if (message->FindRef("directory", &dirRef) != B_OK
821 		|| message->FindString("name", &name) != B_OK)
822 		return B_BAD_VALUE;
823 
824 	BDirectory dir(&dirRef);
825 	BEntry entry(&dir, name);
826 
827 	status_t status = B_ERROR;
828 	if (dir.InitCheck() == B_OK && entry.InitCheck() == B_OK) {
829 		struct stat st;
830 		BFile file(&entry, B_READ_WRITE | B_CREATE_FILE);
831 		if (file.InitCheck() == B_OK
832 			&& (status = file.GetStat(&st)) == B_OK) {
833 			// check the file permissions
834 			if (!((getuid() == st.st_uid && (S_IWUSR & st.st_mode))
835 				|| (getgid() == st.st_gid && (S_IWGRP & st.st_mode))
836 				|| (S_IWOTH & st.st_mode))) {
837 				BString alertText;
838 				bs_printf(&alertText, B_TRANSLATE("This file is marked "
839 					"read-only. Save changes to the document \"%s\"? "), name);
840 				switch (_ShowAlert(alertText, B_TRANSLATE("Cancel"),
841 						B_TRANSLATE("Don't save"),
842 						B_TRANSLATE("Save"), B_WARNING_ALERT)) {
843 					case 0:
844 						return B_CANCELED;
845 					case 1:
846 						return B_OK;
847 					default:
848 						break;
849 				}
850 			}
851 
852 			status = fTextView->WriteStyledEditFile(&file);
853 		}
854 	}
855 
856 	if (status != B_OK) {
857 		BString alertText;
858 		bs_printf(&alertText, B_TRANSLATE("Error saving \"%s\":\n%s"), name,
859 			strerror(status));
860 
861 		_ShowAlert(alertText, B_TRANSLATE("OK"), "", "", B_STOP_ALERT);
862 		return status;
863 	}
864 
865 	SetTitle(name);
866 
867 	if (fSaveMessage != message) {
868 		delete fSaveMessage;
869 		fSaveMessage = new BMessage(*message);
870 	}
871 
872 	// clear clean modes
873 	fSaveItem->SetEnabled(false);
874 	fUndoCleans = false;
875 	fRedoCleans = false;
876 	fClean = true;
877 	fNagOnNodeChange = true;
878 
879 	PostMessage(UPDATE_STATUS);
880 	PostMessage(UPDATE_STATUS_REF);
881 
882 	return status;
883 }
884 
885 
886 #undef B_TRANSLATION_CONTEXT
887 #define B_TRANSLATION_CONTEXT "Open_and_SaveAsPanel"
888 
889 
890 status_t
891 StyledEditWindow::SaveAs(BMessage* message)
892 {
893 	if (fSavePanel == NULL) {
894 		entry_ref* directory = NULL;
895 		entry_ref dirRef;
896 		if (fSaveMessage != NULL) {
897 			if (fSaveMessage->FindRef("directory", &dirRef) == B_OK)
898 				directory = &dirRef;
899 		}
900 
901 		BMessenger target(this);
902 		fSavePanel = new BFilePanel(B_SAVE_PANEL, &target,
903 			directory, B_FILE_NODE, false);
904 
905 		BMenuBar* menuBar = dynamic_cast<BMenuBar*>(
906 			fSavePanel->Window()->FindView("MenuBar"));
907 		if (menuBar != NULL) {
908 			fSavePanelEncodingMenu = new BMenu(B_TRANSLATE("Encoding"));
909 			fSavePanelEncodingMenu->SetRadioMode(true);
910 			menuBar->AddItem(fSavePanelEncodingMenu);
911 
912 			BCharacterSetRoster roster;
913 			BCharacterSet charset;
914 			while (roster.GetNextCharacterSet(&charset) == B_NO_ERROR) {
915 				BString name(charset.GetPrintName());
916 				const char* mime = charset.GetMIMEName();
917 				if (mime) {
918 					name.Append(" (");
919 					name.Append(mime);
920 					name.Append(")");
921 				}
922 				BMenuItem * item = new BMenuItem(name.String(),
923 					new BMessage(SAVE_AS_ENCODING));
924 				item->SetTarget(this);
925 				fSavePanelEncodingMenu->AddItem(item);
926 				if (charset.GetFontID() == fTextView->GetEncoding())
927 					item->SetMarked(true);
928 			}
929 		}
930 	}
931 
932 	fSavePanel->SetSaveText(Title());
933 	if (message != NULL)
934 		fSavePanel->SetMessage(message);
935 
936 	fSavePanel->Show();
937 	return B_OK;
938 }
939 
940 
941 void
942 StyledEditWindow::OpenFile(entry_ref* ref)
943 {
944 	if (_LoadFile(ref) != B_OK) {
945 		fSaveItem->SetEnabled(true);
946 			// allow saving new files
947 		return;
948 	}
949 
950 	fSaveMessage = new(std::nothrow) BMessage(B_SAVE_REQUESTED);
951 	if (fSaveMessage) {
952 		BEntry entry(ref, true);
953 		BEntry parent;
954 		entry_ref parentRef;
955 		char name[B_FILE_NAME_LENGTH];
956 
957 		entry.GetParent(&parent);
958 		entry.GetName(name);
959 		parent.GetRef(&parentRef);
960 		fSaveMessage->AddRef("directory", &parentRef);
961 		fSaveMessage->AddString("name", name);
962 		SetTitle(name);
963 
964 		_LoadAttrs();
965 	}
966 
967 	_SwitchNodeMonitor(true, ref);
968 
969 	PostMessage(UPDATE_STATUS_REF);
970 
971 	fReloadItem->SetEnabled(fSaveMessage != NULL);
972 	fEncodingItem->SetEnabled(fSaveMessage != NULL);
973 }
974 
975 
976 status_t
977 StyledEditWindow::PageSetup(const char* documentName)
978 {
979 	BPrintJob printJob(documentName);
980 
981 	if (fPrintSettings != NULL)
982 		printJob.SetSettings(new BMessage(*fPrintSettings));
983 
984 	status_t result = printJob.ConfigPage();
985 	if (result == B_OK) {
986 		delete fPrintSettings;
987 		fPrintSettings = printJob.Settings();
988 	}
989 
990 	return result;
991 }
992 
993 
994 void
995 StyledEditWindow::Print(const char* documentName)
996 {
997 	BPrintJob printJob(documentName);
998 	if (fPrintSettings)
999 		printJob.SetSettings(new BMessage(*fPrintSettings));
1000 
1001 	if (printJob.ConfigJob() != B_OK)
1002 		return;
1003 
1004 	delete fPrintSettings;
1005 	fPrintSettings = printJob.Settings();
1006 
1007 	// information from printJob
1008 	BRect printableRect = printJob.PrintableRect();
1009 	int32 firstPage = printJob.FirstPage();
1010 	int32 lastPage = printJob.LastPage();
1011 
1012 	// lines eventually to be used to compute pages to print
1013 	int32 firstLine = 0;
1014 	int32 lastLine = fTextView->CountLines();
1015 
1016 	// values to be computed
1017 	int32 pagesInDocument = 1;
1018 	int32 linesInDocument = fTextView->CountLines();
1019 
1020 	int32 currentLine = 0;
1021 	while (currentLine < linesInDocument) {
1022 		float currentHeight = 0;
1023 		while (currentHeight < printableRect.Height() && currentLine
1024 				< linesInDocument) {
1025 			currentHeight += fTextView->LineHeight(currentLine);
1026 			if (currentHeight < printableRect.Height())
1027 				currentLine++;
1028 		}
1029 		if (pagesInDocument == lastPage)
1030 			lastLine = currentLine - 1;
1031 
1032 		if (currentHeight >= printableRect.Height()) {
1033 			pagesInDocument++;
1034 			if (pagesInDocument == firstPage)
1035 				firstLine = currentLine;
1036 		}
1037 	}
1038 
1039 	if (lastPage > pagesInDocument - 1) {
1040 		lastPage = pagesInDocument - 1;
1041 		lastLine = currentLine - 1;
1042 	}
1043 
1044 
1045 	printJob.BeginJob();
1046 	if (fTextView->CountLines() > 0 && fTextView->TextLength() > 0) {
1047 		int32 printLine = firstLine;
1048 		while (printLine <= lastLine) {
1049 			float currentHeight = 0;
1050 			int32 firstLineOnPage = printLine;
1051 			while (currentHeight < printableRect.Height()
1052 				&& printLine <= lastLine)
1053 			{
1054 				currentHeight += fTextView->LineHeight(printLine);
1055 				if (currentHeight < printableRect.Height())
1056 					printLine++;
1057 			}
1058 
1059 			float top = 0;
1060 			if (firstLineOnPage != 0)
1061 				top = fTextView->TextHeight(0, firstLineOnPage - 1);
1062 
1063 			float bottom = fTextView->TextHeight(0, printLine - 1);
1064 			BRect textRect(0.0, top + TEXT_INSET,
1065 				printableRect.Width(), bottom + TEXT_INSET);
1066 			printJob.DrawView(fTextView, textRect, B_ORIGIN);
1067 			printJob.SpoolPage();
1068 		}
1069 	}
1070 
1071 
1072 	printJob.CommitJob();
1073 }
1074 
1075 
1076 void
1077 StyledEditWindow::SearchAllWindows(BString find, BString replace,
1078 	bool caseSensitive)
1079 {
1080 	int32 numWindows;
1081 	numWindows = be_app->CountWindows();
1082 
1083 	BMessage* message;
1084 	message= new BMessage(MSG_REPLACE_ALL);
1085 	message->AddString("FindText", find);
1086 	message->AddString("ReplaceText", replace);
1087 	message->AddBool("casesens", caseSensitive);
1088 
1089 	while (numWindows >= 0) {
1090 		StyledEditWindow* window = dynamic_cast<StyledEditWindow *>(
1091 			be_app->WindowAt(numWindows));
1092 
1093 		BMessenger messenger(window);
1094 		messenger.SendMessage(message);
1095 
1096 		numWindows--;
1097 	}
1098 }
1099 
1100 
1101 bool
1102 StyledEditWindow::IsDocumentEntryRef(const entry_ref* ref)
1103 {
1104 	if (ref == NULL)
1105 		return false;
1106 
1107 	if (fSaveMessage == NULL)
1108 		return false;
1109 
1110 	entry_ref dir;
1111 	const char* name;
1112 	if (fSaveMessage->FindRef("directory", &dir) != B_OK
1113 		|| fSaveMessage->FindString("name", &name) != B_OK)
1114 		return false;
1115 
1116 	entry_ref documentRef;
1117 	BPath documentPath(&dir);
1118 	documentPath.Append(name);
1119 	get_ref_for_path(documentPath.Path(), &documentRef);
1120 
1121 	return *ref == documentRef;
1122 }
1123 
1124 
1125 // #pragma mark - private methods
1126 
1127 
1128 #undef B_TRANSLATION_CONTEXT
1129 #define B_TRANSLATION_CONTEXT "Menus"
1130 
1131 
1132 void
1133 StyledEditWindow::_InitWindow(uint32 encoding)
1134 {
1135 	fPrintSettings = NULL;
1136 	fSaveMessage = NULL;
1137 
1138 	// undo modes
1139 	fUndoFlag = false;
1140 	fCanUndo = false;
1141 	fRedoFlag = false;
1142 	fCanRedo = false;
1143 
1144 	// clean modes
1145 	fUndoCleans = false;
1146 	fRedoCleans = false;
1147 	fClean = true;
1148 
1149 	// search- state
1150 	fReplaceString = "";
1151 	fStringToFind = "";
1152 	fCaseSensitive = false;
1153 	fWrapAround = false;
1154 	fBackSearch = false;
1155 
1156 	fNagOnNodeChange = true;
1157 
1158 
1159 	// add textview and scrollview
1160 
1161 	BRect viewFrame = Bounds();
1162 	BRect textBounds = viewFrame;
1163 	textBounds.OffsetTo(B_ORIGIN);
1164 
1165 	fTextView = new StyledEditView(viewFrame, textBounds, this);
1166 	fTextView->SetInsets(TEXT_INSET, TEXT_INSET, TEXT_INSET, TEXT_INSET);
1167 	fTextView->SetDoesUndo(true);
1168 	fTextView->SetStylable(true);
1169 	fTextView->SetEncoding(encoding);
1170 
1171 	fScrollView = new BScrollView("scrollview", fTextView, B_FOLLOW_ALL, 0,
1172 		true, true, B_PLAIN_BORDER);
1173 
1174 	fStatusView = new StatusView(fScrollView);
1175 	fScrollView->AddChild(fStatusView);
1176 
1177 	BMenuItem* openItem = new BMenuItem(BRecentFilesList::NewFileListMenu(
1178 		B_TRANSLATE("Open" B_UTF8_ELLIPSIS), NULL, NULL, be_app, 9, true,
1179 		NULL, APP_SIGNATURE), new BMessage(MENU_OPEN));
1180 	openItem->SetShortcut('O', 0);
1181 	openItem->SetTarget(be_app);
1182 
1183 	fSaveItem = new BMenuItem(B_TRANSLATE("Save"),new BMessage(MENU_SAVE), 'S');
1184 	fSaveItem->SetEnabled(false);
1185 
1186 	fReloadItem = new BMenuItem(B_TRANSLATE("Reload" B_UTF8_ELLIPSIS),
1187 	new BMessage(MENU_RELOAD), 'L');
1188 	fReloadItem->SetEnabled(false);
1189 
1190 	fUndoItem = new BMenuItem(B_TRANSLATE("Can't undo"),
1191 		new BMessage(B_UNDO), 'Z');
1192 	fUndoItem->SetEnabled(false);
1193 
1194 	fCutItem = new BMenuItem(B_TRANSLATE("Cut"),
1195 		new BMessage(B_CUT), 'X');
1196 	fCutItem->SetEnabled(false);
1197 
1198 	fCopyItem = new BMenuItem(B_TRANSLATE("Copy"),
1199 		new BMessage(B_COPY), 'C');
1200 	fCopyItem->SetEnabled(false);
1201 
1202 	fFindAgainItem = new BMenuItem(B_TRANSLATE("Find again"),
1203 		new BMessage(MENU_FIND_AGAIN), 'G');
1204 	fFindAgainItem->SetEnabled(false);
1205 
1206 	fReplaceItem = new BMenuItem(B_TRANSLATE("Replace" B_UTF8_ELLIPSIS),
1207 		new BMessage(MENU_REPLACE), 'R');
1208 
1209 	fReplaceSameItem = new BMenuItem(B_TRANSLATE("Replace next"),
1210 		new BMessage(MENU_REPLACE_SAME), 'T');
1211 	fReplaceSameItem->SetEnabled(false);
1212 
1213 	fFontSizeMenu = new BMenu(B_TRANSLATE("Size"));
1214 	fFontSizeMenu->SetRadioMode(true);
1215 
1216 	BMenuItem* menuItem;
1217 	for (uint32 i = 0; i < sizeof(fontSizes) / sizeof(fontSizes[0]); i++) {
1218 		BMessage* fontMessage = new BMessage(FONT_SIZE);
1219 		fontMessage->AddFloat("size", fontSizes[i]);
1220 
1221 		char label[64];
1222 		snprintf(label, sizeof(label), "%" B_PRId32, fontSizes[i]);
1223 		fFontSizeMenu->AddItem(menuItem = new BMenuItem(label, fontMessage));
1224 
1225 		if (fontSizes[i] == (int32)be_plain_font->Size())
1226 			menuItem->SetMarked(true);
1227 	}
1228 
1229 	fFontColorMenu = new BMenu(B_TRANSLATE("Color"), 0, 0);
1230 	fFontColorMenu->SetRadioMode(true);
1231 
1232 	_BuildFontColorMenu(fFontColorMenu);
1233 
1234 	fBoldItem = new BMenuItem(B_TRANSLATE("Bold"),
1235 		new BMessage(kMsgSetBold));
1236 	fBoldItem->SetShortcut('B', 0);
1237 
1238 	fItalicItem = new BMenuItem(B_TRANSLATE("Italic"),
1239 		new BMessage(kMsgSetItalic));
1240 	fItalicItem->SetShortcut('I', 0);
1241 
1242 	fUnderlineItem = new BMenuItem(B_TRANSLATE("Underline"),
1243 		new BMessage(kMsgSetUnderline));
1244 	fUnderlineItem->SetShortcut('U', 0);
1245 
1246 	fFontMenu = new BMenu(B_TRANSLATE("Font"));
1247 	fCurrentFontItem = 0;
1248 	fCurrentStyleItem = 0;
1249 
1250 	// premake font menu since we cant add members dynamically later
1251 	BLayoutBuilder::Menu<>(fFontMenu)
1252 		.AddItem(fFontSizeMenu)
1253 		.AddItem(fFontColorMenu)
1254 		.AddSeparator()
1255 		.AddItem(B_TRANSLATE("Increase size"), kMsgSetFontUp, '+')
1256 		.AddItem(B_TRANSLATE("Decrease size"), kMsgSetFontDown, '-')
1257 		.AddItem(fBoldItem)
1258 		.AddItem(fItalicItem)
1259 		.AddItem(fUnderlineItem)
1260 		.AddSeparator()
1261 	.End();
1262 
1263 	BMenu* subMenu;
1264 	int32 numFamilies = count_font_families();
1265 	for (int32 i = 0; i < numFamilies; i++) {
1266 		font_family family;
1267 		if (get_font_family(i, &family) == B_OK) {
1268 			subMenu = new BMenu(family);
1269 			subMenu->SetRadioMode(true);
1270 			fFontMenu->AddItem(new BMenuItem(subMenu,
1271 				new BMessage(FONT_FAMILY)));
1272 
1273 			int32 numStyles = count_font_styles(family);
1274 			for (int32 j = 0; j < numStyles; j++) {
1275 				font_style style;
1276 				uint32 flags;
1277 				if (get_font_style(family, j, &style, &flags) == B_OK) {
1278 					subMenu->AddItem(new BMenuItem(style,
1279 						new BMessage(FONT_STYLE)));
1280 				}
1281 			}
1282 		}
1283 	}
1284 
1285 	// "Align"-subMenu:
1286 	BMenu* alignMenu = new BMenu(B_TRANSLATE("Align"));
1287 	alignMenu->SetRadioMode(true);
1288 
1289 	alignMenu->AddItem(fAlignLeft = new BMenuItem(B_TRANSLATE("Left"),
1290 		new BMessage(ALIGN_LEFT)));
1291 	fAlignLeft->SetMarked(true);
1292 	fAlignLeft->SetShortcut('L', B_OPTION_KEY);
1293 
1294 	alignMenu->AddItem(fAlignCenter = new BMenuItem(B_TRANSLATE("Center"),
1295 		new BMessage(ALIGN_CENTER)));
1296 	fAlignCenter->SetShortcut('C', B_OPTION_KEY);
1297 
1298 	alignMenu->AddItem(fAlignRight = new BMenuItem(B_TRANSLATE("Right"),
1299 		new BMessage(ALIGN_RIGHT)));
1300 	fAlignRight->SetShortcut('R', B_OPTION_KEY);
1301 
1302 	fWrapItem = new BMenuItem(B_TRANSLATE("Wrap lines"),
1303 		new BMessage(WRAP_LINES));
1304 	fWrapItem->SetMarked(true);
1305 	fWrapItem->SetShortcut('W', B_OPTION_KEY);
1306 
1307 	BMessage *message = new BMessage(MENU_RELOAD);
1308 	message->AddString("encoding", "auto");
1309 	fEncodingItem = new BMenuItem(_PopulateEncodingMenu(
1310 		new BMenu(B_TRANSLATE("Text encoding")), "UTF-8"),
1311 		message);
1312 	fEncodingItem->SetEnabled(false);
1313 
1314 	BMenuBar* mainMenu = new BMenuBar("mainMenu");
1315 
1316 	BLayoutBuilder::Menu<>(mainMenu)
1317 		.AddMenu(B_TRANSLATE("File"))
1318 			.AddItem(B_TRANSLATE("New"), MENU_NEW, 'N')
1319 			.AddItem(openItem)
1320 			.AddSeparator()
1321 			.AddItem(fSaveItem)
1322 			.AddItem(B_TRANSLATE("Save as" B_UTF8_ELLIPSIS),
1323 				MENU_SAVEAS, 'S', B_SHIFT_KEY)
1324 			.AddItem(fReloadItem)
1325 			.AddItem(B_TRANSLATE("Close"), MENU_CLOSE, 'W')
1326 			.AddSeparator()
1327 			.AddItem(B_TRANSLATE("Page setup" B_UTF8_ELLIPSIS), MENU_PAGESETUP)
1328 			.AddItem(B_TRANSLATE("Print" B_UTF8_ELLIPSIS), MENU_PRINT, 'P')
1329 			.AddSeparator()
1330 			.AddItem(B_TRANSLATE("Quit"), MENU_QUIT, 'Q')
1331 		.End()
1332 		.AddMenu(B_TRANSLATE("Edit"))
1333 			.AddItem(fUndoItem)
1334 			.AddSeparator()
1335 			.AddItem(fCutItem)
1336 			.AddItem(fCopyItem)
1337 			.AddItem(B_TRANSLATE("Paste"), B_PASTE, 'V')
1338 			.AddSeparator()
1339 			.AddItem(B_TRANSLATE("Select all"), B_SELECT_ALL, 'A')
1340 			.AddSeparator()
1341 			.AddItem(B_TRANSLATE("Find" B_UTF8_ELLIPSIS), MENU_FIND, 'F')
1342 			.AddItem(fFindAgainItem)
1343 			.AddItem(B_TRANSLATE("Find selection"), MENU_FIND_SELECTION, 'H')
1344 			.AddItem(fReplaceItem)
1345 			.AddItem(fReplaceSameItem)
1346 		.End()
1347 		.AddItem(fFontMenu)
1348 		.AddMenu(B_TRANSLATE("Document"))
1349 			.AddItem(alignMenu)
1350 			.AddItem(fWrapItem)
1351 			.AddItem(fEncodingItem)
1352 			.AddSeparator()
1353 			.AddItem(B_TRANSLATE("Statistics" B_UTF8_ELLIPSIS), SHOW_STATISTICS)
1354 		.End();
1355 
1356 
1357 	fSavePanel = NULL;
1358 	fSavePanelEncodingMenu = NULL;
1359 
1360 	BLayoutBuilder::Group<>(this, B_VERTICAL, 0)
1361 		.Add(mainMenu)
1362 		.AddGroup(B_VERTICAL, 0)
1363 			.SetInsets(-1)
1364 			.Add(fScrollView)
1365 		.End()
1366 	.End();
1367 
1368 	SetKeyMenuBar(mainMenu);
1369 	fTextView->MakeFocus(true);
1370 
1371 }
1372 
1373 
1374 void
1375 StyledEditWindow::_BuildFontColorMenu(BMenu* menu)
1376 {
1377 	if (menu == NULL)
1378 		return;
1379 
1380 	BFont font;
1381 	menu->GetFont(&font);
1382 	font_height fh;
1383 	font.GetHeight(&fh);
1384 
1385 	const float itemHeight = ceilf(fh.ascent + fh.descent + 2 * fh.leading);
1386 	const float margin = 8.0;
1387 	const int nbColumns = 5;
1388 
1389 	BMessage msgTemplate(FONT_COLOR);
1390 	BRect matrixArea(0, 0, 0, 0);
1391 
1392 	// we place the color palette, reserving room at the top
1393 	for (uint i = 0; i < sizeof(palette) / sizeof(rgb_color); i++) {
1394 		BPoint topLeft((i % nbColumns) * (itemHeight + margin),
1395 			(i / nbColumns) * (itemHeight + margin));
1396 		BRect buttonArea(topLeft.x, topLeft.y, topLeft.x + itemHeight,
1397 			topLeft.y + itemHeight);
1398 		buttonArea.OffsetBy(margin, itemHeight + margin + margin);
1399 		menu->AddItem(
1400 			new ColorMenuItem("", palette[i], new BMessage(msgTemplate)),
1401 			buttonArea);
1402 		buttonArea.OffsetBy(margin, margin);
1403 		matrixArea = matrixArea | buttonArea;
1404 	}
1405 
1406 	// separator at the bottom to add spacing in the matrix menu
1407 	matrixArea.top = matrixArea.bottom;
1408 	menu->AddItem(new BSeparatorItem(), matrixArea);
1409 
1410 	matrixArea.top = 0;
1411 	matrixArea.bottom = itemHeight + 4;
1412 
1413 	BMessage* msg = new BMessage(msgTemplate);
1414 	msg->AddBool("default", true);
1415 	fDefaultFontColorItem = new ColorMenuItem(B_TRANSLATE("Default"),
1416 		ui_color(B_DOCUMENT_TEXT_COLOR), msg);
1417 	menu->AddItem(fDefaultFontColorItem, matrixArea);
1418 
1419 	matrixArea.top = matrixArea.bottom;
1420 	matrixArea.bottom = matrixArea.top + margin;
1421 	menu->AddItem(new BSeparatorItem(), matrixArea);
1422 }
1423 
1424 
1425 void
1426 StyledEditWindow::_LoadAttrs()
1427 {
1428 	entry_ref dir;
1429 	const char* name;
1430 	if (fSaveMessage->FindRef("directory", &dir) != B_OK
1431 		|| fSaveMessage->FindString("name", &name) != B_OK)
1432 		return;
1433 
1434 	BPath documentPath(&dir);
1435 	documentPath.Append(name);
1436 
1437 	BNode documentNode(documentPath.Path());
1438 	if (documentNode.InitCheck() != B_OK)
1439 		return;
1440 
1441 	// info about position of caret may live in the file attributes
1442 	int32 position = 0;
1443 	if (documentNode.ReadAttr("be:caret_position", B_INT32_TYPE, 0,
1444 			&position, sizeof(position)) != sizeof(position))
1445 		position = 0;
1446 
1447 	fTextView->Select(position, position);
1448 	fTextView->ScrollToOffset(position);
1449 
1450 	BRect newFrame;
1451 	ssize_t bytesRead = documentNode.ReadAttr(kInfoAttributeName, B_RECT_TYPE,
1452 		0, &newFrame, sizeof(BRect));
1453 	if (bytesRead != sizeof(BRect))
1454 		return;
1455 
1456 	swap_data(B_RECT_TYPE, &newFrame, sizeof(BRect), B_SWAP_BENDIAN_TO_HOST);
1457 
1458 	// Check if the frame in on screen, otherwise, ignore it
1459 	BScreen screen(this);
1460 	if (newFrame.Width() > 32 && newFrame.Height() > 32
1461 		&& screen.Frame().Contains(newFrame)) {
1462 		MoveTo(newFrame.left, newFrame.top);
1463 		ResizeTo(newFrame.Width(), newFrame.Height());
1464 	}
1465 }
1466 
1467 
1468 void
1469 StyledEditWindow::_SaveAttrs()
1470 {
1471 	if (!fSaveMessage)
1472 		return;
1473 
1474 	entry_ref dir;
1475 	const char* name;
1476 	if (fSaveMessage->FindRef("directory", &dir) != B_OK
1477 		|| fSaveMessage->FindString("name", &name) != B_OK)
1478 		return;
1479 
1480 	BPath documentPath(&dir);
1481 	documentPath.Append(name);
1482 
1483 	BNode documentNode(documentPath.Path());
1484 	if (documentNode.InitCheck() != B_OK)
1485 		return;
1486 
1487 	BRect frame(Frame());
1488 	swap_data(B_RECT_TYPE, &frame, sizeof(BRect), B_SWAP_HOST_TO_BENDIAN);
1489 
1490 	documentNode.WriteAttr(kInfoAttributeName, B_RECT_TYPE, 0, &frame,
1491 		sizeof(BRect));
1492 
1493 	// preserve caret line and position
1494 	int32 start, end;
1495 	fTextView->GetSelection(&start, &end);
1496 	documentNode.WriteAttr("be:caret_position",
1497 			B_INT32_TYPE, 0, &start, sizeof(start));
1498 }
1499 
1500 
1501 #undef B_TRANSLATION_CONTEXT
1502 #define B_TRANSLATION_CONTEXT "LoadAlert"
1503 
1504 
1505 status_t
1506 StyledEditWindow::_LoadFile(entry_ref* ref, const char* forceEncoding)
1507 {
1508 	BEntry entry(ref, true);
1509 		// traverse an eventual link
1510 
1511 	status_t status = entry.InitCheck();
1512 	if (status == B_OK && entry.IsDirectory())
1513 		status = B_IS_A_DIRECTORY;
1514 
1515 	BFile file;
1516 	if (status == B_OK)
1517 		status = file.SetTo(&entry, B_READ_ONLY);
1518 	if (status == B_OK)
1519 		status = fTextView->GetStyledText(&file, forceEncoding);
1520 
1521 	if (status == B_ENTRY_NOT_FOUND) {
1522 		// Treat non-existing files consideratley; we just want to get an
1523 		// empty window for them - to create this new document
1524 		status = B_OK;
1525 	}
1526 
1527 	if (status != B_OK) {
1528 		// If an error occured, bail out and tell the user what happened
1529 		BEntry entry(ref, true);
1530 		char name[B_FILE_NAME_LENGTH];
1531 		if (entry.GetName(name) != B_OK)
1532 			strlcpy(name, B_TRANSLATE("???"), sizeof(name));
1533 
1534 		BString text;
1535 		if (status == B_BAD_TYPE)
1536 			bs_printf(&text,
1537 				B_TRANSLATE("Error loading \"%s\":\n\tUnsupported format"), name);
1538 		else
1539 			bs_printf(&text, B_TRANSLATE("Error loading \"%s\":\n\t%s"),
1540 				name, strerror(status));
1541 
1542 		_ShowAlert(text, B_TRANSLATE("OK"), "", "", B_STOP_ALERT);
1543 		return status;
1544 	}
1545 
1546 	struct stat st;
1547 	if (file.InitCheck() == B_OK && file.GetStat(&st) == B_OK) {
1548 		bool editable = (getuid() == st.st_uid && S_IWUSR & st.st_mode)
1549 					|| (getgid() == st.st_gid && S_IWGRP & st.st_mode)
1550 					|| (S_IWOTH & st.st_mode);
1551 		BVolume volume(ref->device);
1552 		editable = editable && !volume.IsReadOnly();
1553 		_SetReadOnly(!editable);
1554 	}
1555 
1556 	// update alignment
1557 	switch (fTextView->Alignment()) {
1558 		case B_ALIGN_LEFT:
1559 		default:
1560 			fAlignLeft->SetMarked(true);
1561 			break;
1562 		case B_ALIGN_CENTER:
1563 			fAlignCenter->SetMarked(true);
1564 			break;
1565 		case B_ALIGN_RIGHT:
1566 			fAlignRight->SetMarked(true);
1567 			break;
1568 	}
1569 
1570 	// update word wrapping
1571 	fWrapItem->SetMarked(fTextView->DoesWordWrap());
1572 	return B_OK;
1573 }
1574 
1575 
1576 #undef B_TRANSLATION_CONTEXT
1577 #define B_TRANSLATION_CONTEXT "RevertToSavedAlert"
1578 
1579 
1580 void
1581 StyledEditWindow::_ReloadDocument(BMessage* message)
1582 {
1583 	entry_ref ref;
1584 	const char* name;
1585 
1586 	if (fSaveMessage == NULL || message == NULL
1587 		|| fSaveMessage->FindRef("directory", &ref) != B_OK
1588 		|| fSaveMessage->FindString("name", &name) != B_OK)
1589 		return;
1590 
1591 	BDirectory dir(&ref);
1592 	status_t status = dir.InitCheck();
1593 	BEntry entry;
1594 	if (status == B_OK)
1595 		status = entry.SetTo(&dir, name);
1596 
1597 	if (status == B_OK)
1598 		status = entry.GetRef(&ref);
1599 
1600 	if (status != B_OK || !entry.Exists()) {
1601 		BString alertText;
1602 		bs_printf(&alertText,
1603 			B_TRANSLATE("Cannot revert, file not found: \"%s\"."), name);
1604 		_ShowAlert(alertText, B_TRANSLATE("OK"), "", "", B_STOP_ALERT);
1605 		return;
1606 	}
1607 
1608 	if (!fClean) {
1609 		BString alertText;
1610 		bs_printf(&alertText,
1611 			B_TRANSLATE("\"%s\" has unsaved changes.\n"
1612 				"Revert it to the last saved version? "), Title());
1613 		if (_ShowAlert(alertText, B_TRANSLATE("Cancel"), B_TRANSLATE("Revert"),
1614 			"", B_WARNING_ALERT) != 1)
1615 			return;
1616 	}
1617 
1618 	const BCharacterSet* charset
1619 		= BCharacterSetRoster::GetCharacterSetByFontID(
1620 			fTextView->GetEncoding());
1621 	const char* forceEncoding = NULL;
1622 	if (message->FindString("encoding", &forceEncoding) != B_OK) {
1623 		if (charset != NULL)
1624 			forceEncoding = charset->GetName();
1625 	} else {
1626 		if (charset != NULL) {
1627 			// UTF8 id assumed equal to -1
1628 			const uint32 idUTF8 = (uint32)-1;
1629 			uint32 id = charset->GetConversionID();
1630 			if (strcmp(forceEncoding, "next") == 0)
1631 				id = id == B_MS_WINDOWS_1250_CONVERSION	? idUTF8 : id + 1;
1632 			else if (strcmp(forceEncoding, "previous") == 0)
1633 				id = id == idUTF8 ? B_MS_WINDOWS_1250_CONVERSION : id - 1;
1634 			const BCharacterSet* newCharset
1635 				= BCharacterSetRoster::GetCharacterSetByConversionID(id);
1636 			if (newCharset != NULL)
1637 				forceEncoding = newCharset->GetName();
1638 		}
1639 	}
1640 
1641 	BScrollBar* vertBar = fScrollView->ScrollBar(B_VERTICAL);
1642 	float vertPos = vertBar != NULL ? vertBar->Value() : 0.f;
1643 
1644 	DisableUpdates();
1645 
1646 	fTextView->Reset();
1647 
1648 	status = _LoadFile(&ref, forceEncoding);
1649 
1650 	if (vertBar != NULL)
1651 		vertBar->SetValue(vertPos);
1652 
1653 	EnableUpdates();
1654 
1655 	if (status != B_OK)
1656 		return;
1657 
1658 #undef B_TRANSLATION_CONTEXT
1659 #define B_TRANSLATION_CONTEXT "Menus"
1660 
1661 	// clear undo modes
1662 	fUndoItem->SetLabel(B_TRANSLATE("Can't undo"));
1663 	fUndoItem->SetEnabled(false);
1664 	fUndoFlag = false;
1665 	fCanUndo = false;
1666 	fRedoFlag = false;
1667 	fCanRedo = false;
1668 
1669 	// clear clean modes
1670 	fSaveItem->SetEnabled(false);
1671 
1672 	fUndoCleans = false;
1673 	fRedoCleans = false;
1674 	fClean = true;
1675 
1676 	fNagOnNodeChange = true;
1677 }
1678 
1679 
1680 status_t
1681 StyledEditWindow::_UnlockFile()
1682 {
1683 	_NodeMonitorSuspender nodeMonitorSuspender(this);
1684 
1685 	if (!fSaveMessage)
1686 		return B_ERROR;
1687 
1688 	entry_ref dirRef;
1689 	const char* name;
1690 	if (fSaveMessage->FindRef("directory", &dirRef) != B_OK
1691 		|| fSaveMessage->FindString("name", &name) != B_OK)
1692 		return B_BAD_VALUE;
1693 
1694 	BDirectory dir(&dirRef);
1695 	BEntry entry(&dir, name);
1696 
1697 	status_t status = dir.InitCheck();
1698 	if (status != B_OK)
1699 		return status;
1700 
1701 	status = entry.InitCheck();
1702 	if (status != B_OK)
1703 		return status;
1704 
1705 	struct stat st;
1706 	BFile file(&entry, B_READ_WRITE);
1707 	status = file.InitCheck();
1708 	if (status != B_OK)
1709 		return status;
1710 
1711 	status = file.GetStat(&st);
1712 	if (status != B_OK)
1713 		return status;
1714 
1715 	st.st_mode |= S_IWUSR;
1716 	status = file.SetPermissions(st.st_mode);
1717 	if (status == B_OK)
1718 		_SetReadOnly(false);
1719 
1720 	return status;
1721 }
1722 
1723 
1724 bool
1725 StyledEditWindow::_Search(BString string, bool caseSensitive, bool wrap,
1726 	bool backSearch, bool scrollToOccurence)
1727 {
1728 	int32 start;
1729 	int32 finish;
1730 
1731 	start = B_ERROR;
1732 
1733 	int32 length = string.Length();
1734 	if (length == 0)
1735 		return false;
1736 
1737 	BString viewText(fTextView->Text());
1738 	int32 textStart, textFinish;
1739 	fTextView->GetSelection(&textStart, &textFinish);
1740 	if (backSearch) {
1741 		if (caseSensitive)
1742 			start = viewText.FindLast(string, textStart);
1743 		else
1744 			start = viewText.IFindLast(string, textStart);
1745 	} else {
1746 		if (caseSensitive)
1747 			start = viewText.FindFirst(string, textFinish);
1748 		else
1749 			start = viewText.IFindFirst(string, textFinish);
1750 	}
1751 	if (start == B_ERROR && wrap) {
1752 		if (backSearch) {
1753 			if (caseSensitive)
1754 				start = viewText.FindLast(string, viewText.Length());
1755 			else
1756 				start = viewText.IFindLast(string, viewText.Length());
1757 		} else {
1758 			if (caseSensitive)
1759 				start = viewText.FindFirst(string, 0);
1760 			else
1761 				start = viewText.IFindFirst(string, 0);
1762 		}
1763 	}
1764 
1765 	if (start != B_ERROR) {
1766 		finish = start + length;
1767 		fTextView->Select(start, finish);
1768 
1769 		if (scrollToOccurence)
1770 			fTextView->ScrollToSelection();
1771 		return true;
1772 	}
1773 
1774 	return false;
1775 }
1776 
1777 
1778 void
1779 StyledEditWindow::_FindSelection()
1780 {
1781 	int32 selectionStart, selectionFinish;
1782 	fTextView->GetSelection(&selectionStart, &selectionFinish);
1783 
1784 	int32 selectionLength = selectionFinish- selectionStart;
1785 
1786 	BString viewText = fTextView->Text();
1787 	viewText.CopyInto(fStringToFind, selectionStart, selectionLength);
1788 	fFindAgainItem->SetEnabled(true);
1789 	_Search(fStringToFind, fCaseSensitive, fWrapAround, fBackSearch);
1790 }
1791 
1792 
1793 bool
1794 StyledEditWindow::_Replace(BString findThis, BString replaceWith,
1795 	bool caseSensitive, bool wrap, bool backSearch)
1796 {
1797 	if (_Search(findThis, caseSensitive, wrap, backSearch)) {
1798 		int32 start;
1799 		int32 finish;
1800 		fTextView->GetSelection(&start, &finish);
1801 
1802 		_UpdateCleanUndoRedoSaveRevert();
1803 		fTextView->SetSuppressChanges(true);
1804 		fTextView->Delete(start, start + findThis.Length());
1805 		fTextView->Insert(start, replaceWith.String(), replaceWith.Length());
1806 		fTextView->SetSuppressChanges(false);
1807 		fTextView->Select(start, start + replaceWith.Length());
1808 		fTextView->ScrollToSelection();
1809 		return true;
1810 	}
1811 
1812 	return false;
1813 }
1814 
1815 
1816 void
1817 StyledEditWindow::_ReplaceAll(BString findThis, BString replaceWith,
1818 	bool caseSensitive)
1819 {
1820 	bool first = true;
1821 	fTextView->SetSuppressChanges(true);
1822 
1823 	// start from the beginning of text
1824 	fTextView->Select(0, 0);
1825 
1826 	// iterate occurences of findThis without wrapping around
1827 	while (_Search(findThis, caseSensitive, false, false, false)) {
1828 		if (first) {
1829 			_UpdateCleanUndoRedoSaveRevert();
1830 			first = false;
1831 		}
1832 		int32 start;
1833 		int32 finish;
1834 
1835 		fTextView->GetSelection(&start, &finish);
1836 		fTextView->Delete(start, start + findThis.Length());
1837 		fTextView->Insert(start, replaceWith.String(), replaceWith.Length());
1838 
1839 		// advance the caret behind the inserted text
1840 		start += replaceWith.Length();
1841 		fTextView->Select(start, start);
1842 	}
1843 	fTextView->ScrollToSelection();
1844 	fTextView->SetSuppressChanges(false);
1845 }
1846 
1847 
1848 void
1849 StyledEditWindow::_SetFontSize(float fontSize)
1850 {
1851 	uint32 sameProperties;
1852 	BFont font;
1853 
1854 	fTextView->GetFontAndColor(&font, &sameProperties);
1855 	font.SetSize(fontSize);
1856 	fTextView->SetFontAndColor(&font, B_FONT_SIZE);
1857 
1858 	_UpdateCleanUndoRedoSaveRevert();
1859 }
1860 
1861 
1862 void
1863 StyledEditWindow::_SetFontColor(const rgb_color* color)
1864 {
1865 	uint32 sameProperties;
1866 	BFont font;
1867 
1868 	fTextView->GetFontAndColor(&font, &sameProperties, NULL, NULL);
1869 	fTextView->SetFontAndColor(&font, 0, color);
1870 
1871 	_UpdateCleanUndoRedoSaveRevert();
1872 }
1873 
1874 
1875 void
1876 StyledEditWindow::_SetFontStyle(const char* fontFamily, const char* fontStyle)
1877 {
1878 	BFont font;
1879 	uint32 sameProperties;
1880 
1881 	// find out what the old font was
1882 	font_family oldFamily;
1883 	font_style oldStyle;
1884 	fTextView->GetFontAndColor(&font, &sameProperties);
1885 	font.GetFamilyAndStyle(&oldFamily, &oldStyle);
1886 
1887 	// clear that family's bit on the menu, if necessary
1888 	if (strcmp(oldFamily, fontFamily)) {
1889 		BMenuItem* oldItem = fFontMenu->FindItem(oldFamily);
1890 		if (oldItem != NULL) {
1891 			oldItem->SetMarked(false);
1892 			BMenu* menu = oldItem->Submenu();
1893 			if (menu != NULL) {
1894 				oldItem = menu->FindItem(oldStyle);
1895 				if (oldItem != NULL)
1896 					oldItem->SetMarked(false);
1897 			}
1898 		}
1899 	}
1900 
1901 	font.SetFamilyAndStyle(fontFamily, fontStyle);
1902 
1903 	uint16 face = 0;
1904 
1905 	if (!(font.Face() & B_REGULAR_FACE))
1906 		face = font.Face();
1907 
1908 	if (fBoldItem->IsMarked())
1909 		face |= B_BOLD_FACE;
1910 
1911 	if (fItalicItem->IsMarked())
1912 		face |= B_ITALIC_FACE;
1913 
1914 	if (fUnderlineItem->IsMarked())
1915 		face |= B_UNDERSCORE_FACE;
1916 
1917 	font.SetFace(face);
1918 
1919 	fTextView->SetFontAndColor(&font, B_FONT_FAMILY_AND_STYLE | B_FONT_FACE);
1920 
1921 	BMenuItem* superItem;
1922 	superItem = fFontMenu->FindItem(fontFamily);
1923 	if (superItem != NULL) {
1924 		superItem->SetMarked(true);
1925 		fCurrentFontItem = superItem;
1926 	}
1927 
1928 	_UpdateCleanUndoRedoSaveRevert();
1929 }
1930 
1931 
1932 #undef B_TRANSLATION_CONTEXT
1933 #define B_TRANSLATION_CONTEXT "Statistics"
1934 
1935 
1936 int32
1937 StyledEditWindow::_ShowStatistics()
1938 {
1939 	size_t words = 0;
1940 	bool inWord = false;
1941 	size_t length = fTextView->TextLength();
1942 
1943 	for (size_t i = 0; i < length; i++)	{
1944 		if (BUnicodeChar::IsWhitespace(fTextView->Text()[i])) {
1945 			inWord = false;
1946 		} else if (!inWord)	{
1947 			words++;
1948 			inWord = true;
1949 		}
1950 	}
1951 
1952 	BString result;
1953 	result << B_TRANSLATE("Document statistics") << '\n' << '\n'
1954 		<< B_TRANSLATE("Lines:") << ' ' << fTextView->CountLines() << '\n'
1955 		<< B_TRANSLATE("Characters:") << ' ' << length << '\n'
1956 		<< B_TRANSLATE("Words:") << ' ' << words;
1957 
1958 	BAlert* alert = new BAlert("Statistics", result, B_TRANSLATE("OK"), NULL,
1959 		NULL, B_WIDTH_AS_USUAL, B_EVEN_SPACING, B_INFO_ALERT);
1960 	alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
1961 
1962 	return alert->Go();
1963 }
1964 
1965 
1966 void
1967 StyledEditWindow::_SetReadOnly(bool readOnly)
1968 {
1969 	fReplaceItem->SetEnabled(!readOnly);
1970 	fReplaceSameItem->SetEnabled(!readOnly);
1971 	fFontMenu->SetEnabled(!readOnly);
1972 	fAlignLeft->Menu()->SetEnabled(!readOnly);
1973 	fWrapItem->SetEnabled(!readOnly);
1974 	fTextView->MakeEditable(!readOnly);
1975 }
1976 
1977 
1978 #undef B_TRANSLATION_CONTEXT
1979 #define B_TRANSLATION_CONTEXT "Menus"
1980 
1981 
1982 void
1983 StyledEditWindow::_UpdateCleanUndoRedoSaveRevert()
1984 {
1985 	fClean = false;
1986 	fUndoCleans = false;
1987 	fRedoCleans = false;
1988 	fReloadItem->SetEnabled(fSaveMessage != NULL);
1989 	fEncodingItem->SetEnabled(fSaveMessage != NULL);
1990 	fSaveItem->SetEnabled(true);
1991 	fUndoItem->SetLabel(B_TRANSLATE("Can't undo"));
1992 	fUndoItem->SetEnabled(false);
1993 	fCanUndo = false;
1994 	fCanRedo = false;
1995 }
1996 
1997 
1998 int32
1999 StyledEditWindow::_ShowAlert(const BString& text, const BString& label,
2000 	const BString& label2, const BString& label3, alert_type type) const
2001 {
2002 	const char* button2 = NULL;
2003 	if (label2.Length() > 0)
2004 		button2 = label2.String();
2005 
2006 	const char* button3 = NULL;
2007 	button_spacing spacing = B_EVEN_SPACING;
2008 	if (label3.Length() > 0) {
2009 		button3 = label3.String();
2010 		spacing = B_OFFSET_SPACING;
2011 	}
2012 
2013 	BAlert* alert = new BAlert("Alert", text.String(), label.String(), button2,
2014 		button3, B_WIDTH_AS_USUAL, spacing, type);
2015 	alert->SetShortcut(0, B_ESCAPE);
2016 
2017 	return alert->Go();
2018 }
2019 
2020 
2021 BMenu*
2022 StyledEditWindow::_PopulateEncodingMenu(BMenu* menu, const char* currentEncoding)
2023 {
2024 	menu->SetRadioMode(true);
2025 	BString encoding(currentEncoding);
2026 	if (encoding.Length() == 0)
2027 		encoding.SetTo("UTF-8");
2028 
2029 	BCharacterSetRoster roster;
2030 	BCharacterSet charset;
2031 	while (roster.GetNextCharacterSet(&charset) == B_OK) {
2032 		const char* mime = charset.GetMIMEName();
2033 		BString name(charset.GetPrintName());
2034 
2035 		if (mime)
2036 			name << " (" << mime << ")";
2037 
2038 		BMessage *message = new BMessage(MENU_RELOAD);
2039 		if (message != NULL) {
2040 			message->AddString("encoding", charset.GetName());
2041 			BMenuItem* item = new BMenuItem(name, message);
2042 			if (encoding.Compare(charset.GetName()) == 0)
2043 				item->SetMarked(true);
2044 			menu->AddItem(item);
2045 		}
2046 	}
2047 
2048 	menu->AddSeparatorItem();
2049 	BMessage *message = new BMessage(MENU_RELOAD);
2050 	message->AddString("encoding", "auto");
2051 	menu->AddItem(new BMenuItem(B_TRANSLATE("Autodetect"), message));
2052 
2053 	message = new BMessage(MENU_RELOAD);
2054 	message->AddString("encoding", "next");
2055 	AddShortcut(B_PAGE_DOWN, B_OPTION_KEY, message);
2056 	message = new BMessage(MENU_RELOAD);
2057 	message->AddString("encoding", "previous");
2058 	AddShortcut(B_PAGE_UP, B_OPTION_KEY, message);
2059 
2060 	return menu;
2061 }
2062 
2063 
2064 #undef B_TRANSLATION_CONTEXT
2065 #define B_TRANSLATION_CONTEXT "NodeMonitorAlerts"
2066 
2067 
2068 void
2069 StyledEditWindow::_ShowNodeChangeAlert(const char* name, bool removed)
2070 {
2071 	if (!fNagOnNodeChange)
2072 		return;
2073 
2074 	BString alertText(removed ? B_TRANSLATE("File \"%file%\" was removed by "
2075 		"another application, recover it?")
2076 		: B_TRANSLATE("File \"%file%\" was modified by "
2077 		"another application, reload it?"));
2078 	alertText.ReplaceAll("%file%", name);
2079 
2080 	if (_ShowAlert(alertText, removed ? B_TRANSLATE("Recover")
2081 			: B_TRANSLATE("Reload"), B_TRANSLATE("Ignore"), "",
2082 			B_WARNING_ALERT) == 0)
2083 	{
2084 		if (!removed) {
2085 			// supress the warning - user has already agreed
2086 			fClean = true;
2087 			BMessage msg(MENU_RELOAD);
2088 			_ReloadDocument(&msg);
2089 		} else
2090 			Save();
2091 	} else
2092 		fNagOnNodeChange = false;
2093 
2094 	fSaveItem->SetEnabled(!fClean);
2095 }
2096 
2097 
2098 void
2099 StyledEditWindow::_HandleNodeMonitorEvent(BMessage *message)
2100 {
2101 	int32 opcode = 0;
2102 	if (message->FindInt32("opcode", &opcode) != B_OK)
2103 		return;
2104 
2105 	if (opcode != B_ENTRY_CREATED
2106 		&& message->FindInt64("node") != fNodeRef.node)
2107 		// bypass foreign nodes' event
2108 		return;
2109 
2110 	switch (opcode) {
2111 		case B_STAT_CHANGED:
2112 			{
2113 				int32 fields = 0;
2114 				if (message->FindInt32("fields", &fields) == B_OK
2115 					&& (fields & (B_STAT_SIZE | B_STAT_MODIFICATION_TIME
2116 							| B_STAT_MODE)) == 0)
2117 					break;
2118 
2119 				const char* name = NULL;
2120 				if (fSaveMessage->FindString("name", &name) != B_OK)
2121 					break;
2122 
2123 				_ShowNodeChangeAlert(name, false);
2124 			}
2125 			break;
2126 
2127 		case B_ENTRY_MOVED:
2128 			{
2129 				int32 device = 0;
2130 				int64 srcFolder = 0;
2131 				int64 dstFolder = 0;
2132 				const char* name = NULL;
2133 				if (message->FindInt32("device", &device) != B_OK
2134 					|| message->FindInt64("to directory", &dstFolder) != B_OK
2135 					|| message->FindInt64("from directory", &srcFolder) != B_OK
2136 					|| message->FindString("name", &name) != B_OK)
2137 						break;
2138 
2139 				entry_ref newRef(device, dstFolder, name);
2140 				BEntry entry(&newRef);
2141 
2142 				BEntry dirEntry;
2143 				entry.GetParent(&dirEntry);
2144 
2145 				entry_ref ref;
2146 				dirEntry.GetRef(&ref);
2147 				fSaveMessage->ReplaceRef("directory", &ref);
2148 				fSaveMessage->ReplaceString("name", name);
2149 
2150 				// store previous name - it may be useful in case
2151 				// we have just moved to temporary copy of file (vim case)
2152 				const char* sourceName = NULL;
2153 				if (message->FindString("from name", &sourceName) == B_OK) {
2154 					fSaveMessage->RemoveName("org.name");
2155 					fSaveMessage->AddString("org.name", sourceName);
2156 					fSaveMessage->RemoveName("move time");
2157 					fSaveMessage->AddInt64("move time", system_time());
2158 				}
2159 
2160 				SetTitle(name);
2161 
2162 				if (srcFolder != dstFolder) {
2163 					_SwitchNodeMonitor(false);
2164 					_SwitchNodeMonitor(true);
2165 				}
2166 				PostMessage(UPDATE_STATUS_REF);
2167 			}
2168 			break;
2169 
2170 		case B_ENTRY_REMOVED:
2171 			{
2172 				_SwitchNodeMonitor(false);
2173 
2174 				fClean = false;
2175 
2176 				// some editors like vim save files in following way:
2177 				// 1) move t.txt -> t.txt~
2178 				// 2) re-create t.txt and write data to it
2179 				// 3) remove t.txt~
2180 				// go to catch this case
2181 				int32 device = 0;
2182 				int64 directory = 0;
2183 				BString orgName;
2184 				if (fSaveMessage->FindString("org.name", &orgName) == B_OK
2185 					&& message->FindInt32("device", &device) == B_OK
2186 					&& message->FindInt64("directory", &directory) == B_OK)
2187 				{
2188 					// reuse the source name if it is not too old
2189 					bigtime_t time = fSaveMessage->FindInt64("move time");
2190 					if ((system_time() - time) < 1000000) {
2191 						entry_ref ref(device, directory, orgName);
2192 						BEntry entry(&ref);
2193 						if (entry.InitCheck() == B_OK) {
2194 							_SwitchNodeMonitor(true, &ref);
2195 						}
2196 
2197 						fSaveMessage->ReplaceString("name", orgName);
2198 						fSaveMessage->RemoveName("org.name");
2199 						fSaveMessage->RemoveName("move time");
2200 
2201 						SetTitle(orgName);
2202 						_ShowNodeChangeAlert(orgName, false);
2203 						break;
2204 					}
2205 				}
2206 
2207 				const char* name = NULL;
2208 				if (message->FindString("name", &name) != B_OK
2209 					&& fSaveMessage->FindString("name", &name) != B_OK)
2210 					name = "Unknown";
2211 
2212 				_ShowNodeChangeAlert(name, true);
2213 				PostMessage(UPDATE_STATUS_REF);
2214 			}
2215 			break;
2216 
2217 		default:
2218 			break;
2219 	}
2220 }
2221 
2222 
2223 void
2224 StyledEditWindow::_SwitchNodeMonitor(bool on, entry_ref* ref)
2225 {
2226 	if (!on) {
2227 		watch_node(&fNodeRef, B_STOP_WATCHING, this);
2228 		watch_node(&fFolderNodeRef, B_STOP_WATCHING, this);
2229 		fNodeRef = node_ref();
2230 		fFolderNodeRef = node_ref();
2231 		return;
2232 	}
2233 
2234 	BEntry entry, folderEntry;
2235 
2236 	if (ref != NULL) {
2237 		entry.SetTo(ref, true);
2238 		entry.GetParent(&folderEntry);
2239 
2240 	} else if (fSaveMessage != NULL) {
2241 		entry_ref ref;
2242 		const char* name = NULL;
2243 		if (fSaveMessage->FindRef("directory", &ref) != B_OK
2244 			|| fSaveMessage->FindString("name", &name) != B_OK)
2245 			return;
2246 
2247 		BDirectory dir(&ref);
2248 		entry.SetTo(&dir, name);
2249 		folderEntry.SetTo(&ref);
2250 
2251 	} else
2252 		return;
2253 
2254 	if (entry.InitCheck() != B_OK || folderEntry.InitCheck() != B_OK)
2255 		return;
2256 
2257 	entry.GetNodeRef(&fNodeRef);
2258 	folderEntry.GetNodeRef(&fFolderNodeRef);
2259 
2260 	watch_node(&fNodeRef, B_WATCH_STAT, this);
2261 	watch_node(&fFolderNodeRef, B_WATCH_DIRECTORY, this);
2262 }
2263