void
InitializeFATEditor::SetTo(BPartition* partition)
{
	BString name = partition->Name();
	if (name.IsEmpty())
		name = partition->ContentName();
	if (!name.IsEmpty())
		fNameControl->SetText(name.String());
}
Example #2
0
bool
CommandLineUserInterface::_RegisterCommand(const BString& name,
	CliCommand* command)
{
	BReference<CliCommand> commandReference(command, true);
	if (name.IsEmpty() || command == NULL)
		return false;

	BString nextName;
	int32 startIndex = 0;
	int32 spaceIndex;
	do {
		spaceIndex = name.FindFirst(' ', startIndex);
		if (spaceIndex == B_ERROR)
			spaceIndex = name.Length();
		name.CopyInto(nextName, startIndex, spaceIndex - startIndex);

		CommandEntry* entry = new(std::nothrow) CommandEntry(nextName,
			command);
		if (entry == NULL || !fCommands.AddItem(entry)) {
			delete entry;
			return false;
		}
		startIndex = spaceIndex + 1;
	} while (startIndex < name.Length());

	return true;
}
Example #3
0
bool
TermView::HyperLinkState::_EntryExists(const BString& path,
	BString& _actualPath) const
{
	if (path.IsEmpty())
		return false;

	if (path[0] == '/' || fCurrentDirectory.IsEmpty()) {
		_actualPath = path;
	} else if (path == "~" || path.StartsWith("~/")) {
		// Replace '~' with the user's home directory. We don't handle "~user"
		// here yet.
		BPath homeDirectory;
		if (find_directory(B_USER_DIRECTORY, &homeDirectory) != B_OK)
			return false;
		_actualPath = homeDirectory.Path();
		_actualPath << path.String() + 1;
	} else {
		_actualPath.Truncate(0);
		_actualPath << fCurrentDirectory << '/' << path;
	}

	struct stat st;
	return lstat(_actualPath, &st) == 0;
}
Example #4
0
static void
PutFlag(BString& string, const char* flag)
{
	if (!string.IsEmpty())
		string += " ";
	string += flag;
}
Example #5
0
/*static*/ status_t
FSUtils::OpenSubDirectory(const BDirectory& baseDirectory,
                          const RelativePath& path, bool create, BDirectory& _directory)
{
    // get a string for the path
    BString pathString = path.ToString();
    if (pathString.IsEmpty())
        RETURN_ERROR(B_NO_MEMORY);

    // If creating is not allowed, just try to open it.
    if (!create)
        RETURN_ERROR(_directory.SetTo(&baseDirectory, pathString));

    // get an absolute path and create the subdirectory
    BPath absolutePath;
    status_t error = absolutePath.SetTo(&baseDirectory, pathString);
    if (error != B_OK) {
        ERROR("Volume::OpenSubDirectory(): failed to get absolute path "
              "for subdirectory \"%s\": %s\n", pathString.String(),
              strerror(error));
        RETURN_ERROR(error);
    }

    error = create_directory(absolutePath.Path(),
                             S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
    if (error != B_OK) {
        ERROR("Volume::OpenSubDirectory(): failed to create "
              "subdirectory \"%s\": %s\n", pathString.String(),
              strerror(error));
        RETURN_ERROR(error);
    }

    RETURN_ERROR(_directory.SetTo(&baseDirectory, pathString));
}
Example #6
0
void
InfoWin::_UpdateFile()
{
	bool iconSet = false;
	if (fController->HasFile()) {
		const PlaylistItem* item = fController->Item();
		iconSet = fIconView->SetIcon(item) == B_OK;
		media_file_format fileFormat;
		status_t status = fController->GetFileFormatInfo(&fileFormat);
		if (status == B_OK) {
			fContainerInfo->SetText(fileFormat.pretty_name);
			if (!iconSet)
				iconSet = fIconView->SetIcon(fileFormat.mime_type) == B_OK;
		} else
			fContainerInfo->SetText(strerror(status));

		BString info;
		if (fController->GetLocation(&info) != B_OK)
			info = B_TRANSLATE("<unknown>");
		fLocationInfo->SetText(info.String());
		fLocationInfo->SetToolTip(info.String());

		if (fController->GetName(&info) != B_OK || info.IsEmpty())
			info = B_TRANSLATE("<unnamed media>");
		fFilenameView->SetText(info.String());
		fFilenameView->SetToolTip(info.String());
	} else {
		fFilenameView->SetText(B_TRANSLATE("<no media>"));
		fContainerInfo->SetText("-");
		fLocationInfo->SetText("-");
	}

	if (!iconSet)
		fIconView->SetGenericIcon();
}
Example #7
0
void
TeamWindow::_UpdateSourcePathState()
{
	LocatableFile* sourceFile = NULL;
	BString sourceText = "Source file unavailable.";
	BString truncatedText;

	if (fActiveSourceCode != NULL) {
		sourceFile = fActiveFunction->GetFunctionDebugInfo()->SourceFile();

		if (sourceFile != NULL && !sourceFile->GetLocatedPath(sourceText))
			sourceFile->GetPath(sourceText);

		if (fActiveFunction->GetFunction()->SourceCodeState()
			!= FUNCTION_SOURCE_NOT_LOADED
			&& fActiveSourceCode->GetSourceFile() == NULL
			&& sourceFile != NULL) {
			sourceText.Prepend("Click to locate source file '");
			sourceText += "'";
			truncatedText = sourceText;
			fSourcePathView->TruncateString(&truncatedText, B_TRUNCATE_MIDDLE,
				fSourcePathView->Bounds().Width());
		} else if (sourceFile != NULL)
			sourceText.Prepend("File: ");
	}

	if (!truncatedText.IsEmpty() && truncatedText != sourceText) {
		fSourcePathView->SetToolTip(sourceText);
		fSourcePathView->SetText(truncatedText);
	} else
		fSourcePathView->SetText(sourceText);
}
Example #8
0
void
LaunchDaemon::_AddJob(Target* target, bool service, BMessage& message)
{
	BString name = message.GetString("name");
	if (name.IsEmpty()) {
		// Invalid job description
		return;
	}
	name.ToLower();

	Job* job = FindJob(name);
	if (job == NULL) {
		job = new (std::nothrow) Job(name);
		if (job == NULL)
			return;

		job->SetService(service);
		job->SetCreateDefaultPort(service);
		job->SetTarget(target);
	}

	if (message.HasBool("disabled"))
		job->SetEnabled(!message.GetBool("disabled", !job->IsEnabled()));

	if (message.HasBool("legacy"))
		job->SetCreateDefaultPort(!message.GetBool("legacy", !service));

	_SetCondition(job, message);
	_SetEvent(job, message);
	_SetEnvironment(job, message);

	BMessage portMessage;
	for (int32 index = 0;
			message.FindMessage("port", index, &portMessage) == B_OK; index++) {
		job->AddPort(portMessage);
	}

	if (message.HasString("launch")) {
		job->Arguments().MakeEmpty();

		const char* argument;
		for (int32 index = 0; message.FindString("launch", index, &argument)
				== B_OK; index++) {
			job->AddArgument(argument);
		}
	}

	const char* requirement;
	for (int32 index = 0;
			message.FindString("requires", index, &requirement) == B_OK;
			index++) {
		job->AddRequirement(requirement);
	}
	if (fInitTarget != NULL)
		job->AddRequirement(fInitTarget->Name());

	fJobs.insert(std::make_pair(job->Title(), job));
}
Example #9
0
static inline status_t SaveString(BMessage &msg, const char *string, BString data)
{
	if(data == NULL || data.IsEmpty())
		return B_ERROR;
	
	if(msg.ReplaceString(string, data) == B_NAME_NOT_FOUND)
		return msg.AddString(string, data);
	return msg.ReplaceString(string, data);
}
Example #10
0
BMailFilterAction
RuleFilter::HeaderFetched(entry_ref& ref, BFile& file, BMessage& attributes)
{
	// That field doesn't exist? NO match
	if (fAttribute == "")
		return B_NO_MAIL_ACTION;

	attr_info info;
	if (file.GetAttrInfo("Subject", &info) != B_OK
		|| info.type != B_STRING_TYPE)
		return B_NO_MAIL_ACTION;

	BString data = attributes.GetString(fAttribute.String(), NULL);
	if (data.IsEmpty() || !fMatcher.Match(data)) {
		// We're not supposed to do anything
		return B_NO_MAIL_ACTION;
	}

	switch (fAction) {
		case ACTION_MOVE_TO:
		{
			BDirectory dir(fMoveTarget);
			node_ref nodeRef;
			status_t status = dir.GetNodeRef(&nodeRef);
			if (status != B_OK)
				return status;

			ref.device = nodeRef.device;
			ref.directory = nodeRef.node;
			return B_MOVE_MAIL_ACTION;
		}

		case ACTION_DELETE_MESSAGE:
			return B_DELETE_MAIL_ACTION;

		case ACTION_SET_FLAGS_TO:
			file.WriteAttrString("MAIL:filter_flags", &fSetFlags);
			break;

		case ACTION_REPLY_WITH:
			file.WriteAttr("MAIL:reply_with", B_INT32_TYPE, 0, &fReplyAccount,
				sizeof(int32));
			break;
		case ACTION_SET_AS_READ:
		{
			BInboundMailProtocol& protocol
				= (BInboundMailProtocol&)fMailProtocol;
			protocol.MarkMessageAsRead(ref, B_READ);
			break;
		}
		default:
			fprintf(stderr,"Unknown do_what: 0x%04x!\n", fAction);
	}

	return B_NO_MAIL_ACTION;
}
Example #11
0
	BString MakePath(const BPackageEntry* entry)
	{
		BString path;
		while (entry != NULL) {
			if (!path.IsEmpty())
				path.Prepend('/', 1);
			path.Prepend(entry->Name());
			entry = entry->Parent();
		}
		return path;
	}
Example #12
0
status_t
BDaemonClient::CreateTransaction(BPackageInstallationLocation location,
	BActivationTransaction& _transaction, BDirectory& _transactionDirectory)
{
	// get an info for the location
	BInstallationLocationInfo info;
	status_t error = GetInstallationLocationInfo(location, info);
	if (error != B_OK)
		return error;

	// open admin directory
	entry_ref entryRef;
	entryRef.device = info.PackagesDirectoryRef().device;
	entryRef.directory = info.PackagesDirectoryRef().node;
	error = entryRef.set_name(PACKAGES_DIRECTORY_ADMIN_DIRECTORY);
	if (error != B_OK)
		return error;
	
	BDirectory adminDirectory;
	error = adminDirectory.SetTo(&entryRef);
	if (error != B_OK)
		return error;

	// create a transaction directory
	int uniqueId = 1;
	BString directoryName;
	for (;; uniqueId++) {
		directoryName.SetToFormat("transaction-%d", uniqueId);
		if (directoryName.IsEmpty())
			return B_NO_MEMORY;

		error = adminDirectory.CreateDirectory(directoryName,
			&_transactionDirectory);
		if (error == B_OK)
			break;
		if (error != B_FILE_EXISTS)
			return error;
	}

	// init the transaction
	error = _transaction.SetTo(location, info.ChangeCount(), directoryName);
	if (error != B_OK) {
		BEntry entry;
		_transactionDirectory.GetEntry(&entry);
		_transactionDirectory.Unset();
		if (entry.InitCheck() == B_OK)
			entry.Remove();
		return error;
	}

	return B_OK;
}
Example #13
0
void
InfoWin::_UpdateCopyright()
{
	BString info;

	bool visible = fController->HasFile()
		&& fController->GetCopyright(&info) == B_OK && !info.IsEmpty();
	if (visible)
		fCopyrightInfo->SetText(info.String());

	fCopyrightSeparator->SetVisible(visible);
	_SetVisible(fCopyrightLabel, visible);
	_SetVisible(fCopyrightInfo, visible);
}
Example #14
0
bool
CommandLineUserInterface::_RegisterCommand(const BString& name,
	CliCommand* command)
{
	BReference<CliCommand> commandReference(command, true);
	if (name.IsEmpty() || command == NULL)
		return false;

	CommandEntry* entry = new(std::nothrow) CommandEntry(name, command);
	if (entry == NULL || !fCommands.AddItem(entry)) {
		delete entry;
		return false;
	}

	return true;
}
status_t
BActivationTransaction::SetTo(BPackageInstallationLocation location,
	int64 changeCount, const BString& directoryName)
{
	if (location < 0 || location >= B_PACKAGE_INSTALLATION_LOCATION_ENUM_COUNT
		|| directoryName.IsEmpty()) {
		return B_BAD_VALUE;
	}

	fLocation = location;
	fChangeCount = changeCount;
	fTransactionDirectoryName = directoryName;
	fPackagesToActivate.MakeEmpty();
	fPackagesToDeactivate.MakeEmpty();

	return B_OK;
}
bool
DepotMatchingRepositoryListener::Handle(DumpExportRepository* repository)
{
	int32 i;

	for (i = 0; i < repository->CountRepositorySources(); i++) {
		repository_and_repository_source repositoryAndRepositorySource;
		repositoryAndRepositorySource.repository = repository;
		repositoryAndRepositorySource.repositorySource =
			repository->RepositorySourcesItemAt(i);

		BString* repoInfoURL = repositoryAndRepositorySource
			.repositorySource->RepoInfoUrl();

		if (!repoInfoURL->IsEmpty()) {
			fModel->ReplaceDepotByUrl(*repoInfoURL, this,
				&repositoryAndRepositorySource);
		}
	}

	return !fStoppable->WasStopped();
}
Example #17
0
status_t
Protocol::ProcessCommand(Command& command, bigtime_t timeout)
{
	BString commandString = command.CommandString();
	if (commandString.IsEmpty())
		return B_BAD_VALUE;

	Handler* handler = dynamic_cast<Handler*>(&command);
	if (handler != NULL && !AddHandler(*handler))
		return B_NO_MEMORY;

	int32 commandID = NextCommandID();
	status_t status = SendCommand(commandID, commandString.String());
	if (status == B_OK) {
		fOngoingCommands[commandID] = &command;
		status = HandleResponse(&command, timeout);
	}

	if (handler != NULL)
		RemoveHandler(*handler);

	return status;
}
Example #18
0
void
RatePackageWindow::_SendRatingThread()
{
	if (!Lock()) {
		fprintf(stderr, "upload rating: Failed to lock window\n");
		return;
	}

	BString package = fPackage->Name();
	BString architecture = fPackage->Architecture();
	BString repositoryCode;
	int rating = (int)fRating;
	BString stability = fStability;
	BString comment = fRatingText->Text();
	BString languageCode = fCommentLanguage;
	BString ratingID = fRatingID;
	bool active = fRatingActive;

	const DepotInfo* depot = fModel.DepotForName(fPackage->DepotName());

	if (depot != NULL)
		repositoryCode = depot->WebAppRepositoryCode();

	WebAppInterface interface = fModel.GetWebAppInterface();

	Unlock();

	if (repositoryCode.Length() == 0) {
		printf("unable to find the web app repository code for the local "
			"depot %s\n",
			fPackage->DepotName().String());
		return;
	}

	if (stability == "unspecified")
		stability = "";

	status_t status;
	BMessage info;
	if (ratingID.Length() > 0) {
		status = interface.UpdateUserRating(ratingID,
		languageCode, comment, stability, rating, active, info);
	} else {
		status = interface.CreateUserRating(package, architecture,
			repositoryCode, languageCode, comment, stability, rating, info);
	}

	BString error = B_TRANSLATE(
		"There was a puzzling response from the web service.");

	BMessage result;
	if (status == B_OK) {
		if (info.FindMessage("result", &result) == B_OK) {
			error = "";
		} else if (info.FindMessage("error", &result) == B_OK) {
			result.PrintToStream();
			BString message;
			if (result.FindString("message", &message) == B_OK) {
				if (message == "objectnotfound") {
					error = B_TRANSLATE("The package was not found by the "
						"web service. This probably means that it comes "
						"from a depot which is not tracked there. Rating "
						"such packages is unfortunately not supported.");
				} else {
					error << B_TRANSLATE(" It responded with: ");
					error << message;
				}
			}
		}
	} else {
		error = B_TRANSLATE(
			"It was not possible to contact the web service.");
	}

	if (!error.IsEmpty()) {
		BString failedTitle;
		if (ratingID.Length() > 0)
			failedTitle = B_TRANSLATE("Failed to update rating");
		else
			failedTitle = B_TRANSLATE("Failed to rate package");

		BAlert* alert = new(std::nothrow) BAlert(
			failedTitle,
			error,
			B_TRANSLATE("Close"), NULL, NULL,
			B_WIDTH_AS_USUAL, B_WARNING_ALERT);

		if (alert != NULL)
			alert->Go();

		fprintf(stderr,
			B_TRANSLATE("Failed to create or update rating: %s\n"),
			error.String());
		if (!info.IsEmpty())
			info.PrintToStream();

		_SetWorkerThread(-1);
	} else {
		_SetWorkerThread(-1);

		fModel.PopulatePackage(fPackage,
			Model::POPULATE_FORCE | Model::POPULATE_USER_RATINGS);

		BMessenger(this).SendMessage(B_QUIT_REQUESTED);

		BString message;
		if (ratingID.Length() > 0) {
			message = B_TRANSLATE("Your rating was updated successfully.");
		} else {
			message = B_TRANSLATE("Your rating was uploaded successfully. "
				"You can update or remove it at any time by rating the "
				"package again.");
		}

		BAlert* alert = new(std::nothrow) BAlert(
			B_TRANSLATE("Success"),
			message,
			B_TRANSLATE("Close"));

		if (alert != NULL)
			alert->Go();
	}
}
Example #19
0
status_t
CLanguageFamily::ParseTypeExpression(const BString& expression,
	TeamTypeInformation* info, Type*& _resultType) const
{
	status_t result = B_OK;
	Type* baseType = NULL;

	BString parsedName = expression;
	BString baseTypeName;
	BString arraySpecifier;
	parsedName.RemoveAll(" ");

	int32 modifierIndex = -1;
	modifierIndex = parsedName.FindFirst('*');
	if (modifierIndex == -1)
		modifierIndex = parsedName.FindFirst('&');
	if (modifierIndex == -1)
		modifierIndex = parsedName.FindFirst('[');
	if (modifierIndex == -1)
		modifierIndex = parsedName.Length();

	parsedName.MoveInto(baseTypeName, 0, modifierIndex);

	modifierIndex = parsedName.FindFirst('[');
	if (modifierIndex >= 0) {
		parsedName.MoveInto(arraySpecifier, modifierIndex,
			parsedName.Length() - modifierIndex);
	}

	result = info->LookupTypeByName(baseTypeName, TypeLookupConstraints(),
		baseType);
	if (result != B_OK)
		return result;

	BReference<Type> typeRef;
	typeRef.SetTo(baseType, true);

	if (!parsedName.IsEmpty()) {
		AddressType* derivedType = NULL;
		// walk the list of modifiers trying to add each.
		for (int32 i = 0; i < parsedName.Length(); i++) {
			if (!IsModifierValid(parsedName[i]))
				return B_BAD_VALUE;

			address_type_kind typeKind;
			switch (parsedName[i]) {
				case '*':
				{
					typeKind = DERIVED_TYPE_POINTER;
					break;
				}
				case '&':
				{
					typeKind = DERIVED_TYPE_REFERENCE;
					break;
				}
				default:
				{
					return B_BAD_VALUE;
				}

			}

			if (derivedType == NULL) {
				result = baseType->CreateDerivedAddressType(typeKind,
					derivedType);
			} else {
				result = derivedType->CreateDerivedAddressType(typeKind,
					derivedType);
			}

			if (result != B_OK)
				return result;
			typeRef.SetTo(derivedType, true);
		}

		_resultType = derivedType;
	} else
		_resultType = baseType;


	if (!arraySpecifier.IsEmpty()) {
		ArrayType* arrayType = NULL;

		int32 startIndex = 1;
		do {
			int32 size = strtoul(arraySpecifier.String() + startIndex,
				NULL, 10);
			if (size < 0)
				return B_ERROR;

			if (arrayType == NULL) {
				result = _resultType->CreateDerivedArrayType(0, size, true,
					arrayType);
			} else {
				result = arrayType->CreateDerivedArrayType(0, size, true,
					arrayType);
			}

			if (result != B_OK)
				return result;

			typeRef.SetTo(arrayType, true);

			startIndex = arraySpecifier.FindFirst('[', startIndex + 1);

		} while (startIndex >= 0);

		// since a C/C++ array is essentially pointer math,
		// the resulting array has to be wrapped in a pointer to
		// ensure the element addresses wind up being against the
		// correct address.
		AddressType* addressType = NULL;
		result = arrayType->CreateDerivedAddressType(DERIVED_TYPE_POINTER,
			addressType);
		if (result != B_OK)
			return result;

		_resultType = addressType;
	}

	typeRef.Detach();

	return result;
}
Example #20
0
bool
TermView::HyperLinkState::_GetHyperLinkAt(BPoint where, bool pathPrefixOnly,
	HyperLink& _link, TermPos& _start, TermPos& _end)
{
	TerminalBuffer* textBuffer = fView->fTextBuffer;
	BAutolock textBufferLocker(textBuffer);

	TermPos pos = fView->_ConvertToTerminal(where);

	// try to get a URL first
	BString text;
	if (!textBuffer->FindWord(pos, &fURLCharClassifier, false, _start, _end))
		return false;

	text.Truncate(0);
	textBuffer->GetStringFromRegion(text, _start, _end);
	text.Trim();

	// We're only happy, if it has a protocol part which we know.
	int32 colonIndex = text.FindFirst(':');
	if (colonIndex >= 0) {
		BString protocol(text, colonIndex);
		if (strstr(kKnownURLProtocols, protocol) != NULL) {
			_link = HyperLink(text, HyperLink::TYPE_URL);
			return true;
		}
	}

	// no obvious URL -- try file name
	if (!textBuffer->FindWord(pos, fView->fCharClassifier, false, _start, _end))
		return false;

	// In path-prefix-only mode we determine the end position anew by omitting
	// the '/' in the allowed word chars.
	if (pathPrefixOnly) {
		TermPos componentStart;
		TermPos componentEnd;
		if (textBuffer->FindWord(pos, &fPathComponentCharClassifier, false,
				componentStart, componentEnd)) {
			_end = componentEnd;
		} else {
			// That means pos points to a '/'. We simply use the previous
			// position.
			_end = pos;
			if (_start == _end) {
				// Well, must be just "/". Advance to the next position.
				if (!textBuffer->NextLinePos(_end, false))
					return false;
			}
		}
	}

	text.Truncate(0);
	textBuffer->GetStringFromRegion(text, _start, _end);
	text.Trim();
	if (text.IsEmpty())
		return false;

	// Collect a list of colons in the string and their respective positions in
	// the text buffer. We do this up-front so we can unlock the text buffer
	// while we're doing all the entry existence tests.
	typedef Array<CharPosition> ColonList;
	ColonList colonPositions;
	TermPos searchPos = _start;
	for (int32 index = 0; (index = text.FindFirst(':', index)) >= 0;) {
		TermPos foundStart;
		TermPos foundEnd;
		if (!textBuffer->Find(":", searchPos, true, true, false, foundStart,
				foundEnd)) {
			return false;
		}

		CharPosition colonPosition;
		colonPosition.index = index;
		colonPosition.position = foundStart;
		if (!colonPositions.Add(colonPosition))
			return false;

		index++;
		searchPos = foundEnd;
	}

	textBufferLocker.Unlock();

	// Since we also want to consider ':' a potential path delimiter, in two
	// nested loops we chop off components from the beginning respective the
	// end.
	BString originalText = text;
	TermPos originalStart = _start;
	TermPos originalEnd = _end;

	int32 colonCount = colonPositions.Count();
	for (int32 startColonIndex = -1; startColonIndex < colonCount;
			startColonIndex++) {
		int32 startIndex;
		if (startColonIndex < 0) {
			startIndex = 0;
			_start = originalStart;
		} else {
			startIndex = colonPositions[startColonIndex].index + 1;
			_start = colonPositions[startColonIndex].position;
			if (_start >= pos)
				break;
			_start.x++;
				// Note: This is potentially a non-normalized position (i.e.
				// the end of a soft-wrapped line). While not that nice, it
				// works anyway.
		}

		for (int32 endColonIndex = colonCount; endColonIndex > startColonIndex;
				endColonIndex--) {
			int32 endIndex;
			if (endColonIndex == colonCount) {
				endIndex = originalText.Length();
				_end = originalEnd;
			} else {
				endIndex = colonPositions[endColonIndex].index;
				_end = colonPositions[endColonIndex].position;
				if (_end <= pos)
					break;
			}

			originalText.CopyInto(text, startIndex, endIndex - startIndex);
			if (text.IsEmpty())
				continue;

			// check, whether the file exists
			BString actualPath;
			if (_EntryExists(text, actualPath)) {
				_link = HyperLink(text, actualPath, HyperLink::TYPE_PATH);
				return true;
			}

			// As such this isn't an existing path. We also want to recognize:
			// * "<path>:<line>"
			// * "<path>:<line>:<column>"

			BString path = text;

			for (int32 i = 0; i < 2; i++) {
				int32 colonIndex = path.FindLast(':');
				if (colonIndex <= 0 || colonIndex == path.Length() - 1)
					break;

				char* numberEnd;
				strtol(path.String() + colonIndex + 1, &numberEnd, 0);
				if (*numberEnd != '\0')
					break;

				path.Truncate(colonIndex);
				if (_EntryExists(path, actualPath)) {
					BString address = path == actualPath
						? text
						: BString(actualPath) << (text.String() + colonIndex);
					_link = HyperLink(text, address,
						i == 0
							? HyperLink::TYPE_PATH_WITH_LINE
							: HyperLink::TYPE_PATH_WITH_LINE_AND_COLUMN);
					return true;
				}
			}
		}
	}

	return false;
}
Example #21
0
void
BaseJob::_GetSourceFileEnvironment(const char* script, BStringList& environment)
{
	int pipes[2];
	if (pipe(&pipes[0]) != 0) {
		// TODO: log error
		return;
	}

	pid_t child = fork();
	if (child < 0) {
		// TODO: log error
		debug_printf("could not fork: %s\n", strerror(errno));
	} else if (child == 0) {
		// We're the child, redirect stdout
		close(STDOUT_FILENO);
		close(STDERR_FILENO);
		dup2(pipes[1], STDOUT_FILENO);
		dup2(pipes[1], STDERR_FILENO);

		for (int32 i = 0; i < 2; i++)
			close(pipes[i]);

		BString command;
		command.SetToFormat(". \"%s\"; export -p", script);
		execl("/bin/sh", "/bin/sh", "-c", command.String(), NULL);
		exit(1);
	} else {
		// Retrieve environment from child

		close(pipes[1]);

		BString line;
		char buffer[4096];
		while (true) {
			ssize_t bytesRead = read(pipes[0], buffer, sizeof(buffer) - 1);
			if (bytesRead <= 0)
				break;

			// Make sure the buffer is null terminated
			buffer[bytesRead] = 0;

			const char* chunk = buffer;
			while (true) {
				const char* separator = strchr(chunk, '\n');
				if (separator == NULL) {
					line.Append(chunk, bytesRead);
					break;
				}
				line.Append(chunk, separator - chunk);
				chunk = separator + 1;

				_ParseExportVariable(environment, line);
				line.Truncate(0);
			}
		}
		if (!line.IsEmpty())
			_ParseExportVariable(environment, line);

		close(pipes[0]);
	}
}
Example #22
0
status_t
PackageView::_InstallTypeChanged(int32 index)
{
	if (index < 0)
		return B_ERROR;

	// Clear the choice list
	for (int32 i = fDestination->CountItems() - 1; i >= 0; i--) {
		BMenuItem* item = fDestination->RemoveItem(i);
		delete item;
	}

	fCurrentType = index;
	pkg_profile* profile = fInfo.GetProfile(index);

	if (profile == NULL)
		return B_ERROR;

	BString typeDescription = profile->description;
	if (typeDescription.IsEmpty())
		typeDescription = profile->name;

	fInstallTypeDescriptionView->SetText(typeDescription.String());

	BPath path;
	BVolume volume;

	if (profile->path_type == P_INSTALL_PATH) {
		BMenuItem* item = NULL;
		if (find_directory(B_SYSTEM_NONPACKAGED_DIRECTORY, &path) == B_OK) {
			dev_t device = dev_for_path(path.Path());
			if (volume.SetTo(device) == B_OK && !volume.IsReadOnly()
				&& path.Append("apps") == B_OK) {
				item = _AddDestinationMenuItem(path.Path(), volume.FreeBytes(),
					path.Path());
			}
		}

		if (item != NULL) {
			item->SetMarked(true);
			fCurrentPath.SetTo(path.Path());
			fDestination->AddSeparatorItem();
		}

		_AddMenuItem(B_TRANSLATE("Other" B_UTF8_ELLIPSIS),
			new BMessage(P_MSG_OPEN_PANEL), fDestination);

		fDestField->SetEnabled(true);
	} else if (profile->path_type == P_USER_PATH) {
		bool defaultPathSet = false;
		BVolumeRoster roster;

		while (roster.GetNextVolume(&volume) != B_BAD_VALUE) {
			BDirectory mountPoint;
			if (volume.IsReadOnly() || !volume.IsPersistent()
				|| volume.GetRootDirectory(&mountPoint) != B_OK) {
				continue;
			}

			if (path.SetTo(&mountPoint, NULL) != B_OK)
				continue;

			char volumeName[B_FILE_NAME_LENGTH];
			volume.GetName(volumeName);
	
			BMenuItem* item = _AddDestinationMenuItem(volumeName,
				volume.FreeBytes(), path.Path());

			// The first volume becomes the default element
			if (!defaultPathSet) {
				item->SetMarked(true);
				fCurrentPath.SetTo(path.Path());
				defaultPathSet = true;
			}
		}

		fDestField->SetEnabled(true);
	} else
		fDestField->SetEnabled(false);

	return B_OK;
}
status_t
CppLanguage::ParseTypeExpression(const BString &expression,
									TeamTypeInformation* info,
									Type*& _resultType) const
{
	status_t result = B_OK;
	Type* baseType = NULL;

	BString parsedName = expression;
	BString baseTypeName;
	parsedName.RemoveAll(" ");

	int32 modifierIndex = -1;
	for (int32 i = parsedName.Length() - 1; i >= 0; i--) {
		if (parsedName[i] == '*' || parsedName[i] == '&')
			modifierIndex = i;
	}

	if (modifierIndex >= 0) {
		parsedName.CopyInto(baseTypeName, 0, modifierIndex);
		parsedName.Remove(0, modifierIndex);
	} else
		baseTypeName = parsedName;

	result = info->LookupTypeByName(baseTypeName, TypeLookupConstraints(),
		baseType);
	if (result != B_OK)
		return result;

	BReference<Type> typeRef;
	typeRef.SetTo(baseType, true);

	if (!parsedName.IsEmpty()) {
		AddressType* derivedType = NULL;
		// walk the list of modifiers trying to add each.
		for (int32 i = 0; i < parsedName.Length(); i++) {
			address_type_kind typeKind;
			switch (parsedName[i]) {
				case '*':
				{
					typeKind = DERIVED_TYPE_POINTER;
					break;
				}
				case '&':
				{
					typeKind = DERIVED_TYPE_REFERENCE;
					break;
				}
				default:
				{
					return B_BAD_VALUE;
				}

			}

			if (derivedType == NULL) {
				result = baseType->CreateDerivedAddressType(typeKind,
					derivedType);
			} else {
				result = derivedType->CreateDerivedAddressType(typeKind,
					derivedType);
			}

			if (result != B_OK)
				return result;
			typeRef.SetTo(derivedType, true);
		}

		_resultType = derivedType;
	} else
		_resultType = baseType;

	typeRef.Detach();

	return result;
}
Example #24
0
void
NetworkStatusView::MouseDown(BPoint point)
{
	BPopUpMenu* menu = new BPopUpMenu(B_EMPTY_STRING, false, false);
	menu->SetAsyncAutoDestruct(true);
	menu->SetFont(be_plain_font);
	BString wifiInterface;
	BNetworkDevice wifiDevice;

	// Add interfaces

	for (std::map<BString, int32>::const_iterator it
		= fInterfaceStatuses.begin(); it != fInterfaceStatuses.end(); ++it) {
		const BString& name = it->first;

		BString label = name;
		label += ": ";
		label += kStatusDescriptions[
			_DetermineInterfaceStatus(name.String())];

		BMessage* info = new BMessage(kMsgShowConfiguration);
		info->AddString("interface", name.String());
		menu->AddItem(new BMenuItem(label.String(), info));

		// We only show the networks of the first wireless device we find.
		if (wifiInterface.IsEmpty()) {
			wifiDevice.SetTo(name);
			if (wifiDevice.IsWireless())
				wifiInterface = name;
		}
	}

	if (!fInterfaceStatuses.empty())
		menu->AddSeparatorItem();

	// Add wireless networks, if any

	if (!wifiInterface.IsEmpty()) {
		std::set<BNetworkAddress> associated;
		BNetworkAddress address;
		uint32 cookie = 0;
		while (wifiDevice.GetNextAssociatedNetwork(cookie, address) == B_OK)
			associated.insert(address);

		cookie = 0;
		wireless_network network;
		typedef std::vector<wireless_network> WirelessNetworkVector;
		WirelessNetworkVector wirelessNetworks;
		while (wifiDevice.GetNextNetwork(cookie, network) == B_OK)
			wirelessNetworks.push_back(network);

		std::sort(wirelessNetworks.begin(), wirelessNetworks.end(),
			signal_strength_compare);

		int32 count = 0;
		for (WirelessNetworkVector::iterator it = wirelessNetworks.begin();
				it != wirelessNetworks.end(); it++) {
			wireless_network &network = *it;

			BMessage* message = new BMessage(kMsgJoinNetwork);
			message->AddString("device", wifiInterface);
			message->AddString("name", network.name);
			message->AddFlat("address", &network.address);

			BMenuItem* item = new WirelessNetworkMenuItem(network.name,
				network.signal_strength, network.authentication_mode, message);
			menu->AddItem(item);
			if (associated.find(network.address) != associated.end())
				item->SetMarked(true);

			count++;
		}
		if (count == 0) {
			BMenuItem* item = new BMenuItem(
				B_TRANSLATE("<no wireless networks found>"), NULL);
			item->SetEnabled(false);
			menu->AddItem(item);
		}
		menu->AddSeparatorItem();
	}

	menu->AddItem(new BMenuItem(B_TRANSLATE(
		"Open network preferences" B_UTF8_ELLIPSIS),
		new BMessage(kMsgOpenNetworkPreferences)));

	if (fInDeskbar) {
		menu->AddItem(new BMenuItem(B_TRANSLATE("Quit"),
			new BMessage(B_QUIT_REQUESTED)));
	}
	menu->SetTargetForItems(this);

	ConvertToScreen(&point);
	menu->Go(point, true, true, true);
}
Example #25
0
int
main(int argc, const char* const* argv)
{
	const char* architecture = NULL;
	const char* dependency = NULL;
	const char* referencePath = NULL;
	bool existingOnly = false;
	const char* separator = NULL;

	while (true) {
		static struct option sLongOptions[] = {
			{ "architecture", required_argument, 0, 'a' },
			{ "dependency", required_argument, 0, 'd' },
			{ "help", no_argument, 0, 'h' },
			{ "path", required_argument, 0, 'p' },
			{ 0, 0, 0, 0 }
		};

		opterr = 0; // don't print errors
		int c = getopt_long(argc, (char**)argv, "+a:c:d:ehlp:",
			sLongOptions, NULL);
		if (c == -1)
			break;

		switch (c) {
			case 'a':
				architecture = optarg;
				break;

			case 'c':
				separator = optarg;
				break;

			case 'd':
				dependency = optarg;
				break;

			case 'e':
				existingOnly = true;
				break;

			case 'h':
				print_usage_and_exit(false);
				break;

			case 'l':
				for (size_t i = 0; i < kDirectoryConstantCount; i++) {
					const DirectoryConstantEntry& entry
						= kDirectoryConstants[i];
					printf("%s\n    - %s\n", entry.string, entry.description);
				}
				exit(0);

			case 'p':
				referencePath = optarg;
				break;

			default:
				print_usage_and_exit(true);
				break;
		}
	}

	// The remaining arguments are the kind constant and optionally the subpath.
	if (optind >= argc || optind + 2 < argc)
		print_usage_and_exit(true);

	const char* kindConstant = argv[optind++];

	const char* subPath = NULL;
	if (optind >= argc)
		subPath = argv[optind++];

	// resolve the directory constant
	path_base_directory baseDirectory = B_FIND_PATH_IMAGE_PATH;
	bool found = false;
	for (size_t i = 0; i < kDirectoryConstantCount; i++) {
		const DirectoryConstantEntry& entry = kDirectoryConstants[i];
		if (strcmp(kindConstant, entry.string) == 0) {
			found = true;
			baseDirectory = entry.constant;
			break;
		}
	}

	if (!found) {
		fprintf(stderr, "Error: Unsupported directory constant \"%s\".\n",
			kindConstant);
		exit(1);
	}

	if (referencePath != NULL) {
		BPath path;
		status_t error = BPathFinder(referencePath, dependency).FindPath(
			architecture, baseDirectory, subPath,
			existingOnly ? B_FIND_PATH_EXISTING_ONLY : 0, path);
		if (error != B_OK) {
			fprintf(stderr, "Error: Failed to find path: %s\n",
				strerror(error));
			exit(1);
		}

		printf("%s\n", path.Path());
	} else {
		BStringList paths;
		status_t error = BPathFinder::FindPaths(architecture, baseDirectory,
			subPath, existingOnly ? B_FIND_PATH_EXISTING_ONLY : 0, paths);
		if (error != B_OK) {
			fprintf(stderr, "Error: Failed to find paths: %s\n",
				strerror(error));
			exit(1);
		}

		if (separator != NULL) {
			BString result = paths.Join(separator);
			if (result.IsEmpty()) {
				fprintf(stderr, "Error: Out of memory!\n");
				exit(1);
			}
			printf("%s\n", result.String());
		} else {
			int32 count = paths.CountStrings();
			for (int32 i = 0; i < count; i++)
				printf("%s\n", paths.StringAt(i).String());
		}
	}

	return 0;
}