Beispiel #1
0
void
WriterImplBase::_AddStringAttributeList(BHPKGAttributeID id,
	const BStringList& value, DoublyLinkedList<PackageAttribute>& list)
{
	for (int32 i = 0; i < value.CountStrings(); i++)
		AddStringAttribute(id, value.StringAt(i), list);
}
Beispiel #2
0
void
MidiSettingsView::_RetrieveSoftSynthList()
{
	BStringList paths;
	status_t status = BPathFinder::FindPaths(B_FIND_PATH_DATA_DIRECTORY,
			"synth", paths);
	if (status != B_OK)
		return;

	fListView->MakeEmpty();

	for (int32 i = 0; i < paths.CountStrings(); i++) {
		BDirectory directory(paths.StringAt(i).String());
		BEntry entry;
		if (directory.InitCheck() != B_OK)
			continue;
		while (directory.GetNextEntry(&entry) == B_OK) {
			BNode node(&entry);
			BNodeInfo nodeInfo(&node);
			char mimeType[B_MIME_TYPE_LENGTH];
			// TODO: For some reason this doesn't work
			if (nodeInfo.GetType(mimeType) == B_OK
					/*&& !strcmp(mimeType, "audio/x-soundfont")*/) {
				BPath fullPath = paths.StringAt(i).String();
				fullPath.Append(entry.Name());
				fListView->AddItem(new BStringItem(fullPath.Path()));
			}
		}
	}
}
status_t
RepositoriesSettings::GetRepositories(int32& repoCount, BStringList& nameList,
	BStringList& urlList)
{
	BMessage settings(_ReadFromFile());
	type_code type;
	int32 count;
	settings.GetInfo(key_name, &type, &count);

	status_t result = B_OK;
	int32 index, total = 0;
	BString foundName, foundUrl;
	// get each repository and add to lists
	for (index = 0; index < count; index++) {
		status_t result1 = settings.FindString(key_name, index, &foundName);
		status_t result2 = settings.FindString(key_url, index, &foundUrl);
		if (result1 == B_OK && result2 == B_OK) {
			nameList.Add(foundName);
			urlList.Add(foundUrl);
			total++;
		} else
			result = B_ERROR;
	}
	repoCount = total;
	return result;
}
Beispiel #4
0
/*static*/ status_t
BPathFinder::FindPaths(const char* architecture,
	path_base_directory baseDirectory, const char* subPath, uint32 flags,
	BStringList& _paths)
{
	_paths.MakeEmpty();

	// get the paths
	char** pathArray;
	size_t pathCount;
	status_t error = find_paths_etc(architecture, baseDirectory, subPath, flags,
		&pathArray, &pathCount);
	if (error != B_OK)
		return error;

	MemoryDeleter pathArrayDeleter(pathArray);

	// add them to BStringList
	for (size_t i = 0; i < pathCount; i++) {
		BString path(pathArray[i]);
		if (path.IsEmpty() || !_paths.Add(path)) {
			_paths.MakeEmpty();
			return B_NO_MEMORY;
		}
	}

	return B_OK;
}
Beispiel #5
0
void
LaunchDaemon::ReadyToRun()
{
	_RetrieveKernelOptions();
	_SetupEnvironment();

	fReadOnlyBootVolume = Utility::IsReadOnlyVolume("/boot");
	if (fReadOnlyBootVolume)
		Utility::BlockMedia("/boot", true);

	if (fUserMode) {
		BLaunchRoster roster;
		BLaunchRoster::Private(roster).RegisterSessionDaemon(this);
	} else
		_InitSystem();

	BStringList paths;
	BPathFinder::FindPaths(B_FIND_PATH_DATA_DIRECTORY, kLaunchDirectory,
		fUserMode ? B_FIND_PATHS_USER_ONLY : B_FIND_PATHS_SYSTEM_ONLY, paths);
	_ReadPaths(paths);

	BPathFinder::FindPaths(B_FIND_PATH_SETTINGS_DIRECTORY, kLaunchDirectory,
		fUserMode ? B_FIND_PATHS_USER_ONLY : B_FIND_PATHS_SYSTEM_ONLY, paths);
	_ReadPaths(paths);

	_InitJobs(NULL);
	_LaunchJobs(NULL);

	// Launch run targets (ignores events)
	for (int32 index = 0; index < fRunTargets.CountStrings(); index++) {
		Target* target = FindTarget(fRunTargets.StringAt(index));
		if (target != NULL)
			_LaunchJobs(target);
	}
}
void
PackageManager::_PrintResult(InstalledRepository& installationRepository)
{
	if (!installationRepository.HasChanges())
		return;

	printf("  in %s:\n", installationRepository.Name().String());

	PackageList& packagesToActivate
		= installationRepository.PackagesToActivate();
	PackageList& packagesToDeactivate
		= installationRepository.PackagesToDeactivate();

	BStringList upgradedPackages;
	for (int32 i = 0;
		BSolverPackage* installPackage = packagesToActivate.ItemAt(i);
		i++) {
		for (int32 j = 0;
			BSolverPackage* uninstallPackage = packagesToDeactivate.ItemAt(j);
			j++) {
			if (installPackage->Info().Name() == uninstallPackage->Info().Name()) {
				upgradedPackages.Add(installPackage->Info().Name());
				break;
			}
		}
	}

	for (int32 i = 0; BSolverPackage* package = packagesToActivate.ItemAt(i);
		i++) {
		BString repository;
		if (dynamic_cast<MiscLocalRepository*>(package->Repository()) != NULL)
			repository = "local file";
		else
			repository.SetToFormat("repository %s", package->Repository()->Name().String());

		if (upgradedPackages.HasString(package->Info().Name())) {
			printf("    upgrade package %s to %s from %s\n",
				package->Info().Name().String(),
				package->Info().Version().ToString().String(),
				repository.String());
		} else {
			printf("    install package %s-%s from %s\n",
				package->Info().Name().String(),
				package->Info().Version().ToString().String(),
				repository.String());
		}
	}

	for (int32 i = 0; BSolverPackage* package = packagesToDeactivate.ItemAt(i);
		i++) {
		if (upgradedPackages.HasString(package->Info().Name()))
			continue;
		printf("    uninstall package %s\n", package->VersionedName().String());
	}
// TODO: Print file/download sizes. Unfortunately our package infos don't
// contain the file size. Which is probably correct. The file size (and possibly
// other information) should, however, be provided by the repository cache in
// some way. Extend BPackageInfo? Create a BPackageFileInfo?
}
Beispiel #7
0
void
Job::_AddStringList(std::vector<const char*>& array, const BStringList& list)
{
	int32 count = list.CountStrings();
	for (int32 index = 0; index < count; index++) {
		array.push_back(list.StringAt(index).String());
	}
}
Beispiel #8
0
static void
NotHere(BStringList& that, BStringList& otherList, BStringList* results)
{
	for (int32 i = 0; i < otherList.CountStrings(); i++) {
		if (!that.HasString(otherList.StringAt(i)))
			results->Add(otherList.StringAt(i));
	}
}
Beispiel #9
0
void
LaunchDaemon::ReadyToRun()
{
	_RetrieveKernelOptions();
	_SetupEnvironment();

	fReadOnlyBootVolume = Utility::IsReadOnlyVolume("/boot");
	if (fReadOnlyBootVolume)
		Utility::BlockMedia("/boot", true);

	if (fUserMode) {
		BLaunchRoster roster;
		BLaunchRoster::Private(roster).RegisterSessionDaemon(this);
	} else
		_InitSystem();

	BStringList paths;
	if (fUserMode) {
		// System-wide user specific jobs
		BPathFinder::FindPaths(B_FIND_PATH_DATA_DIRECTORY, kUserLaunchDirectory,
			B_FIND_PATHS_SYSTEM_ONLY, paths);
		_ReadPaths(paths);
	}

	BPathFinder::FindPaths(B_FIND_PATH_DATA_DIRECTORY, kLaunchDirectory,
		fUserMode ? B_FIND_PATHS_USER_ONLY : B_FIND_PATHS_SYSTEM_ONLY, paths);
	_ReadPaths(paths);

	if (fUserMode) {
		BPathFinder::FindPaths(B_FIND_PATH_SETTINGS_DIRECTORY,
			kUserLaunchDirectory, B_FIND_PATHS_SYSTEM_ONLY, paths);
		_ReadPaths(paths);
	}

	BPathFinder::FindPaths(B_FIND_PATH_SETTINGS_DIRECTORY, kLaunchDirectory,
		fUserMode ? B_FIND_PATHS_USER_ONLY : B_FIND_PATHS_SYSTEM_ONLY, paths);
	_ReadPaths(paths);

	BMessenger target(this);
	BMessenger::Private messengerPrivate(target);
	port_id port = messengerPrivate.Port();
	int32 token = messengerPrivate.Token();
	__start_watching_system(-1, B_WATCH_SYSTEM_TEAM_DELETION, port, token);

	_InitJobs(NULL);
	_LaunchJobs(NULL);

	// Launch run targets (ignores events)
	for (int32 index = 0; index < fRunTargets.CountStrings(); index++) {
		Target* target = FindTarget(fRunTargets.StringAt(index));
		if (target != NULL)
			_LaunchJobs(target);
	}

	if (fUserMode)
		be_roster->StartWatching(this, B_REQUEST_LAUNCHED);
}
Beispiel #10
0
static void add_replaces_list(Repo *repo, Offset &dependencies,
  const BStringList &packageNames)
{
  int32 count = packageNames.CountStrings();
  for (int32 i = 0; i < count; i++)
    {
      const BString &packageName = packageNames.StringAt(i);
      add_dependency(repo, dependencies, packageName, BPackageVersion(), 0);
    }
}
Beispiel #11
0
void
LaunchDaemon::_ReadPaths(const BStringList& paths)
{
	for (int32 i = 0; i < paths.CountStrings(); i++) {
		BEntry entry(paths.StringAt(i));
		if (entry.InitCheck() != B_OK || !entry.Exists())
			continue;

		_ReadDirectory(NULL, entry);
	}
}
void
BPackageManager::Init(uint32 flags)
{
	if (fSolver != NULL)
		return;

	// create the solver
	status_t error = BSolver::Create(fSolver);
	if (error != B_OK)
		DIE(error, "failed to create solver");

	if (fSystemRepository == NULL || fHomeRepository == NULL
		|| fLocalRepository == NULL) {
		throw std::bad_alloc();
	}

	fSolver->SetDebugLevel(fDebugLevel);

	BRepositoryBuilder(*fLocalRepository).AddToSolver(fSolver, false);

	// add installation location repositories
	if ((flags & B_ADD_INSTALLED_REPOSITORIES) != 0) {
		// We add only the repository of our actual installation location as the
		// "installed" repository. The repositories for the more general
		// installation locations are added as regular repositories, but with
		// better priorities than the actual (remote) repositories. This
		// prevents the solver from showing conflicts when a package in a more
		// specific installation location overrides a package in a more general
		// one. Instead any requirement that is already installed in a more
		// general installation location will turn up as to be installed as
		// well. But we can easily filter those out.
		_AddInstalledRepository(fSystemRepository);

		if (!fSystemRepository->IsInstalled())
			_AddInstalledRepository(fHomeRepository);
	}

	// add other repositories
	if ((flags & B_ADD_REMOTE_REPOSITORIES) != 0) {
		BPackageRoster roster;
		BStringList repositoryNames;
		error = roster.GetRepositoryNames(repositoryNames);
		if (error != B_OK) {
			fUserInteractionHandler->Warn(error,
				"failed to get repository names");
		}

		int32 repositoryNameCount = repositoryNames.CountStrings();
		for (int32 i = 0; i < repositoryNameCount; i++) {
			_AddRemoteRepository(roster, repositoryNames.StringAt(i),
				(flags & B_REFRESH_REPOSITORIES) != 0);
		}
	}
}
status_t
VirtualDirectoryEntryList::_InitMergedDirectory(
	const BStringList& directoryPaths)
{
	status_t error = fMergedDirectory.Init();
	if (error != B_OK)
		return error;

	int32 count = directoryPaths.CountStrings();
	for (int32 i = 0; i < count; i++)
		fMergedDirectory.AddDirectory(directoryPaths.StringAt(i));

	return B_OK;
}
		status_t operator()(const BEntry& entry)
		{
			char name[B_FILE_NAME_LENGTH];
			status_t result = entry.GetName(name);
			if (result != B_OK)
				return result;
			int32 count = names.CountStrings();
			for (int i = 0; i < count; ++i) {
				if (names.StringAt(i).Compare(name) == 0)
					return B_OK;
			}
			names.Add(name);
			return B_OK;
		}
Beispiel #15
0
void
RepositoriesSettings::SetRepositories(BStringList& nameList, BStringList& urlList)
{
	BMessage settings(_ReadFromFile());
	settings.RemoveName(key_name);
	settings.RemoveName(key_url);

	int32 index, count = nameList.CountStrings();
	for (index = 0; index < count; index++) {
		settings.AddString(key_name, nameList.StringAt(index));
		settings.AddString(key_url, urlList.StringAt(index));
	}
	_SaveToFile(settings);
}
Beispiel #16
0
static void
list_targets(bool verbose)
{
	BLaunchRoster roster;
	BStringList targets;
	status_t status = roster.GetTargets(targets);
	if (status != B_OK) {
		fprintf(stderr, "%s: Could not get target listing: %s\n", kProgramName,
			strerror(status));
		exit(EXIT_FAILURE);
	}

	for (int32 i = 0; i < targets.CountStrings(); i++)
		puts(targets.StringAt(i).String());
}
Beispiel #17
0
void
MainWindow::_RefreshRepositories(bool force)
{
	if (fSinglePackageMode)
		return;

	BPackageRoster roster;
	BStringList repositoryNames;

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

	DecisionProvider decisionProvider;
	JobStateListener listener;
	BContext context(decisionProvider, listener);

	BRepositoryCache cache;
	for (int32 i = 0; i < repositoryNames.CountStrings(); ++i) {
		const BString& repoName = repositoryNames.StringAt(i);
		BRepositoryConfig repoConfig;
		result = roster.GetRepositoryConfig(repoName, &repoConfig);
		if (result != B_OK) {
			// TODO: notify user
			continue;
		}

		if (roster.GetRepositoryCache(repoName, &cache) != B_OK || force) {
			try {
				BRefreshRepositoryRequest refreshRequest(context, repoConfig);

				result = refreshRequest.Process();
			} catch (BFatalErrorException ex) {
				BString message(B_TRANSLATE("An error occurred while "
					"refreshing the repository: %error% (%details%)"));
 				message.ReplaceFirst("%error%", ex.Message());
				message.ReplaceFirst("%details%", ex.Details());
				_NotifyUser("Error", message.String());
			} catch (BException ex) {
				BString message(B_TRANSLATE("An error occurred while "
					"refreshing the repository: %error%"));
				message.ReplaceFirst("%error%", ex.Message());
				_NotifyUser("Error", message.String());
			}
		}
	}
}
	virtual status_t HandleRepositoryInfo(const BRepositoryInfo& repositoryInfo)
	{
		printf("repository-info:\n");
		printf("\tname: %s\n", repositoryInfo.Name().String());
		printf("\tsummary: %s\n", repositoryInfo.Summary().String());
		printf("\turl: %s\n", repositoryInfo.OriginalBaseURL().String());
		printf("\tvendor: %s\n", repositoryInfo.Vendor().String());
		printf("\tpriority: %u\n", repositoryInfo.Priority());
		printf("\tarchitecture: %s\n",
			BPackageInfo::kArchitectureNames[repositoryInfo.Architecture()]);
		const BStringList licenseNames = repositoryInfo.LicenseNames();
		if (!licenseNames.IsEmpty()) {
			printf("\tlicenses:\n");
			for (int i = 0; i < licenseNames.CountStrings(); ++i)
				printf("\t\t%s\n", licenseNames.StringAt(i).String());
		}

		return B_OK;
	}
Beispiel #19
0
int
get_lines(BString *message, BStringList& list, int *longestLine)
{
	BString copy(*message);
	// Convert tabs to 4 spaces
	copy.ReplaceAll("\t", "    ");
	if (copy.Split("\n", false, list)) {
		int maxLength = 0;
		int32 count = list.CountStrings();
		for (int32 i = 0; i < count; i++) {
			int32 length = list.StringAt(i).Length();
			if (length  > maxLength) {
				maxLength = length;
				*longestLine = i;
			}
		}
		return count;
	}
	return 0;
}
Beispiel #20
0
void
LaunchDaemon::_AddRunTargets(BMessage& message, const char* name)
{
	BMessage targets;
	if (name != NULL && message.FindMessage(name, &targets) != B_OK)
		return;

	const char* target;
	for (int32 index = 0; targets.FindString("target", index, &target) == B_OK;
			index++) {
		fRunTargets.Add(target);
	}
}
Beispiel #21
0
void
MainWindow::_ShowDocumentation()
{
	BPathFinder pathFinder;
	BStringList paths;
	BPath path;
	BEntry entry;

	status_t error = pathFinder.FindPaths(B_FIND_PATH_DOCUMENTATION_DIRECTORY,
		"packages/pecorename", paths);

	for (int i = 0; i < paths.CountStrings(); ++i) {
		if (error == B_OK && path.SetTo(paths.StringAt(i)) == B_OK
				&& path.Append(B_TRANSLATE_COMMENT("ReadMe.html",
				"Path to the help file. Only change if a translated file is "
				"provided.")) == B_OK) {
			entry = path.Path();
			entry_ref ref;
			entry.GetRef(&ref);
			be_roster->Launch(&ref);
		}
	}
}
Beispiel #22
0
status_t
TeamWindow::_RetrieveMatchingSourceWorker(void* arg)
{
	TeamWindow* window = (TeamWindow*)arg;

	BStringList* entries = new(std::nothrow) BStringList();
	if (entries == NULL)
		return B_NO_MEMORY;
	ObjectDeleter<BStringList> stringListDeleter(entries);

	if (!window->Lock())
		return B_BAD_VALUE;

	BString path;
	window->fActiveFunction->GetFunctionDebugInfo()->SourceFile()
		->GetPath(path);
	window->Unlock();

	status_t error = window->_RetrieveMatchingSourceEntries(path, entries);
	if (error != B_OK)
		return error;

	entries->Sort();
	BMessenger messenger(window);
	if (messenger.IsValid() && messenger.LockTarget()) {
		if (window->fActiveSourceWorker == find_thread(NULL)) {
			BMessage message(MSG_SOURCE_ENTRY_QUERY_COMPLETE);
			message.AddPointer("entries", entries);
			if (messenger.SendMessage(&message) == B_OK)
				stringListDeleter.Detach();
		}
		window->Unlock();
	}

	return B_OK;
}
Beispiel #23
0
void
POP3Protocol::CheckForDeletedMessages()
{
	{
		// Delete things from the manifest no longer on the server
		BStringList list;
		NotHere(fUniqueIDs, fManifest, &list);
		fManifest.Remove(list);
	}

	if (!fSettings.FindBool("delete_remote_when_local")
		|| fManifest.CountStrings() == 0)
		return;

	BStringList toDelete;

	BStringList queryContents;
	BVolumeRoster volumes;
	BVolume volume;

	while (volumes.GetNextVolume(&volume) == B_OK) {
		BQuery fido;
		entry_ref entry;

		fido.SetVolume(&volume);
		fido.PushAttr(B_MAIL_ATTR_ACCOUNT_ID);
		fido.PushInt32(fAccountSettings.AccountID());
		fido.PushOp(B_EQ);

		fido.Fetch();

		BString uid;
		while (fido.GetNextRef(&entry) == B_OK) {
			BNode(&entry).ReadAttrString("MAIL:unique_id", &uid);
			queryContents.Add(uid);
		}
	}
	NotHere(queryContents, fManifest, &toDelete);

	for (int32 i = 0; i < toDelete.CountStrings(); i++) {
		printf("delete mail on server uid %s\n", toDelete.StringAt(i).String());
		Delete(fUniqueIDs.IndexOf(toDelete.StringAt(i)));
	}

	// Don't remove ids from fUniqueIDs, the indices have to stay the same when
	// retrieving new messages.
	fManifest.Remove(toDelete);

	// TODO: at some point the purged manifest should be written to disk
	// otherwise it will grow forever
}
Beispiel #24
0
void
BaseJob::_ParseExportVariable(BStringList& environment, const BString& line)
{
	if (!line.StartsWith("export "))
		return;

	int separator = line.FindFirst("=\"");
	if (separator < 0)
		return;

	BString variable;
	line.CopyInto(variable, 7, separator - 7);

	BString value;
	line.CopyInto(value, separator + 2, line.Length() - separator - 3);

	variable << "=" << value;
	environment.Add(variable);
}
Beispiel #25
0
thread_id
TeamDebugHandler::_EnterDebugger(bool saveReport)
{
	TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): team %" B_PRId32
		"\n", fTeam));

	// prepare a debugger handover
	TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): preparing "
		"debugger handover for team %" B_PRId32 "...\n", fTeam));

	status_t error = send_debug_message(&fDebugContext,
		B_DEBUG_MESSAGE_PREPARE_HANDOVER, NULL, 0, NULL, 0);
	if (error != B_OK) {
		debug_printf("debug_server: Failed to prepare debugger handover: %s\n",
			strerror(error));
		return error;
	}

	BStringList arguments;
	const char *argv[16];
	int argc = 0;

	bool debugInConsoled = _IsGUIServer() || !_AreGUIServersAlive();
#ifdef HANDOVER_USE_GDB

	error = _SetupGDBArguments(arguments, debugInConsoled);
	if (error != B_OK) {
		debug_printf("debug_server: Failed to set up gdb arguments: %s\n",
			strerror(error));
		return error;
	}

	// start the terminal
	TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): starting  "
		"terminal (debugger) for team %" B_PRId32 "...\n", fTeam));

#elif defined(HANDOVER_USE_DEBUGGER)
	if (debugInConsoled) {
		error = _SetupGDBArguments(arguments, debugInConsoled);
		if (error != B_OK) {
			debug_printf("debug_server: Failed to set up gdb arguments: %s\n",
				strerror(error));
			return error;
		}
	} else {
		// prepare the argument vector
		BPath debuggerPath;
		error = find_directory(B_SYSTEM_APPS_DIRECTORY, &debuggerPath);
		if (error != B_OK) {
			debug_printf("debug_server: can't find system-apps directory: %s\n",
				strerror(error));
			return error;
		}
		error = debuggerPath.Append("Debugger");
		if (error != B_OK) {
			debug_printf("debug_server: can't append to system-apps path: %s\n",
				strerror(error));
			return error;
		}
		if (!arguments.Add(debuggerPath.Path()))
			return B_NO_MEMORY;

		BString debuggerParam;
		debuggerParam.SetToFormat("%" B_PRId32, fTeam);
		if (saveReport) {
			if (!arguments.Add("--save-report"))
				return B_NO_MEMORY;
		}
		if (!arguments.Add("--team") || !arguments.Add(debuggerParam))
			return B_NO_MEMORY;

		// start the debugger
		TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): starting  "
			"graphical debugger for team %" B_PRId32 "...\n", fTeam));
	}
#endif

	for (int32 i = 0; i < arguments.CountStrings(); i++)
		argv[argc++] = arguments.StringAt(i).String();
	argv[argc] = NULL;

	thread_id thread = load_image(argc, argv, (const char**)environ);
	if (thread < 0) {
		debug_printf("debug_server: Failed to start debugger: %s\n",
			strerror(thread));
		return thread;
	}
	resume_thread(thread);

	TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): debugger started "
		"for team %" B_PRId32 ": thread: %" B_PRId32 "\n", fTeam, thread));

	return thread;
}
bool
BActivationTransaction::SetPackagesToDeactivate(const BStringList& packages)
{
	fPackagesToDeactivate = packages;
	return fPackagesToDeactivate.CountStrings() == packages.CountStrings();
}
Beispiel #27
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");
	}
}
/*
iterate over add-on-folders and collect information about each
catalog-add-ons (types of catalogs) into fCatalogAddOnInfos.
*/
status_t
LocaleRosterData::_InitializeCatalogAddOns()
{
	BAutolock lock(fLock);
	if (!lock.IsLocked())
		return B_ERROR;

	// add info about embedded default catalog:
	CatalogAddOnInfo* defaultCatalogAddOnInfo
		= new(std::nothrow) CatalogAddOnInfo("Default", "",
			DefaultCatalog::kDefaultCatalogAddOnPriority);
	if (!defaultCatalogAddOnInfo)
		return B_NO_MEMORY;

	defaultCatalogAddOnInfo->fInstantiateFunc = DefaultCatalog::Instantiate;
	defaultCatalogAddOnInfo->fCreateFunc = DefaultCatalog::Create;
	fCatalogAddOnInfos.AddItem((void*)defaultCatalogAddOnInfo);

	BStringList folders;
	BPathFinder::FindPaths(B_FIND_PATH_ADD_ONS_DIRECTORY, "locale/catalogs/",
		B_FIND_PATH_EXISTING_ONLY, folders);

	BPath addOnPath;
	BDirectory addOnFolder;
	char buf[4096];
	status_t err;
	for (int32 f = 0; f < folders.CountStrings(); f++) {
		BString addOnFolderName = folders.StringAt(f);
		err = addOnFolder.SetTo(addOnFolderName.String());
		if (err != B_OK)
			continue;

		// scan through all the folder's entries for catalog add-ons:
		int32 count;
		int8 priority;
		entry_ref eref;
		BNode node;
		BEntry entry;
		dirent* dent;
		while ((count = addOnFolder.GetNextDirents((dirent*)buf, sizeof(buf)))
				> 0) {
			dent = (dirent*)buf;
			while (count-- > 0) {
				if (strcmp(dent->d_name, ".") != 0
						&& strcmp(dent->d_name, "..") != 0
						&& strcmp(dent->d_name, "x86") != 0
						&& strcmp(dent->d_name, "x86_gcc2") != 0) {
					// we have found (what should be) a catalog-add-on:
					eref.device = dent->d_pdev;
					eref.directory = dent->d_pino;
					eref.set_name(dent->d_name);
					entry.SetTo(&eref, true);
						// traverse through any links to get to the real thang!
					node.SetTo(&entry);
					priority = -1;
					if (node.ReadAttr(kPriorityAttr, B_INT8_TYPE, 0,
						&priority, sizeof(int8)) <= 0) {
						// add-on has no priority-attribute yet, so we load it
						// to fetch the priority from the corresponding
						// symbol...
						BString fullAddOnPath(addOnFolderName);
						fullAddOnPath << "/" << dent->d_name;
						image_id image = load_add_on(fullAddOnPath.String());
						if (image >= B_OK) {
							uint8* prioPtr;
							if (get_image_symbol(image, "gCatalogAddOnPriority",
								B_SYMBOL_TYPE_DATA,
								(void**)&prioPtr) == B_OK) {
								priority = *prioPtr;
								node.WriteAttr(kPriorityAttr, B_INT8_TYPE, 0,
									&priority, sizeof(int8));
							}
							unload_add_on(image);
						}
					}

					if (priority >= 0) {
						// add-ons with priority < 0 will be ignored
						CatalogAddOnInfo* addOnInfo
							= new(std::nothrow) CatalogAddOnInfo(dent->d_name,
								addOnFolderName, priority);
						if (addOnInfo)
							fCatalogAddOnInfos.AddItem((void*)addOnInfo);
					}
				}
				// Bump the dirent-pointer by length of the dirent just handled:
				dent = (dirent*)((char*)dent + dent->d_reclen);
			}
		}
	}
	fCatalogAddOnInfos.SortItems(CompareInfos);

	return B_OK;
}
Beispiel #29
0
status_t
TeamDebugHandler::_SetupGDBArguments(BStringList &arguments, bool usingConsoled)
{
    // prepare the argument vector
    BString teamString;
    teamString.SetToFormat("--pid=%" B_PRId32, fTeam);

    status_t error;
    BPath terminalPath;
    if (usingConsoled) {
        error = find_directory(B_SYSTEM_BIN_DIRECTORY, &terminalPath);
        if (error != B_OK) {
            debug_printf("debug_server: can't find system-bin directory: %s\n",
                         strerror(error));
            return error;
        }
        error = terminalPath.Append("consoled");
        if (error != B_OK) {
            debug_printf("debug_server: can't append to system-bin path: %s\n",
                         strerror(error));
            return error;
        }
    } else {
        error = find_directory(B_SYSTEM_APPS_DIRECTORY, &terminalPath);
        if (error != B_OK) {
            debug_printf("debug_server: can't find system-apps directory: %s\n",
                         strerror(error));
            return error;
        }
        error = terminalPath.Append("Terminal");
        if (error != B_OK) {
            debug_printf("debug_server: can't append to system-apps path: %s\n",
                         strerror(error));
            return error;
        }
    }

    arguments.MakeEmpty();
    if (!arguments.Add(terminalPath.Path()))
        return B_NO_MEMORY;

    if (!usingConsoled) {
        BString windowTitle;
        windowTitle.SetToFormat("Debug of Team %" B_PRId32 ": %s", fTeam,
                                _LastPathComponent(fExecutablePath));
        if (!arguments.Add("-t") || !arguments.Add(windowTitle))
            return B_NO_MEMORY;
    }

    BPath gdbPath;
    error = find_directory(B_SYSTEM_BIN_DIRECTORY, &gdbPath);
    if (error != B_OK) {
        debug_printf("debug_server: can't find system-bin directory: %s\n",
                     strerror(error));
        return error;
    }
    error = gdbPath.Append("gdb");
    if (error != B_OK) {
        debug_printf("debug_server: can't append to system-bin path: %s\n",
                     strerror(error));
        return error;
    }
    if (!arguments.Add(gdbPath.Path()) || !arguments.Add(teamString))
        return B_NO_MEMORY;

    if (strlen(fExecutablePath) > 0 && !arguments.Add(fExecutablePath))
        return B_NO_MEMORY;

    return B_OK;
}
Beispiel #30
0
thread_id
TeamDebugHandler::_EnterDebugger(bool saveReport)
{
    TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): team %" B_PRId32
           "\n", fTeam));

    // prepare a debugger handover
    TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): preparing "
           "debugger handover for team %" B_PRId32 "...\n", fTeam));

    status_t error = send_debug_message(&fDebugContext,
                                        B_DEBUG_MESSAGE_PREPARE_HANDOVER, NULL, 0, NULL, 0);
    if (error != B_OK) {
        debug_printf("debug_server: Failed to prepare debugger handover: %s\n",
                     strerror(error));
        return error;
    }

    BStringList arguments;
    const char *argv[16];
    int argc = 0;

    bool debugInConsoled = _IsGUIServer() || !_AreGUIServersAlive();
#ifdef HANDOVER_USE_GDB

    error = _SetupGDBArguments(arguments, debugInConsoled);
    if (error != B_OK) {
        debug_printf("debug_server: Failed to set up gdb arguments: %s\n",
                     strerror(error));
        return error;
    }

    // start the terminal
    TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): starting  "
           "terminal (debugger) for team %" B_PRId32 "...\n", fTeam));

#elif defined(HANDOVER_USE_DEBUGGER)
    if (!debugInConsoled && !saveReport
            && be_roster->IsRunning(kDebuggerSignature)) {

        // for graphical handovers, check if Debugger is already running,
        // and if it is, simply send it a message to attach to the requested
        // team.
        BMessenger messenger(kDebuggerSignature);
        BMessage message(MSG_DEBUG_THIS_TEAM);
        if (message.AddInt32("team", fTeam) == B_OK
                && messenger.SendMessage(&message) == B_OK) {
            return 0;
        }
    }

    // prepare the argument vector
    BPath debuggerPath;
    if (debugInConsoled) {
        error = find_directory(B_SYSTEM_BIN_DIRECTORY, &debuggerPath);
        if (error != B_OK) {
            debug_printf("debug_server: can't find system-bin directory: %s\n",
                         strerror(error));
            return error;
        }
        error = debuggerPath.Append("consoled");
        if (error != B_OK) {
            debug_printf("debug_server: can't append to system-bin path: %s\n",
                         strerror(error));
            return error;
        }

        if (!arguments.Add(debuggerPath.Path()))
            return B_NO_MEMORY;
    }

    error = find_directory(B_SYSTEM_APPS_DIRECTORY, &debuggerPath);
    if (error != B_OK) {
        debug_printf("debug_server: can't find system-apps directory: %s\n",
                     strerror(error));
        return error;
    }
    error = debuggerPath.Append("Debugger");
    if (error != B_OK) {
        debug_printf("debug_server: can't append to system-apps path: %s\n",
                     strerror(error));
        return error;
    }
    if (!arguments.Add(debuggerPath.Path()))
        return B_NO_MEMORY;

    if (debugInConsoled && !arguments.Add("--cli"))
        return B_NO_MEMORY;

    BString debuggerParam;
    debuggerParam.SetToFormat("%" B_PRId32, fTeam);
    if (saveReport) {
        if (!arguments.Add("--save-report"))
            return B_NO_MEMORY;
    }
    if (!arguments.Add("--team") || !arguments.Add(debuggerParam))
        return B_NO_MEMORY;

    // start the debugger
    TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): starting  "
           "%s debugger for team %" B_PRId32 "...\n",
           debugInConsoled ? "command line" : "graphical", fTeam));
#endif

    for (int32 i = 0; i < arguments.CountStrings(); i++)
        argv[argc++] = arguments.StringAt(i).String();
    argv[argc] = NULL;

    thread_id thread = load_image(argc, argv, (const char**)environ);
    if (thread < 0) {
        debug_printf("debug_server: Failed to start debugger: %s\n",
                     strerror(thread));
        return thread;
    }
    resume_thread(thread);

    TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): debugger started "
           "for team %" B_PRId32 ": thread: %" B_PRId32 "\n", fTeam, thread));

    return thread;
}