Пример #1
0
BMenu*
MenuBuilder::BuildMenu(KeyBind* bind, MenuFilter* filter,
	 CustomMenuCreator* custom)
{
	if (bind == NULL)
		return NULL;

	// The first item describe the menu
	BMenu* menu = new BMenu(bind[0].label);

	if (filter != NULL)
		filter->FilterMenu(menu, bind[0].message);

	BObjectList<BMenu> menuList;
	menuList.AddItem(menu);

	for (int i = 1; bind[i].itemType != FABER_EOF; i++) {
		menu = menuList.ItemAt(menuList.CountItems()-1);

		if (bind[i].itemType == FABER_ITEM_START) {
			BMenu* subMenu = NULL;
			subMenu = new BMenu(bind[i].label);

			if (filter != NULL)
				filter->FilterMenu(subMenu, bind[i].message);

			menu->AddItem(subMenu);
			menuList.AddItem(subMenu);

		} else if (bind[i].itemType == FABER_ITEM_END) {
			if (menuList.CountItems() > 1)
				menuList.RemoveItemAt(menuList.CountItems()-1);
		} else if (bind[i].itemType == FABER_CUSTOM_ITEM) {
			if (custom == NULL)
				continue;

			BMenu* customMenu = custom->CreateCustomMenu(bind[i].message);

			if (customMenu != NULL)
				menu->AddItem(customMenu);

		} else if (bind[i].itemType == FABER_SUBITEM) {
			BMenuItem* item = BuildMenuItem(bind[i].message, bind[i].label);

			if (filter != NULL)
				filter->FilterItem(item, bind[i].message);

			menu->AddItem(item);
		} else if (bind[i].itemType == FABER_SPLITTER)
			menu->AddItem(new BSeparatorItem());
	}
	return menuList.ItemAt(0);
}
Пример #2
0
// TODO: move this to the KeyStore or the registrar backend if needed
static bool
CompareLists(BObjectList<BString> a, BObjectList<BString> b)
{
	if (a.CountItems() != b.CountItems())
		return false;

	for (int32 i = 0; i < a.CountItems(); i++) {
		if (*a.ItemAt(i) != *b.ItemAt(i))
			return false;
	}

	return true;
}
Пример #3
0
status_t
ImageDebugInfo::FinishInit(DebuggerInterface* interface)
{
	BObjectList<SymbolInfo> symbols(50, true);
	status_t error = interface->GetSymbolInfos(fImageInfo.TeamID(),
		fImageInfo.ImageID(), symbols);
	if (error != B_OK)
		return error;
	symbols.SortItems(&_CompareSymbols);

	// get functions -- get them from most expressive debug info first and add
	// missing functions from less expressive debug infos
	for (int32 i = 0; SpecificImageDebugInfo* specificInfo
			= fSpecificInfos.ItemAt(i); i++) {
		BObjectList<FunctionDebugInfo> functions;
		error = specificInfo->GetFunctions(symbols, functions);
		if (error != B_OK)
			return error;

		for (int32 k = 0; FunctionDebugInfo* function = functions.ItemAt(k);
				k++) {
			if (FunctionAtAddress(function->Address()) != NULL)
				continue;

			FunctionInstance* instance = new(std::nothrow) FunctionInstance(
				this, function);
			if (instance == NULL
				|| !fFunctions.BinaryInsert(instance, &_CompareFunctions)) {
				delete instance;
				error = B_NO_MEMORY;
				break;
			}

			if (function->IsMain())
				fMainFunction = instance;
		}

		// Remove references returned by the specific debug info -- the
		// FunctionInstance objects have references, now.
		for (int32 k = 0; FunctionDebugInfo* function = functions.ItemAt(k);
				k++) {
			function->ReleaseReference();
		}

		if (error != B_OK)
			return error;
	}

	return B_OK;
}
Пример #4
0
/*static*/ status_t
SpecificImageDebugInfo::GetFunctionsFromSymbols(
	const BObjectList<SymbolInfo>& symbols,
	BObjectList<FunctionDebugInfo>& functions, DebuggerInterface* interface,
	const ImageInfo& imageInfo, SpecificImageDebugInfo* info)
{
	// 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(
			info, 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;
}
Пример #5
0
BSolverPackage*
PackageManager::_GetSolverPackage(PackageInfoRef package)
{
	int32 flags = BSolver::B_FIND_IN_NAME;
	if (package->State() == ACTIVATED || package->State() == INSTALLED)
		flags |= BSolver::B_FIND_INSTALLED_ONLY;

	BObjectList<BSolverPackage> packages;
	status_t result = Solver()->FindPackages(package->Title(),
		flags, packages);
	if (result == B_OK) {
		for (int32 i = 0; i < packages.CountItems(); i++) {
			BSolverPackage* solverPackage = packages.ItemAt(i);
			if (solverPackage->Name() != package->Title())
				continue;
			else if (package->State() == NONE
				&& dynamic_cast<BPackageManager::RemoteRepository*>(
					solverPackage->Repository()) == NULL) {
				continue;
			}
			return solverPackage;
		}
	}

	return NULL;
}
Пример #6
0
void
PairsView::Draw(BRect updateRect)
{
	BObjectList<BBitmap>* bitmapsList;
	switch (fIconSize) {
		case kSmallIconSize:
			bitmapsList = fSmallBitmapsList;
			break;

		case kLargeIconSize:
			bitmapsList = fLargeBitmapsList;
			break;

		case kMediumIconSize:
		default:
			bitmapsList = fMediumBitmapsList;
	}

	for (int32 i = 0; i < fButtonsCount; i++) {
		SetDrawingMode(B_OP_ALPHA);
		DrawBitmap(bitmapsList->ItemAt(i % (fButtonsCount / 2)),
			BPoint(fPositionX[i], fPositionY[i]));
		SetDrawingMode(B_OP_COPY);
	}
}
Пример #7
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);
		bool hasVersion = resolvableExpr->Version().InitCheck() == B_OK;

		PackageAttribute* name = new PackageAttribute((BHPKGAttributeID)id,
			B_HPKG_ATTRIBUTE_TYPE_STRING,
			B_HPKG_ATTRIBUTE_ENCODING_STRING_TABLE);
		name->string = fPackageStringCache.Get(resolvableExpr->Name().String());
		attributeList.Add(name);

		if (hasVersion) {
			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());
		}
	}
}
Пример #8
0
/** We share one global list for all BMediaFormats in the team - since the
 *	format data can change at any time, we have to update the list to ensure
 *	that we are working on the latest data set. The list is always sorted by
 *	description. The formats lock has to be held when you call this function.
 */
static status_t
update_media_formats()
{
	if (!sLock.IsLocked())
		return B_NOT_ALLOWED;

	// We want the add-ons to register themselves with the format manager, so
	// the list is up to date.
	AddOnManager::GetInstance()->RegisterAddOns();

	BMessage reply;
	FormatManager::GetInstance()->GetFormats(sLastFormatsUpdate, reply);

	// do we need an update at all?
	bool needUpdate;
	if (reply.FindBool("need_update", &needUpdate) < B_OK)
		return B_ERROR;
	if (!needUpdate)
		return B_OK;

	// update timestamp and check if the message is okay
	type_code code;
	int32 count;
	if (reply.FindInt64("timestamp", &sLastFormatsUpdate) < B_OK
		|| reply.GetInfo("formats", &code, &count) < B_OK)
		return B_ERROR;

	// overwrite already existing formats

	int32 index = 0;
	for (; index < sFormats.CountItems() && index < count; index++) {
		meta_format* item = sFormats.ItemAt(index);

		const meta_format* newItem;
		ssize_t size;
		if (reply.FindData("formats", MEDIA_META_FORMAT_TYPE, index,
				(const void**)&newItem, &size) == B_OK)
			*item = *newItem;
	}

	// allocate additional formats

	for (; index < count; index++) {
		const meta_format* newItem;
		ssize_t size;
		if (reply.FindData("formats", MEDIA_META_FORMAT_TYPE, index,
				(const void**)&newItem, &size) == B_OK)
			sFormats.AddItem(new meta_format(*newItem));
	}

	// remove no longer used formats

	while (count < sFormats.CountItems())
		delete sFormats.RemoveItemAt(count);

	return B_OK;
}
Пример #9
0
void
reconnect_bitmaps_to_app_server()
{
	BAutolock _(sBitmapListLock);
	for (int32 i = 0; i < sBitmapList.CountItems(); i++) {
		BBitmap::Private bitmap(sBitmapList.ItemAt(i));
		bitmap.ReconnectToAppServer();
	}
}
Пример #10
0
static void add_resolvables(Repo *repo, Offset &dependencies,
  const BObjectList<BPackageResolvable> &resolvables)
{
  for (int32 i = 0; BPackageResolvable *resolvable = resolvables.ItemAt(i); i++)
    {
      add_dependency(repo, dependencies, resolvable->Name(),
        resolvable->Version().ToString(), REL_EQ,
        resolvable->CompatibleVersion().ToString());
    }
}
Пример #11
0
void ChannelAgent::RemoveNickFromList(BObjectList<BString>& list, const char* data)
{
	int32 count(list.CountItems());
	for (int32 i = 0; i < count; i++) {
		if (list.ItemAt(i)->ICompare(data) == 0) {
			delete list.RemoveItemAt(i);
			break;
		}
	}
}
Пример #12
0
Task* TaskMerge::MergeTasks(Task* firstTask, Task *secondTask)
{
	int32	i	= 0;
	BObjectList<TaskSync>* oldSyncs = NULL;
	if ((*firstTask) == (*secondTask))
		return firstTask;
	if ((*firstTask)>(*secondTask)){
		oldSyncs	= secondTask->Source();
		secondTask->SetTo(firstTask);
		for (i=0;i<oldSyncs->CountItems();i++)
				secondTask->AddSource(oldSyncs->ItemAt(i));
		return secondTask;
	}
	else{
		oldSyncs	= firstTask->Source();
		firstTask->SetTo(secondTask);
		for (i=0;i<oldSyncs->CountItems();i++)
				firstTask->AddSource(oldSyncs->ItemAt(i));
		return firstTask;
	}
}
Пример #13
0
status_t
ImageDebugInfo::FinishInit()
{
	// get functions -- get them from most expressive debug info first and add
	// missing functions from less expressive debug infos
	for (int32 i = 0; SpecificImageDebugInfo* specificInfo
			= fSpecificInfos.ItemAt(i); i++) {
		BObjectList<FunctionDebugInfo> functions;
		status_t error = specificInfo->GetFunctions(functions);
		if (error != B_OK)
			return error;

		for (int32 k = 0; FunctionDebugInfo* function = functions.ItemAt(k);
				k++) {
			if (FunctionAtAddress(function->Address()) != NULL)
				continue;

			FunctionInstance* instance = new(std::nothrow) FunctionInstance(
				this, function);
			if (instance == NULL
				|| !fFunctions.BinaryInsert(instance, &_CompareFunctions)) {
				delete instance;
				error = B_NO_MEMORY;
				break;
			}
		}

		// Remove references returned by the specific debug info -- the
		// FunctionInstance objects have references, now.
		for (int32 k = 0; FunctionDebugInfo* function = functions.ItemAt(k);
				k++) {
			function->ReleaseReference();
		}

		if (error != B_OK)
			return error;
	}

	return B_OK;
}
Пример #14
0
status_t
DebugReportGenerator::_DumpRunningThreads(BFile& _output)
{
	AutoLocker< ::Team> locker(fTeam);

	BString data("\nActive Threads:\n");
	WRITE_AND_CHECK(_output, data);
	BObjectList< ::Thread> threads;
	::Thread* thread;
	for (ThreadList::ConstIterator it = fTeam->Threads().GetIterator();
		  (thread = it.Next());) {
		 threads.AddItem(thread);
	}

	threads.SortItems(&_CompareThreads);
	for (int32 i = 0; (thread = threads.ItemAt(i)) != NULL; i++) {
		try {
			data.SetToFormat("\tthread %" B_PRId32 ": %s %s\n", thread->ID(),
					thread->Name(), thread->IsMainThread()
						? "(main)" : "");
			WRITE_AND_CHECK(_output, data);

			if (thread->State() == THREAD_STATE_STOPPED) {
				data.SetToFormat("\t\tstate: %s",
					UiUtils::ThreadStateToString(thread->State(),
							thread->StoppedReason()));
				const BString& stoppedInfo = thread->StoppedReasonInfo();
				if (stoppedInfo.Length() != 0)
					data << " (" << stoppedInfo << ")";
				data << "\n\n";
				WRITE_AND_CHECK(_output, data);

				// we need to release our lock on the team here
				// since we might need to block and wait
				// on the stack trace.
				BReference< ::Thread> threadRef(thread);
				locker.Unlock();
				status_t error = _DumpDebuggedThreadInfo(_output, thread);
				if (error != B_OK)
					return error;
				locker.Lock();
			}
		} catch (...) {
			return B_NO_MEMORY;
		}
	}

	return B_OK;
}
Пример #15
0
status_t
ModuleManager::_GetAddOn(const char *name, ModuleAddOn **_addon)
{
	// search list first
	for (int32 i = 0; ModuleAddOn *addon = fAddOns.ItemAt(i); i++) {
		BString addonName(addon->Name());
		addonName << "/";
		if (!strcmp(name, addon->Name())
			|| !strncmp(addonName.String(), name, addonName.Length())) {
			addon->Get();
			*_addon = addon;
			return B_OK;
		}
	}
	// not in list yet, load from disk
	// iterate through module dirs
	for (int32 i = 0; gModuleDirs[i]; i++) {
		BPath path;
		if (path.SetTo(gModuleDirs[i]) == B_OK
			&& path.SetTo(path.Path(), name) == B_OK) {
			BEntry entry;
			for (;;) {
				if (entry.SetTo(path.Path()) == B_OK && entry.Exists()) {
					// found an entry: if it is a file, try to load it
					if (entry.IsFile()) {
						ModuleAddOn *addon = new ModuleAddOn;
						if (addon->Load(path.Path(), gModuleDirs[i]) == B_OK) {
							status_t status = addon->Get();
							if (status < B_OK) {
								delete addon;
								return status;
							}

							fAddOns.AddItem(addon);
							*_addon = addon;
							return B_OK;
						}
						delete addon;
					}
					break;
				}
				// chop off last path component
				if (path.GetParent(&path) != B_OK)
					break;
			}
		}
	}
	return B_ENTRY_NOT_FOUND;
}
Пример #16
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);
	}
}
Пример #17
0
status_t
DebugReportGenerator::_DumpLoadedImages(BFile& _output)
{
	AutoLocker< ::Team> locker(fTeam);

	BString data("\nLoaded Images:\n");
	WRITE_AND_CHECK(_output, data);
	BObjectList<Image> images;
	for (ImageList::ConstIterator it = fTeam->Images().GetIterator();
		 Image* image = it.Next();) {
		 images.AddItem(image);
	}

	images.SortItems(&_CompareImages);

	Image* image = NULL;
	data.SetToFormat("\tID\t\tText Base\tText End\tData Base\tData"
		" End\tType\tName\n\t");
	WRITE_AND_CHECK(_output, data);
	data.Truncate(0L);
	data.Append('-', 80);
	data.Append("\n");
	WRITE_AND_CHECK(_output, data);
	for (int32 i = 0; (image = images.ItemAt(i)) != NULL; i++) {
		const ImageInfo& info = image->Info();
		char buffer[32];
		try {
			target_addr_t textBase = info.TextBase();
			target_addr_t dataBase = info.DataBase();

			data.SetToFormat("\t%" B_PRId32 "\t0x%08" B_PRIx64 "\t"
				"0x%08" B_PRIx64 "\t0x%08" B_PRIx64 "\t0x%08" B_PRIx64 "\t"
				"%-7s\t%s\n", info.ImageID(), textBase, textBase + info.TextSize(),
				dataBase, dataBase + info.DataSize(),
				UiUtils::ImageTypeToString(info.Type(), buffer,
					sizeof(buffer)), info.Name().String());

			WRITE_AND_CHECK(_output, data);
		} catch (...) {
			return B_NO_MEMORY;
		}
	}

	return B_OK;
}
Пример #18
0
void
TFilePanel::HandleOpenButton()
{
	PoseView()->CommitActivePose();
	BObjectList<BPose>* selection = PoseView()->SelectionList();

	// if we have only one directory and we're not opening dirs, enter.
	if ((fNodeFlavors & B_DIRECTORY_NODE) == 0
		&& selection->CountItems() == 1) {
		Model* model = selection->FirstItem()->TargetModel();

		if (model->IsDirectory()
			|| (model->IsSymLink() && !(fNodeFlavors & B_SYMLINK_NODE)
				&& model->ResolveIfLink()->IsDirectory())) {

			BMessage message(B_REFS_RECEIVED);
			message.AddRef("refs", model->EntryRef());
			PostMessage(&message);
			return;
		}
	}

	// don't do anything unless there are items selected
    // message->fMessage->message from here to end
	if (selection->CountItems()) {
		BMessage message(*fMessage);
		// go through selection and add appropriate items
		for (int32 index = 0; index < selection->CountItems(); index++) {
			Model* model = selection->ItemAt(index)->TargetModel();

			if (((fNodeFlavors & B_DIRECTORY_NODE) != 0
					&& model->ResolveIfLink()->IsDirectory())
				|| ((fNodeFlavors & B_SYMLINK_NODE) != 0 && model->IsSymLink())
				|| ((fNodeFlavors & B_FILE_NODE) != 0
					&& model->ResolveIfLink()->IsFile())) {
				message.AddRef("refs", model->EntryRef());
			}
		}

		OpenSelectionCommon(&message);
	}
}
Пример #19
0
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();
}
Пример #20
0
static void add_resolvable_expressions(Repo *repo, Offset &dependencies,
  const BObjectList<BPackageResolvableExpression> &expressions)
{
  for (int32 i = 0;
    BPackageResolvableExpression *expression = expressions.ItemAt(i); i++)
    {
      // It is possible that no version is specified. In that case any version
      // is acceptable.
      if (expression->Version().InitCheck() != B_OK)
        {
          BPackageVersion version;
          add_dependency(repo, dependencies, expression->Name(), NULL, 0);
          continue;
        }

      int flags = 0;
      switch (expression->Operator())
        {
          case B_PACKAGE_RESOLVABLE_OP_LESS:
            flags |= REL_LT;
            break;
          case B_PACKAGE_RESOLVABLE_OP_LESS_EQUAL:
            flags |= REL_LT | REL_EQ;
            break;
          case B_PACKAGE_RESOLVABLE_OP_EQUAL:
            flags |= REL_EQ;
            break;
          case B_PACKAGE_RESOLVABLE_OP_NOT_EQUAL:
            break;
          case B_PACKAGE_RESOLVABLE_OP_GREATER_EQUAL:
            flags |= REL_GT | REL_EQ;
            break;
          case B_PACKAGE_RESOLVABLE_OP_GREATER:
              flags |= REL_GT;
            break;
        }

      add_dependency(repo, dependencies, expression->Name(),
        expression->Version(), flags);
    }
}
Пример #21
0
status_t
AutoConfig::GetMXRecord(const char* provider, provider_info *info)
{
	BObjectList<mx_record> mxList;
	DNSQuery dnsQuery;
	if (dnsQuery.GetMXRecords(provider, &mxList) != B_OK)
		return B_ERROR;

	mx_record *mxRec = mxList.ItemAt(0);
	if (mxRec == NULL)
		return B_ERROR;

	info->imap_server = mxRec->serverName;
	info->pop_server =  mxRec->serverName;
	info->smtp_server =  mxRec->serverName;

	info->authentification_pop = 0;
	info->authentification_smtp = 0;
	info->username_pattern = 0;
	return B_OK;

}
Пример #22
0
status_t 
BMediaFormats::GetNextFormat(media_format* _format,
	media_format_description* _description)
{
	if (!sLock.IsLocked() || sLock.LockingThread() != find_thread(NULL)) {
		// TODO: Shouldn't we simply drop into the debugger in this case?
		return B_NOT_ALLOWED;
	}

	if (fIteratorIndex == 0) {
		// This is the first call, so let's make sure we have current data to
		// operate on.
		status_t status = update_media_formats();
		if (status < B_OK)
			return status;
	}

	meta_format* format = sFormats.ItemAt(fIteratorIndex++);
	if (format == NULL)
		return B_BAD_INDEX;

	return B_OK;
}
Пример #23
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);
	}
}
Пример #24
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;
}
Пример #25
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;
}
Пример #26
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);
}
Пример #27
0
BaseJob*
ExternalEventSource::ListenerAt(int32 index) const
{
	return fListeners.ItemAt(index);
}
Пример #28
0
status_t
TeamDebugInfo::AddImageDebugInfo(ImageDebugInfo* imageDebugInfo)
{
	AutoLocker<BLocker> locker(fLock);
		// We have both locks now, so that for read-only access either lock
		// suffices.

	if (!fImages.AddItem(imageDebugInfo))
		return B_NO_MEMORY;

	// Match all of the image debug info's functions instances with functions.
	BObjectList<SourceFileEntry> sourceFileEntries;
	for (int32 i = 0;
		FunctionInstance* instance = imageDebugInfo->FunctionAt(i); i++) {
		// lookup the function or create it, if it doesn't exist yet
		Function* function = fFunctions->Lookup(instance);
		if (function != NULL) {
// TODO: Also update possible user breakpoints in this function!
			function->AddInstance(instance);
			instance->SetFunction(function);

			// The new image debug info might have additional information about
			// the source file of the function, so remember the source file
			// entry.
			if (LocatableFile* sourceFile = function->SourceFile()) {
				SourceFileEntry* entry = fSourceFiles->Lookup(sourceFile);
				if (entry != NULL && entry->GetSourceCode() != NULL)
					sourceFileEntries.AddItem(entry);
			}
		} else {
			function = new(std::nothrow) Function;
			if (function == NULL) {
				RemoveImageDebugInfo(imageDebugInfo);
				return B_NO_MEMORY;
			}
			function->AddInstance(instance);
			instance->SetFunction(function);

			status_t error = _AddFunction(function);
				// Insert after adding the instance. Otherwise the function
				// wouldn't be hashable/comparable.
			if (error != B_OK) {
				function->RemoveInstance(instance);
				instance->SetFunction(NULL);
				RemoveImageDebugInfo(imageDebugInfo);
				return error;
			}
		}
	}

	// update the source files the image debug info knows about
	for (int32 i = 0; SourceFileEntry* entry = sourceFileEntries.ItemAt(i);
			i++) {
		FileSourceCode* sourceCode = entry->GetSourceCode();
		sourceCode->Lock();
		if (imageDebugInfo->AddSourceCodeInfo(entry->SourceFile(),
				sourceCode) == B_OK) {
			// TODO: Notify interesting parties! Iterate through all functions
			// for this source file?
		}
		sourceCode->Unlock();
	}

	return B_OK;
}
Пример #29
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");
	}
}
Пример #30
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);
}