Exemple #1
0
BColumn::BColumn(const BMessage &message, int32 index)
{
	message.FindString(kColumnTitleName, index, &fTitle);
	message.FindFloat(kColumnOffsetName, index, &fOffset);
	message.FindFloat(kColumnWidthName, index, &fWidth);
	message.FindInt32(kColumnAlignmentName, index, (int32 *)&fAlignment);
	message.FindString(kColumnAttrName, index, &fAttrName);
	message.FindInt32(kColumnAttrHashName, index, (int32 *)&fAttrHash);
	message.FindInt32(kColumnAttrTypeName, index, (int32 *)&fAttrType);
	message.FindBool(kColumnStatFieldName, index, &fStatField);
	message.FindBool(kColumnEditableName, index, &fEditable);
}
// GetAttribute
Font
AttributeMessage::GetAttribute(const char* name,
	const Font& defaultValue) const
{
	Font value(defaultValue);
	BString valueString;
	BMessage archivedFont;
	if (FindMessage(name, &archivedFont) == B_OK) {
		// find family part
		const char* family;
		const char* style;
		float size;
		if (archivedFont.FindString("family", &family) == B_OK
			&& archivedFont.FindString("style", &style) == B_OK
			&& archivedFont.FindFloat("size", &size) == B_OK) {
			font_family fontFamily;
			font_style fontStyle;
			snprintf(fontFamily, sizeof(fontFamily), "%s", family);
			snprintf(fontStyle, sizeof(fontStyle), "%s", style);

			if (strlen(family) == 0 || strlen(style) == 0)
				return value;

			value.SetFamilyAndStyle(fontFamily, fontStyle);
			if (size > 0.0f)
				value.SetSize(size);
		}
	}
	return value;
}
Exemple #3
0
status_t
AGMSBayesianSpamFilter::_GetSpamRatio(const char* stringBuffer, off_t dataSize,
	float& ratio)
{
	// Send off a scripting command to the database server, asking it to
	// evaluate the string for spaminess.  Note that it can return ENOMSG
	// when there are no words (a good indicator of spam which is pure HTML
	// if you are using plain text only tokenization), so we could use that
	// as a spam marker too.  Code copied for the reevaluate stuff below.

	BMessage scriptingMessage(B_SET_PROPERTY);
	scriptingMessage.AddSpecifier("EvaluateString");
	status_t errorCode = scriptingMessage.AddData("data", B_STRING_TYPE,
		stringBuffer, dataSize + 1, false /* fixed size */);
	if (errorCode != B_OK)
		return errorCode;
	BMessage replyMessage;
	errorCode = fMessengerToServer.SendMessage(&scriptingMessage,
		&replyMessage);
	if (errorCode != B_OK
		|| replyMessage.FindInt32("error", &errorCode) != B_OK)
		return errorCode; // Unable to read the return code.
	if (errorCode == ENOMSG && fNoWordsMeansSpam)
		ratio = fSpamCutoffRatio; // Yes, no words and that means spam.
	else if (errorCode != B_OK
		|| replyMessage.FindFloat("result", &ratio) != B_OK)
		return errorCode; // Classification failed in one of many ways.

	return errorCode;
}
void
NotificationWindow::_LoadDisplaySettings(BMessage& settings)
{
	int32 setting;
	float originalWidth = fWidth;

	if (settings.FindFloat(kWidthName, &fWidth) != B_OK)
		fWidth = kDefaultWidth;
	if (originalWidth != fWidth)
		GetLayout()->SetExplicitSize(BSize(fWidth, B_SIZE_UNSET));

	if (settings.FindInt32(kIconSizeName, &setting) != B_OK)
		fIconSize = kDefaultIconSize;
	else
		fIconSize = (icon_size)setting;

	int32 position;
	if (settings.FindInt32(kNotificationPositionName, &position) != B_OK)
		fPosition = kDefaultNotificationPosition;
	else
		fPosition = position;

	// Notify the views about the change
	appview_t::iterator aIt;
	for (aIt = fAppViews.begin(); aIt != fAppViews.end(); ++aIt) {
		AppGroupView* view = aIt->second;
		view->Invalidate();
	}
}
status_t SeqManageRosterWindow::SetConfiguration(const BMessage* config)
{
	ArpASSERT(config);
	status_t	err = SetDimensions(config, this);
	if (err != B_OK) return err;
	/* Set the columns
	 */
	BColumnListView* table = dynamic_cast<BColumnListView*>( FindView(TABLE_STR) );
	if (table) {
		BMessage	colMsg;
		for (int32 k = 0; config->FindMessage("column", k, &colMsg) == B_OK; k++) {
			const char*		colName;
			float			colW;
			bool			colVis;
			if (colMsg.FindString("name", &colName) == B_OK
					&& colMsg.FindFloat("width", &colW) == B_OK
					&& colMsg.FindBool("visible", &colVis) == B_OK) {
				BColumn*	col = col_named(colName, table);
				if (col) {
					col->SetWidth(colW);
					col->SetVisible(colVis);
				}
			}
		}
	}
	return B_OK;
}
Exemple #6
0
status_t
SoundsThemesAddon::ApplyTheme(BMessage &theme, uint32 flags)
{
	BMessage sounds;
	status_t err;
	BMediaFiles bmfs;
	BString item;
	entry_ref entry;
	BEntry ent;
	BPath path;
	const char *p;
	float gain;
	int32 index;
	char *field_name;
	type_code field_code;
	int32 field_count;
	BMessage msg;

	if (!(flags & UI_THEME_SETTINGS_SET_ALL) || !(AddonFlags() & Z_THEME_ADDON_DO_SET_ALL))
		return B_OK;
	
	err = MyMessage(theme, sounds);
	if (err)
		return err;

	bmfs.RewindRefs(BMediaFiles::B_SOUNDS);
	for (index = 0; sounds.GetInfo(B_ANY_TYPE, index,  
							GET_INFO_NAME_PTR(&field_name), 
							&field_code, 
							&field_count) == B_OK; index++) {
		if (field_code != B_MESSAGE_TYPE)
			continue;
		if (sounds.FindMessage(field_name, &msg) < B_OK)
			continue;
		/* remove old ref if any */
		if ((bmfs.GetRefFor(BMediaFiles::B_SOUNDS, field_name, &entry) >= B_OK)
				 && (entry.device >= 0))
			bmfs.RemoveRefFor(BMediaFiles::B_SOUNDS, field_name, entry);
		if (msg.FindString("sounds:file", &p) < B_OK)
			continue;
		path.SetTo(p);
		if (ent.SetTo(path.Path()) < B_OK)
			continue;
		if (ent.GetRef(&entry) < B_OK)
			continue;
		if (bmfs.SetRefFor(BMediaFiles::B_SOUNDS, field_name, entry) < B_OK)
			continue;
		if (msg.FindFloat("sounds:volume", &gain) < B_OK)
			continue;
#if defined(__ANTARES__) || defined(B_BEOS_VERSION_DANO)
		if (bmfs.SetAudioGainFor(BMediaFiles::B_SOUNDS, field_name, gain) < B_OK)
			continue;
#endif
	}

	return B_OK;
}
void
PageSetupWindow::UpdateSetupMessage()
{
    SetInt32(fSetupMsg, "xres", 300);
    SetInt32(fSetupMsg, "yres", 300);
    SetInt32(fSetupMsg, "orientation", fCurrentOrientation);

    // Save scaling factor
    float scale = atoi(fScaleControl->Text());
    if (scale <= 0.0) scale = 100.0;
    if (scale > 1000.0) scale = 1000.0;
    SetFloat(fSetupMsg, "scale", scale);

    float scaleR = 100.0 / scale;
    BMenuItem *item = fPageSizeMenu->Menu()->FindMarked();
    if (item) {
        float w, h;
        BMessage *msg = item->Message();
        msg->FindFloat("width", &w);
        msg->FindFloat("height", &h);
        BRect r(0, 0, w, h);
        if (fCurrentOrientation == PrinterDriver::LANDSCAPE_ORIENTATION)
            r.Set(0, 0, h, w);

        SetRect(fSetupMsg, "preview:paper_rect", r);
        SetRect(fSetupMsg, "paper_rect", ScaleRect(r, scaleR));
        SetString(fSetupMsg, "preview:paper_size", item->Label());

        // Save the printable_rect
        BRect margin = fMarginView->Margin();
        if (fCurrentOrientation == PrinterDriver::PORTRAIT_ORIENTATION) {
            margin.right = w - margin.right;
            margin.bottom = h - margin.bottom;
        } else {
            margin.right = h - margin.right;
            margin.bottom = w - margin.bottom;
        }
        SetRect(fSetupMsg, "preview:printable_rect", margin);
        SetRect(fSetupMsg, "printable_rect", ScaleRect(margin, scaleR));

        SetInt32(fSetupMsg, "units", fMarginView->Unit());
    }
}
Exemple #8
0
bool
TabDecorator::_SetSettings(const BMessage& settings, BRegion* updateRegion)
{
	float tabLocation;
	bool modified = false;
	for (int32 i = 0; i < fTabList.CountItems(); i++) {
		if (settings.FindFloat("tab location", i, &tabLocation) != B_OK)
			return false;
		modified |= SetTabLocation(i, tabLocation, updateRegion);
	}
	return modified;
}
Exemple #9
0
BColumn::BColumn(const BMessage &message, int32 index)
{
	if (message.FindString(kColumnTitleName, index, &fTitle) != B_OK)
		fTitle.SetTo(B_EMPTY_STRING);

	if (message.FindFloat(kColumnOffsetName, index, &fOffset) != B_OK)
		fOffset = -1.0f;

	if (message.FindFloat(kColumnWidthName, index, &fWidth) != B_OK)
		fWidth = -1.0f;

	if (message.FindInt32(kColumnAlignmentName, index, (int32*)&fAlignment)
			!= B_OK) {
		fAlignment = B_ALIGN_LEFT;
	}

	if (message.FindString(kColumnAttrName, index, &fAttrName) != B_OK)
		fAttrName = BString(B_EMPTY_STRING);

	if (message.FindInt32(kColumnAttrHashName, index, (int32*)&fAttrHash)
			!= B_OK) {
		fAttrHash = 0;
	}

	if (message.FindInt32(kColumnAttrTypeName, index, (int32*)&fAttrType)
			!= B_OK) {
		fAttrType = 0;
	}

	if (message.FindString(kColumnDisplayAsName, index, &fDisplayAs) != B_OK)
		fDisplayAs.SetTo(B_EMPTY_STRING);

	if (message.FindBool(kColumnStatFieldName, index, &fStatField) != B_OK)
		fStatField = false;

	if (message.FindBool(kColumnEditableName, index, &fEditable) != B_OK)
		fEditable = false;

}
Exemple #10
0
// constructor
MediaClip::MediaClip(const entry_ref* ref, const BMessage& archive)
	: FileBasedClip(ref),
	  fHasVideoTrack(false),
	  fHasAudioTrack(false),
	  fBounds(0, 0, -1, -1),
	  fVideoFrameCount(0),
	  fAudioFrameCount(0),
	  fVideoFPS(0.0),
	  fAudioFPS(0.0)
{
	if (archive.FindInt64("video frames", (int64*)&fVideoFrameCount) == B_OK
		&& archive.FindFloat("video fps", &fVideoFPS) == B_OK
		&& archive.FindRect("bounds", &fBounds) == B_OK)
		fHasVideoTrack = true;

	if (archive.FindInt64("audio frames", (int64*)&fAudioFrameCount) == B_OK
		&& archive.FindFloat("audio fps", &fAudioFPS) == B_OK)
		fHasAudioTrack = true;

	SetValue(PROPERTY_WIDTH, fBounds.Width() + 1);
	SetValue(PROPERTY_HEIGHT, fBounds.Height() + 1);
}
status_t
DisplayView::Load()
{
	BPath path;

	if (find_directory(B_USER_SETTINGS_DIRECTORY, &path) != B_OK)
		return B_ERROR;

	path.Append(kSettingsDirectory);

	if (create_directory(path.Path(), 0755) != B_OK) {
		BAlert* alert = new BAlert("",
			B_TRANSLATE("There was a problem saving the preferences.\n"
				"It's possible you don't have write access to the "
				"settings directory."), B_TRANSLATE("OK"), NULL, NULL,
			B_WIDTH_AS_USUAL, B_STOP_ALERT);
		alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
		(void)alert->Go();
	}

	path.Append(kDisplaySettings);

	BFile file(path.Path(), B_READ_ONLY);
	BMessage settings;
	settings.Unflatten(&file);

	char buffer[255];
	int32 setting;
	BMenuItem* item = NULL;

	float width;
	if (settings.FindFloat(kWidthName, &width) != B_OK)
		width = kDefaultWidth;
	(void)sprintf(buffer, "%.2f", width);
	fWindowWidth->SetText(buffer);

	icon_size iconSize;
	if (settings.FindInt32(kIconSizeName, &setting) != B_OK)
		iconSize = kDefaultIconSize;
	else
		iconSize = (icon_size)setting;
	if (iconSize == B_MINI_ICON)
		item = fIconSize->ItemAt(0);
	else
		item = fIconSize->ItemAt(1);
	if (item)
		item->SetMarked(true);

	return B_OK;
}
Exemple #12
0
/*static*/ void
GuiSettingsUtils::UnarchiveSplitView(const BMessage& settings,
	BSplitView* view)
{
	for (int32 i = 0; i < view->CountItems(); i++) {
		float weight;
		if (settings.FindFloat("weight", i, &weight) == B_OK)
			view->SetItemWeight(i, weight, i == view->CountItems() - 1);

		bool collapsed;
		if (settings.FindBool("collapsed", i, &collapsed) == B_OK)
			view->SetItemCollapsed(i, collapsed);
	}
}
/*!	Enable/disable refresh options according to current mode. */
void
ScreenWindow::_CheckRefreshMenu()
{
	float min, max;
	if (fScreenMode.GetRefreshLimits(fSelected, min, max) != B_OK || min == max)
		return;

	for (int32 i = fRefreshMenu->CountItems(); i-- > 0;) {
		BMenuItem* item = fRefreshMenu->ItemAt(i);
		BMessage* message = item->Message();
		float refresh;
		if (message != NULL && message->FindFloat("refresh", &refresh) == B_OK)
			item->SetEnabled(refresh >= min && refresh <= max);
	}
}
//------------------------------------------------------------------------------
void TMessageEasyFindTest::MessageEasyFindTest1()
{
	BRect r(0, 0, -1, -1);
	BPoint p(0, 0);
	BMessage msg;
	CPPUNIT_ASSERT(msg.FindRect("data") == r);
	CPPUNIT_ASSERT(msg.FindPoint("data") == p);
	CPPUNIT_ASSERT(msg.FindString("data") == NULL);
	CPPUNIT_ASSERT(msg.FindInt8("data") == 0);
	CPPUNIT_ASSERT(msg.FindInt16("data") == 0);
	CPPUNIT_ASSERT(msg.FindInt32("data") == 0);
	CPPUNIT_ASSERT(msg.FindInt64("data") == 0);
	CPPUNIT_ASSERT(msg.FindBool("data") == false);
	CPPUNIT_ASSERT(msg.FindFloat("data") == 0);
	CPPUNIT_ASSERT(msg.FindDouble("data") == 0);
}
void
NotificationWindow::_LoadDisplaySettings(bool startMonitor)
{
	BPath path;
	BMessage settings;

	if (find_directory(B_USER_SETTINGS_DIRECTORY, &path) != B_OK)
		return;

	path.Append(kSettingsDirectory);
	if (create_directory(path.Path(), 0755) == B_OK) {
		path.Append(kDisplaySettings);

		BFile file(path.Path(), B_READ_ONLY);
		settings.Unflatten(&file);
	}

	int32 setting;

	if (settings.FindFloat(kWidthName, &fWidth) != B_OK)
		fWidth = kDefaultWidth;

	if (settings.FindInt32(kIconSizeName, &setting) != B_OK)
		fIconSize = kDefaultIconSize;
	else
		fIconSize = (icon_size)setting;

	// Notify the view about the change
	views_t::iterator it;
	for (it = fViews.begin(); it != fViews.end(); ++it) {
		NotificationView* view = (*it);
		view->Invalidate();
	}

	if (startMonitor) {
		node_ref nref;
		BEntry entry(path.Path());
		entry.GetNodeRef(&nref);

		if (watch_node(&nref, B_WATCH_ALL, BMessenger(this)) != B_OK) {
			BAlert* alert = new BAlert(B_TRANSLATE("Warning"),
				B_TRANSLATE("Couldn't start display settings monitor.\n"
					"Live filter changes disabled."), B_TRANSLATE("OK"));
			alert->Go();
		}
	}
}
Exemple #16
0
status_t
Settings::Load()
{
	SetDefaults();
	
	BPath path;
	status_t status = find_directory(B_USER_SETTINGS_DIRECTORY, &path);
	if (status == B_OK)
		status = path.Append("BeScreenCapture");
	
	BFile file;
	if (status == B_OK)
		status = file.SetTo(path.Path(), B_READ_ONLY);
	
	BMessage tempMessage;	
	if (status == B_OK)	
		status = tempMessage.Unflatten(&file);
	
	if (status == B_OK) {
		// Copy the loaded fields to the real settings message
		BRect rect;
		bool boolean;
		int32 integer;
		float decimal;
		const char *string = NULL;
		if (tempMessage.FindRect(kCaptureRect, &rect) == B_OK)
			sSettings.ReplaceRect(kCaptureRect, rect);
		if (tempMessage.FindInt32(kClipDepth, &integer) == B_OK)
			sSettings.ReplaceInt32(kClipDepth, integer);
		if (tempMessage.FindFloat(kClipShrink, &decimal) == B_OK)
			sSettings.ReplaceFloat(kClipShrink, decimal);
		if (tempMessage.FindBool(kUseDirectWindow, &boolean) == B_OK)
			sSettings.ReplaceBool(kUseDirectWindow, boolean);
		if (tempMessage.FindBool(kIncludeCursor, &boolean) == B_OK)
			sSettings.ReplaceBool(kIncludeCursor, boolean);
		if (tempMessage.FindBool(kMinimize, &boolean) == B_OK)
			sSettings.ReplaceBool(kMinimize, boolean);
		if (tempMessage.FindString(kOutputFile, &string) == B_OK)
			sSettings.ReplaceString(kOutputFile, string);
		if (tempMessage.FindInt32(kThreadPriority, &integer) == B_OK)
			sSettings.ReplaceInt32(kThreadPriority, integer);	
	}	
	
	return status;
}
Exemple #17
0
void
NotificationWindow::_LoadDisplaySettings(BMessage& settings)
{
	int32 setting;

	if (settings.FindFloat(kWidthName, &fWidth) != B_OK)
		fWidth = kDefaultWidth;
	GetLayout()->SetExplicitMaxSize(BSize(fWidth, B_SIZE_UNSET));
	GetLayout()->SetExplicitMinSize(BSize(fWidth, B_SIZE_UNSET));

	if (settings.FindInt32(kIconSizeName, &setting) != B_OK)
		fIconSize = kDefaultIconSize;
	else
		fIconSize = (icon_size)setting;

	// Notify the view about the change
	views_t::iterator it;
	for (it = fViews.begin(); it != fViews.end(); ++it) {
		NotificationView* view = (*it);
		view->Invalidate();
	}
}
// Loads the application settings file from (loadMsg) and resizes the interface
// to match the previously saved settings.  Because this is a non-essential
// file, errors are ignored when loading the settings.
void
ShortcutsWindow::_LoadWindowSettings(const BMessage& loadMsg)
{
	BRect frame;
	if (loadMsg.FindRect("window frame", &frame) == B_OK) {
		// Ensure the frame does not resize below the computed minimum.
		float width = max_c(Bounds().right, frame.right - frame.left);
		float height = max_c(Bounds().bottom, frame.bottom - frame.top);
		ResizeTo(width, height);

		// Ensure the frame is not placed outside of the screen.
		BScreen screen(this);
		float left = min_c(screen.Frame().right - width, frame.left);
		float top = min_c(screen.Frame().bottom - height, frame.top);
		MoveTo(left, top);
	}

	for (int i = 0; i < fColumnListView->CountColumns(); i++) {
		CLVColumn* column = fColumnListView->ColumnAt(i);
		float columnWidth;
		if (loadMsg.FindFloat("column width", i, &columnWidth) == B_OK)
			column->SetWidth(max_c(column->Width(), columnWidth));
	}
}
Exemple #19
0
void
PageSetupWindow::_UpdateSetupMessage()
{
	SetInt32(fSetupMsg, "orientation", fCurrentOrientation);

	BMenuItem *item = fPDFCompatibilityMenu->Menu()->FindMarked();
	if (item)
		SetString(fSetupMsg, "pdf_compatibility", item->Label());

	SetInt32(fSetupMsg, "pdf_compression", fPDFCompressionSlider->Value());

	item = fPageSizeMenu->Menu()->FindMarked();
	if (item) {
		float w, h;
		BMessage *msg = item->Message();
		msg->FindFloat("width", &w);
		msg->FindFloat("height", &h);
		BRect r(0, 0, w, h);
		if (fCurrentOrientation == PrinterDriver::LANDSCAPE_ORIENTATION)
			r.Set(0, 0, h, w);

		// Save the printable_rect
		BRect margin = fMarginView->Margin();
		if (fCurrentOrientation == PrinterDriver::PORTRAIT_ORIENTATION) {
			margin.right = w - margin.right;
			margin.bottom = h - margin.bottom;
		} else {
			margin.right = h - margin.right;
			margin.bottom = w - margin.bottom;
		}

		SetRect(fSetupMsg, "paper_rect", r);
		SetRect(fSetupMsg, "printable_rect", margin);
		SetInt32(fSetupMsg, "units", fMarginView->Unit());
		SetString(fSetupMsg, "pdf_paper_size", item->Label());
	}

	BMessage fonts;
	if (fFonts->Archive(&fonts) == B_OK) {
		fSetupMsg->RemoveName("fonts");
		fSetupMsg->AddMessage("fonts", &fonts);
	}

	// advanced settings
	BString value;
	if (fAdvancedSettings.FindString("pdflib_license_key", &value) == B_OK)
		SetString(fSetupMsg, "pdflib_license_key", value);

	bool webLinks;
	if (fAdvancedSettings.FindBool("create_web_links", &webLinks) == B_OK)
		SetBool(fSetupMsg, "create_web_links", webLinks);

	float linkBorder;
	if (fAdvancedSettings.FindFloat("link_border_width", &linkBorder) == B_OK)
		SetFloat(fSetupMsg, "link_border_width", linkBorder);

	bool createBookmarks;
	if (fAdvancedSettings.FindBool("create_bookmarks", &createBookmarks) == B_OK)
		SetBool(fSetupMsg, "create_bookmarks", createBookmarks);

	if (fAdvancedSettings.FindString("bookmark_definition_file", &value) == B_OK)
		SetString(fSetupMsg, "bookmark_definition_file", value);

	bool createXrefs;
	if (fAdvancedSettings.FindBool("create_xrefs", &createXrefs) == B_OK)
		SetBool(fSetupMsg, "create_xrefs", createXrefs);

	if (fAdvancedSettings.FindString("xrefs_file", &value) == B_OK)
		SetString(fSetupMsg, "xrefs_file", value.String());

	int32 closeOption;
	if (fAdvancedSettings.FindInt32("close_option", &closeOption) == B_OK)
		SetInt32(fSetupMsg, "close_option", closeOption);
}
Exemple #20
0
void
BrowserApp::ReadyToRun()
{
	// Since we will essentially run the GUI...
	set_thread_priority(Thread(), B_DISPLAY_PRIORITY);

	BWebPage::InitializeOnce();
	BWebPage::SetCacheModel(B_WEBKIT_CACHE_MODEL_WEB_BROWSER);

	BPath path;
	if (find_directory(B_USER_SETTINGS_DIRECTORY, &path) == B_OK
		&& path.Append(kApplicationName) == B_OK
		&& create_directory(path.Path(), 0777) == B_OK) {

		BWebSettings::SetPersistentStoragePath(path.Path());
	}

	BString mainSettingsPath(kApplicationName);
	mainSettingsPath << "/Application";
	fSettings = new SettingsMessage(B_USER_SETTINGS_DIRECTORY,
		mainSettingsPath.String());
#if ENABLE_NATIVE_COOKIES
	mainSettingsPath = kApplicationName;
	mainSettingsPath << "/Cookies";
	fCookies = new SettingsMessage(B_USER_SETTINGS_DIRECTORY,
		mainSettingsPath.String());
	BMessage cookieArchive;
	cookieArchive = fCookies->GetValue("cookies", cookieArchive);
	fCookieJar = new BNetworkCookieJar(cookieArchive);
	BWebPage::SetCookieJar(fCookieJar);
#endif

	fLastWindowFrame = fSettings->GetValue("window frame", fLastWindowFrame);
	BRect defaultDownloadWindowFrame(-10, -10, 365, 265);
	BRect downloadWindowFrame = fSettings->GetValue("downloads window frame",
		defaultDownloadWindowFrame);
	BRect settingsWindowFrame = fSettings->GetValue("settings window frame",
		BRect());
	bool showDownloads = fSettings->GetValue("show downloads", false);

	fDownloadWindow = new DownloadWindow(downloadWindowFrame, showDownloads,
		fSettings);
	if (downloadWindowFrame == defaultDownloadWindowFrame) {
		// Initially put download window in lower right of screen.
		BRect screenFrame = BScreen().Frame();
		BMessage decoratorSettings;
		fDownloadWindow->GetDecoratorSettings(&decoratorSettings);
		float borderWidth = 0;
		if (decoratorSettings.FindFloat("border width", &borderWidth) != B_OK)
			borderWidth = 5;
		fDownloadWindow->MoveTo(screenFrame.Width()
			- fDownloadWindow->Frame().Width() - borderWidth,
			screenFrame.Height() - fDownloadWindow->Frame().Height()
			- borderWidth);
	}
	fSettingsWindow = new SettingsWindow(settingsWindowFrame, fSettings);

	BWebPage::SetDownloadListener(BMessenger(fDownloadWindow));

	fInitialized = true;

	int32 pagesCreated = 0;
	bool fullscreen = false;
	if (fLaunchRefsMessage) {
		_RefsReceived(fLaunchRefsMessage, &pagesCreated, &fullscreen);
		delete fLaunchRefsMessage;
		fLaunchRefsMessage = NULL;
	}
	if (pagesCreated == 0)
		_CreateNewWindow("", fullscreen);

	PostMessage(PRELOAD_BROWSING_HISTORY);
}
Exemple #21
0
status_t
DesktopSettingsPrivate::_Load()
{
    // TODO: add support for old app_server_settings file as well

    BPath basePath;
    status_t status = _GetPath(basePath);
    if (status < B_OK)
        return status;

    // read workspaces settings

    BPath path(basePath);
    path.Append("workspaces");

    BFile file;
    status = file.SetTo(path.Path(), B_READ_ONLY);
    if (status == B_OK) {
        BMessage settings;
        status = settings.Unflatten(&file);
        if (status == B_OK) {
            int32 columns;
            int32 rows;
            if (settings.FindInt32("columns", &columns) == B_OK
                    && settings.FindInt32("rows", &rows) == B_OK) {
                _ValidateWorkspacesLayout(columns, rows);
                fWorkspacesColumns = columns;
                fWorkspacesRows = rows;
            }

            int32 i = 0;
            while (i < kMaxWorkspaces && settings.FindMessage("workspace",
                    i, &fWorkspaceMessages[i]) == B_OK) {
                i++;
            }
        }
    }

    // read font settings

    path = basePath;
    path.Append("fonts");

    status = file.SetTo(path.Path(), B_READ_ONLY);
    if (status == B_OK) {
        BMessage settings;
        status = settings.Unflatten(&file);
        if (status == B_OK && gFontManager->Lock()) {
            const char* family;
            const char* style;
            float size;

            if (settings.FindString("plain family", &family) == B_OK
                    && settings.FindString("plain style", &style) == B_OK
                    && settings.FindFloat("plain size", &size) == B_OK) {
                FontStyle* fontStyle = gFontManager->GetStyle(family, style);
                fPlainFont.SetStyle(fontStyle);
                fPlainFont.SetSize(size);
            }

            if (settings.FindString("bold family", &family) == B_OK
                    && settings.FindString("bold style", &style) == B_OK
                    && settings.FindFloat("bold size", &size) == B_OK) {
                FontStyle* fontStyle = gFontManager->GetStyle(family, style);
                fBoldFont.SetStyle(fontStyle);
                fBoldFont.SetSize(size);
            }

            if (settings.FindString("fixed family", &family) == B_OK
                    && settings.FindString("fixed style", &style) == B_OK
                    && settings.FindFloat("fixed size", &size) == B_OK) {
                FontStyle* fontStyle = gFontManager->GetStyle(family, style);
                if (fontStyle != NULL && fontStyle->IsFixedWidth())
                    fFixedFont.SetStyle(fontStyle);
                fFixedFont.SetSize(size);
            }

            int32 hinting;
            if (settings.FindInt32("hinting", &hinting) == B_OK)
                gDefaultHintingMode = hinting;

            gFontManager->Unlock();
        }
    }

    // read mouse settings

    path = basePath;
    path.Append("mouse");

    status = file.SetTo(path.Path(), B_READ_ONLY);
    if (status == B_OK) {
        BMessage settings;
        status = settings.Unflatten(&file);
        if (status == B_OK) {
            int32 mode;
            if (settings.FindInt32("mode", &mode) == B_OK)
                fMouseMode = (mode_mouse)mode;

            int32 focusFollowsMouseMode;
            if (settings.FindInt32("focus follows mouse mode",
                                   &focusFollowsMouseMode) == B_OK) {
                fFocusFollowsMouseMode
                    = (mode_focus_follows_mouse)focusFollowsMouseMode;
            }

            bool acceptFirstClick;
            if (settings.FindBool("accept first click", &acceptFirstClick)
                    == B_OK) {
                fAcceptFirstClick = acceptFirstClick;
            }
        }
    }

    // read appearance settings

    path = basePath;
    path.Append("appearance");

    status = file.SetTo(path.Path(), B_READ_ONLY);
    if (status == B_OK) {
        BMessage settings;
        status = settings.Unflatten(&file);
        if (status == B_OK) {
            // menus
            float fontSize;
            if (settings.FindFloat("font size", &fontSize) == B_OK)
                fMenuInfo.font_size = fontSize;

            const char* fontFamily;
            if (settings.FindString("font family", &fontFamily) == B_OK)
                strlcpy(fMenuInfo.f_family, fontFamily, B_FONT_FAMILY_LENGTH);

            const char* fontStyle;
            if (settings.FindString("font style", &fontStyle) == B_OK)
                strlcpy(fMenuInfo.f_style, fontStyle, B_FONT_STYLE_LENGTH);

            rgb_color bgColor;
            if (settings.FindInt32("bg color", (int32*)&bgColor) == B_OK)
                fMenuInfo.background_color = bgColor;

            int32 separator;
            if (settings.FindInt32("separator", &separator) == B_OK)
                fMenuInfo.separator = separator;

            bool clickToOpen;
            if (settings.FindBool("click to open", &clickToOpen) == B_OK)
                fMenuInfo.click_to_open = clickToOpen;

            bool triggersAlwaysShown;
            if (settings.FindBool("triggers always shown", &triggersAlwaysShown)
                    == B_OK) {
                fMenuInfo.triggers_always_shown = triggersAlwaysShown;
            }

            // scrollbars
            bool proportional;
            if (settings.FindBool("proportional", &proportional) == B_OK)
                fScrollBarInfo.proportional = proportional;

            bool doubleArrows;
            if (settings.FindBool("double arrows", &doubleArrows) == B_OK)
                fScrollBarInfo.double_arrows = doubleArrows;

            int32 knob;
            if (settings.FindInt32("knob", &knob) == B_OK)
                fScrollBarInfo.knob = knob;

            int32 minKnobSize;
            if (settings.FindInt32("min knob size", &minKnobSize) == B_OK)
                fScrollBarInfo.min_knob_size = minKnobSize;

            // subpixel font rendering
            bool subpix;
            if (settings.FindBool("subpixel antialiasing", &subpix) == B_OK)
                gSubpixelAntialiasing = subpix;

            int8 averageWeight;
            if (settings.FindInt8("subpixel average weight", &averageWeight)
                    == B_OK) {
                gSubpixelAverageWeight = averageWeight;
            }

            bool subpixelOrdering;
            if (settings.FindBool("subpixel ordering", &subpixelOrdering)
                    == B_OK) {
                gSubpixelOrderingRGB = subpixelOrdering;
            }

            // colors
            for (int32 i = 0; i < kNumColors; i++) {
                char colorName[12];
                snprintf(colorName, sizeof(colorName), "color%" B_PRId32,
                         (int32)index_to_color_which(i));

                settings.FindInt32(colorName, (int32*)&fShared.colors[i]);
            }
        }
    }

    // read dragger settings

    path = basePath;
    path.Append("dragger");

    status = file.SetTo(path.Path(), B_READ_ONLY);
    if (status == B_OK) {
        BMessage settings;
        status = settings.Unflatten(&file);
        if (status == B_OK) {
            if (settings.FindBool("show", &fShowAllDraggers) != B_OK)
                fShowAllDraggers = true;
        }
    }

    return B_OK;
}
Exemple #22
0
void
DecorInfo::_Init(bool isUpdate)
{
	if (!isUpdate && InitCheck() != B_NO_INIT) {
		// TODO: remove after validation
		fprintf(stderr, "DecorInfo::_Init()\tImproper init state\n");
		return;
	}

	BEntry entry;

	if (fPath == "Default") {
		if (isUpdate) {
			// should never happen
			fprintf(stderr, "DecorInfo::_Init(true)\tBUG BUG updating default"
				"decorator!?!?!\n");
			return;
		}

		fAuthors = "DarkWyrm, Stephan Aßmus, Clemens Zeidler, Ingo Weinhold";
		fLongDescription = fShortDescription;
		fLicenseURL = "http://";
		fLicenseName = "MIT";
		fSupportURL = "http://www.haiku-os.org/";
		fVersion = 0.5;
		fInitStatus = B_OK;

		fName = gSystemCatalog.GetString(B_TRANSLATE_MARK("Default"),
			B_TRANSLATION_CONTEXT);
		fShortDescription = gSystemCatalog.GetString(B_TRANSLATE_MARK(
				"Default Haiku window decorator."),
			B_TRANSLATION_CONTEXT);

		// The following is to get the modification time of the app_server
		// and, thusly, the Default decorator...
		// If you can make it more simple, please do!
		BPath path;
		find_directory(B_SYSTEM_SERVERS_DIRECTORY, &path);
		path.Append("app_server");
		entry.SetTo(path.Path(), true);
		if (!entry.Exists()) {
			fprintf(stderr, "Server MIA the world has become its slave! "
				"Call the CIA!\n");
			return;
		}

		entry.GetModificationTime(&fModificationTime);
		return;
	}

	// Is a file system object...

	entry.SetTo(&fRef, true);	// follow link
	if (entry.InitCheck() != B_OK) {
		fInitStatus = entry.InitCheck();
		return;
	}

	if (!entry.Exists()) {
		if (isUpdate) {
			fprintf(stderr, "DecorInfo::_Init()\tERROR: decorator deleted"
					" after CheckForChanges() found it!\n");
			fprintf(stderr, "DecorInfo::_Init()\tERROR: DecorInfo will "
					"Unset\n");
			Unset();
		}
		return;
	}

	// update fRef to match file system object
	entry.GetRef(&fRef);
	entry.GetModificationTime(&fModificationTime);

	BResources resources(&fRef);
	if (resources.InitCheck() != B_OK) {
		fprintf(stderr, "DecorInfo::_Init()\t BResource InitCheck() failure\n");
		return;
	}

	size_t infoSize = 0;
	const void* infoData = resources.LoadResource(B_MESSAGE_TYPE,
		"be:decor:info", &infoSize);
	BMessage infoMessage;

	if (infoData == NULL || infoSize == 0
		|| infoMessage.Unflatten((const char*)infoData) != B_OK) {
		fprintf(stderr, "DecorInfo::_init()\tNo extended information found for"
			" \"%s\"\n", fRef.name);
	} else {
		infoMessage.FindString("name", &fName);
		infoMessage.FindString("authors", &fAuthors);
		infoMessage.FindString("short_descr", &fShortDescription);
		infoMessage.FindString("long_descr", &fLongDescription);
		infoMessage.FindString("lic_url", &fLicenseURL);
		infoMessage.FindString("lic_name", &fLicenseName);
		infoMessage.FindString("support_url", &fSupportURL);
		infoMessage.FindFloat ("version", &fVersion);
	}

	fInitStatus = B_OK;
	fName = fRef.name;
}
Exemple #23
0
WorkspacesWindow::WorkspacesWindow(WorkspacesSettings *settings)
	:
	BWindow(settings->WindowFrame(), B_TRANSLATE_SYSTEM_NAME("Workspaces"),
		B_TITLED_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL,
		B_AVOID_FRONT | B_WILL_ACCEPT_FIRST_CLICK | B_CLOSE_ON_ESCAPE,
		B_ALL_WORKSPACES),
	fSettings(settings),
	fSwitchOnWheel(false)
{
	// Turn window decor on to grab decor widths.
	BMessage windowSettings;
	float borderWidth = 0;

	SetLook(B_TITLED_WINDOW_LOOK);
	if (GetDecoratorSettings(&windowSettings) == B_OK) {
		BRect tabFrame = windowSettings.FindRect("tab frame");
		borderWidth = windowSettings.FindFloat("border width");
		fTabHeight = tabFrame.Height();
		fBorderWidth = borderWidth;
	}

	if (!fSettings->SettingsLoaded()) {
		// No settings, compute a reasonable default frame.
		// We aim for previews at 10% of actual screen size, and matching the
		// aspect ratio. We then scale that down, until it fits the screen.
		// Finally, we put the window on the bottom right of the screen so the
		// auto-raise mode can be used.

		BScreen screen;

		float screenWidth = screen.Frame().Width();
		float screenHeight = screen.Frame().Height();
		float aspectRatio = screenWidth / screenHeight;

		uint32 columns, rows;
		BPrivate::get_workspaces_layout(&columns, &rows);

		// default size of ~1/10 of screen width
		float workspaceWidth = screenWidth / 10;
		float workspaceHeight = workspaceWidth / aspectRatio;

		float width = floor(workspaceWidth * columns);
		float height = floor(workspaceHeight * rows);

		// If you have too many workspaces to fit on the screen, shrink until
		// they fit.
		while (width + 2 * borderWidth > screenWidth
				|| height + 2 * borderWidth + GetTabHeight() > screenHeight) {
			width = floor(0.95 * width);
			height = floor(0.95 * height);
		}

		BRect frame = fSettings->ScreenFrame();
		frame.OffsetBy(-2.0 * borderWidth, -2.0 * borderWidth);
		frame.left = frame.right - width;
		frame.top = frame.bottom - height;
		ResizeTo(frame.Width(), frame.Height());

		// Put it in bottom corner by default.
		MoveTo(screenWidth - frame.Width() - borderWidth,
			screenHeight - frame.Height() - borderWidth);

		fSettings->SetWindowFrame(frame);
	}

	if (!fSettings->HasBorder())
		SetLook(B_NO_BORDER_WINDOW_LOOK);
	else if (!fSettings->HasTitle())
		SetLook(B_MODAL_WINDOW_LOOK);

	AddChild(new WorkspacesView(Bounds()));

	if (fSettings->AlwaysOnTop())
		SetFeel(B_FLOATING_ALL_WINDOW_FEEL);
	else
		SetAutoRaise(fSettings->AutoRaising());

	SetSwitchOnWheel(fSettings->SwitchOnWheel());
}
Exemple #24
0
status_t
TMailApp::LoadSettings()
{
	BMailSettings accountSettings;
	fDefaultAccount = accountSettings.DefaultOutboundAccount();

	BPath path;
	status_t status = GetSettingsPath(path);
	if (status != B_OK)
		return status;

	path.Append("BeMail Settings");

	BFile file;
	status = file.SetTo(path.Path(), B_READ_ONLY);
	if (status != B_OK)
		return LoadOldSettings();

	BMessage settings;
	status = settings.Unflatten(&file);
	if (status < B_OK || settings.what != 'BeMl') {
		// the current settings are corrupted, try old ones
		return LoadOldSettings();
	}

	BRect rect;
	if (settings.FindRect("MailWindowSize", &rect) == B_OK)
		fMailWindowFrame = rect;

	int32 int32Value;
//	if (settings.FindInt32("ExperienceLevel", &int32Value) == B_OK)
//		level = int32Value;

	const char *fontFamily;
	if (settings.FindString("FontFamily", &fontFamily) == B_OK) {
		const char *fontStyle;
		if (settings.FindString("FontStyle", &fontStyle) == B_OK) {
			float size;
			if (settings.FindFloat("FontSize", &size) == B_OK) {
				if (size >= 7)
					fContentFont.SetSize(size);

				if (fontFamily[0] && fontStyle[0]) {
					fContentFont.SetFamilyAndStyle(fontFamily[0] ? fontFamily : NULL,
						fontStyle[0] ? fontStyle : NULL);
				}
			}
		}
	}

	if (settings.FindRect("SignatureWindowSize", &rect) == B_OK)
		fSignatureWindowFrame = rect;

	bool boolValue;
	if (settings.FindBool("WordWrapMode", &boolValue) == B_OK)
		fWrapMode = boolValue;

	BPoint point;
	if (settings.FindPoint("PreferencesWindowLocation", &point) == B_OK)
		fPrefsWindowPos = point;

	if (settings.FindBool("AutoMarkRead", &boolValue) == B_OK)
		fAutoMarkRead = boolValue;

	const char *string;
	if (settings.FindString("SignatureText", &string) == B_OK) {
		free(fSignature);
		fSignature = strdup(string);
	}

	if (settings.FindInt32("CharacterSet", &int32Value) == B_OK)
		fMailCharacterSet = int32Value;
	if (fMailCharacterSet != B_MAIL_UTF8_CONVERSION
		&& fMailCharacterSet != B_MAIL_US_ASCII_CONVERSION
		&& BCharacterSetRoster::GetCharacterSetByConversionID(fMailCharacterSet) == NULL)
		fMailCharacterSet = B_MS_WINDOWS_CONVERSION;

	if (settings.FindString("FindString", &string) == B_OK)
		FindWindow::SetFindString(string);

	int8 int8Value;
	if (settings.FindInt8("ShowButtonBar", &int8Value) == B_OK)
		fShowToolBar = int8Value;

	if (settings.FindInt32("UseAccountFrom", &int32Value) == B_OK)
		fUseAccountFrom = int32Value;
	if (fUseAccountFrom < ACCOUNT_USE_DEFAULT
		|| fUseAccountFrom > ACCOUNT_FROM_MAIL)
		fUseAccountFrom = ACCOUNT_USE_DEFAULT;

	if (settings.FindBool("ColoredQuotes", &boolValue) == B_OK)
		fColoredQuotes = boolValue;

	if (settings.FindString("ReplyPreamble", &string) == B_OK) {
		free(fReplyPreamble);
		fReplyPreamble = strdup(string);
	}

	if (settings.FindBool("AttachAttributes", &boolValue) == B_OK)
		fAttachAttributes = boolValue;

	if (settings.FindBool("WarnAboutUnencodableCharacters", &boolValue) == B_OK)
		fWarnAboutUnencodableCharacters = boolValue;

	if (settings.FindBool("StartWithSpellCheck", &boolValue) == B_OK)
		fStartWithSpellCheckOn = boolValue;

	return B_OK;
}
status_t
PoorManWindow::ReadSettings()
{
	BPath p;
	BFile f;
	BMessage m;
	
	if (find_directory(B_USER_SETTINGS_DIRECTORY, &p) != B_OK)
		return B_ERROR;
	p.Append(STR_SETTINGS_FILE_NAME);
	
	f.SetTo(p.Path(), B_READ_ONLY);
	if (f.InitCheck() != B_OK)
		return B_ERROR;
	
	if (m.Unflatten(&f) != B_OK)
		return B_ERROR;
	
	if (MSG_PREF_FILE != m.what)
		return B_ERROR;
	
	//site tab
	if (m.FindString("fWebDirectory", &fWebDirectory) != B_OK)
		fWebDirectory.SetTo(STR_DEFAULT_WEB_DIRECTORY);
	if (m.FindString("fIndexFileName", &fIndexFileName) != B_OK)
		fIndexFileName.SetTo("index.html");
	if (m.FindBool("fDirListFlag", &fDirListFlag) != B_OK)
		fDirListFlag = false;
	
	//logging tab
	if (m.FindBool("fLogConsoleFlag", &fLogConsoleFlag) != B_OK)
		fLogConsoleFlag = true;
	if (m.FindBool("fLogFileFlag", &fLogFileFlag) != B_OK)
		fLogFileFlag = false;
	if (m.FindString("fLogPath", &fLogPath) != B_OK)
		fLogPath.SetTo("");
	
	//advance tab
	if (m.FindInt16("fMaxConnections", &fMaxConnections) != B_OK)
		fMaxConnections = (int16)32;
	
	//windows' position and size
	if (m.FindRect("frame", &fFrame) != B_OK)
		fFrame.Set(82.0f, 30.0f, 400.0f, 350.0f);
	if (m.FindRect("fSetwindowFrame", &fSetwindowFrame) != B_OK)
		fSetwindowFrame.Set(112.0f, 60.0f, 492.0f, 340.0f);
	if (m.FindBool("fIsZoomed", &fIsZoomed) != B_OK)
		fIsZoomed = true;
	if (m.FindFloat("fLastWidth", &fLastWidth) != B_OK)
		fLastWidth = 318.0f;
	if (m.FindFloat("fLastHeight", &fLastHeight) != B_OK)
		fLastHeight = 320.0f;
	
	fIsZoomed?ResizeTo(fLastWidth, fLastHeight):ResizeTo(318, 53);
	MoveTo(fFrame.left, fFrame.top);
	
	fLogFile = new BFile(fLogPath.String(), B_CREATE_FILE | B_WRITE_ONLY
		| B_OPEN_AT_END);
	if (fLogFile->InitCheck() != B_OK) {
		fLogFileFlag = false;
		//log it to console, "log to file unavailable."
		return B_OK;
	}
	
	SetDirLabel(fWebDirectory.String());
	
	return B_OK;
}
Exemple #26
0
void
TBarApp::InitSettings()
{
	desk_settings settings;
	settings.vertical = true;
	settings.left = false;
	settings.top = true;
	settings.ampmMode = true;
	settings.showTime = true;
	settings.state = kExpandoState;
	settings.width = 0;
	settings.switcherLoc = BPoint(5000, 5000);
	settings.recentAppsCount = 10;
	settings.recentDocsCount = 10;
	settings.timeShowSeconds = false;
	settings.recentFoldersCount = 10;
	settings.alwaysOnTop = false;
	settings.timeFullDate = false;
	settings.trackerAlwaysFirst = false;
	settings.sortRunningApps = false;
	settings.superExpando = false;
	settings.expandNewTeams = false;
	settings.autoRaise = false;
	settings.autoHide = false;
	settings.recentAppsEnabled = true;
	settings.recentDocsEnabled = true;
	settings.recentFoldersEnabled = true;

	BPath dirPath;
	const char* settingsFileName = "Deskbar_settings";

	find_directory(B_USER_DESKBAR_DIRECTORY, &dirPath, true);
	// just make it

	if (find_directory (B_USER_SETTINGS_DIRECTORY, &dirPath, true) == B_OK) {
		BPath filePath = dirPath;
		filePath.Append(settingsFileName);
		fSettingsFile = new BFile(filePath.Path(), O_RDWR);
		if (fSettingsFile->InitCheck() != B_OK) {
			BDirectory theDir(dirPath.Path());
			if (theDir.InitCheck() == B_OK)
				theDir.CreateFile(settingsFileName, fSettingsFile);
		}

		BMessage storedSettings;
		if (fSettingsFile->InitCheck() == B_OK
			&& storedSettings.Unflatten(fSettingsFile) == B_OK) {
			storedSettings.FindBool("vertical", &settings.vertical);
			storedSettings.FindBool("left", &settings.left);
			storedSettings.FindBool("top", &settings.top);
			storedSettings.FindBool("ampmMode", &settings.ampmMode);

			storedSettings.FindInt32("state", (int32*)&settings.state);
			storedSettings.FindFloat("width", &settings.width);
			storedSettings.FindBool("showTime", &settings.showTime);
			storedSettings.FindPoint("switcherLoc", &settings.switcherLoc);
			storedSettings.FindInt32("recentAppsCount",
				&settings.recentAppsCount);
			storedSettings.FindInt32("recentDocsCount",
				&settings.recentDocsCount);
			storedSettings.FindBool("timeShowSeconds",
				&settings.timeShowSeconds);
			storedSettings.FindInt32("recentFoldersCount",
				&settings.recentFoldersCount);
			storedSettings.FindBool("alwaysOnTop", &settings.alwaysOnTop);
			storedSettings.FindBool("timeFullDate", &settings.timeFullDate);
			storedSettings.FindBool("trackerAlwaysFirst",
				&settings.trackerAlwaysFirst);
			storedSettings.FindBool("sortRunningApps",
				&settings.sortRunningApps);
			storedSettings.FindBool("superExpando", &settings.superExpando);
			storedSettings.FindBool("expandNewTeams", &settings.expandNewTeams);
			storedSettings.FindBool("autoRaise", &settings.autoRaise);
			storedSettings.FindBool("autoHide", &settings.autoHide);
			storedSettings.FindBool("recentAppsEnabled",
				&settings.recentAppsEnabled);
			storedSettings.FindBool("recentDocsEnabled",
				&settings.recentDocsEnabled);
			storedSettings.FindBool("recentFoldersEnabled",
				&settings.recentFoldersEnabled);
		}
	}

	fSettings = settings;
}
Exemple #27
0
status_t
AGMSBayesianSpamFilter::ProcessMailMessage (
	BPositionIO** io_message,
	BEntry* io_entry,
	BMessage* io_headers,
	BPath* io_folder,
	const char* io_uid)
{
	ssize_t		 amountRead;
	attr_info	 attributeInfo;
	const char	*classificationString;
	off_t		 dataSize;
	BPositionIO	*dataStreamPntr = *io_message;
	status_t	 errorCode = B_OK;
	int32        headerLength;
	BString      headerString;
	BString		 newSubjectString;
	BNode        nodeForOutputFile;
	bool		 nodeForOutputFileInitialised = false;
	const char	*oldSubjectStringPntr;
	char         percentageString [30];
	BMessage	 replyMessage;
	BMessage	 scriptingMessage;
	team_id		 serverTeam;
	float		 spamRatio;
	char		*stringBuffer = NULL;
	char         tempChar;
	status_t     tempErrorCode;
	const char  *tokenizeModeStringPntr;

	// Set up a BNode to the final output file so that we can write custom
	// attributes to it.  Non-custom attributes are stored separately in
	// io_headers.

	if (io_entry != NULL && B_OK == nodeForOutputFile.SetTo (io_entry))
		nodeForOutputFileInitialised = true;

	// Get a connection to the spam database server.  Launch if needed, should
	// only need it once, unless another e-mail thread shuts down the server
	// inbetween messages.  This code used to be in InitCheck, but apparently
	// that isn't called.

	printf("Checking for Spam Server.\n");
	if (fLaunchAttemptCount == 0 || !fMessengerToServer.IsValid ()) {
		if (fLaunchAttemptCount > 3)
			goto ErrorExit; // Don't try to start the server too many times.
		fLaunchAttemptCount++;

		// Make sure the server is running.
		if (!be_roster->IsRunning (kServerSignature)) {
			errorCode = be_roster->Launch (kServerSignature);
			if (errorCode != B_OK) {
				BPath path;
				entry_ref ref;
				directory_which places[] = {B_COMMON_BIN_DIRECTORY,B_BEOS_BIN_DIRECTORY};
				for (int32 i = 0; i < 2; i++) {
					find_directory(places[i],&path);
					path.Append("spamdbm");
					if (!BEntry(path.Path()).Exists())
						continue;
					get_ref_for_path(path.Path(),&ref);
					if ((errorCode =  be_roster->Launch (&ref)) == B_OK)
						break;
				}
				if (errorCode != B_OK)
					goto ErrorExit;
			}
		}

		// Set up the messenger to the database server.
		serverTeam = be_roster->TeamFor (kServerSignature);
		if (serverTeam < 0)
			goto ErrorExit;
		fMessengerToServer =
			BMessenger (kServerSignature, serverTeam, &errorCode);
		if (!fMessengerToServer.IsValid ())
			goto ErrorExit;

		// Check if the server is running in headers only mode.  If so, we only
		// need to download the header rather than the entire message.
		scriptingMessage.MakeEmpty ();
		scriptingMessage.what = B_GET_PROPERTY;
		scriptingMessage.AddSpecifier ("TokenizeMode");
		replyMessage.MakeEmpty ();
		if ((errorCode = fMessengerToServer.SendMessage (&scriptingMessage,
			&replyMessage)) != B_OK)
			goto ErrorExit;
		if ((errorCode = replyMessage.FindInt32 ("error", &tempErrorCode))
			!= B_OK)
			goto ErrorExit;
		if ((errorCode = tempErrorCode) != B_OK)
			goto ErrorExit;
		if ((errorCode = replyMessage.FindString ("result",
			&tokenizeModeStringPntr)) != B_OK)
			goto ErrorExit;
		fHeaderOnly = (tokenizeModeStringPntr != NULL
			&& strcmp (tokenizeModeStringPntr, "JustHeader") == 0);
	}

	// See if the message has already been classified.  Happens for messages
	// which are partially downloaded when you have auto-training on.  Could
	// untrain the partial part before training on the complete message, but we
	// don't know how big it was, so instead just ignore the message.

	if (nodeForOutputFileInitialised) {
		if (nodeForOutputFile.GetAttrInfo ("MAIL:classification",
			&attributeInfo) == B_OK)
			return B_OK;
	}

	// Copy the message to a string so that we can pass it to the spam database
	// (the even messier alternative is a temporary file).  Do it in a fashion
	// which allows NUL bytes in the string.  This method of course limits the
	// message size to a few hundred megabytes.  If we're using header mode,
	// only read the header rather than the full message.

	if (fHeaderOnly) {
		// Read just the header, it ends with an empty CRLF line.
		dataStreamPntr->Seek (0, SEEK_SET);
		while ((errorCode = dataStreamPntr->Read (&tempChar, 1)) == 1) {
			headerString.Append (tempChar, 1);
			headerLength = headerString.Length();
			if (headerLength >= 4 && strcmp (headerString.String() +
				headerLength - 4, "\r\n\r\n") == 0)
				break;
		}
		if (errorCode < 0)
			goto ErrorExit;

		dataSize = headerString.Length();
		stringBuffer = new char [dataSize + 1];
		memcpy (stringBuffer, headerString.String(), dataSize);
		stringBuffer[dataSize] = 0;
	} else {
		// Read the whole file.  The seek to the end may take a while since
		// that triggers downloading of the entire message (and caching in a
		// slave file - see the MessageIO class).
		dataSize = dataStreamPntr->Seek (0, SEEK_END);
		if (dataSize <= 0)
			goto ErrorExit;

		try {
			stringBuffer = new char [dataSize + 1];
		} catch (...) {
			errorCode = ENOMEM;
			goto ErrorExit;
		}

		dataStreamPntr->Seek (0, SEEK_SET);
		amountRead = dataStreamPntr->Read (stringBuffer, dataSize);
		if (amountRead != dataSize)
			goto ErrorExit;
		stringBuffer[dataSize] = 0; // Add an end of string NUL, just in case.
	}

	// Send off a scripting command to the database server, asking it to
	// evaluate the string for spaminess.  Note that it can return ENOMSG
	// when there are no words (a good indicator of spam which is pure HTML
	// if you are using plain text only tokenization), so we could use that
	// as a spam marker too.  Code copied for the reevaluate stuff below.

	scriptingMessage.MakeEmpty ();
	scriptingMessage.what = B_SET_PROPERTY;
	scriptingMessage.AddSpecifier ("EvaluateString");
	errorCode = scriptingMessage.AddData ("data", B_STRING_TYPE,
		stringBuffer, dataSize + 1, false /* fixed size */);
	if (errorCode != B_OK)
		goto ErrorExit;
	replyMessage.MakeEmpty ();
	errorCode = fMessengerToServer.SendMessage (&scriptingMessage,
		&replyMessage);
	if (errorCode != B_OK
		|| replyMessage.FindInt32 ("error", &errorCode) != B_OK)
		goto ErrorExit; // Unable to read the return code.
	if (errorCode == ENOMSG && fNoWordsMeansSpam)
		spamRatio = fSpamCutoffRatio; // Yes, no words and that means spam.
	else if (errorCode != B_OK
		|| replyMessage.FindFloat ("result", &spamRatio) != B_OK)
		goto ErrorExit; // Classification failed in one of many ways.

	// If we are auto-training, feed back the message to the server as a
	// training example (don't train if it is uncertain).  Also redo the
	// evaluation after training.

	if (fAutoTraining) {
		if (spamRatio >= fSpamCutoffRatio || spamRatio < fGenuineCutoffRatio) {
			scriptingMessage.MakeEmpty ();
			scriptingMessage.what = B_SET_PROPERTY;
			scriptingMessage.AddSpecifier ((spamRatio >= fSpamCutoffRatio)
				? "SpamString" : "GenuineString");
			errorCode = scriptingMessage.AddData ("data", B_STRING_TYPE,
				stringBuffer, dataSize + 1, false /* fixed size */);
			if (errorCode != B_OK)
				goto ErrorExit;
			replyMessage.MakeEmpty ();
			errorCode = fMessengerToServer.SendMessage (&scriptingMessage,
				&replyMessage);
			if (errorCode != B_OK
				|| replyMessage.FindInt32 ("error", &errorCode) != B_OK)
				goto ErrorExit; // Unable to read the return code.
			if (errorCode != B_OK)
				goto ErrorExit; // Failed to set a good example.
		}

		// Note the kind of example made so that the user doesn't reclassify
		// the message twice (the spam server looks for this attribute).

		classificationString =
			(spamRatio >= fSpamCutoffRatio)
			? "Spam"
			: ((spamRatio < fGenuineCutoffRatio) ? "Genuine" : "Uncertain");
		if (nodeForOutputFileInitialised)
			nodeForOutputFile.WriteAttr ("MAIL:classification", B_STRING_TYPE,
				0 /* offset */, classificationString,
				strlen (classificationString) + 1);

		// Now that the database has changed due to training, recompute the
		// spam ratio.  Hopefully it will have become more extreme in the
		// correct direction (not switched from being spam to being genuine).
		// Code copied from above.

		scriptingMessage.MakeEmpty ();
		scriptingMessage.what = B_SET_PROPERTY;
		scriptingMessage.AddSpecifier ("EvaluateString");
		errorCode = scriptingMessage.AddData ("data", B_STRING_TYPE,
			stringBuffer, dataSize + 1, false /* fixed size */);
		if (errorCode != B_OK)
			goto ErrorExit;
		replyMessage.MakeEmpty ();
		errorCode = fMessengerToServer.SendMessage (&scriptingMessage,
			&replyMessage);
		if (errorCode != B_OK
			|| replyMessage.FindInt32 ("error", &errorCode) != B_OK)
			goto ErrorExit; // Unable to read the return code.
		if (errorCode == ENOMSG && fNoWordsMeansSpam)
			spamRatio = fSpamCutoffRatio; // Yes, no words and that means spam.
		else if (errorCode != B_OK
			|| replyMessage.FindFloat ("result", &spamRatio) != B_OK)
			goto ErrorExit; // Classification failed in one of many ways.
	}

	// Store the spam ratio in an attribute called MAIL:ratio_spam,
	// attached to the eventual output file.

	if (nodeForOutputFileInitialised)
		nodeForOutputFile.WriteAttr ("MAIL:ratio_spam",
			B_FLOAT_TYPE, 0 /* offset */, &spamRatio, sizeof (spamRatio));

	// Also add it to the subject, if requested.

	if (fAddSpamToSubject
		&& spamRatio >= fSpamCutoffRatio
		&& io_headers->FindString ("Subject", &oldSubjectStringPntr) == B_OK) {
		newSubjectString.SetTo ("[Spam ");
		sprintf (percentageString, "%05.2f", spamRatio * 100.0);
		newSubjectString << percentageString << "%] ";
		newSubjectString << oldSubjectStringPntr;
		io_headers->ReplaceString ("Subject", newSubjectString);
	}

	// Beep using different sounds for spam and genuine, as Jeremy Friesner
	// nudged me to get around to implementing.  And add uncertain to that, as
	// "BiPolar" suggested.  If the user doesn't want to hear the sound, they
	// can turn it off in the system sound preferences.

	if (spamRatio >= fSpamCutoffRatio) {
		system_beep (kAGMSBayesBeepSpamName);
	} else if (spamRatio < fGenuineCutoffRatio) {
		system_beep (kAGMSBayesBeepGenuineName);
	} else {
		system_beep (kAGMSBayesBeepUncertainName);
	}

	return B_OK;

ErrorExit:
	fprintf (stderr, "Error exit from "
		"SpamFilter::ProcessMailMessage, code maybe %ld (%s).\n",
		errorCode, strerror (errorCode));
	delete [] stringBuffer;
	return B_OK; // Not MD_ERROR so the message doesn't get left on server.
}
Exemple #28
0
void
BrowserApp::ReadyToRun()
{
	// Since we will essentially run the GUI...
	set_thread_priority(Thread(), B_DISPLAY_PRIORITY);

	BWebPage::InitializeOnce();
	BWebPage::SetCacheModel(B_WEBKIT_CACHE_MODEL_WEB_BROWSER);

	BPath path;
	if (find_directory(B_USER_SETTINGS_DIRECTORY, &path) == B_OK
		&& path.Append(kApplicationName) == B_OK
		&& create_directory(path.Path(), 0777) == B_OK) {

		BWebSettings::SetPersistentStoragePath(path.Path());
	}

	BString mainSettingsPath(kApplicationName);
	mainSettingsPath << "/Application";
	fSettings = new SettingsMessage(B_USER_SETTINGS_DIRECTORY,
		mainSettingsPath.String());

	fLastWindowFrame = fSettings->GetValue("window frame", fLastWindowFrame);
	BRect defaultDownloadWindowFrame(-10, -10, 365, 265);
	BRect downloadWindowFrame = fSettings->GetValue("downloads window frame",
		defaultDownloadWindowFrame);
	BRect settingsWindowFrame = fSettings->GetValue("settings window frame",
		BRect());
	BRect consoleWindowFrame = fSettings->GetValue("console window frame",
		BRect(50, 50, 400, 300));
	BRect cookieWindowFrame = fSettings->GetValue("cookie window frame",
		BRect(50, 50, 400, 300));
	bool showDownloads = fSettings->GetValue("show downloads", false);

	fDownloadWindow = new DownloadWindow(downloadWindowFrame, showDownloads,
		fSettings);
	if (downloadWindowFrame == defaultDownloadWindowFrame) {
		// Initially put download window in lower right of screen.
		BRect screenFrame = BScreen().Frame();
		BMessage decoratorSettings;
		fDownloadWindow->GetDecoratorSettings(&decoratorSettings);
		float borderWidth = 0;
		if (decoratorSettings.FindFloat("border width", &borderWidth) != B_OK)
			borderWidth = 5;
		fDownloadWindow->MoveTo(screenFrame.Width()
			- fDownloadWindow->Frame().Width() - borderWidth,
			screenFrame.Height() - fDownloadWindow->Frame().Height()
			- borderWidth);
	}
	fSettingsWindow = new SettingsWindow(settingsWindowFrame, fSettings);

	BWebPage::SetDownloadListener(BMessenger(fDownloadWindow));

	fConsoleWindow = new ConsoleWindow(consoleWindowFrame);
	fCookieWindow = new CookieWindow(cookieWindowFrame, fContext->GetCookieJar());

	fInitialized = true;

	int32 pagesCreated = 0;
	bool fullscreen = false;
	if (fLaunchRefsMessage) {
		_RefsReceived(fLaunchRefsMessage, &pagesCreated, &fullscreen);
		delete fLaunchRefsMessage;
		fLaunchRefsMessage = NULL;
	}

	// If no refs led to a new open page, open new session if set
	if (fSession->InitCheck() == B_OK && pagesCreated == 0) {
		const char* kSettingsKeyStartUpPolicy = "start up policy";
		uint32 fStartUpPolicy = fSettings->GetValue(kSettingsKeyStartUpPolicy,
			(uint32)ResumePriorSession);
		if (fStartUpPolicy == StartNewSession) {
			PostMessage(NEW_WINDOW);
		} else {
			// otherwise, restore previous session
			BMessage archivedWindow;
			for (int i = 0; fSession->FindMessage("window", i, &archivedWindow)
				== B_OK; i++) {
				BRect frame = archivedWindow.FindRect("window frame");
				BString url;
				archivedWindow.FindString("tab", 0, &url);
				BrowserWindow* window = new(std::nothrow) BrowserWindow(frame,
					fSettings, url, fContext);

				if (window != NULL) {
					window->Show();
					pagesCreated++;

					for (int j = 1; archivedWindow.FindString("tab", j, &url)
						== B_OK; j++) {
						printf("Create %d:%d\n", i, j);
						_CreateNewTab(window, url, false);
						pagesCreated++;
					}
				}
			}
		}
	}

	// If previous session did not contain any window, create a new empty one.
	if (pagesCreated == 0)
		_CreateNewWindow("", fullscreen);

	PostMessage(PRELOAD_BROWSING_HISTORY);
}
FileTypesWindow::FileTypesWindow(const BMessage& settings)
	:
	BWindow(_Frame(settings), B_TRANSLATE_SYSTEM_NAME("FileTypes"),
		B_TITLED_WINDOW, B_NOT_ZOOMABLE | B_ASYNCHRONOUS_CONTROLS
		| B_AUTO_UPDATE_SIZE_LIMITS),
	fNewTypeWindow(NULL)
{
	bool showIcons;
	bool showRule;
	if (settings.FindBool("show_icons", &showIcons) != B_OK)
		showIcons = true;
	if (settings.FindBool("show_rule", &showRule) != B_OK)
		showRule = false;

	float padding = be_control_look->DefaultItemSpacing();
	BAlignment labelAlignment = be_control_look->DefaultLabelAlignment();
	BAlignment fullAlignment(B_ALIGN_USE_FULL_WIDTH, B_ALIGN_USE_FULL_HEIGHT);

	// add the menu
	BMenuBar* menuBar = new BMenuBar("");

	BMenu* menu = new BMenu(B_TRANSLATE("File"));
	BMenuItem* item = new BMenuItem(
		B_TRANSLATE("New resource file" B_UTF8_ELLIPSIS), NULL, 'N',
		B_COMMAND_KEY);
	item->SetEnabled(false);
	menu->AddItem(item);

	BMenu* recentsMenu = BRecentFilesList::NewFileListMenu(
		B_TRANSLATE("Open" B_UTF8_ELLIPSIS), NULL, NULL,
		be_app, 10, false, NULL, kSignature);
	item = new BMenuItem(recentsMenu, new BMessage(kMsgOpenFilePanel));
	item->SetShortcut('O', B_COMMAND_KEY);
	menu->AddItem(item);

	menu->AddItem(new BMenuItem(
		B_TRANSLATE("Application types" B_UTF8_ELLIPSIS),
		new BMessage(kMsgOpenApplicationTypesWindow)));
	menu->AddSeparatorItem();

	menu->AddItem(new BMenuItem(B_TRANSLATE("Quit"),
		new BMessage(B_QUIT_REQUESTED), 'Q', B_COMMAND_KEY));
	menu->SetTargetForItems(be_app);
	menuBar->AddItem(menu);

	menu = new BMenu(B_TRANSLATE("Settings"));
	item = new BMenuItem(B_TRANSLATE("Show icons in list"),
		new BMessage(kMsgToggleIcons));
	item->SetMarked(showIcons);
	item->SetTarget(this);
	menu->AddItem(item);

	item = new BMenuItem(B_TRANSLATE("Show recognition rule"),
		new BMessage(kMsgToggleRule));
	item->SetMarked(showRule);
	item->SetTarget(this);
	menu->AddItem(item);
	menuBar->AddItem(menu);
	menuBar->SetExplicitAlignment(BAlignment(B_ALIGN_LEFT, B_ALIGN_TOP));

	// MIME Types list
	BButton* addTypeButton = new BButton("add",
		B_TRANSLATE("Add" B_UTF8_ELLIPSIS), new BMessage(kMsgAddType));

	fRemoveTypeButton = new BButton("remove", B_TRANSLATE("Remove"),
		new BMessage(kMsgRemoveType) );

	fTypeListView = new MimeTypeListView("typeview", NULL, showIcons, false);
	fTypeListView->SetSelectionMessage(new BMessage(kMsgTypeSelected));
	fTypeListView->SetExplicitMinSize(BSize(200, B_SIZE_UNSET));

	BScrollView* typeListScrollView = new BScrollView("scrollview",
		fTypeListView, B_FRAME_EVENTS | B_WILL_DRAW, false, true);

	// "Icon" group

	fIconView = new TypeIconView("icon");
	fIconBox = new BBox("Icon BBox");
	fIconBox->SetLabel(B_TRANSLATE("Icon"));
	BLayoutBuilder::Group<>(fIconBox, B_VERTICAL, padding)
		.SetInsets(padding)
		.AddGlue(1)
		.Add(fIconView, 3)
		.AddGlue(1);

	// "File Recognition" group

	fRecognitionBox = new BBox("Recognition Box");
	fRecognitionBox->SetLabel(B_TRANSLATE("File recognition"));
	fRecognitionBox->SetExplicitAlignment(fullAlignment);

	fExtensionLabel = new StringView(B_TRANSLATE("Extensions:"), NULL);
	fExtensionLabel->LabelView()->SetExplicitAlignment(labelAlignment);

	fAddExtensionButton = new BButton("add ext",
		B_TRANSLATE("Add" B_UTF8_ELLIPSIS), new BMessage(kMsgAddExtension));
	fAddExtensionButton->SetExplicitMaxSize(
		BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));

	fRemoveExtensionButton = new BButton("remove ext", B_TRANSLATE("Remove"),
		new BMessage(kMsgRemoveExtension));

	fExtensionListView = new ExtensionListView("listview ext",
		B_SINGLE_SELECTION_LIST);
	fExtensionListView->SetSelectionMessage(
		new BMessage(kMsgExtensionSelected));
	fExtensionListView->SetInvocationMessage(
		new BMessage(kMsgExtensionInvoked));

	BScrollView* scrollView = new BScrollView("scrollview ext",
		fExtensionListView, B_FRAME_EVENTS | B_WILL_DRAW, false, true);

	fRuleControl = new BTextControl("rule", B_TRANSLATE("Rule:"), "",
		new BMessage(kMsgRuleEntered));
	fRuleControl->SetAlignment(B_ALIGN_RIGHT, B_ALIGN_LEFT);
	fRuleControl->Hide();

	BLayoutBuilder::Grid<>(fRecognitionBox, padding, padding / 2)
		.SetInsets(padding, padding * 2, padding, padding)
		.Add(fExtensionLabel->LabelView(), 0, 0)
		.Add(scrollView, 0, 1, 2, 2)
		.Add(fAddExtensionButton, 2, 1)
		.Add(fRemoveExtensionButton, 2, 2)
		.Add(fRuleControl, 0, 3, 3, 1);

	// "Description" group

	fDescriptionBox = new BBox("description BBox");
	fDescriptionBox->SetLabel(B_TRANSLATE("Description"));
	fDescriptionBox->SetExplicitAlignment(fullAlignment);

	fInternalNameView = new StringView(B_TRANSLATE("Internal name:"), NULL);
	fInternalNameView->SetEnabled(false);
	fTypeNameControl = new BTextControl("type", B_TRANSLATE("Type name:"), "",
		new BMessage(kMsgTypeEntered));
	fDescriptionControl = new BTextControl("description",
		B_TRANSLATE("Description:"), "", new BMessage(kMsgDescriptionEntered));

	BLayoutBuilder::Grid<>(fDescriptionBox, padding / 2, padding / 2)
		.SetInsets(padding, padding * 2, padding, padding)
		.Add(fInternalNameView->LabelView(), 0, 0)
		.Add(fInternalNameView->TextView(), 1, 0)
		.Add(fTypeNameControl->CreateLabelLayoutItem(), 0, 1)
		.Add(fTypeNameControl->CreateTextViewLayoutItem(), 1, 1, 2)
		.Add(fDescriptionControl->CreateLabelLayoutItem(), 0, 2)
		.Add(fDescriptionControl->CreateTextViewLayoutItem(), 1, 2, 2);

	// "Preferred Application" group

	fPreferredBox = new BBox("preferred BBox");
	fPreferredBox->SetLabel(B_TRANSLATE("Preferred application"));

	menu = new BPopUpMenu("preferred");
	menu->AddItem(item = new BMenuItem(B_TRANSLATE("None"),
		new BMessage(kMsgPreferredAppChosen)));
	item->SetMarked(true);
	fPreferredField = new BMenuField("preferred", (char*)NULL, menu);

	fSelectButton = new BButton("select",
		B_TRANSLATE("Select" B_UTF8_ELLIPSIS),
		new BMessage(kMsgSelectPreferredApp));

	fSameAsButton = new BButton("same as",
		B_TRANSLATE("Same as" B_UTF8_ELLIPSIS),
		new BMessage(kMsgSamePreferredAppAs));

	BLayoutBuilder::Group<>(fPreferredBox, B_HORIZONTAL, padding)
		.SetInsets(padding, padding * 2, padding, padding)
		.Add(fPreferredField)
		.Add(fSelectButton)
		.Add(fSameAsButton);

	// "Extra Attributes" group

	fAttributeBox = new BBox("Attribute Box");
	fAttributeBox->SetLabel(B_TRANSLATE("Extra attributes"));

	fAddAttributeButton = new BButton("add attr",
		B_TRANSLATE("Add" B_UTF8_ELLIPSIS), new BMessage(kMsgAddAttribute));
	fAddAttributeButton->SetExplicitMaxSize(
		BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));

	fRemoveAttributeButton = new BButton("remove attr", B_TRANSLATE("Remove"),
		new BMessage(kMsgRemoveAttribute));
	fRemoveAttributeButton->SetExplicitMaxSize(
		BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));

	fMoveUpAttributeButton = new BButton("move up attr", B_TRANSLATE("Move up"),
		new BMessage(kMsgMoveUpAttribute));
	fMoveUpAttributeButton->SetExplicitMaxSize(
		BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));
	fMoveDownAttributeButton = new BButton("move down attr",
		B_TRANSLATE("Move down"), new BMessage(kMsgMoveDownAttribute));
	fMoveDownAttributeButton->SetExplicitMaxSize(
		BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));

	fAttributeListView = new AttributeListView("listview attr");
	fAttributeListView->SetSelectionMessage(
		new BMessage(kMsgAttributeSelected));
	fAttributeListView->SetInvocationMessage(
		new BMessage(kMsgAttributeInvoked));

	BScrollView* attributesScroller = new BScrollView("scrollview attr",
		fAttributeListView, B_FRAME_EVENTS | B_WILL_DRAW, false, true);

	BLayoutBuilder::Group<>(fAttributeBox, B_HORIZONTAL, padding)
		.SetInsets(padding, padding * 2, padding, padding)
		.Add(attributesScroller, 1.0f)
		.AddGroup(B_VERTICAL, padding / 2, 0.0f)
			.SetInsets(0)
			.Add(fAddAttributeButton)
			.Add(fRemoveAttributeButton)
			.AddStrut(padding)
			.Add(fMoveUpAttributeButton)
			.Add(fMoveDownAttributeButton)
			.AddGlue();

	fMainSplitView = new BSplitView(B_HORIZONTAL, floorf(padding / 2));

	BLayoutBuilder::Group<>(this, B_VERTICAL, 0)
		.SetInsets(0)
		.Add(menuBar)
		.AddGroup(B_HORIZONTAL, 0)
			.SetInsets(padding, padding, padding, padding)
			.AddSplit(fMainSplitView)
				.AddGroup(B_VERTICAL, padding)
					.Add(typeListScrollView)
					.AddGroup(B_HORIZONTAL, padding)
						.Add(addTypeButton)
						.Add(fRemoveTypeButton)
						.AddGlue()
						.End()
					.End()
				// Right side
				.AddGroup(B_VERTICAL, padding)
					.AddGroup(B_HORIZONTAL, padding)
						.Add(fIconBox, 1)
						.Add(fRecognitionBox, 3)
						.End()
					.Add(fDescriptionBox)
					.Add(fPreferredBox)
					.Add(fAttributeBox, 5);

	_SetType(NULL);
	_ShowSnifferRule(showRule);

	float leftWeight;
	float rightWeight;
	if (settings.FindFloat("left_split_weight", &leftWeight) != B_OK
		|| settings.FindFloat("right_split_weight", &rightWeight) != B_OK) {
		leftWeight = 0.2;
		rightWeight = 1.0 - leftWeight;
	}
	fMainSplitView->SetItemWeight(0, leftWeight, false);
	fMainSplitView->SetItemWeight(1, rightWeight, true);

	BMimeType::StartWatching(this);
}