Example #1
0
void
PreferencesAccounts::_LoadListView(ProtocolSettings* settings)
{
	if (!settings)
		return;

	BObjectList<BString> accounts = settings->Accounts();

	// Add accounts to list view
	for (int32 i = 0; i < accounts.CountItems(); i++) {
		BString* account = accounts.ItemAt(i);
		AccountListItem* listItem
			= new AccountListItem(settings, account->String());
		fListView->AddItem(listItem);
	}
}
void
WPASupplicantApp::_NotifyInterfaceStateChanged(BMessage *message)
{
	const wpa_supplicant *interface;
	if (message->FindPointer("interface", (void **)&interface) != B_OK)
		return;

	if (!fWatchingEntryListLocker.Lock())
		return;

	for (int32 i = 0; i < fWatchingEntryList.CountItems(); i++) {
		StateChangeWatchingEntry *entry = fWatchingEntryList.ItemAt(i);
		if (entry->MessageReceived(interface, message)) {
			delete fWatchingEntryList.RemoveItemAt(i);
			i--;
		}
	}

	fWatchingEntryListLocker.Unlock();
}
Example #3
0
void
WriterImplBase::RegisterPackageResolvableExpressionList(
	PackageAttributeList& attributeList,
	const BObjectList<BPackageResolvableExpression>& expressionList, uint8 id)
{
	for (int i = 0; i < expressionList.CountItems(); ++i) {
		BPackageResolvableExpression* resolvableExpr = expressionList.ItemAt(i);
		PackageAttribute* name = AddStringAttribute((BHPKGAttributeID)id,
			resolvableExpr->Name(), attributeList);

		if (resolvableExpr->Version().InitCheck() == B_OK) {
			PackageAttribute* op = new PackageAttribute(
				B_HPKG_ATTRIBUTE_ID_PACKAGE_RESOLVABLE_OPERATOR,
				B_HPKG_ATTRIBUTE_TYPE_UINT,
				B_HPKG_ATTRIBUTE_ENCODING_INT_8_BIT);
			op->unsignedInt = resolvableExpr->Operator();
			name->children.Add(op);
			RegisterPackageVersion(name->children, resolvableExpr->Version());
		}
	}
}
status_t
DebuggerImageDebugInfo::GetFunctions(BObjectList<FunctionDebugInfo>& functions)
{
	BObjectList<SymbolInfo> symbols(20, true);
	status_t error = fDebuggerInterface->GetSymbolInfos(fImageInfo.TeamID(),
		fImageInfo.ImageID(), symbols);
	if (error != B_OK)
		return error;

	// sort the symbols -- not necessary, but a courtesy to ImageDebugInfo which
	// will peform better when inserting functions at the end of a list
	symbols.SortItems(&_CompareSymbols);

	// create the function infos
	int32 functionsAdded = 0;
	for (int32 i = 0; SymbolInfo* symbol = symbols.ItemAt(i); i++) {
		if (symbol->Type() != B_SYMBOL_TYPE_TEXT)
			continue;

		FunctionDebugInfo* function = new(std::nothrow) BasicFunctionDebugInfo(
			this, symbol->Address(), symbol->Size(), symbol->Name(),
			Demangler::Demangle(symbol->Name()));
		if (function == NULL || !functions.AddItem(function)) {
			delete function;
			int32 index = functions.CountItems() - 1;
			for (; functionsAdded >= 0; functionsAdded--, index--) {
				function = functions.RemoveItemAt(index);
				delete function;
			}
			return B_NO_MEMORY;
		}

		functionsAdded++;
	}

	return B_OK;
}
Example #5
0
void
TTracker::CloseWindowAndChildren(const node_ref *node)
{
	BDirectory dir(node);
	if (dir.InitCheck() != B_OK)
		return;

	AutoLock<WindowList> lock(&fWindowList);
	BObjectList<BContainerWindow> closeList;

	// make a list of all windows to be closed
	// count from end to beginning so we can remove items safely
	for (int32 index = fWindowList.CountItems() - 1; index >= 0; index--) {
		BContainerWindow *window = dynamic_cast<BContainerWindow *>
			(fWindowList.ItemAt(index));
		if (window && window->TargetModel()) {
			BEntry wind_entry;
			wind_entry.SetTo(window->TargetModel()->EntryRef());

			if ((*window->TargetModel()->NodeRef() == *node)
				|| dir.Contains(&wind_entry)) {
				
				// ToDo:
				// get rid of the Remove here, BContainerWindow::Quit does it
				fWindowList.RemoveItemAt(index);
				closeList.AddItem(window);
			}
		}
	}

	// now really close the windows
	int32 numItems = closeList.CountItems();
	for (int32 index = 0; index < numItems; index++) {
		BContainerWindow *window = closeList.ItemAt(index);
		window->PostMessage(B_CLOSE_REQUESTED);
	}
}
Example #6
0
int32 CommandThread::_Thread(void* data)
{
	on_exit_thread(CommandThread::_ThreadExit, data);

	CommandThread* commandThread = static_cast<CommandThread*>(data);

	if (commandThread == NULL)
		return B_ERROR;

	// TODO acquire autolock

	BCommandPipe pipe;

	BObjectList<BString>* args = commandThread->Arguments();

	for (int32 x = 0; x < args->CountItems(); x++)
		pipe << *args->ItemAt(x);

	FILE* stdOutAndErrPipe = NULL;

	thread_id pipeThread = pipe.PipeInto(&stdOutAndErrPipe);

	if (pipeThread < B_OK)
		return B_ERROR;

	BPrivate::BCommandPipe::LineReader* reader = new CommandReader(commandThread->Invoker());

	if (pipe.ReadLines(stdOutAndErrPipe, reader) != B_OK) {
		kill_thread(pipeThread);
		status_t exitval;
		wait_for_thread(pipeThread, &exitval);
		return B_ERROR;
	}

	return B_OK;
}
Example #7
0
status_t 
BMediaFormats::GetCodeFor(const media_format& format,
	media_format_family family,
	media_format_description* _description)
{
	BAutolock locker(sLock);

	status_t status = update_media_formats();
	if (status < B_OK)
		return status;

	// search for a matching format

	for (int32 index = sFormats.CountItems(); index-- > 0;) {
		meta_format* metaFormat = sFormats.ItemAt(index);

		if (metaFormat->Matches(format, family)) {
			*_description = metaFormat->description;
			return B_OK;
		}
	}

	return B_MEDIA_BAD_FORMAT;
}
Example #8
0
void
TFilePanel::AdjustButton()
{
	// adjust button state
	BButton* button = dynamic_cast<BButton*>(FindView("default button"));
	if (button == NULL)
		return;

	BTextControl* textControl
		= dynamic_cast<BTextControl*>(FindView("text view"));
	BObjectList<BPose>* selectionList = fPoseView->SelectionList();
	BString buttonText = fButtonText;
	bool enabled = false;

	if (fIsSavePanel && textControl != NULL) {
		enabled = textControl->Text()[0] != '\0';
		if (fPoseView->IsFocus()) {
			fPoseView->ShowSelection(true);
			if (selectionList->CountItems() == 1) {
				Model* model = selectionList->FirstItem()->TargetModel();
				if (model->ResolveIfLink()->IsDirectory()) {
					enabled = true;
					buttonText = B_TRANSLATE("Open");
				} else {
					// insert the name of the selected model into
					// the text field
					textControl->SetText(model->Name());
					textControl->MakeFocus(true);
				}
			}
		} else
			fPoseView->ShowSelection(false);
	} else {
		int32 count = selectionList->CountItems();
		if (count) {
			enabled = true;

			// go through selection list looking at content
			for (int32 index = 0; index < count; index++) {
				Model* model = selectionList->ItemAt(index)->TargetModel();

				uint32 modelFlavor = GetLinkFlavor(model, false);
				uint32 linkFlavor = GetLinkFlavor(model, true);

				// if only one item is selected and we're not in dir
				// selection mode then we don't disable button ever
				if ((modelFlavor == B_DIRECTORY_NODE
						|| linkFlavor == B_DIRECTORY_NODE)
					&& count == 1)
				  break;

				if ((fNodeFlavors & modelFlavor) == 0
					&& (fNodeFlavors & linkFlavor) == 0) {
		    		enabled = false;
					break;
				}
			}
		}
	}

	button->SetLabel(buttonText.String());
	button->SetEnabled(enabled);
}
Example #9
0
int32
ExternalEventSource::CountListeners() const
{
	return fListeners.CountItems();
}
Example #10
0
void
MainWindow::_RefreshPackageList()
{
	BPackageRoster roster;
	BStringList repositoryNames;

	status_t result = roster.GetRepositoryNames(repositoryNames);
	if (result != B_OK)
		return;

	DepotInfoMap depots;
	for (int32 i = 0; i < repositoryNames.CountStrings(); i++) {
		const BString& repoName = repositoryNames.StringAt(i);
		depots[repoName] = DepotInfo(repoName);
	}

	PackageManager manager(B_PACKAGE_INSTALLATION_LOCATION_HOME);
	try {
		manager.Init(PackageManager::B_ADD_INSTALLED_REPOSITORIES
			| PackageManager::B_ADD_REMOTE_REPOSITORIES);
	} catch (BException ex) {
		BString message(B_TRANSLATE("An error occurred while "
			"initializing the package manager: %message%"));
		message.ReplaceFirst("%message%", ex.Message());
		_NotifyUser("Error", message.String());
		return;
	}

	BObjectList<BSolverPackage> packages;
	result = manager.Solver()->FindPackages("",
		BSolver::B_FIND_CASE_INSENSITIVE | BSolver::B_FIND_IN_NAME
			| BSolver::B_FIND_IN_SUMMARY | BSolver::B_FIND_IN_DESCRIPTION
			| BSolver::B_FIND_IN_PROVIDES,
		packages);
	if (result != B_OK) {
		// TODO: notify user
		return;
	}

	if (packages.IsEmpty())
		return;

	PackageInfoMap foundPackages;
		// if a given package is installed locally, we will potentially
		// get back multiple entries, one for each local installation
		// location, and one for each remote repository the package
		// is available in. The above map is used to ensure that in such
		// cases we consolidate the information, rather than displaying
		// duplicates
	PackageInfoMap remotePackages;
		// any package that we find in a remote repository goes in this map.
		// this is later used to discern which packages came from a local
		// installation only, as those must be handled a bit differently
		// upon uninstallation, since we'd no longer be able to pull them
		// down remotely.
	BStringList systemFlaggedPackages;
		// any packages flagged as a system package are added to this list.
		// such packages cannot be uninstalled, nor can any of their deps.
	PackageInfoMap systemInstalledPackages;
		// any packages installed in system are added to this list.
		// This is later used for dependency resolution of the actual
		// system packages in order to compute the list of protected
		// dependencies indicated above.

	BitmapRef defaultIcon(new(std::nothrow) SharedBitmap(
		"application/x-vnd.haiku-package"), true);

	for (int32 i = 0; i < packages.CountItems(); i++) {
		BSolverPackage* package = packages.ItemAt(i);
		const BPackageInfo& repoPackageInfo = package->Info();
		PackageInfoRef modelInfo;
		PackageInfoMap::iterator it = foundPackages.find(
			repoPackageInfo.Name());
		if (it != foundPackages.end())
			modelInfo.SetTo(it->second);
		else {
			// Add new package info
			BString publisherURL;
			if (repoPackageInfo.URLList().CountStrings() > 0)
				publisherURL = repoPackageInfo.URLList().StringAt(0);

			BString publisherName = repoPackageInfo.Vendor();
			const BStringList& rightsList = repoPackageInfo.CopyrightList();
			if (rightsList.CountStrings() > 0)
				publisherName = rightsList.StringAt(0);

			modelInfo.SetTo(new(std::nothrow) PackageInfo(
					repoPackageInfo.Name(),
					repoPackageInfo.Version().ToString(),
					PublisherInfo(BitmapRef(), publisherName,
					"", publisherURL), repoPackageInfo.Summary(),
					repoPackageInfo.Description(),
					repoPackageInfo.Flags()),
				true);

			if (modelInfo.Get() == NULL)
				return;

			foundPackages[repoPackageInfo.Name()] = modelInfo;
		}

		modelInfo->SetIcon(defaultIcon);
		modelInfo->AddListener(this);

		BSolverRepository* repository = package->Repository();
		if (dynamic_cast<BPackageManager::RemoteRepository*>(repository)
				!= NULL) {
			depots[repository->Name()].AddPackage(modelInfo);
			remotePackages[modelInfo->Title()] = modelInfo;
		} else {
			if (repository == static_cast<const BSolverRepository*>(
					manager.SystemRepository())) {
				modelInfo->AddInstallationLocation(
					B_PACKAGE_INSTALLATION_LOCATION_SYSTEM);
				if (!modelInfo->IsSystemPackage()) {
					systemInstalledPackages[repoPackageInfo.FileName()]
						= modelInfo;
				}
			} else if (repository == static_cast<const BSolverRepository*>(
					manager.HomeRepository())) {
				modelInfo->AddInstallationLocation(
					B_PACKAGE_INSTALLATION_LOCATION_HOME);
			}
		}

		if (modelInfo->IsSystemPackage())
			systemFlaggedPackages.Add(repoPackageInfo.FileName());
	}

	BAutolock lock(fModel.Lock());

	fModel.Clear();

	// filter remote packages from the found list
	// any packages remaining will be locally installed packages
	// that weren't acquired from a repository
	for (PackageInfoMap::iterator it = remotePackages.begin();
			it != remotePackages.end(); it++) {
		foundPackages.erase(it->first);
	}

	if (!foundPackages.empty()) {
		BString repoName = B_TRANSLATE("Local");
		depots[repoName] = DepotInfo(repoName);
		DepotInfoMap::iterator depot = depots.find(repoName);
		for (PackageInfoMap::iterator it = foundPackages.begin();
				it != foundPackages.end(); ++it) {
			depot->second.AddPackage(it->second);
		}
	}

	for (DepotInfoMap::iterator it = depots.begin(); it != depots.end(); it++) {
		fModel.AddDepot(it->second);
	}

	// start retrieving package icons and average ratings
	fModel.PopulateAllPackages();

	// compute the OS package dependencies
	try {
		// create the solver
		BSolver* solver;
		status_t error = BSolver::Create(solver);
		if (error != B_OK)
			throw BFatalErrorException(error, "Failed to create solver.");

		ObjectDeleter<BSolver> solverDeleter(solver);
		BPath systemPath;
		error = find_directory(B_SYSTEM_PACKAGES_DIRECTORY, &systemPath);
		if (error != B_OK) {
			throw BFatalErrorException(error,
				"Unable to retrieve system packages directory.");
		}

		// add the "installed" repository with the given packages
		BSolverRepository installedRepository;
		{
			BRepositoryBuilder installedRepositoryBuilder(installedRepository,
				"installed");
			for (int32 i = 0; i < systemFlaggedPackages.CountStrings(); i++) {
				BPath packagePath(systemPath);
				packagePath.Append(systemFlaggedPackages.StringAt(i));
				installedRepositoryBuilder.AddPackage(packagePath.Path());
			}
			installedRepositoryBuilder.AddToSolver(solver, true);
		}

		// add system repository
		BSolverRepository systemRepository;
		{
			BRepositoryBuilder systemRepositoryBuilder(systemRepository,
				"system");
			for (PackageInfoMap::iterator it = systemInstalledPackages.begin();
					it != systemInstalledPackages.end(); it++) {
				BPath packagePath(systemPath);
				packagePath.Append(it->first);
				systemRepositoryBuilder.AddPackage(packagePath.Path());
			}
			systemRepositoryBuilder.AddToSolver(solver, false);
		}

		// solve
		error = solver->VerifyInstallation();
		if (error != B_OK) {
			throw BFatalErrorException(error, "Failed to compute packages to "
				"install.");
		}

		BSolverResult solverResult;
		error = solver->GetResult(solverResult);
		if (error != B_OK) {
			throw BFatalErrorException(error, "Failed to retrieve system "
				"package dependency list.");
		}

		for (int32 i = 0; const BSolverResultElement* element
				= solverResult.ElementAt(i); i++) {
			BSolverPackage* package = element->Package();
			if (element->Type() == BSolverResultElement::B_TYPE_INSTALL) {
				PackageInfoMap::iterator it = systemInstalledPackages.find(
					package->Info().FileName());
				if (it != systemInstalledPackages.end())
					it->second->SetSystemDependency(true);
			}
		}
	} catch (BFatalErrorException ex) {
		printf("Fatal exception occurred while resolving system dependencies: "
			"%s, details: %s\n", strerror(ex.Error()), ex.Details().String());
	} catch (BNothingToDoException) {
		// do nothing
	} catch (BException ex) {
		printf("Exception occurred while resolving system dependencies: %s\n",
			ex.Message().String());
	} catch (...) {
		printf("Unknown exception occurred while resolving system "
			"dependencies.\n");
	}
}
Example #11
0
void 
Message::Draw(BView *view, int32 frame)
{
	if (view == NULL || view->Window() == NULL || !view->Window()->IsLocked())
		return;

	BScreen screen(view->Window());
	if (!screen.IsValid())
		return;

	// Double-buffered drawing
	BBitmap buffer(view->Bounds(), screen.ColorSpace(), true);
	if (buffer.InitCheck() != B_OK)
		return;

	BView offscreen(view->Bounds(), NULL, 0, 0);
	buffer.AddChild(&offscreen);
	buffer.Lock();

	// Set up the colors
	rgb_color base_color = {(uint8)(rand() % 25), (uint8)(rand() % 25),
		(uint8)(rand() % 25)};
	offscreen.SetHighColor(base_color); 
	offscreen.SetLowColor(tint_color(base_color, 0.815F));
	offscreen.FillRect(offscreen.Bounds(), kCheckered);
	rgb_color colors[8] = {
		tint_color(base_color, B_LIGHTEN_1_TINT),
		tint_color(base_color, 0.795F),
		tint_color(base_color, 0.851F),
		tint_color(base_color, 0.926F),
		tint_color(base_color, 1.05F),
		tint_color(base_color, B_DARKEN_1_TINT),
		tint_color(base_color, B_DARKEN_2_TINT),
		tint_color(base_color, B_DARKEN_3_TINT),
	};

	offscreen.SetDrawingMode(B_OP_OVER);

	// Set the basic font parameters, including random font family
	BFont font;
	offscreen.GetFont(&font);
	font.SetFace(B_BOLD_FACE);
	font.SetFamilyAndStyle(*(fFontFamilies.ItemAt(rand() % fFontFamilies.CountItems())), NULL);
	offscreen.SetFont(&font);

	// Get the message
	BString *message = get_message();
	BString *origMessage = new BString();
	message->CopyInto(*origMessage, 0, message->Length());
	// Replace newlines and tabs with spaces
	message->ReplaceSet("\n\t", ' ');

	int height = (int) offscreen.Bounds().Height();
	int width = (int) offscreen.Bounds().Width();

	// From 14 to 22 iterations
	int32 iterations = (rand() % 8) + 14;
	for (int32 i = 0; i < iterations; i++) {
		// Randomly set font size and shear
		BFont font;
		offscreen.GetFont(&font);
		float fontSize = ((rand() % 320) + 42) * fScaleFactor;
		font.SetSize(fontSize);
		// Set the shear off 90 about 1/2 of the time
		if (rand() % 2 == 1)
			font.SetShear((float) ((rand() % 135) + (rand() % 45)));
		else
			font.SetShear(90.0);
		offscreen.SetFont(&font);

		// Randomly set drawing location
		int x = (rand() % width) - (rand() % width/((rand() % 8)+1));
		int y = rand() % height;

		// Draw new text
		offscreen.SetHighColor(colors[rand() % 8]);
		int strLength = message->Length();
		// See how wide this string is with the current font
		float strWidth = offscreen.StringWidth(message->String());
		int drawingLength = (int) (strLength * (width / strWidth));
		int start = 0;
		if (drawingLength >= strLength)
			drawingLength = strLength;
		else
			start = rand() % (strLength - drawingLength);
		char *toDraw = new char[drawingLength+1];
		strncpy(toDraw, message->String()+start, drawingLength);
		toDraw[drawingLength] = 0;
		offscreen.DrawString(toDraw, BPoint(x, y));
		delete[] toDraw;
	}

	// Now draw the full message in a nice translucent box, but only
	// if this isn't preview mode
	if (!fPreview) {
		BFont font(be_fixed_font);
		font.SetSize(14.0); 
		offscreen.SetFont(&font);
		font_height fontHeight;
		font.GetHeight(&fontHeight);
		float lineHeight = fontHeight.ascent + fontHeight.descent
			+ fontHeight.leading;
		
		BStringList lines;
		int longestLine = 0;
		int32 count = get_lines(origMessage, lines, &longestLine);

		float stringWidth = font.StringWidth(lines.StringAt(longestLine).String());
		BRect box(0, 0, stringWidth + 20, (lineHeight * count) + 20);
		box.OffsetTo((width - box.Width()) / 2, height - box.Height() - 40);

		offscreen.SetDrawingMode(B_OP_ALPHA);
		base_color.alpha = 128;
		offscreen.SetHighColor(base_color);
		offscreen.FillRoundRect(box, 8, 8);
		offscreen.SetHighColor(205, 205, 205);
		BPoint start = box.LeftTop();
		start.x += 10;
		start.y += 10 + fontHeight.ascent + fontHeight.leading;
		for (int i = 0; i < count; i++) {
			offscreen.DrawString(lines.StringAt(i).String(), start);
			start.y += lineHeight;
		}
	}

	delete origMessage;
	delete message;

	offscreen.Sync();
	buffer.Unlock();
	view->DrawBitmap(&buffer);
	buffer.RemoveChild(&offscreen);
}
Example #12
0
int32
RegisteredEvent::CountListeners() const
{
	return fListeners.CountItems();
}
// ---------------------------------------------------------------
// AddTranslationItems
//
// Envious of that "Save As" menu in ShowImage? Well, you can have your own!
// AddTranslationItems will add menu items for all translations from the
// basic format you specify (B_TRANSLATOR_BITMAP, B_TRANSLATOR_TEXT etc).
// The translator ID and format constant chosen will be added to the message
// that is sent to you when the menu item is selected.
//
// The following code is a modified version of code
// written by Jon Watte from
// http://www.b500.com/bepage/TranslationKit2.html
//
// Preconditions:
//
// Parameters: intoMenu, the menu where the entries are created
//             fromType, the type of translators to put on
//                       intoMenu
//             kModel, the BMessage model for creating the menu
//                     if NULL, B_TRANSLATION_MENU is used
//             kTranslationIdName, the name used for
//                                 translator_id in the menuitem,
//                                 if NULL, be:translator is used
//             kTranslatorTypeName, the name used for
//                                  output format id in the menuitem
//             roster, BTranslatorRoster used to find translators
//                     if NULL, the default translators are used
//             
//
// Postconditions:
//
// Returns: B_BAD_VALUE, if intoMenu is NULL
//          B_OK, if successful
//          error value if not successful
// ---------------------------------------------------------------
status_t
BTranslationUtils::AddTranslationItems(BMenu *intoMenu, uint32 fromType,
	const BMessage *kModel, const char *kTranslatorIdName,
	const char *kTranslatorTypeName, BTranslatorRoster *roster)
{
	if (!intoMenu)
		return B_BAD_VALUE;
		
	if (!roster)
		roster = BTranslatorRoster::Default();

	if (!kTranslatorIdName)
		kTranslatorIdName = "be:translator";

	if (!kTranslatorTypeName)
		kTranslatorTypeName = "be:type";

	translator_id * ids = NULL;
	int32 count = 0;
	status_t err = roster->GetAllTranslators(&ids, &count);
	if (err < B_OK)
		return err;

	BObjectList<translator_info> infoList;

	for (int tix = 0; tix < count; tix++) {
		const translation_format *formats = NULL;
		int32 numFormats = 0;
		bool ok = false;
		err = roster->GetInputFormats(ids[tix], &formats, &numFormats);
		if (err == B_OK) {
			for (int iix = 0; iix < numFormats; iix++) {
				if (formats[iix].type == fromType) {
					ok = true;
					break;
				}
			}
		}
		if (!ok)
			continue;

		// Get supported output formats
		err = roster->GetOutputFormats(ids[tix], &formats, &numFormats); 
		if (err == B_OK) {
			for (int oix = 0; oix < numFormats; oix++) {
				if (formats[oix].type != fromType) {
					infoList.AddItem(_BuildTranslatorInfo(ids[tix],
						const_cast<translation_format*>(&formats[oix])));
				}
			}
		}
	}

	// Sort alphabetically by name
	infoList.SortItems(&_CompareTranslatorInfoByName);

	// Now add the menu items
	for (int i = 0; i < infoList.CountItems(); i++) {
		translator_info* info = infoList.ItemAt(i);

		BMessage *itemmsg;
		if (kModel)
			itemmsg = new BMessage(*kModel);
		else
			itemmsg = new BMessage(B_TRANSLATION_MENU);
		itemmsg->AddInt32(kTranslatorIdName, info->translator);
		itemmsg->AddInt32(kTranslatorTypeName, info->type);
		intoMenu->AddItem(new BMenuItem(info->name, itemmsg));

		// Delete object created in _BuildTranslatorInfo
		delete info;
	}

	delete[] ids;
	return B_OK;
}
Example #14
0
void
PairsWindow::MessageReceived(BMessage* message)
{
	switch (message->what) {
		case MENU_NEW:
			NewGame();
			break;

		case MENU_DIFFICULTY:
		{
			int32 rows;
			int32 cols;
			if (message->FindInt32("rows", &rows) == B_OK
				&& message->FindInt32("cols", &cols) == B_OK) {
				SetGameSize(rows, cols);
			}
			break;
		}

		case MENU_ICON_SIZE:
		{
			int32 size;
			if (message->FindInt32("size", &size) == B_OK) {
				fPairsView->SetIconSize(size);
				_ResizeWindow(fPairsView->Rows(), fPairsView->Cols());
			}

			break;
		}

		case MENU_QUIT:
			be_app->PostMessage(B_QUIT_REQUESTED);
			break;

		case kMsgCardButton:
		{
			if (!fIsPairsActive)
				break;

			int32 buttonNumber;
			if (message->FindInt32("button number", &buttonNumber) != B_OK)
				break;

			BObjectList<PairsButton>* pairsButtonList
				= fPairsView->PairsButtonList();
			if (pairsButtonList == NULL)
				break;

			// look at what icon is behind a button
			int32 buttonCount = pairsButtonList->CountItems();
			for (int32 i = 0; i < buttonCount; i++) {
				int32 iconPosition = fPairsView->GetIconPosition(i);
				if (iconPosition == buttonNumber) {
					fPairCardPosition = i % (buttonCount / 2);
					fButtonPosition = iconPosition;
					break;
				}
			}

			// gameplay
			fButtonClicks++;
			pairsButtonList->ItemAt(fButtonPosition)->Hide();

			if (fIsFirstClick) {
				fPairCardTmpPosition = fPairCardPosition;
				fButtonTmpPosition = fButtonPosition;
			} else {
				delete fPairComparing;
					// message of message runner might not have arrived
					// yet, so it is deleted here to prevent any leaking
					// just in case
				BMessage message(kMsgPairComparing);
				fPairComparing = new BMessageRunner(BMessenger(this),
					&message,  5 * 100000L, 1);
				fIsPairsActive = false;
			}

			fIsFirstClick = !fIsFirstClick;
			break;
		}

		case kMsgPairComparing:
		{
			BObjectList<PairsButton>* pairsButtonList
				= fPairsView->PairsButtonList();
			if (pairsButtonList == NULL)
				break;

			delete fPairComparing;
			fPairComparing = NULL;

			fIsPairsActive = true;

			if (fPairCardPosition == fPairCardTmpPosition)
				fFinishPairs++;
			else {
				pairsButtonList->ItemAt(fButtonPosition)->Show();
				pairsButtonList->ItemAt(fButtonTmpPosition)->Show();
			}

			// game end and results
			if (fFinishPairs == pairsButtonList->CountItems() / 2) {
				BString score;
				score << fButtonClicks;
				BString strAbout = B_TRANSLATE("%app%\n"
					"\twritten by Ralf Schülke\n"
					"\tCopyright 2008-2010, Haiku Inc.\n"
					"\n"
					"You completed the game in %num% clicks.\n");

				strAbout.ReplaceFirst("%app%",
					B_TRANSLATE_SYSTEM_NAME("Pairs"));
				strAbout.ReplaceFirst("%num%", score);

				BAlert* alert = new BAlert("about",
					strAbout.String(),
					B_TRANSLATE("New game"),
					B_TRANSLATE("Quit game"));

				BTextView* view = alert->TextView();
				BFont font;

				view->SetStylable(true);

				view->GetFont(&font);
				font.SetSize(18);
				font.SetFace(B_BOLD_FACE);
				view->SetFontAndColor(0,
					strlen(B_TRANSLATE_SYSTEM_NAME("Pairs")), &font);
				view->ResizeToPreferred();
				alert->SetShortcut(0, B_ESCAPE);

				if (alert->Go() == 0)
					NewGame();
				else
					be_app->PostMessage(B_QUIT_REQUESTED);
			}
			break;
		}

		default:
			BWindow::MessageReceived(message);
	}
}
Example #15
0
status_t
ThreadModelLoader::_Load()
{
	// create a model
	fThreadModel = new(std::nothrow) ThreadModel(fModel, fThread);
	if (fThreadModel == NULL)
		return B_NO_MEMORY;

	// collect all wait objects
	BObjectList<Model::ThreadWaitObject> waitObjects;

	int32 groupCount = fThread->CountThreadWaitObjectGroups();
	for (int32 i = 0; i < groupCount; i++) {
		Model::ThreadWaitObjectGroup* group
			= fThread->ThreadWaitObjectGroupAt(i);

		if (!group->GetThreadWaitObjects(waitObjects))
			return B_NO_MEMORY;
	}

	// sort them by type and name
	waitObjects.SortItems(&compare_by_type_and_name);

	// create the groups
	int32 waitObjectCount = waitObjects.CountItems();
	printf("%" B_PRId32 " wait objects\n", waitObjectCount);
	for (int32 i = 0; i < waitObjectCount;) {
		printf("new wait object group at %" B_PRId32 "\n", i);
		// collect the objects for this group
		Model::ThreadWaitObject* firstObject = waitObjects.ItemAt(i);
		int32 k = i + 1;
		for (; k < waitObjectCount; k++) {
			if (compare_by_type_and_name(firstObject, waitObjects.ItemAt(k))
					!= 0) {
				break;
			}
		}

		if (fThreadModel->AddWaitObjectGroup(waitObjects, i, k) == NULL)
			return B_NO_MEMORY;

		i = k;
	}

	// filter the events
	thread_id threadID = fThread->ID();
	bool done = false;
	uint32 count = 0;

	system_profiler_event_header** events = fModel->Events();
	size_t eventCount = fModel->CountEvents();
	for (size_t i = 0; i < eventCount; i++) {
		system_profiler_event_header* header = events[i];
		void* buffer = header + 1;

		// process the event
		bool keepEvent = false;

		switch (header->event) {
			case B_SYSTEM_PROFILER_THREAD_REMOVED:
			{
				system_profiler_thread_removed* event
					= (system_profiler_thread_removed*)buffer;
				if (event->thread == threadID)
					done = true;
				break;
			}

			case B_SYSTEM_PROFILER_THREAD_SCHEDULED:
			{
				system_profiler_thread_scheduled* event
					= (system_profiler_thread_scheduled*)buffer;
				keepEvent = event->thread == threadID
					|| event->previous_thread == threadID ;
				break;
			}

			case B_SYSTEM_PROFILER_THREAD_ENQUEUED_IN_RUN_QUEUE:
			{
				thread_enqueued_in_run_queue* event
					= (thread_enqueued_in_run_queue*)buffer;
				keepEvent = event->thread == threadID;
				break;
			}

			case B_SYSTEM_PROFILER_THREAD_REMOVED_FROM_RUN_QUEUE:
			{
				thread_removed_from_run_queue* event
					= (thread_removed_from_run_queue*)buffer;
				keepEvent = event->thread == threadID;
				break;
			}

			default:
				break;
		}

		if (keepEvent)
			fThreadModel->AddSchedulingEvent(header);

		// periodically check whether we're supposed to abort
		if (++count % 32 == 0) {
			AutoLocker<BLocker> locker(fLock);
			if (fAborted)
				return B_ERROR;
		}
	}

	return B_OK;
}
Example #16
0
bool
FSClipboardPaste(Model *model, uint32 linksMode)
{
	if (!FSClipboardHasRefs())
		return false;

	BMessenger tracker(kTrackerSignature);

	node_ref *destNodeRef = (node_ref *)model->NodeRef();

	// these will be passed to the asynchronous copy/move process
	BObjectList<entry_ref> *moveList = new BObjectList<entry_ref>(0, true);
	BObjectList<entry_ref> *copyList = new BObjectList<entry_ref>(0, true);

	if ((be_clipboard->Lock())) {
		BMessage *clip = be_clipboard->Data();
		if (clip != NULL) {
			char modeName[64];
			uint32 moveMode = 0;

			BMessage *updateMessage = NULL;
			node_ref updateNodeRef;
			updateNodeRef.device = -1;

			char *refName;
			type_code type;
			int32 count;
			for (int32 index = 0; clip->GetInfo(B_REF_TYPE, index,
#ifdef B_BEOS_VERSION_DANO
				(const char **)
#endif
				&refName, &type, &count) == B_OK; index++) {
				entry_ref ref;
				if (clip->FindRef(refName, &ref) != B_OK)
					continue;

				// If the entry_ref's directory has changed, send previous notification
				// (if any), and start new one for the new directory
				if (updateNodeRef.device != ref.device
					|| updateNodeRef.node != ref.directory) {
					if (updateMessage != NULL) {
						tracker.SendMessage(updateMessage);
						delete updateMessage;
					}

					updateNodeRef.device = ref.device;
					updateNodeRef.node = ref.directory;

					updateMessage = new BMessage(kFSClipboardChanges);
					updateMessage->AddInt32("device", updateNodeRef.device);
					updateMessage->AddInt64("directory", updateNodeRef.node);					
				}

				// we need this data later on
				MakeModeNameFromRefName(modeName, refName);
				if (!linksMode && clip->FindInt32(modeName, (int32 *)&moveMode) != B_OK)
					continue;

				BEntry entry(&ref);

				uint32 newMoveMode = 0;
				bool sameDirectory = destNodeRef->device == ref.device && destNodeRef->node == ref.directory;
				
				if (!entry.Exists()) {
					// The entry doesn't exist anymore, so we'll remove
					// that entry from the clipboard as well
					clip->RemoveName(refName);
					clip->RemoveName(modeName);

					newMoveMode = kDelete;
				} else {
					// the entry does exist, so lets see what we will
					// do with it
					if (!sameDirectory) {
						if (linksMode || moveMode == kMoveSelectionTo) {
							// the linksMode uses the moveList as well
							moveList->AddItem(new entry_ref(ref));
						} else if (moveMode == kCopySelectionTo)
							copyList->AddItem(new entry_ref(ref));
					}

					// if the entry should have been removed from its directory,
					// we want to copy that entry next time, no matter if the
					// items don't have to be moved at all (source == target)
					if (moveMode == kMoveSelectionTo)
						newMoveMode = kCopySelectionTo;
				}

				// add the change to the update message (if necessary)
				if (newMoveMode) {
					clip->ReplaceInt32(modeName, kCopySelectionTo);

					TClipboardNodeRef clipNode;
					MakeNodeFromName(&clipNode.node, modeName);
					clipNode.moveMode = kDelete;
					updateMessage->AddData("tcnode", T_CLIPBOARD_NODE, &clipNode,
						sizeof(TClipboardNodeRef), true);
				}
			}
			be_clipboard->Commit();

			// send notification for the last directory
			if (updateMessage != NULL) {
				tracker.SendMessage(updateMessage);
				delete updateMessage;
			}
		}
		be_clipboard->Unlock();
	}

	bool okToMove = true;

	// can't copy/paste to root('/') directory
	if (model->IsRoot()) {
		(new BAlert("", kNoCopyToRootStr, "Cancel", NULL, NULL,
			B_WIDTH_AS_USUAL, B_WARNING_ALERT))->Go();
		okToMove = false;			
	}

	BEntry entry;
	model->GetEntry(&entry);

	// can't copy items into the trash
	if (copyList->CountItems() > 0 && FSIsTrashDir(&entry)) {
		(new BAlert("", kNoCopyToTrashStr, "Cancel", NULL, NULL,
			B_WIDTH_AS_USUAL, B_WARNING_ALERT))->Go();
		okToMove = false;
	}

	if (!okToMove) {
		// there was some problem with our target, so we bail out here
		delete moveList;
		delete copyList;
		return false;
	}

	// asynchronous calls take over ownership of the objects passed to it
	if (moveList->CountItems() > 0)
		FSMoveToFolder(moveList, new BEntry(entry), linksMode ? linksMode : kMoveSelectionTo);
	else
		delete moveList;

	if (copyList->CountItems() > 0)
		FSMoveToFolder(copyList, new BEntry(entry), kCopySelectionTo);
	else
		delete copyList;

	return true;
}
void
BreakpointManager::_UpdateImageBreakpoints(Image* image, bool removeOnly)
{
	AutoLocker<BLocker> installLocker(fLock);
	AutoLocker<Team> teamLocker(fTeam);

	// remove obsolete user breakpoint instances
	BObjectList<Breakpoint> breakpointsToUpdate;
	for (UserBreakpointList::ConstIterator it
			= fTeam->UserBreakpoints().GetIterator();
		UserBreakpoint* userBreakpoint = it.Next();) {
		int32 instanceCount = userBreakpoint->CountInstances();
		for (int32 i = instanceCount - 1; i >= 0; i--) {
			UserBreakpointInstance* instance = userBreakpoint->InstanceAt(i);
			Breakpoint* breakpoint = instance->GetBreakpoint();
			if (breakpoint == NULL || breakpoint->GetImage() != image)
				continue;

			userBreakpoint->RemoveInstanceAt(i);
			breakpoint->RemoveUserBreakpoint(instance);

			if (!breakpointsToUpdate.AddItem(breakpoint)) {
				_UpdateBreakpointInstallation(breakpoint);
				if (breakpoint->IsUnused())
					fTeam->RemoveBreakpoint(breakpoint);
			}

			delete instance;
		}
	}

	// update breakpoints
	teamLocker.Unlock();
	for (int32 i = 0; Breakpoint* breakpoint = breakpointsToUpdate.ItemAt(i);
			i++) {
		_UpdateBreakpointInstallation(breakpoint);
	}

	teamLocker.Lock();
	for (int32 i = 0; Breakpoint* breakpoint = breakpointsToUpdate.ItemAt(i);
			i++) {
		if (breakpoint->IsUnused())
			fTeam->RemoveBreakpoint(breakpoint);
	}

	// add breakpoint instances for function instances in the image (if we have
	// an image debug info)
	BObjectList<UserBreakpointInstance> newInstances;
	ImageDebugInfo* imageDebugInfo = image->GetImageDebugInfo();
	if (imageDebugInfo == NULL)
		return;

	for (UserBreakpointList::ConstIterator it
			= fTeam->UserBreakpoints().GetIterator();
		UserBreakpoint* userBreakpoint = it.Next();) {
		// get the function
		Function* function = fTeam->FunctionByID(
			userBreakpoint->Location().GetFunctionID());
		if (function == NULL)
			continue;

		const SourceLocation& sourceLocation
			= userBreakpoint->Location().GetSourceLocation();
		target_addr_t relativeAddress
			= userBreakpoint->Location().RelativeAddress();

		// iterate through the function instances
		for (FunctionInstanceList::ConstIterator it
				= function->Instances().GetIterator();
			FunctionInstance* functionInstance = it.Next();) {
			if (functionInstance->GetImageDebugInfo() != imageDebugInfo)
				continue;

			// get the breakpoint address for the instance
			target_addr_t instanceAddress = 0;
			if (functionInstance->SourceFile() != NULL) {
				// We have a source file, so get the address for the source
				// location.
				Statement* statement = NULL;
				FunctionDebugInfo* functionDebugInfo
					= functionInstance->GetFunctionDebugInfo();
				functionDebugInfo->GetSpecificImageDebugInfo()
					->GetStatementAtSourceLocation(functionDebugInfo,
						sourceLocation, statement);
				if (statement != NULL) {
					instanceAddress = statement->CoveringAddressRange().Start();
						// TODO: What about BreakpointAllowed()?
					statement->ReleaseReference();
					// TODO: Make sure we do hit the function in question!
				}
			}

			if (instanceAddress == 0) {
				// No source file (or we failed getting the statement), so try
				// to use the same relative address.
				if (relativeAddress > functionInstance->Size())
					continue;
				instanceAddress = functionInstance->Address() + relativeAddress;
					// TODO: Make sure it does at least hit an instruction!
			}

			// create the user breakpoint instance
			UserBreakpointInstance* instance = new(std::nothrow)
				UserBreakpointInstance(userBreakpoint, instanceAddress);
			if (instance == NULL || !newInstances.AddItem(instance)) {
				delete instance;
				continue;
			}

			if (!userBreakpoint->AddInstance(instance)) {
				newInstances.RemoveItemAt(newInstances.CountItems() - 1);
				delete instance;
			}

			// get/create the breakpoint for the address
			target_addr_t address = instance->Address();
			Breakpoint* breakpoint = fTeam->BreakpointAtAddress(address);
			if (breakpoint == NULL) {
				breakpoint = new(std::nothrow) Breakpoint(image, address);
				if (breakpoint == NULL || !fTeam->AddBreakpoint(breakpoint)) {
					delete breakpoint;
					break;
				}
			}

			breakpoint->AddUserBreakpoint(instance);
			instance->SetBreakpoint(breakpoint);
		}
	}

	// install the breakpoints for the new user breakpoint instances
	teamLocker.Unlock();
	for (int32 i = 0; UserBreakpointInstance* instance = newInstances.ItemAt(i);
			i++) {
		Breakpoint* breakpoint = instance->GetBreakpoint();
		if (breakpoint == NULL
			|| _UpdateBreakpointInstallation(breakpoint) != B_OK) {
			// something went wrong -- remove the instance
			teamLocker.Lock();

			instance->GetUserBreakpoint()->RemoveInstance(instance);
			if (breakpoint != NULL) {
				breakpoint->AddUserBreakpoint(instance);
				if (breakpoint->IsUnused())
					fTeam->RemoveBreakpoint(breakpoint);
			}

			teamLocker.Unlock();
		}
	}
}
Example #18
0
THeaderView::THeaderView(BRect rect, BRect windowRect, bool incoming,
	bool resending, uint32 defaultCharacterSet, int32 defaultAccount)
	:
	BBox(rect, "m_header", B_FOLLOW_LEFT_RIGHT, B_WILL_DRAW, B_NO_BORDER),

	fAccountMenu(NULL),
	fEncodingMenu(NULL),
	fAccountID(defaultAccount),
	fAccountTo(NULL),
	fAccount(NULL),
	fBcc(NULL),
	fCc(NULL),
	fSubject(NULL),
	fTo(NULL),
	fDateLabel(NULL),
	fDate(NULL),
	fIncoming(incoming),
	fCharacterSetUserSees(defaultCharacterSet),
	fResending(resending),
	fBccMenu(NULL),
	fCcMenu(NULL),
	fToMenu(NULL),
	fEmailList(NULL)
{
	BMenuField* field;
	BMessage* msg;

	BString kAttachments(B_TRANSLATE("Attachments: "));
	BString kDecoding(B_TRANSLATE("Decoding:"));
	BString kFrom(B_TRANSLATE("From:"));
	BString kTo(B_TRANSLATE("To:"));
	BString kEncoding(B_TRANSLATE("Encoding:"));
	BString kAccount(B_TRANSLATE("Account:"));
	BString kCc(B_TRANSLATE("Cc:"));
	BString kSubject(B_TRANSLATE("Subject:"));
	BString kBcc(B_TRANSLATE("Bcc:"));
	
	BObjectList<BString> kToCompare;
	kToCompare.AddItem(&kAttachments);
	kToCompare.AddItem(&kDecoding);
	kToCompare.AddItem(&kFrom);
	kToCompare.AddItem(&kTo);
	kToCompare.AddItem(&kEncoding);
	kToCompare.AddItem(&kAccount);
	kToCompare.AddItem(&kCc);
	kToCompare.AddItem(&kSubject);
	kToCompare.AddItem(&kBcc);
	
	float x = 0;
	// Get the longest translated string's width to use when calculating
	// horizontal positions
	for(int i = 0; i < kToCompare.CountItems(); ++i) {
		float stringWidth = StringWidth(kToCompare.ItemAt(i)->String()) + 9;
		if (stringWidth > x)
			x = stringWidth;
	}
	float y = TO_FIELD_V;
	
	BMenuBar* dummy = new BMenuBar(BRect(0, 0, 100, 15), "Dummy");
	AddChild(dummy);
	float width, menuBarHeight;
	dummy->GetPreferredSize(&width, &menuBarHeight);
	dummy->RemoveSelf();
	delete dummy;

	float menuFieldHeight = menuBarHeight + 2;
	float controlHeight = menuBarHeight + floorf(be_plain_font->Size() / 1.15);

	if (!fIncoming) {
		InitEmailCompletion();
		InitGroupCompletion();
	}

	// Prepare the character set selection pop-up menu (we tell the user that
	// it is the Encoding menu, even though it is really the character set).
	// It may appear in the first line, to the right of the From box if the
	// user is reading an e-mail.  It appears on the second line, to the right
	// of the e-mail account menu, if the user is composing a message.  It lets
	// the user quickly select a character set different from the application
	// wide default one, and also shows them which character set is active.  If
	// you are reading a message, you also see an item that says "Automatic"
	// for automatic decoding character set choice.  It can slide around as the
	// window is resized when viewing a message, but not when composing
	// (because the adjacent pop-up menu can't resize dynamically due to a BeOS
	// bug).

	float widestCharacterSet = 0;
	bool markedCharSet = false;
	BMenuItem* item;

	fEncodingMenu = new BPopUpMenu(B_EMPTY_STRING);

	BCharacterSetRoster roster;
	BCharacterSet charset;
	while (roster.GetNextCharacterSet(&charset) == B_OK) {
		BString name(charset.GetPrintName());
		const char* mime = charset.GetMIMEName();
		if (mime)
			name << " (" << mime << ")";

		uint32 convertID;
		if (mime == NULL || strcasecmp(mime, "UTF-8") != 0)
			convertID = charset.GetConversionID();
		else
			convertID = B_MAIL_UTF8_CONVERSION;

		msg = new BMessage(kMsgEncoding);
		msg->AddInt32("charset", convertID);
		fEncodingMenu->AddItem(item = new BMenuItem(name.String(), msg));
		if (convertID == fCharacterSetUserSees && !markedCharSet) {
			item->SetMarked(true);
			markedCharSet = true;
		}
		if (StringWidth(name.String()) > widestCharacterSet)
			widestCharacterSet = StringWidth(name.String());
	}

	msg = new BMessage(kMsgEncoding);
	msg->AddInt32("charset", B_MAIL_US_ASCII_CONVERSION);
	fEncodingMenu->AddItem(item = new BMenuItem("US-ASCII", msg));
	if (fCharacterSetUserSees == B_MAIL_US_ASCII_CONVERSION && !markedCharSet) {
		item->SetMarked(true);
		markedCharSet = true;
	}

	if (!resending && fIncoming) {
		// reading a message, display the Automatic item
		fEncodingMenu->AddSeparatorItem();
		msg = new BMessage(kMsgEncoding);
		msg->AddInt32("charset", B_MAIL_NULL_CONVERSION);
		fEncodingMenu->AddItem(item = new BMenuItem(B_TRANSLATE("Automatic"), msg));
		if (!markedCharSet)
			item->SetMarked(true);
	}

	// First line of the header, From for reading e-mails (includes the
	// character set choice at the right), To when composing (nothing else in
	// the row).

	BRect r;
	char string[20];
	if (fIncoming && !resending) {
		// Set up the character set pop-up menu on the right of "To" box.
		r.Set (windowRect.Width() - widestCharacterSet -
			StringWidth (kDecoding.String()) - 2 * SEPARATOR_MARGIN,
				y - 2, windowRect.Width() - SEPARATOR_MARGIN,
				y + menuFieldHeight);
		field = new BMenuField (r, "decoding", kDecoding.String(),
			fEncodingMenu, true /* fixedSize */,
			B_FOLLOW_TOP | B_FOLLOW_RIGHT,
			B_WILL_DRAW | B_NAVIGABLE | B_NAVIGABLE_JUMP);
		field->SetDivider(field->StringWidth(kDecoding.String()) + 5);
		AddChild(field);
		r.Set(SEPARATOR_MARGIN, y,
			  field->Frame().left - SEPARATOR_MARGIN, y + menuFieldHeight);
		sprintf(string, kFrom.String());
	} else {
		r.Set(x - 12, y, windowRect.Width() - SEPARATOR_MARGIN,
			y + menuFieldHeight);
		string[0] = 0;
	}

	y += controlHeight;
	fTo = new TTextControl(r, string, new BMessage(TO_FIELD), fIncoming,
		resending, B_FOLLOW_LEFT_RIGHT);
	fTo->SetFilter(mail_to_filter);

	if (!fIncoming || resending) {
		fTo->SetChoiceList(&fEmailList);
		fTo->SetAutoComplete(true);
	} else {
		fTo->SetDivider(x - 12 - SEPARATOR_MARGIN);
		fTo->SetAlignment(B_ALIGN_RIGHT, B_ALIGN_LEFT);
	}

	AddChild(fTo);
	msg = new BMessage(FIELD_CHANGED);
	msg->AddInt32("bitmask", FIELD_TO);
	fTo->SetModificationMessage(msg);

	if (!fIncoming || resending) {
		r.right = r.left - 5;
		r.left = r.right - ceilf(be_plain_font->StringWidth(
			kTo.String()) + 25);
		r.top -= 1;
		fToMenu = new QPopupMenu(kTo.String());
		field = new BMenuField(r, "", "", fToMenu, true,
			B_FOLLOW_LEFT | B_FOLLOW_TOP, B_WILL_DRAW);
		field->SetDivider(0.0);
		field->SetEnabled(true);
		AddChild(field);
	}

	// "From:" accounts Menu and Encoding Menu.
	if (!fIncoming || resending) {
		// Put the character set box on the right of the From field.
		r.Set(windowRect.Width() - widestCharacterSet -
			StringWidth(kEncoding.String()) - 2 * SEPARATOR_MARGIN,
			y - 2, windowRect.Width() - SEPARATOR_MARGIN, y + menuFieldHeight);
		BMenuField* encodingField = new BMenuField(r, "encoding",
			kEncoding.String(), fEncodingMenu, true /* fixedSize */,
			B_FOLLOW_TOP | B_FOLLOW_RIGHT,
			B_WILL_DRAW | B_NAVIGABLE | B_NAVIGABLE_JUMP);
		encodingField->SetDivider(encodingField->StringWidth(
			kEncoding.String()) + 5);
		AddChild(encodingField);

		field = encodingField;

		// And now the "from account" pop-up menu, on the left side, taking the
		// remaining space.

		fAccountMenu = new BPopUpMenu(B_EMPTY_STRING);

		BMailAccounts accounts;
		bool marked = false;
		for (int32 i = 0; i < accounts.CountAccounts(); i++) {
			BMailAccountSettings* account = accounts.AccountAt(i);
			BString name = account->Name();
			name << ":   " << account->RealName() << "  <"
				<< account->ReturnAddress() << ">";

			msg = new BMessage(kMsgFrom);
			BMenuItem *item = new BMenuItem(name, msg);

			msg->AddInt32("id", account->AccountID());

			if (defaultAccount == account->AccountID()) {
				item->SetMarked(true);
				marked = true;
			}
			fAccountMenu->AddItem(item);
		}

		if (!marked) {
			BMenuItem *item = fAccountMenu->ItemAt(0);
			if (item != NULL) {
				item->SetMarked(true);
				fAccountID = item->Message()->FindInt32("id");
			} else {
				fAccountMenu->AddItem(
					item = new BMenuItem(B_TRANSLATE("<none>"), NULL));
				item->SetEnabled(false);
				fAccountID = ~(int32)0;
			}
			// default account is invalid, set to marked
			// TODO: do this differently, no casting and knowledge
			// of TMailApp here....
			if (TMailApp* app = dynamic_cast<TMailApp*>(be_app))
				app->SetDefaultAccount(fAccountID);
		}

		r.Set(SEPARATOR_MARGIN, y - 2,
			  field->Frame().left - SEPARATOR_MARGIN, y + menuFieldHeight);
		field = new BMenuField(r, "account", kFrom.String(),
			fAccountMenu, true /* fixedSize */,
			B_FOLLOW_TOP | B_FOLLOW_LEFT_RIGHT,
			B_WILL_DRAW | B_NAVIGABLE | B_NAVIGABLE_JUMP);
		AddChild(field, encodingField);
		field->SetDivider(x - 12 - SEPARATOR_MARGIN + kMenuFieldDividerOffset);
		field->SetAlignment(B_ALIGN_RIGHT);
		y += controlHeight;
	} else {
		// To: account
		bool account = BMailAccounts().CountAccounts() > 0;

		r.Set(SEPARATOR_MARGIN, y,
			  windowRect.Width() - SEPARATOR_MARGIN, y + menuFieldHeight);
		if (account)
			r.right -= SEPARATOR_MARGIN + ACCOUNT_FIELD_WIDTH;
		fAccountTo = new TTextControl(r, kTo.String(), NULL, fIncoming,
			false, B_FOLLOW_LEFT_RIGHT);
		fAccountTo->SetEnabled(false);
		fAccountTo->SetDivider(x - 12 - SEPARATOR_MARGIN);
		fAccountTo->SetAlignment(B_ALIGN_RIGHT, B_ALIGN_LEFT);
		AddChild(fAccountTo);

		if (account) {
			r.left = r.right + 6;  r.right = windowRect.Width() - SEPARATOR_MARGIN;
			fAccount = new TTextControl(r, kAccount.String(), NULL,
				fIncoming, false, B_FOLLOW_RIGHT | B_FOLLOW_TOP);
			fAccount->SetEnabled(false);
			AddChild(fAccount);
		}
		y += controlHeight;
	}
	
	if (fIncoming) {
		--y;
		r.Set(SEPARATOR_MARGIN, y,
			windowRect.Width() - SEPARATOR_MARGIN, y + menuFieldHeight);
		y += controlHeight;
		fCc = new TTextControl(r, kCc.String(),
			NULL, fIncoming, false, B_FOLLOW_LEFT_RIGHT);
		fCc->SetEnabled(false);
		fCc->SetDivider(x - 12 - SEPARATOR_MARGIN);
		fCc->SetAlignment(B_ALIGN_RIGHT, B_ALIGN_LEFT);
		AddChild(fCc);
	}

	--y;
	r.Set(SEPARATOR_MARGIN, y,
		windowRect.Width() - SEPARATOR_MARGIN, y + menuFieldHeight);
	y += controlHeight;
	fSubject = new TTextControl(r, kSubject.String(),
		new BMessage(SUBJECT_FIELD),fIncoming, false, B_FOLLOW_LEFT_RIGHT);
	AddChild(fSubject);
	(msg = new BMessage(FIELD_CHANGED))->AddInt32("bitmask", FIELD_SUBJECT);
	fSubject->SetModificationMessage(msg);
	fSubject->SetDivider(x - 12 - SEPARATOR_MARGIN);
	fSubject->SetAlignment(B_ALIGN_RIGHT, B_ALIGN_LEFT);
	if (fResending)
		fSubject->SetEnabled(false);

	--y;

	if (!fIncoming) {
		r.Set(x - 12, y, CC_FIELD_H + CC_FIELD_WIDTH, y + menuFieldHeight);
		fCc = new TTextControl(r, "", new BMessage(CC_FIELD), fIncoming, false);
		fCc->SetFilter(mail_to_filter);
		fCc->SetChoiceList(&fEmailList);
		fCc->SetAutoComplete(true);
		AddChild(fCc);
		(msg = new BMessage(FIELD_CHANGED))->AddInt32("bitmask", FIELD_CC);
		fCc->SetModificationMessage(msg);

		r.right = r.left - 5;
		r.left = r.right - ceilf(be_plain_font->StringWidth(
			kCc.String()) + 25);
		r.top -= 1;
		fCcMenu = new QPopupMenu(kCc.String());
		field = new BMenuField(r, "", "", fCcMenu, true,
			B_FOLLOW_LEFT | B_FOLLOW_TOP, B_WILL_DRAW);

		field->SetDivider(0.0);
		field->SetEnabled(true);
		AddChild(field);

		r.Set(BCC_FIELD_H + be_plain_font->StringWidth(kBcc.String()), y,
			  windowRect.Width() - SEPARATOR_MARGIN, y + menuFieldHeight);
		y += controlHeight;
		fBcc = new TTextControl(r, "", new BMessage(BCC_FIELD),
						fIncoming, false, B_FOLLOW_LEFT_RIGHT);
		fBcc->SetFilter(mail_to_filter);
		fBcc->SetChoiceList(&fEmailList);
		fBcc->SetAutoComplete(true);
		AddChild(fBcc);
		(msg = new BMessage(FIELD_CHANGED))->AddInt32("bitmask", FIELD_BCC);
		fBcc->SetModificationMessage(msg);

		r.right = r.left - 5;
		r.left = r.right - ceilf(be_plain_font->StringWidth(
			kBcc.String()) + 25);
		r.top -= 1;
		fBccMenu = new QPopupMenu(kBcc.String());
		field = new BMenuField(r, "", "", fBccMenu, true,
			B_FOLLOW_LEFT | B_FOLLOW_TOP, B_WILL_DRAW);
		field->SetDivider(0.0);
		field->SetEnabled(true);
		AddChild(field);
	} else {
		y -= SEPARATOR_MARGIN;
		r.Set(SEPARATOR_MARGIN, y, x - 12 - 1, y + menuFieldHeight);
		fDateLabel = new BStringView(r, "", kDateLabel);
		fDateLabel->SetAlignment(B_ALIGN_RIGHT);
		AddChild(fDateLabel);
		fDateLabel->SetHighColor(0, 0, 0);

		r.Set(r.right + 9, y, windowRect.Width() - SEPARATOR_MARGIN,
			y + menuFieldHeight);
		fDate = new BStringView(r, "", "");
		AddChild(fDate);
		fDate->SetHighColor(0, 0, 0);

		y += controlHeight + 5;
	}
	ResizeTo(Bounds().Width(), y);
}