Example #1
0
//----------------------------------------------------------------------------------------
nsresult nsFileSpec::ResolveSymlink(PRBool& wasAliased)
//----------------------------------------------------------------------------------------
{
    wasAliased = PR_FALSE;

    char resolvedPath[MAXPATHLEN];
    int charCount = readlink(mPath, (char*)&resolvedPath, MAXPATHLEN);
    if (0 < charCount)
    {
        if (MAXPATHLEN > charCount)
            resolvedPath[charCount] = '\0';
        
        wasAliased = PR_TRUE;
		/* if it's not an absolute path, 
		   replace the leaf with what got resolved */
		if (resolvedPath[0] != '/') {
			SetLeafName(resolvedPath);
		}
		else {
			mPath = (char*)resolvedPath;
		} 

		BEntry e((const char *)mPath, true);	// traverse symlink
		BPath p;
		status_t err;
		err = e.GetPath(&p);
		NS_ASSERTION(err == B_OK, "realpath failed");

		const char* canonicalPath = p.Path();
		if(err == B_OK)
			mPath = (char*)canonicalPath;
		else
			return NS_ERROR_FAILURE;
    }
    return NS_OK;
} // nsFileSpec::ResolveSymlink
Example #2
0
status_t
MouseSettings::_SaveSettings()
{
	BPath path;
	status_t status = _GetSettingsPath(path);
	if (status < B_OK)
		return status;

	BFile file(path.Path(), B_READ_WRITE | B_CREATE_FILE);
	if (status < B_OK)
		return status;

#if R5_COMPATIBLE
	const off_t kOffset = sizeof(mouse_settings) - sizeof(mouse_map)
		+ sizeof(int32) * 3;
	// we have to do this because mouse_map counts 16 buttons in OBOS
#else
	const off_t kOffset = sizeof(mouse_settings);
#endif

	file.WriteAt(kOffset, &fWindowPosition, sizeof(BPoint));

	return B_OK;
}
Example #3
0
_EXPORT
int32
BTestShell::LoadSuitesFrom(BDirectory *libDir) {
	if (!libDir || libDir->InitCheck() != B_OK)
		return 0;

	BEntry addonEntry;
	BPath addonPath;
	image_id addonImage;
	int count = 0;

	typedef BTestSuite* (*suiteFunc)(void);
	suiteFunc func;

	while (libDir->GetNextEntry(&addonEntry, true) == B_OK) {
		status_t err;
		err = addonEntry.GetPath(&addonPath);
		if (!err) {
//			cout << "Checking " << addonPath.Path() << "..." << endl;
			addonImage = load_add_on(addonPath.Path());
			err = (addonImage >= 0 ? B_OK : B_ERROR);
		}
		if (err == B_OK) {
//			cout << "..." << endl;
			err = get_image_symbol(addonImage, "getTestSuite",
				B_SYMBOL_TYPE_TEXT, reinterpret_cast<void **>(&func));
		} else {
//			cout << " !!! err == " << err << endl;
		}
		if (err == B_OK)
			err = AddSuite(func());
		if (err == B_OK)
			count++;
	}
	return count;
}
Example #4
0
void
DataTranslationsWindow::_ShowInfoAlert(int32 id)
{
	const char* name = NULL;
	const char* info = NULL;
	BPath path;
	int32 version = 0;
	_GetTranslatorInfo(id, name, info, version, path);

	BString message;
	message << "Name: " << name << "\nVersion: ";

	// Convert the version number into a readable format
	message << (int)B_TRANSLATION_MAJOR_VERSION(version)
		<< '.' << (int)B_TRANSLATION_MINOR_VERSION(version)
		<< '.' << (int)B_TRANSLATION_REVISION_VERSION(version);
	message << "\nInfo: " << info <<
		"\n\nPath:\n" << path.Path() << "\n";

	BAlert *alert = new BAlert("info", message.String(), "OK");
	BTextView *view = alert->TextView();
	BFont font;

	view->SetStylable(true);

	view->GetFont(&font);
	font.SetFace(B_BOLD_FACE);

	const char* labels[] = {"Name:", "Version:", "Info:", "Path:", NULL};
	for (int32 i = 0; labels[i]; i++) {
		int32 index = message.FindFirst(labels[i]);
		view->SetFontAndColor(index, index + strlen(labels[i]), &font);
	}

	alert->Go();
}
Example #5
0
status_t
IconView::SetIcon(const BPath& path, icon_size iconSize)
{
	fDrawIcon = false;
	
	if (iconSize != fIconSize) {
		BBitmap* bitmap = new BBitmap(BRect(iconSize), B_RGBA32);
		if (bitmap == NULL)
			return B_NO_MEMORY;

		delete fIconBitmap;
		fIconBitmap = bitmap;
		fIconSize = iconSize;
	}

	status_t status = fIconBitmap->InitCheck();
	if (status != B_OK)
		return status;

	BEntry entry(path.Path());
	BNode node(&entry);
	BNodeInfo info(&node);

	status = info.GetTrackerIcon(fIconBitmap, fIconSize);
	if (status != B_OK)
		return status;

	if (!fIconBitmap->IsValid())
		return fIconBitmap->InitCheck();

	_SetSize();

	fDrawIcon = true;
	Invalidate();
	return B_OK;
}
Example #6
0
Preferences::Preferences(const char* prefsFileName)
	: file(NULL)
{
	prefs = new BMessage();
	changeClients = new BList();

	// open the file
	BPath path;
	initStatus = find_directory(B_USER_SETTINGS_DIRECTORY, &path, true);
	if (initStatus != B_NO_ERROR)
		return;
	path.Append(prefsFileName);
	file = new BFile(path.Path(), B_READ_WRITE | B_CREATE_FILE);
	initStatus = file->InitCheck();
	if (initStatus != B_NO_ERROR) {
		delete file;
		file = NULL;
		return;
		}

	// read the prefs
	file->Seek(0, SEEK_SET);
	prefs->Unflatten(file);
}
/***********************************************************
 * Save trackers.
 ***********************************************************/
void
HAddTrackerWindow::SaveTracker(const char* name,const char* address)
{
	AppUtils utils;
	BPath path = utils.GetAppDirPath(be_app);
	path.Append("Trackers");
	path.Append(name);

	BFile file(path.Path(),B_WRITE_ONLY|B_CREATE_FILE);
	if(file.InitCheck() == B_OK)
	{
		BMessage msg;
		msg.AddString("address",address);
		msg.Flatten(&file);

		BMessage msg2(M_NEW_TRACKER);
		msg2.AddString("address",address);
		msg2.AddString("name",name);
		msg2.AddInt16("port",5948);
		be_app->PostMessage(&msg2);
	}else{
		( new MAlert("Cannot save a tracker","file initialize failed","OK"))->Go();
	}
}
Example #8
0
status_t
Settings::Load()
{
	status_t status;

	BPath path;
	if ((status = _GetPath(path)) != B_OK)
		return status;

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

	BMessage load;
	if ((status = load.Unflatten(&file)) != B_OK)
		return status;

	if (load.what != kMsgNetworkTimeSettings)
		return B_BAD_TYPE;

	fMessage = load;
	fOldMessage = fMessage;
	return B_OK;
}
Example #9
0
bool
FavoritesMenu::AddNextItem()
{
	// run the next chunk of code for a given item adding state

	if (fState == kStart) {
		fState = kAddingFavorites;
		fSectionItemCount = 0;
		fAddedSeparatorForSection = false;
		// set up adding the GoTo menu items

		try {
			BPath path;
			ThrowOnError(find_directory(B_USER_SETTINGS_DIRECTORY,
				&path, true));
			path.Append(kGoDirectory);
			mkdir(path.Path(), 0777);

			BEntry entry(path.Path());
			Model startModel(&entry, true);
			ThrowOnInitCheckError(&startModel);

			if (!startModel.IsContainer())
				throw B_ERROR;

			if (startModel.IsQuery())
				fContainer = new QueryEntryListCollection(&startModel);
			else
				fContainer = new DirectoryEntryList(*dynamic_cast<BDirectory*>
					(startModel.Node()));

			ThrowOnInitCheckError(fContainer);
			ThrowOnError( fContainer->Rewind() );

		} catch (...) {
			delete fContainer;
			fContainer = NULL;
		}
	}


	if (fState == kAddingFavorites) {
		entry_ref ref;
		if (fContainer
			&& fContainer->GetNextRef(&ref) == B_OK) {
			Model model(&ref, true);
			if (model.InitCheck() != B_OK)
				return true;

			if (!ShouldShowModel(&model))
				return true;

			BMenuItem* item = BNavMenu::NewModelItem(&model,
				model.IsDirectory() ? fOpenFolderMessage : fOpenFileMessage,
				fTarget);
				
			if (item == NULL)
				return true;

			item->SetLabel(ref.name);
				// this is the name of the link in the Go dir

			if (!fAddedSeparatorForSection) {
				fAddedSeparatorForSection = true;
				AddItem(new TitledSeparatorItem(B_TRANSLATE("Favorites")));
			}
			fUniqueRefCheck.push_back(*model.EntryRef());
			AddItem(item);
			fSectionItemCount++;
			return true;
		}

		// done with favorites, set up for adding recent files
		fState = kAddingFiles;

		fAddedSeparatorForSection = false;

		app_info info;
		be_app->GetAppInfo(&info);
		fItems.MakeEmpty();

		int32 apps, docs, folders;
		TrackerSettings().RecentCounts(&apps, &docs, &folders);

		BRoster().GetRecentDocuments(&fItems, docs, NULL, info.signature);
		fIndex = 0;
		fSectionItemCount = 0;
	}

	if (fState == kAddingFiles) {
		//	if this is a Save panel, not an Open panel
		//	then don't add the recent documents
		if (!fIsSavePanel) {
			for (;;) {
				entry_ref ref;
				if (fItems.FindRef("refs", fIndex++, &ref) != B_OK)
					break;

				Model model(&ref, true);
				if (model.InitCheck() != B_OK)
					return true;

				if (!ShouldShowModel(&model))
					return true;

				BMenuItem* item = BNavMenu::NewModelItem(&model,
					fOpenFileMessage, fTarget);
				if (item) {
					if (!fAddedSeparatorForSection) {
						fAddedSeparatorForSection = true;
						AddItem(new TitledSeparatorItem(
							B_TRANSLATE("Recent documents")));
					}
					AddItem(item);
					fSectionItemCount++;
					return true;
				}
			}
		}

		// done with recent files, set up for adding recent folders
		fState = kAddingFolders;

		fAddedSeparatorForSection = false;

		app_info info;
		be_app->GetAppInfo(&info);
		fItems.MakeEmpty();

		int32 apps, docs, folders;
		TrackerSettings().RecentCounts(&apps, &docs, &folders);

		BRoster().GetRecentFolders(&fItems, folders, info.signature);
		fIndex = 0;
	}

	if (fState == kAddingFolders) {
		for (;;) {
			entry_ref ref;
			if (fItems.FindRef("refs", fIndex++, &ref) != B_OK)
				break;

			// don't add folders that are already in the GoTo section
			if (find_if(fUniqueRefCheck.begin(), fUniqueRefCheck.end(),
				bind2nd(std::equal_to<entry_ref>(), ref))
					!= fUniqueRefCheck.end()) {
				continue;
			}

			Model model(&ref, true);
			if (model.InitCheck() != B_OK)
				return true;

			if (!ShouldShowModel(&model))
				return true;

			BMenuItem* item = BNavMenu::NewModelItem(&model,
				fOpenFolderMessage, fTarget, true);
			if (item) {
				if (!fAddedSeparatorForSection) {
					fAddedSeparatorForSection = true;
					AddItem(new TitledSeparatorItem(
						B_TRANSLATE("Recent folders")));
				}
				AddItem(item);
				item->SetEnabled(true);
					// BNavMenu::NewModelItem returns a disabled item here -
					// need to fix this in BNavMenu::NewModelItem
				return true;
			}
		}
	}
	return false;
}
/*!	\brief		Creates and initializes the file panels.
 *	
 */
void 	EventEditorMainWindow::InitializeFilePanels( BString path )
{
	BPath eventualDirectoryPath;
	BPath pathToFile;
	bool	initToDefaults = false;
	BDirectory parentDirectory, eventualDirectory;
	status_t	status;

	// Initializing from a submitted path	
	do {
		if ( path != BString("") ) {
			pathToFile.SetTo( path.String() );
			if ( ( pathToFile.InitCheck() != B_OK ) ||
			 	  ( pathToFile.GetParent( &eventualDirectoryPath ) != B_OK ) ||
			 	  ( eventualDirectory.SetTo( eventualDirectoryPath.Path() ) != B_OK ) )
			{
				initToDefaults = true;
				break;	// Go to after "while"
			}
		}
		else
		{
			initToDefaults = true;
		}
	} while ( false );
	
	// Else, initialize to defaults
	if ( initToDefaults )
	{
		find_directory( B_USER_DIRECTORY,
						 &eventualDirectoryPath,
						 true );	// Useless flag - system can't boot without "home"
		parentDirectory.SetTo( eventualDirectoryPath.Path() );
		status = parentDirectory.CreateDirectory( "events", &eventualDirectory );
		if ( status == B_FILE_EXISTS ) {
			eventualDirectory.SetTo( &parentDirectory, "events" );
			status = eventualDirectory.InitCheck();
		}
		if ( status != B_OK )
		{
			global_toReturn = ( uint32 )status;
			be_app->PostMessage( B_QUIT_REQUESTED );
		}
	} // <-- end of setting default directories
	
	
	// At this point, eventualDirectory is set to the directory where files
	// should be stored.
	
	BEntry entry;
	entry_ref ref;
	eventualDirectory.GetEntry( &entry );
	entry.GetRef( &ref );

	// Construct file panels
	fOpenFile = new BFilePanel( B_OPEN_PANEL,
										 new BMessenger( Looper(), this ),
										 &ref,
										 B_FILE_NODE,
										 false,
										 new BMessage( kFileOpenConfirmed ),
										 fRefFilter );

	fSaveFile = new BFilePanel( B_SAVE_PANEL,
										 new BMessenger( Looper(), this ),
										 &ref,
										 B_FILE_NODE,
										 false,
										 new BMessage( kFileSaveConfirmed ),
										 fRefFilter );
	entry.Unset();
	if ( !fOpenFile || !fSaveFile ) {
		global_toReturn = ( uint32 )B_NO_MEMORY;
		be_app->PostMessage( B_QUIT_REQUESTED );
	}

}	// <-- end of function EventEditorMainWindow::InitializeFilePanels
Example #11
0
void
DeskbarView::MessageReceived(BMessage* message)
{
	switch(message->what)
	{
		case MD_CHECK_SEND_NOW:
			// also happens in DeskbarView::MouseUp() with
			// B_TERTIARY_MOUSE_BUTTON pressed
			BMailDaemon::CheckAndSendQueuedMail();
			break;
		case MD_CHECK_FOR_MAILS:
			BMailDaemon::CheckMail(message->FindInt32("account"));
			break;
		case MD_SEND_MAILS:
			BMailDaemon::SendQueuedMail();
			break;

		case MD_OPEN_NEW:
		{
			char* argv[] = {(char *)"New Message", (char *)"mailto:"};
			be_roster->Launch("text/x-email", 2, argv);
			break;
		}
		case MD_OPEN_PREFS:
			be_roster->Launch("application/x-vnd.Haiku-Mail");
			break;

		case MD_REFRESH_QUERY:
			_RefreshMailQuery();
			break;

		case B_QUERY_UPDATE:
		{
			int32 what;
			dev_t device;
			ino_t directory;
			const char *name;
			entry_ref ref;
			message->FindInt32("opcode", &what);
			message->FindInt32("device", &device);
			message->FindInt64("directory", &directory);
			switch (what) {
				case B_ENTRY_CREATED:
					if (message->FindString("name", &name) == B_OK) {
						ref.device = device;
						ref.directory = directory;
						ref.set_name(name);
						if (!_EntryInTrash(&ref))
							fNewMessages++;
					}
					break;
				case B_ENTRY_REMOVED:
					node_ref node;
					node.device = device;
					node.node = directory;
					BDirectory dir(&node);
					BEntry entry(&dir, NULL);
					entry.GetRef(&ref);
					if (!_EntryInTrash(&ref))
						fNewMessages--;
					break;
			}
			fStatus = (fNewMessages > 0) ? kStatusNewMail : kStatusNoMail;
			Invalidate();
			break;
		}
		case B_QUIT_REQUESTED:
			BMailDaemon::Quit();
			break;

		// open received files in the standard mail application
		case B_REFS_RECEIVED:
		{
			BMessage argv(B_ARGV_RECEIVED);
			argv.AddString("argv", "E-mail");

			entry_ref ref;
			BPath path;
			int i = 0;

			while (message->FindRef("refs", i++, &ref) == B_OK
				&& path.SetTo(&ref) == B_OK) {
				//fprintf(stderr,"got %s\n", path.Path());
				argv.AddString("argv", path.Path());
			}

			if (i > 1) {
				argv.AddInt32("argc", i);
				be_roster->Launch("text/x-email", &argv);
			}
			break;
		}
		default:
			BView::MessageReceived(message);
	}
}
bool
ShortcutsSpec::_AttemptTabCompletion()
{
	bool ret = false;

	int32 argc;
	char** argv = ParseArgvFromString(fCommand, argc);
	if (argc > 0) {
		// Try to complete the path partially expressed in the last argument!
		char* arg = argv[argc - 1];
		char* fileFragment = strrchr(arg, '/');
		if (fileFragment) {
			const char* directoryName = (fileFragment == arg) ? "/" : arg;
			*fileFragment = '\0';
			fileFragment++;
			int fragLen = strlen(fileFragment);

			BDirectory dir(directoryName);
			if (dir.InitCheck() == B_NO_ERROR) {
				BEntry nextEnt;
				BPath nextPath;
				BList matchList;
				int maxEntryLen = 0;

				// Read in all the files in the directory whose names start
				// with our fragment.
				while (dir.GetNextEntry(&nextEnt) == B_NO_ERROR) {
					if (nextEnt.GetPath(&nextPath) == B_NO_ERROR) {
						char* filePath = strrchr(nextPath.Path(), '/') + 1;
						if (strncmp(filePath, fileFragment, fragLen) == 0) {
							int len = strlen(filePath);
							if (len > maxEntryLen)
								maxEntryLen = len;
							char* newStr = new char[len + 1];
							strcpy(newStr, filePath);
							matchList.AddItem(newStr);
						}
					}
				}

				// Now slowly extend our keyword to its full length, counting
				// numbers of matches at each step. If the match list length
				// is 1, we can use that whole entry. If it's greater than one
				// , we can use just the match length.
				int matchLen = matchList.CountItems();
				if (matchLen > 0) {
					int i;
					BString result(fileFragment);
					for (i = fragLen; i < maxEntryLen; i++) {
						// See if all the matching entries have the same letter
						// in the next position... if so, we can go farther.
						char commonLetter = '\0';
						for (int j = 0; j < matchLen; j++) {
							char nextLetter = GetLetterAt(
								(char*)matchList.ItemAt(j), i);
							if (commonLetter == '\0')
								commonLetter = nextLetter;

							if ((commonLetter != '\0')
								&& (commonLetter != nextLetter)) {
								commonLetter = '\0';// failed;
								beep();
								break;
							}
						}
						if (commonLetter == '\0')
							break;
						else
							result.Append(commonLetter, 1);
					}

					// Free all the strings we allocated
					for (int k = 0; k < matchLen; k++)
						delete [] ((char*)matchList.ItemAt(k));

					DoStandardEscapes(result);

					BString wholeLine;
					for (int l = 0; l < argc - 1; l++) {
						wholeLine += argv[l];
						wholeLine += " ";
					}

					BString file(directoryName);
					DoStandardEscapes(file);

					if (directoryName[strlen(directoryName) - 1] != '/')
						file += "/";

					file += result;

					// Remove any trailing slash...
					const char* fileStr = file.String();
					if (fileStr[strlen(fileStr)-1] == '/')
						file.RemoveLast("/");

					// And re-append it iff the file is a dir.
					BDirectory testFileAsDir(file.String());
					if ((strcmp(file.String(), "/") != 0)
						&& (testFileAsDir.InitCheck() == B_NO_ERROR))
						file.Append("/");

					wholeLine += file;

					SetCommand(wholeLine.String());
					ret = true;
				}
			}
			*(fileFragment - 1) = '/';
		}
	}
	FreeArgv(argv);
	return ret;
}
Example #13
0
WorkspacesSettings::WorkspacesSettings()
	:
	fAutoRaising(false),
	fAlwaysOnTop(false),
	fHasTitle(true),
	fHasBorder(true)
{
	UpdateScreenFrame();

	bool loaded = false;
	BScreen screen;

	BFile file;
	if (_Open(file, B_READ_ONLY) == B_OK) {
		BMessage settings;
		if (settings.Unflatten(&file) == B_OK) {
			if (settings.FindRect("window", &fWindowFrame) == B_OK
				&& settings.FindRect("screen", &fScreenFrame) == B_OK)
				loaded = true;

			settings.FindBool("auto-raise", &fAutoRaising);
			settings.FindBool("always on top", &fAlwaysOnTop);

			if (settings.FindBool("has title", &fHasTitle) != B_OK)
				fHasTitle = true;
			if (settings.FindBool("has border", &fHasBorder) != B_OK)
				fHasBorder = true;
		}
	} else {
		// try reading BeOS compatible settings
		BPath path;
		if (find_directory(B_USER_SETTINGS_DIRECTORY, &path) == B_OK) {
			path.Append(kOldSettingFile);
			BFile file(path.Path(), B_READ_ONLY);
			if (file.InitCheck() == B_OK
				&& file.Read(&fWindowFrame, sizeof(BRect)) == sizeof(BRect)) {
				// we now also store the frame of the screen to know
				// in which context the window frame has been chosen
				BRect frame;
				if (file.Read(&frame, sizeof(BRect)) == sizeof(BRect))
					fScreenFrame = frame;
				else
					fScreenFrame = screen.Frame();

				loaded = true;
			}
		}
	}

	if (loaded) {
		// if the current screen frame is different from the one
		// just loaded, we need to alter the window frame accordingly
		if (fScreenFrame != screen.Frame())
			UpdateFramesForScreen(screen.Frame());
	}

	if (!loaded
		|| !(screen.Frame().right + 5 >= fWindowFrame.right
			&& screen.Frame().bottom + 5 >= fWindowFrame.bottom
			&& screen.Frame().left - 5 <= fWindowFrame.left
			&& screen.Frame().top - 5 <= fWindowFrame.top)) {
		// set to some usable defaults
		float screenWidth = screen.Frame().Width();
		float screenHeight = screen.Frame().Height();
		float aspectRatio = screenWidth / screenHeight;

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

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

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

		float tabHeight = 20;
			// TODO: find tabHeight without being a window

		// shrink to fit more
		while (width + 2 * kScreenBorderOffset > screenWidth
			|| height + 2 * kScreenBorderOffset + tabHeight > screenHeight) {
			width = floor(0.95 * width);
			height = floor(0.95 * height);
		}

		fWindowFrame = fScreenFrame;
		fWindowFrame.OffsetBy(-kScreenBorderOffset, -kScreenBorderOffset);
		fWindowFrame.left = fWindowFrame.right - width;
		fWindowFrame.top = fWindowFrame.bottom - height;
	}
}
Example #14
0
bool
TTracker::QuitRequested()
{
	// don't allow user quitting
	if (CurrentMessage() && CurrentMessage()->FindBool("shortcut"))
		return false;

	gStatusWindow->AttemptToQuit();
		// try quitting the copy/move/empty trash threads
		
	BVolume bootVolume;
	DEBUG_ONLY(status_t err =) BVolumeRoster().GetBootVolume(&bootVolume);
	ASSERT(err == B_OK);
	BMessage message;
	AutoLock<WindowList> lock(&fWindowList);
	// save open windows in a message inside an attribute of the desktop
	int32 count = fWindowList.CountItems();
	for (int32 i = 0; i < count; i++) {
		BContainerWindow *window = dynamic_cast<BContainerWindow *>
			(fWindowList.ItemAt(i));

		if (window && window->TargetModel() && !window->PoseView()->IsDesktopWindow()) {
			if (window->TargetModel()->IsRoot())
				message.AddBool("open_disks_window", true);
			else {
				BEntry entry;
				BPath path;
				const entry_ref *ref = window->TargetModel()->EntryRef();
				if (entry.SetTo(ref) == B_OK && entry.GetPath(&path) == B_OK) {
					int8 flags = window->IsMinimized() ? kOpenWindowMinimized : kOpenWindowNoFlags;
					uint32 deviceFlags = GetVolumeFlags(window->TargetModel());

					// save state for every window which is
					//	a) already open on another workspace
					//	b) on a volume not capable of writing attributes
					if (window != FindContainerWindow(ref)
						|| (deviceFlags & (B_FS_HAS_ATTR | B_FS_IS_READONLY)) != B_FS_HAS_ATTR) {
						BMessage stateMessage;
						window->SaveState(stateMessage);
						window->SetSaveStateEnabled(false);
							// This is to prevent its state to be saved to the node when closed.
						message.AddMessage("window state", &stateMessage);
						flags |= kOpenWindowHasState;
					}
					const char *target;
					bool pathAlreadyExists = false;
					for (int32 index = 0;message.FindString("paths", index, &target) == B_OK;index++) {
						if (!strcmp(target,path.Path())) {
							pathAlreadyExists = true;
							break;
						}
					}
					if (!pathAlreadyExists)
						message.AddString("paths", path.Path());
					message.AddInt8(path.Path(), flags);
				}
			}	
		}
	}
	lock.Unlock();

	// write windows to open on disk
	BDirectory deskDir;
	if (!BootedInSafeMode() && FSGetDeskDir(&deskDir, bootVolume.Device()) == B_OK) {
		// if message is empty, delete the corresponding attribute
		if (message.CountNames(B_ANY_TYPE)) {
			size_t size = (size_t)message.FlattenedSize();
			char *buffer = new char[size];
			message.Flatten(buffer, (ssize_t)size);
			deskDir.WriteAttr(kAttrOpenWindows, B_MESSAGE_TYPE, 0, buffer, size);
			delete [] buffer;
		} else
			deskDir.RemoveAttr(kAttrOpenWindows);
	}

	for (int32 count = 0; count == 50; count++) {
		// wait 5 seconds for the copiing/moving to quit
		if (gStatusWindow->AttemptToQuit())
			break;

		snooze(100000);
	}

	return _inherited::QuitRequested();
}
Example #15
0
status_t
RunPopUpMenu(BPoint where, BString &header, BString &fileName, 
	CLanguageInterface *languageInterface)
{
	status_t err;
	BPath path;
	BDirectory dir;
	err = GetSettingsDir(dir, path);
	err = B_ERROR;
	BPopUpMenu *menu = BuildPopUp(dir);
	if (menu == NULL)
		return B_ERROR;
	
	BMenuItem *item = menu->Go(where, false, true);
	//if (item && item->Message())
	//	item->Message()->PrintToStream();

	switch ((item && item->Message()) ? item->Message()->what : 0)
	{
		case 'head':
		{
			if (item->Message()->FindString("template", &header) < B_OK)
				break;
			BString tmp;
			time_t now = time(NULL);
			struct tm *tim = localtime(&now);
			// date
			char *p;
			p = tmp.LockBuffer(100);
			memset(p, 0, 100);
			strftime(p, 100, "%Y-%m-%d", tim);
			tmp.UnlockBuffer();
			header.ReplaceAll("%DATE%", tmp.String());
			tmp.Truncate(0);
			
			p = tmp.LockBuffer(100);
			memset(p, 0, 100);
			strftime(p, 100, "%T", tim);
			tmp.UnlockBuffer();
			header.ReplaceAll("%TIME%", tmp.String());
			tmp.Truncate(0);

			// year
			p = tmp.LockBuffer(10);
			memset(p, 0, 10);
			strftime(p, 10, "%Y", tim);
			tmp.UnlockBuffer();
			header.ReplaceAll("%YEAR%", tmp.String());
			tmp.Truncate(0);

			// fetch from query on META:email==** ?
			p = tmp.LockBuffer(B_PATH_NAME_LENGTH);
			memset(p, 0, B_PATH_NAME_LENGTH);
			err = dir.ReadAttr("pe:author_people", B_STRING_TYPE, 0LL, p, 
				B_PATH_NAME_LENGTH);
			tmp.UnlockBuffer();
			//printf("ppl:%s\n", tmp.String());
			BNode people;
			if (err > 0)
				people.SetTo(tmp.String());
			tmp.Truncate(0);
			
			BString attr;

			static struct {
				const char *tmplName;
				const char *attrName;
			} attrMap[] = {
				{ "%AUTHOR%", "META:name" },
				{ "%AUTHORMAIL%", "META:email" },
				{ "%COMPANY%", "META:company" },
				{ "%AUTHORURL%", "META:url" },
				{ NULL, NULL }
			};
			int i;

			for (i = 0; attrMap[i].tmplName; i++)
			{
				p = attr.LockBuffer(256);
				memset(p, 0, 256);
				err = people.ReadAttr(attrMap[i].attrName, B_ANY_TYPE, 
					0LL, p, 256);
				//printf("ReadAttr: %d, %s\n", err, attr.String());
				attr.UnlockBuffer();

				tmp << attr;
				header.ReplaceAll(attrMap[i].tmplName, tmp.String());
				tmp.Truncate(0);
				attr.Truncate(0);
			}

			BString fileNameNoExt(fileName);
			if (fileNameNoExt.FindLast('.') > -1)
				fileNameNoExt.Truncate(fileNameNoExt.FindLast('.'));
			header.ReplaceAll("%FILENAMENOEXT%", fileNameNoExt.String());
			header.ReplaceAll("%FILENAME%", fileName.String());
			/*
			tmp << "Haiku";
			header.ReplaceAll("%PROJECT%", tmp.String());
			tmp.Truncate(0);
			*/

			// better values for C++
			BString language("C/C++");
			BString commentLineStart("/*");
			BString commentLineEnd("");
			BString commentBlockStart("/*");
			BString commentBlockCont(" *");
			BString commentBlockLazy("");
			BString commentBlockLineEnd("");
			BString commentBlockEnd(" */");
			if (languageInterface)
			{
				// if not C++
				if (language != languageInterface->Name())
				{
					language = languageInterface->Name();
					commentLineStart = languageInterface->LineCommentStart();
					commentLineEnd = languageInterface->LineCommentEnd();
					// I'd miss a CommentCanSpanLines()
					// let's assume line end means can span
					if (commentLineEnd.Length())
					{
						commentBlockStart = commentLineStart;
						commentBlockCont = "";
						commentBlockLazy = "";
						commentBlockLineEnd = "";
						commentBlockEnd = commentLineEnd;
					}
					else
					{
						commentBlockStart = commentLineStart;
						commentBlockCont = commentLineStart;
						commentBlockLazy = commentLineStart;
						commentBlockLineEnd = commentLineEnd;
						commentBlockEnd = commentLineStart;
					}
					/*
					printf("LANG:'%s' CS:'%s' CE:'%s'\n", 
						language.String(), 
						commentLineStart.String(), 
						commentLineEnd.String());
					*/
				}
			}
			// comment start
			header.ReplaceAll("%COMMS%", commentBlockStart.String());
			// comment cont'd
			header.ReplaceAll("%COMMC%", commentBlockCont.String());
			// comment cont'd lazy (blank if possible)
			header.ReplaceAll("%COMML%", commentBlockLazy.String());
			// comment end
			header.ReplaceAll("%COMME%", commentBlockEnd.String());
			// comment line end
			commentBlockLineEnd << "\n";
			header.ReplaceAll("\n", commentBlockLineEnd.String());


			err = B_OK;
			break;
		}
		case 'optf':
		{
			const char *args[] = {path.Path(), NULL};
			err = be_roster->Launch(sTrackerSig, 1, (char **)args);
			//printf("err %s\n", strerror(err));
			err = B_CANCELED;
			break;
		}
		case 'seta':
		{
			MimeRefFilter filter("application/x-person");
			BPath path;
			entry_ref people;

			if (find_directory(B_USER_DIRECTORY, &path) == B_OK)
			{
				path.Append("people");
				get_ref_for_path(path.Path(), &people);
			}

			BFilePanel *panel;
			panel = new BFilePanel(B_OPEN_PANEL, NULL, &people,
				B_FILE_NODE, false, NULL, &filter);
			// trick to synchronously use BFilePanel
			PanelHandler *handler = new PanelHandler;
			if (panel->Window()->Lock())
			{
				panel->Window()->AddHandler(handler);
				panel->Window()->Unlock();
			}
			panel->SetTarget(BMessenger(handler));
			panel->Show();
			if (handler->Wait() < B_OK)
				break;
			if (!handler->Message())
				break;
			if (handler->Message()->what == B_CANCEL)
				break;
			entry_ref ref;
			//panel->Message()->PrintToStream();
			if (panel->GetNextSelectedRef(&ref) == B_OK)
			{
				//printf("ref:%s\n", ref.name);
				path.SetTo(&ref);
				dir.WriteAttr("pe:author_people", B_STRING_TYPE, 0LL, 
					path.Path(), strlen(path.Path()));
			}
			delete panel;
			delete handler;
			err = B_CANCELED;
			break;
		}
		case B_ABOUT_REQUESTED:
		{
			BString tmpPath("/tmp/Pe-HeaderHeader-About-");
			tmpPath << system_time() << "-" << getpid() << ".txt";
			entry_ref ref;
			get_ref_for_path(tmpPath.String(), &ref);
			{
				BFile f(&ref, B_CREATE_FILE | B_WRITE_ONLY);
				err = f.InitCheck();
				if (err < 0)
					break;
				f.Write(sAboutText, strlen(sAboutText));
				f.SetPermissions(0444);
			}
			BMessage msg(B_REFS_RECEIVED);
			msg.AddRef("refs", &ref);
			err = be_app_messenger.SendMessage(&msg);
			err = B_CANCELED;
			break;
		}
		case 0:
			err = B_CANCELED;
			break;
		default:
			break;
	}
	delete menu;
	return err;
}
/**
 * Determine the base (personal dir and game data dir) paths
 * @param exe the path to the executable
 */
void DetermineBasePaths(const char *exe)
{
	char tmp[MAX_PATH];
#if defined(__MORPHOS__) || defined(__AMIGA__) || defined(DOS) || defined(OS2) || !defined(WITH_PERSONAL_DIR)
	_searchpaths[SP_PERSONAL_DIR] = NULL;
#else
#ifdef __HAIKU__
	BPath path;
	find_directory(B_USER_SETTINGS_DIRECTORY, &path);
	const char *homedir = path.Path();
#else
	const char *homedir = getenv("HOME");

	if (homedir == NULL) {
		const struct passwd *pw = getpwuid(getuid());
		homedir = (pw == NULL) ? "" : pw->pw_dir;
	}
#endif

	snprintf(tmp, MAX_PATH, "%s" PATHSEP "%s", homedir, PERSONAL_DIR);
	AppendPathSeparator(tmp, MAX_PATH);

	_searchpaths[SP_PERSONAL_DIR] = strdup(tmp);
#endif

#if defined(WITH_SHARED_DIR)
	snprintf(tmp, MAX_PATH, "%s", SHARED_DIR);
	AppendPathSeparator(tmp, MAX_PATH);
	_searchpaths[SP_SHARED_DIR] = strdup(tmp);
#else
	_searchpaths[SP_SHARED_DIR] = NULL;
#endif

#if defined(__MORPHOS__) || defined(__AMIGA__)
	_searchpaths[SP_WORKING_DIR] = NULL;
#else
	if (getcwd(tmp, MAX_PATH) == NULL) *tmp = '\0';
	AppendPathSeparator(tmp, MAX_PATH);
	_searchpaths[SP_WORKING_DIR] = strdup(tmp);
#endif

	_do_scan_working_directory = DoScanWorkingDirectory();

	/* Change the working directory to that one of the executable */
	if (ChangeWorkingDirectoryToExecutable(exe)) {
		if (getcwd(tmp, MAX_PATH) == NULL) *tmp = '\0';
		AppendPathSeparator(tmp, MAX_PATH);
		_searchpaths[SP_BINARY_DIR] = strdup(tmp);
	} else {
		_searchpaths[SP_BINARY_DIR] = NULL;
	}

	if (_searchpaths[SP_WORKING_DIR] != NULL) {
		/* Go back to the current working directory. */
		if (chdir(_searchpaths[SP_WORKING_DIR]) != 0) {
			DEBUG(misc, 0, "Failed to return to working directory!");
		}
	}

#if defined(__MORPHOS__) || defined(__AMIGA__) || defined(DOS) || defined(OS2)
	_searchpaths[SP_INSTALLATION_DIR] = NULL;
#else
	snprintf(tmp, MAX_PATH, "%s", GLOBAL_DATA_DIR);
	AppendPathSeparator(tmp, MAX_PATH);
	_searchpaths[SP_INSTALLATION_DIR] = strdup(tmp);
#endif
#ifdef WITH_COCOA
extern void cocoaSetApplicationBundleDir();
	cocoaSetApplicationBundleDir();
#else
	_searchpaths[SP_APPLICATION_BUNDLE_DIR] = NULL;
#endif
}
status_t
PeThemesAddon::ApplyTheme(BMessage &theme, uint32 flags)
{
	BMessage uisettings;
	BMessage peColors;
	status_t err;
	BPath PeSPath;
	rgb_color col;
	BString text;
	char buffer[10];
	int i;
	
	err = theme.FindMessage(Z_THEME_UI_SETTINGS, &uisettings);
	if (err)
		return err;
	
	for (i = 0; sPeColors[i].pe; i++) {
		if (FindRGBColor(uisettings, sPeColors[i].dano, 0, &col) < B_OK)
			if (sPeColors[i].fallback &&
				FindRGBColor(uisettings, sPeColors[i].fallback, 0, &col) < B_OK)
				continue;
		sprintf(buffer, "%02x%02x%02x", col.red, col.green, col.blue);
		text << sPeColors[i].pe << " color=#" << buffer << "\n";
	}
	
	// apply
	BMessenger msgrPrefs;
	if (flags & UI_THEME_SETTINGS_APPLY &&
		AddonFlags() & Z_THEME_ADDON_DO_APPLY &&
		FindPrefWindow(msgrPrefs) == B_OK) {


		for (i = 0; sPeColors[i].pe; i++) {
			if (FindRGBColor(uisettings, sPeColors[i].dano, 0, &col) < B_OK)
				if (FindRGBColor(uisettings, sPeColors[i].fallback, 0, &col) < B_OK)
					continue;
			BMessage msgColor(msg_NewColor);
			msgColor.AddData("color", B_RGB_COLOR_TYPE, &col, sizeof(col));
			msgColor.AddSpecifier("View", sPeColors[i].view);
			msgrPrefs.SendMessage(&msgColor);
		}
		
		// simulate a click on the "Ok" button in prefs
		// this doesn't seem to work anymore in Haiku !?
		BMessage click(B_SET_PROPERTY);
		click.AddSpecifier("Value");
		click.AddSpecifier("View", "ok  ");
		click.AddInt32("data", B_CONTROL_ON);
		msgrPrefs.SendMessage(&click);

		// just in case
		click.RemoveName("data");
		click.AddInt32("data", B_CONTROL_OFF);
		msgrPrefs.SendMessage(&click);

		// instead simulate a button down/up
		snooze(100000);
		click.MakeEmpty();
		click.what = B_MOUSE_DOWN;
		click.AddSpecifier("View", "ok  ");
		click.AddSpecifier("View", (int32)0);
		msgrPrefs.SendMessage(&click);

		snooze(100000);
		click.what = B_MOUSE_UP;
		msgrPrefs.SendMessage(&click);
	}

	// save
	if (flags & UI_THEME_SETTINGS_SAVE && AddonFlags() & Z_THEME_ADDON_DO_SAVE) {
		if (find_directory(B_USER_SETTINGS_DIRECTORY, &PeSPath) < B_OK)
			return B_ERROR;
		PeSPath.Append(PE_SETTINGS_NAME);
		BFile PeSettings(PeSPath.Path(), B_WRITE_ONLY|B_OPEN_AT_END);
		if (PeSettings.InitCheck() < B_OK)
			return PeSettings.InitCheck();
	
		if (PeSettings.Write(text.String(), strlen(text.String())) < B_OK)
			return B_ERROR;
	}
	
	return B_OK;
}
Example #18
0
bool
get_team_name_and_icon(info_pack& infoPack, bool icon)
{
	BPath systemPath;
	find_directory(B_BEOS_SYSTEM_DIRECTORY, &systemPath);

	bool nameFromArgs = false;
	bool tryTrackerIcon = true;

	for (int len = strlen(infoPack.team_info.args) - 1;
			len >= 0 && infoPack.team_info.args[len] == ' '; len--) {
		infoPack.team_info.args[len] = 0;
	}

	app_info info;
	status_t status = be_roster->GetRunningAppInfo(infoPack.team_info.team, &info);
	if (status != B_OK) {
		if (infoPack.team_info.team == B_SYSTEM_TEAM) {
			// Get icon and name from kernel image
			system_info	systemInfo;
			get_system_info(&systemInfo);

			BPath kernelPath(systemPath);
			kernelPath.Append(systemInfo.kernel_name);
			get_ref_for_path(kernelPath.Path(), &info.ref);
			nameFromArgs = true;
		} else {
#ifdef __HAIKU__
			status = BPrivate::get_app_ref(infoPack.team_info.team, &info.ref);
			nameFromArgs = true;
#else

			BEntry entry(infoPack.team_info.args, true);
			status = entry.GetRef(&info.ref);
			if (status != B_OK
				|| strncmp(infoPack.team_info.args, systemPath.Path(),
					strlen(systemPath.Path())) != 0)
				nameFromArgs = true;
#endif
			tryTrackerIcon = (status == B_OK);
		}
	}

	strncpy(infoPack.team_name, nameFromArgs ? infoPack.team_info.args : info.ref.name,
		B_PATH_NAME_LENGTH - 1);

	if (icon) {
#ifdef __HAIKU__
		infoPack.team_icon = new BBitmap(BRect(0, 0, 15, 15), B_RGBA32);
#else
		infoPack.team_icon = new BBitmap(BRect(0, 0, 15, 15), B_CMAP8);
#endif
		if (!tryTrackerIcon
			|| BNodeInfo::GetTrackerIcon(&info.ref, infoPack.team_icon,
				B_MINI_ICON) != B_OK) {
			BMimeType genericAppType(B_APP_MIME_TYPE);
			status = genericAppType.GetIcon(infoPack.team_icon, B_MINI_ICON);
		}
	} else
		infoPack.team_icon = NULL;

	return true;
}
Example #19
0
void
ModulesView::MessageReceived(BMessage* message)
{
	switch (message->what) {
		case kMsgSaverSelected:
		{
			int selection = fScreenSaversListView->CurrentSelection();
			if (selection < 0)
				break;

			ScreenSaverItem* item
				= (ScreenSaverItem*)fScreenSaversListView->ItemAt(selection);
			if (item == NULL)
				break;

			if (strcmp(item->Text(), B_TRANSLATE("Blackness")) == 0)
				fSettings.SetModuleName("");
			else
				fSettings.SetModuleName(item->Text());

			SaveState();
			_CloseSaver();
			_OpenSaver();
			fSettings.Save();
			break;
		}

		case kMsgTestSaver:
		{
			SaveState();
			fSettings.Save();

			_CloseSaver();

			be_roster->StartWatching(BMessenger(this, Looper()),
				B_REQUEST_QUIT);
			if (be_roster->Launch(SCREEN_BLANKER_SIG, &fSettings.Message(),
					&fScreenSaverTestTeam) == B_OK) {
				break;
			}

			// Try really hard to launch it. It's very likely that this fails
			// when we run from the CD, and there is only an incomplete mime
			// database for example...
			BPath path;
			if (find_directory(B_SYSTEM_BIN_DIRECTORY, &path) != B_OK
				|| path.Append("screen_blanker") != B_OK) {
				path.SetTo("/bin/screen_blanker");
			}

			BEntry entry(path.Path());
			entry_ref ref;
			if (entry.GetRef(&ref) == B_OK) {
				be_roster->Launch(&ref, &fSettings.Message(),
					&fScreenSaverTestTeam);
			}
			break;
		}

		case kMsgAddSaver:
			fFilePanel->Show();
			break;

		case B_SOME_APP_QUIT:
		{
			team_id team;
			if (message->FindInt32("be:team", &team) == B_OK
				&& team == fScreenSaverTestTeam) {
				be_roster->StopWatching(this);
				_OpenSaver();
			}
			break;
		}

		default:
			BView::MessageReceived(message);
	}
}
Example #20
0
nsresult
GRE_GetGREPathWithProperties(const GREVersionRange *versions,
                             PRUint32 versionsLength,
                             const GREProperty *properties,
                             PRUint32 propertiesLength,
                             char *aBuffer, PRUint32 aBufLen)
{
#ifdef TARGET_XPCOM_ABI
  // append the ABI to the properties to match only binary 
  // compatible GREs
  static const GREProperty kExtraProperty =
    { "abi", TARGET_XPCOM_ABI };

  nsAutoArrayPtr<GREProperty> allProperties(new GREProperty[propertiesLength + 1]);
  if (!allProperties)
    return NS_ERROR_OUT_OF_MEMORY;

  for (PRUint32 i=0; i<propertiesLength; i++) {
    allProperties[i].property = properties[i].property;
    allProperties[i].value    = properties[i].value;
  }
  allProperties[propertiesLength].property = kExtraProperty.property;
  allProperties[propertiesLength].value    = kExtraProperty.value;
  PRUint32 allPropertiesLength = propertiesLength + 1;
#else
  const GREProperty *allProperties = properties;
  PRUint32 allPropertiesLength = propertiesLength;
#endif

  // if GRE_HOME is in the environment, use that GRE
  const char* env = getenv("GRE_HOME");
  if (env && *env) {
    char p[MAXPATHLEN];
    snprintf(p, sizeof(p), "%s" XPCOM_FILE_PATH_SEPARATOR XPCOM_DLL, env);
    p[sizeof(p) - 1] = '\0';

#if XP_UNIX
    if (realpath(p, aBuffer))
      return NS_OK;
#elif WINCE
    if (p[0] != '\\') 
    {
      WCHAR dir[MAX_PATH];
      WCHAR path[MAX_PATH];
      MultiByteToWideChar(CP_ACP, 0, p, -1, path, MAX_PATH);
      _wfullpath(dir,path,MAX_PATH);
      WideCharToMultiByte(CP_ACP, 0, dir, -1, aBuffer, MAX_PATH, NULL, NULL);
    }
    else {
      strcpy(aBuffer, p);
    }
    return NS_OK;
#elif XP_WIN
    if (_fullpath(aBuffer, p, aBufLen))
      return NS_OK;
#elif XP_OS2
    // realpath on OS/2 returns a unix-ized path, so re-native-ize
    if (realpath(p, aBuffer)) {
      for (char* ptr = strchr(aBuffer, '/'); ptr; ptr = strchr(ptr, '/'))
        *ptr = '\\';
      return NS_OK;
    }
#elif XP_BEOS
    BPath path;
    status_t result;
    result = path.SetTo(p,0,true);
    if (result == B_OK)
    {
      sprintf(aBuffer, path.Path());
      return NS_OK;
    }
#else
    // hope for the best
    // xxxbsmedberg: other platforms should have a "make absolute" function
#endif

    if (strlen(p) >= aBufLen)
      return NS_ERROR_FILE_NAME_TOO_LONG;

    strcpy(aBuffer, p);

    return NS_OK;
  }

  // the Gecko bits that sit next to the application or in the LD_LIBRARY_PATH
  env = getenv("USE_LOCAL_GRE");
  if (env && *env) {
    *aBuffer = nsnull;
    return NS_OK;
  }

#ifdef XP_MACOSX
  aBuffer[0] = '\0';

  // Check the bundle first, for <bundle>/Contents/Frameworks/XUL.framework/libxpcom.dylib
  CFBundleRef appBundle = CFBundleGetMainBundle();
  if (appBundle) {
    CFURLRef fwurl = CFBundleCopyPrivateFrameworksURL(appBundle);
    CFURLRef absfwurl = nsnull;
    if (fwurl) {
      absfwurl = CFURLCopyAbsoluteURL(fwurl);
      CFRelease(fwurl);
    }

    if (absfwurl) {
      CFURLRef xulurl =
        CFURLCreateCopyAppendingPathComponent(NULL, absfwurl,
                                              CFSTR(GRE_FRAMEWORK_NAME),
                                              PR_TRUE);

      if (xulurl) {
        CFURLRef xpcomurl =
          CFURLCreateCopyAppendingPathComponent(NULL, xulurl,
                                                CFSTR("libxpcom.dylib"),
                                                PR_FALSE);

        if (xpcomurl) {
          char tbuffer[MAXPATHLEN];

          if (CFURLGetFileSystemRepresentation(xpcomurl, PR_TRUE,
                                               (UInt8*) tbuffer,
                                               sizeof(tbuffer)) &&
              access(tbuffer, R_OK | X_OK) == 0) {
            if (!realpath(tbuffer, aBuffer)) {
              aBuffer[0] = '\0';
            }
          }

          CFRelease(xpcomurl);
        }

        CFRelease(xulurl);
      }

      CFRelease(absfwurl);
    }
  }

  if (aBuffer[0])
    return NS_OK;

  // Check ~/Library/Frameworks/XUL.framework/Versions/<version>/libxpcom.dylib
  const char *home = getenv("HOME");
  if (home && *home && GRE_FindGREFramework(home,
                                            versions, versionsLength,
                                            allProperties, allPropertiesLength,
                                            aBuffer, aBufLen)) {
    return NS_OK;
  }

  // Check /Library/Frameworks/XUL.framework/Versions/<version>/libxpcom.dylib
  if (GRE_FindGREFramework("",
                           versions, versionsLength,
                           allProperties, allPropertiesLength,
                           aBuffer, aBufLen)) {
    return NS_OK;
  }

#elif defined(XP_UNIX) 
  env = getenv("MOZ_GRE_CONF");
  if (env && GRE_GetPathFromConfigFile(env,
                                       versions, versionsLength,
                                       allProperties, allPropertiesLength,
                                       aBuffer, aBufLen)) {
    return NS_OK;
  }

  env = getenv("HOME");
  if (env && *env) {
    char buffer[MAXPATHLEN];

    // Look in ~/.gre.config

    snprintf(buffer, sizeof(buffer),
             "%s" XPCOM_FILE_PATH_SEPARATOR GRE_CONF_NAME, env);
    
    if (GRE_GetPathFromConfigFile(buffer,
                                  versions, versionsLength,
                                  allProperties, allPropertiesLength,
                                  aBuffer, aBufLen)) {
      return NS_OK;
    }

    // Look in ~/.gre.d/*.conf

    snprintf(buffer, sizeof(buffer),
             "%s" XPCOM_FILE_PATH_SEPARATOR GRE_USER_CONF_DIR, env);

    if (GRE_GetPathFromConfigDir(buffer,
                                 versions, versionsLength,
                                 allProperties, allPropertiesLength,
                                 aBuffer, aBufLen)) {
      return NS_OK;
    }
  }

  // Look for a global /etc/gre.conf file
  if (GRE_GetPathFromConfigFile(GRE_CONF_PATH,
                                versions, versionsLength,
                                allProperties, allPropertiesLength,
                                aBuffer, aBufLen)) {
    return NS_OK;
  }

  // Look for a group of config files in /etc/gre.d/
  if (GRE_GetPathFromConfigDir(GRE_CONF_DIR,
                               versions, versionsLength,
                               allProperties, allPropertiesLength,
                               aBuffer, aBufLen)) {
    return NS_OK;
  }

#elif defined(XP_BEOS)
  env = getenv("MOZ_GRE_CONF");
  if (env && GRE_GetPathFromConfigFile(env,
                                       versions, versionsLength,
                                       allProperties, allPropertiesLength,
                                       aBuffer, aBufLen)) {
    return NS_OK;
  }

  char p[MAXPATHLEN]; 
  if (find_directory(B_USER_SETTINGS_DIRECTORY, 0, 0, p, MAXPATHLEN)) {
    char buffer[MAXPATHLEN];

    // Look in B_USER_SETTINGS_DIRECTORY/gre.config
    snprintf(buffer, sizeof(buffer),
             "%s" XPCOM_FILE_PATH_SEPARATOR GRE_CONF_NAME, p);
    
    if (GRE_GetPathFromConfigFile(buffer,
                                  versions, versionsLength,
                                  allProperties, allPropertiesLength,
                                  aBuffer, aBufLen)) {
      return NS_OK;
    }

    // Look in B_USER_SETTINGS_DIRECTORY/gre.d/*.conf
    snprintf(buffer, sizeof(buffer),
             "%s" XPCOM_FILE_PATH_SEPARATOR GRE_CONF_DIR, p);

    if (GRE_GetPathFromConfigDir(buffer,
                                 versions, versionsLength,
                                 allProperties, allPropertiesLength,
                                 aBuffer, aBufLen)) {
      return NS_OK;
    }
  }
  
  // Hope Zeta OS and Haiku OS multiuser versions will respect BeBook,
  // for BeOS R5 COMMON and USER are equal
  if (find_directory(B_COMMON_SETTINGS_DIRECTORY, 0, 0, p, MAXPATHLEN)) {
    char buffer[MAXPATHLEN];
    
    // Look for a B_COMMON_SETTINGS_DIRECTORY/gre.conf file
    snprintf(buffer, sizeof(buffer),
             "%s" XPCOM_FILE_PATH_SEPARATOR GRE_CONF_PATH, p);
    if (GRE_GetPathFromConfigFile(buffer,
                                  versions, versionsLength,
                                  allProperties, allPropertiesLength,
                                  aBuffer, aBufLen)) {
      return NS_OK;
    }

    // Look for a group of config files in B_COMMON_SETTINGS_DIRECTORY/gre.d/
    snprintf(buffer, sizeof(buffer),
             "%s" XPCOM_FILE_PATH_SEPARATOR GRE_CONF_DIR, p);
    if (GRE_GetPathFromConfigDir(buffer,
                                 versions, versionsLength,
                                 allProperties, allPropertiesLength,
                                 aBuffer, aBufLen)) {
      return NS_OK;
    }
  }

#elif defined(XP_WIN)
  HKEY hRegKey = NULL;
    
  // A couple of key points here:
  // 1. Note the usage of the "Software\\mozilla.org\\GRE" subkey - this allows
  //    us to have multiple versions of GREs on the same machine by having
  //    subkeys such as 1.0, 1.1, 2.0 etc. under it.
  // 2. In this sample below we're looking for the location of GRE version 1.2
  //    i.e. we're compatible with GRE 1.2 and we're trying to find it's install
  //    location.
  //
  // Please see http://www.mozilla.org/projects/embedding/GRE.html for
  // more info.
  //
  if (::RegOpenKeyExW(HKEY_CURRENT_USER, GRE_WIN_REG_LOC, 0,
                      KEY_READ, &hRegKey) == ERROR_SUCCESS) {
      PRBool ok = GRE_GetPathFromRegKey(hRegKey,
                                        versions, versionsLength,
                                        allProperties, allPropertiesLength,
                                        aBuffer, aBufLen);
      ::RegCloseKey(hRegKey);

      if (ok)
          return NS_OK;
  }

  if (::RegOpenKeyExW(HKEY_LOCAL_MACHINE, GRE_WIN_REG_LOC, 0,
                      KEY_ENUMERATE_SUB_KEYS, &hRegKey) == ERROR_SUCCESS) {
      PRBool ok = GRE_GetPathFromRegKey(hRegKey,
                                        versions, versionsLength,
                                        allProperties, allPropertiesLength,
                                        aBuffer, aBufLen);
      ::RegCloseKey(hRegKey);

      if (ok)
          return NS_OK;
  }
#endif

  return NS_ERROR_FAILURE;
}
Example #21
0
void
BrowserApp::ReadyToRun()
{
	// Since we will essentially run the GUI...
	set_thread_priority(Thread(), B_DISPLAY_PRIORITY);

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

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

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

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

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

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

	BWebPage::SetDownloadListener(BMessenger(fDownloadWindow));

	fInitialized = true;

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

	PostMessage(PRELOAD_BROWSING_HISTORY);
}
Example #22
0
void
DriveItem::DrawItem(BView* owner, BRect frame, bool complete)
{
	owner->PushState();
	owner->SetDrawingMode(B_OP_ALPHA);

	if (IsSelected() || complete) {
		if (IsSelected()) {
			owner->SetHighColor(ui_color(B_LIST_SELECTED_BACKGROUND_COLOR));
			owner->SetLowColor(owner->HighColor());
		} else
			owner->SetHighColor(owner->LowColor());

		owner->FillRect(frame);
	}

	if (!IsEnabled()) {
		rgb_color textColor;
		if (IsSelected())
			textColor = ui_color(B_LIST_SELECTED_ITEM_TEXT_COLOR);
		else
			textColor = ui_color(B_LIST_ITEM_TEXT_COLOR);

		if (textColor.red + textColor.green + textColor.blue > 128 * 3)
			owner->SetHighColor(tint_color(textColor, B_DARKEN_1_TINT));
		else
			owner->SetHighColor(tint_color(textColor, B_LIGHTEN_1_TINT));
	} else {
		if (IsSelected())
			owner->SetHighColor(ui_color(B_LIST_SELECTED_ITEM_TEXT_COLOR));
		else
			owner->SetHighColor(ui_color(B_LIST_ITEM_TEXT_COLOR));
	}


	// icon
	owner->MovePenTo(frame.left + 4, frame.top + 1);
	owner->DrawBitmap(fIcon);

	// device
	owner->MovePenTo(frame.left + 8 + fIcon->Bounds().Width(),
		frame.top + fSecondBaselineOffset);
	owner->DrawString(fPath.Path());

	// name
	BFont boldFont;
	BFont ownerFont;
	owner->GetFont(&ownerFont);
	owner->GetFont(&boldFont);
	boldFont.SetFace(B_BOLD_FACE);
	owner->SetFont(&boldFont);

	BPoint namePosition(frame.left + 8 + fIcon->Bounds().Width(),
		frame.top + fBaselineOffset);

	owner->MovePenTo(namePosition);
	owner->DrawString(fName.String());

	float nameWidth = owner->StringWidth(fName.String());
	float messageWidth = frame.right - 4 - fSizeWidth
		- (frame.left + 8 + fIcon->Bounds().Width()) - nameWidth
		- fBaselineOffset * 2;

	if (fCanBeInstalled != B_OK) {
		rgb_color highColor = owner->HighColor();
		owner->SetHighColor(ui_color(B_FAILURE_COLOR));
		owner->MovePenBy(fBaselineOffset, 0);
		const char* message;
		switch (fCanBeInstalled) {
			case B_PARTITION_TOO_SMALL:
				message = B_TRANSLATE_COMMENT("No space available!",
					"Cannot install");
				break;
			case B_ENTRY_NOT_FOUND:
				message = B_TRANSLATE_COMMENT("Incompatible format!",
					"Cannot install");
				break;
			default:
				message = B_TRANSLATE_COMMENT("Cannot access!",
					"Cannot install");
				break;
		}
		BString truncatedMessage = message;
		owner->TruncateString(&truncatedMessage, B_TRUNCATE_END, messageWidth);
		owner->DrawString(truncatedMessage);
		owner->SetHighColor(highColor);
	}
	owner->SetFont(&ownerFont);
		// size
	BPoint sizePosition(frame.right - 4 - fSizeWidth,
		frame.top + fBaselineOffset);
	if (sizePosition.x > namePosition.x + nameWidth) {
		owner->MovePenTo(sizePosition);
		owner->DrawString(fSize.String());
	}

	owner->PopState();
}
Example #23
0
ConfigWindow::ConfigWindow()
    :
    BWindow(BRect(100.0, 100.0, 580.0, 540.0), "E-mail", B_TITLED_WINDOW,
           B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_RESIZABLE),
    fLastSelectedAccount(NULL),
    fSaveSettings(false)
{
    // create controls

    BRect rect(Bounds());
    BView *top = new BView(rect, NULL, B_FOLLOW_ALL, 0);
    top->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
    AddChild(top);

    // determine font height
    font_height fontHeight;
    top->GetFontHeight(&fontHeight);
    int32 height = (int32)(fontHeight.ascent + fontHeight.descent
                           + fontHeight.leading) + 5;

    rect.InsetBy(5, 5);
    rect.bottom -= 11 + height;
    BTabView *tabView = new BTabView(rect, NULL);

    BView *view;
    rect = tabView->Bounds();
    rect.bottom -= tabView->TabHeight() + 4;
    tabView->AddTab(view = new BView(rect, NULL, B_FOLLOW_ALL, 0));
    tabView->TabAt(0)->SetLabel(B_TRANSLATE("Accounts"));
    view->SetViewColor(top->ViewColor());

    // accounts listview

    rect = view->Bounds().InsetByCopy(8, 8);
    rect.right = 140 - B_V_SCROLL_BAR_WIDTH;
    rect.bottom -= height + 12;
    fAccountsListView = new AccountsListView(rect);
    view->AddChild(new BScrollView(NULL, fAccountsListView, B_FOLLOW_ALL, 0,
                                   false, true));
    rect.right += B_V_SCROLL_BAR_WIDTH;

    rect.top = rect.bottom + 8;
    rect.bottom = rect.top + height;
    BRect sizeRect = rect;
    sizeRect.right = sizeRect.left + 30 + view->StringWidth(
                         B_TRANSLATE("Add"));
    view->AddChild(new BButton(sizeRect, NULL, B_TRANSLATE("Add"),
                               new BMessage(kMsgAddAccount), B_FOLLOW_BOTTOM));

    sizeRect.left = sizeRect.right+3;
    sizeRect.right = sizeRect.left + 30 + view->StringWidth(
                         B_TRANSLATE("Remove"));
    view->AddChild(fRemoveButton = new BButton(
        sizeRect, NULL, B_TRANSLATE("Remove"),
        new BMessage(kMsgRemoveAccount), B_FOLLOW_BOTTOM));

    // accounts config view
    rect = view->Bounds();
    rect.left = fAccountsListView->Frame().right + B_V_SCROLL_BAR_WIDTH + 16;
    rect.right -= 10;
    view->AddChild(fConfigView = new CenterContainer(rect));

    MakeHowToView();

    // general settings

    rect = tabView->Bounds();
    rect.bottom -= tabView->TabHeight() + 4;
    tabView->AddTab(view = new CenterContainer(rect));
    tabView->TabAt(1)->SetLabel(B_TRANSLATE("Settings"));

    rect = view->Bounds().InsetByCopy(8, 8);
    rect.right -= 1;
    rect.bottom = rect.top + height * 5 + 15;
    BBox *box = new BBox(rect);
    box->SetLabel(B_TRANSLATE("Mail checking"));
    view->AddChild(box);

    rect = box->Bounds().InsetByCopy(8, 8);
    rect.top += 7;
    rect.bottom = rect.top + height + 5;
    BRect tile = rect.OffsetByCopy(0, 1);
    int32 labelWidth = (int32)view->StringWidth(B_TRANSLATE("Check every")) + 6;
    tile.right = 80 + labelWidth;
    fIntervalControl = new BTextControl(tile, "time",
                                        B_TRANSLATE("Check every"), NULL, NULL);
    fIntervalControl->SetDivider(labelWidth);
    box->AddChild(fIntervalControl);

    BPopUpMenu *frequencyPopUp = new BPopUpMenu(B_EMPTY_STRING);
    const char *frequencyStrings[] = {
        B_TRANSLATE("never"),
        B_TRANSLATE("minutes"),
        B_TRANSLATE("hours"),
        B_TRANSLATE("days")
    };
    BMenuItem *item;
    for (int32 i = 0; i < 4; i++) {
        frequencyPopUp->AddItem(item = new BMenuItem(frequencyStrings[i],
                new BMessage(kMsgIntervalUnitChanged)));
        if (i == 1)
            item->SetMarked(true);
    }
    tile.left = tile.right + 5;
    tile.right = rect.right;
    tile.OffsetBy(0,-1);
    fIntervalUnitField = new BMenuField(tile, "frequency", B_EMPTY_STRING,
                                        frequencyPopUp);
    fIntervalUnitField->SetDivider(0.0);
    box->AddChild(fIntervalUnitField);

    rect.OffsetBy(0,height + 9);
    rect.bottom -= 2;
    fPPPActiveCheckBox = new BCheckBox(rect, "ppp active",
                                       B_TRANSLATE("Only when dial-up is connected"), NULL);
    box->AddChild(fPPPActiveCheckBox);

    rect.OffsetBy(0,height + 9);
    rect.bottom -= 2;
    fPPPActiveSendCheckBox = new BCheckBox(rect, "ppp activesend",
                                           B_TRANSLATE("Schedule outgoing mail when dial-up is disconnected"),
                                           NULL);
    box->AddChild(fPPPActiveSendCheckBox);

    // Miscellaneous settings box

    rect = box->Frame();
    rect.bottom = rect.top + 3 * height + 30;
    box = new BBox(rect);
    box->SetLabel(B_TRANSLATE("Miscellaneous"));
    view->AddChild(box);

    BPopUpMenu *statusPopUp = new BPopUpMenu(B_EMPTY_STRING);
    const char *statusModes[] = {
        B_TRANSLATE("Never"),
        B_TRANSLATE("While sending"),
        B_TRANSLATE("While sending and receiving"),
        B_TRANSLATE("Always")
    };
    BMessage *msg;
    for (int32 i = 0; i < 4; i++) {
        statusPopUp->AddItem(item = new BMenuItem(statusModes[i],
                msg = new BMessage(kMsgShowStatusWindowChanged)));
        msg->AddInt32("ShowStatusWindow", i);
        if (i == 0)
            item->SetMarked(true);
    }
    rect = box->Bounds().InsetByCopy(8,8);
    rect.top += 7;
    rect.bottom = rect.top + height + 5;
    labelWidth
        = (int32)view->StringWidth(
              B_TRANSLATE("Show connection status window:"))	+ 8;
    fStatusModeField = new BMenuField(rect, "show status",
                                      B_TRANSLATE("Show connection status window:"), statusPopUp);
    fStatusModeField->SetDivider(labelWidth);
    box->AddChild(fStatusModeField);

    rect = fStatusModeField->Frame();;
    rect.OffsetBy(0, rect.Height() + 10);
    BButton *button = new BButton(rect, B_EMPTY_STRING,
                                  B_TRANSLATE("Edit mailbox menu…"),
                                  msg = new BMessage(B_REFS_RECEIVED));
    button->ResizeToPreferred();
    box->AddChild(button);
    button->SetTarget(BMessenger("application/x-vnd.Be-TRAK"));

    BPath path;
    find_directory(B_USER_SETTINGS_DIRECTORY, &path);
    path.Append("Mail/Menu Links");
    BEntry entry(path.Path());
    if (entry.InitCheck() == B_OK && entry.Exists()) {
        entry_ref ref;
        entry.GetRef(&ref);
        msg->AddRef("refs", &ref);
    }
    else
        button->SetEnabled(false);

    rect = button->Frame();
    rect.OffsetBy(rect.Width() + 30,0);
    fAutoStartCheckBox = new BCheckBox(rect, "start daemon",
                                       B_TRANSLATE("Start mail services on startup"), NULL);
    fAutoStartCheckBox->ResizeToPreferred();
    box->AddChild(fAutoStartCheckBox);

    // save/revert buttons

    top->AddChild(tabView);

    rect = tabView->Frame();
    rect.top = rect.bottom + 5;
    rect.bottom = rect.top + height + 5;
    BButton *saveButton = new BButton(rect, "apply", B_TRANSLATE("Apply"),
                                      new BMessage(kMsgSaveSettings));
    float w,h;
    saveButton->GetPreferredSize(&w, &h);
    saveButton->ResizeTo(w, h);
    saveButton->MoveTo(rect.right - w, rect.top);
    top->AddChild(saveButton);

    BButton *revertButton = new BButton(rect, "revert", B_TRANSLATE("Revert"),
                                        new BMessage(kMsgRevertSettings));
    revertButton->GetPreferredSize(&w, &h);
    revertButton->ResizeTo(w,h);
    revertButton->MoveTo(saveButton->Frame().left - 25 - w, rect.top);
    top->AddChild(revertButton);

    LoadSettings();
    // this will also move our window to the stored position

    fAccountsListView->SetSelectionMessage(new BMessage(kMsgAccountSelected));
    fAccountsListView->MakeFocus(true);
}
/*
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);

	directory_which folders[] = {
		B_USER_ADDONS_DIRECTORY,
		B_COMMON_ADDONS_DIRECTORY,
		B_SYSTEM_ADDONS_DIRECTORY,
	};
	BPath addOnPath;
	BDirectory addOnFolder;
	char buf[4096];
	status_t err;
	for (uint32 f = 0; f < sizeof(folders) / sizeof(directory_which); ++f) {
		find_directory(folders[f], &addOnPath);
		BString addOnFolderName(addOnPath.Path());
		addOnFolderName << "/locale/catalogs";

		system_info info;
		if (get_system_info(&info) == B_OK
				&& (info.abi & B_HAIKU_ABI_MAJOR)
				!= (B_HAIKU_ABI & B_HAIKU_ABI_MAJOR)) {
			switch (B_HAIKU_ABI & B_HAIKU_ABI_MAJOR) {
				case B_HAIKU_ABI_GCC_2:
					addOnFolderName << "/gcc2";
					break;
				case B_HAIKU_ABI_GCC_4:
					addOnFolderName << "/gcc4";
					break;
			}
		}


		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, 4096)) > 0) {
			dent = (dirent*)buf;
			while (count-- > 0) {
				if (strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..")
						&& strcmp(dent->d_name, "gcc2")
						&& strcmp(dent->d_name, "gcc4")) {
					// 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;
}
Example #25
0
bool duplicates_exist (const char * signature)
{
	BVolumeRoster	roster;
	BVolume			volume;
	BQuery			query;
	BString			query_string	=	"BEOS:APP_SIG=";
	BEntry			entry;
	mode_t			permissions;
	uid_t			owner;
	gid_t			group;
	int32			query_hits		=	0;
	
	query_string += signature;
	
	while (roster.GetNextVolume(& volume) == B_OK)
	{
		if (volume.KnowsQuery())
		{
			PRINT(("volume.KnowsQuery()\n"));
			
			char volname [B_FILE_NAME_LENGTH];
			volume.GetName(volname);
			PRINT(("volume: %s\n", volname));
			
			query.Clear();
			
			if (query.SetVolume(& volume) == B_OK)
			{
				PRINT(("query.SetVolume(& volume) == B_OK\n"));
			
				if (query.SetPredicate(query_string.String()) == B_OK)
				{
					PRINT(("query.SetPredicate(%s) == B_OK\n", query_string.String()));
				
					if (query.Fetch() == B_OK)
					{
						PRINT(("query.Fetch() == B_OK\n"));
					
						while (query.GetNextEntry(& entry) == B_OK)
						{
							PRINT(("query.GetNextEntry(& entry) == B_OK\n"));
							
							entry.GetPermissions(& permissions);
							entry.GetOwner(& owner);
							entry.GetGroup(& group);
							
							BPath path (& entry);

							// if (access(path.Path(), X_OK))

							if	(((owner == getuid()) && (permissions & S_IXUSR))
							||	((group == getgid()) && (permissions & S_IXGRP))
							||	(permissions & S_IXOTH))
							{
								PRINT(("path is executable: %s\n", path.Path()));
								query_hits++;
							}
							else
							{
								PRINT(("path is NOT executable: %s\n", path.Path()));
							}
						}
					}
				}
			}
		}
	
		fflush(stdout);
	}
	
	if (query_hits > 1)
		return true;
	else
		return false;
}
ConfigWindow::ConfigWindow()
		: BWindow(BRect(200.0, 200.0, 640.0, 640.0),
				  "E-mail", B_TITLED_WINDOW,
				  B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_RESIZABLE),
		fLastSelectedAccount(NULL),
		fSaveSettings(false)
{
	/*** create controls ***/

	BRect rect(Bounds());
	BView *top = new BView(rect,NULL,B_FOLLOW_ALL,0);
	top->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	AddChild(top);

	// determine font height
	font_height fontHeight;
	top->GetFontHeight(&fontHeight);
	int32 height = (int32)(fontHeight.ascent + fontHeight.descent + fontHeight.leading) + 5;

	rect.InsetBy(5,5);	rect.bottom -= 11 + height;
	BTabView *tabView = new BTabView(rect,NULL);

	BView *view,*generalView;
	rect = tabView->Bounds();  rect.bottom -= tabView->TabHeight() + 4;
	tabView->AddTab(view = new BView(rect,NULL,B_FOLLOW_ALL,0));
	tabView->TabAt(0)->SetLabel(MDR_DIALECT_CHOICE ("Accounts","アカウント"));
	view->SetViewColor(top->ViewColor());

	// accounts listview

	rect = view->Bounds().InsetByCopy(8,8);
	rect.right = 140 - B_V_SCROLL_BAR_WIDTH;
	rect.bottom -= height + 12;
	fAccountsListView = new AccountsListView(rect);
	view->AddChild(new BScrollView(NULL,fAccountsListView,B_FOLLOW_ALL,0,false,true));
	rect.right += B_V_SCROLL_BAR_WIDTH;

	rect.top = rect.bottom + 8;  rect.bottom = rect.top + height;
	BRect sizeRect = rect;
	sizeRect.right = sizeRect.left + 30 + view->StringWidth(MDR_DIALECT_CHOICE ("Add","追加"));
	view->AddChild(new BButton(sizeRect,NULL,MDR_DIALECT_CHOICE ("Add","追加"),
		new BMessage(kMsgAddAccount),B_FOLLOW_BOTTOM));

	sizeRect.left = sizeRect.right+3;
	sizeRect.right = sizeRect.left + 30 + view->StringWidth(MDR_DIALECT_CHOICE ("Remove","削除"));
	view->AddChild(fRemoveButton = new BButton(sizeRect,NULL,MDR_DIALECT_CHOICE ("Remove","削除"),
		new BMessage(kMsgRemoveAccount),B_FOLLOW_BOTTOM));

	// accounts config view
	rect = view->Bounds();
	rect.left = fAccountsListView->Frame().right + B_V_SCROLL_BAR_WIDTH + 16;
	rect.right -= 10;
	view->AddChild(fConfigView = new CenterContainer(rect));

	MakeHowToView();

	// general settings

	rect = tabView->Bounds();	rect.bottom -= tabView->TabHeight() + 4;
	tabView->AddTab(view = new CenterContainer(rect));
	tabView->TabAt(1)->SetLabel(MDR_DIALECT_CHOICE ("General","一般"));

	rect = view->Bounds().InsetByCopy(8,8);
	rect.right -= 1;	rect.bottom = rect.top + height * 5 + 15;
	BBox *box = new BBox(rect);
	box->SetLabel(MDR_DIALECT_CHOICE ("Retrieval Frequency","メールチェック間隔"));
	view->AddChild(box);

	rect = box->Bounds().InsetByCopy(8,8);
	rect.top += 7;	rect.bottom = rect.top + height + 5;
	BRect tile = rect.OffsetByCopy(0,1);
	int32 labelWidth = (int32)view->StringWidth(MDR_DIALECT_CHOICE ("Check every:","メールチェック間隔:"))+6;
	tile.right = 80 + labelWidth;
	fIntervalControl = new BTextControl(tile,"time",MDR_DIALECT_CHOICE ("Check every:","メールチェック間隔:"),
	NULL,NULL);
	fIntervalControl->SetDivider(labelWidth);
	box->AddChild(fIntervalControl);

	BPopUpMenu *frequencyPopUp = new BPopUpMenu(B_EMPTY_STRING);
	const char *frequencyStrings[] = {
		MDR_DIALECT_CHOICE ("Never","チェックしない"),
		MDR_DIALECT_CHOICE ("Minutes","分毎チェック"),
		MDR_DIALECT_CHOICE ("Hours","時間毎チェック"),
		MDR_DIALECT_CHOICE ("Days","日間毎チェック")};
	BMenuItem *item;
	for (int32 i = 0;i < 4;i++)
	{
		frequencyPopUp->AddItem(item = new BMenuItem(frequencyStrings[i],new BMessage(kMsgIntervalUnitChanged)));
		if (i == 1)
			item->SetMarked(true);
	}
	tile.left = tile.right + 5;  tile.right = rect.right;
	tile.OffsetBy(0,-1);
	fIntervalUnitField = new BMenuField(tile,"frequency", B_EMPTY_STRING, frequencyPopUp);
	fIntervalUnitField->SetDivider(0.0);
	box->AddChild(fIntervalUnitField);

	rect.OffsetBy(0,height + 9);	rect.bottom -= 2;
	fPPPActiveCheckBox = new BCheckBox(rect,"ppp active",
		MDR_DIALECT_CHOICE ("only when PPP is active","PPP接続中時のみ"), NULL);
	box->AddChild(fPPPActiveCheckBox);
	
	rect.OffsetBy(0,height + 9);	rect.bottom -= 2;
	fPPPActiveSendCheckBox = new BCheckBox(rect,"ppp activesend",
		MDR_DIALECT_CHOICE ("Queue outgoing mail when PPP is inactive","PPP切断時、送信メールを送信箱に入れる"), NULL);
	box->AddChild(fPPPActiveSendCheckBox);

	rect = box->Frame();  rect.bottom = rect.top + 4*height + 20;
	box = new BBox(rect);
	box->SetLabel(MDR_DIALECT_CHOICE ("Status Window","送受信状況の表示"));
	view->AddChild(box);

	BPopUpMenu *statusPopUp = new BPopUpMenu(B_EMPTY_STRING);
	const char *statusModes[] = {
		MDR_DIALECT_CHOICE ("Never","表示しない"),
		MDR_DIALECT_CHOICE ("While Sending","送信時"),
		MDR_DIALECT_CHOICE ("While Sending / Fetching","送受信時"),
		MDR_DIALECT_CHOICE ("Always","常に表示")};
	BMessage *msg;
	for (int32 i = 0;i < 4;i++)
	{
		statusPopUp->AddItem(item = new BMenuItem(statusModes[i],msg = new BMessage(kMsgShowStatusWindowChanged)));
		msg->AddInt32("ShowStatusWindow",i);
		if (i == 0)
			item->SetMarked(true);
	}
	rect = box->Bounds().InsetByCopy(8,8);
	rect.top += 7;	rect.bottom = rect.top + height + 5;
	labelWidth = (int32)view->StringWidth(
		MDR_DIALECT_CHOICE ("Show Status Window:","ステータスの表示:")) + 8;
	fStatusModeField = new BMenuField(rect,"show status",
		MDR_DIALECT_CHOICE ("Show Status Window:","ステータスの表示:"),
	statusPopUp);
	fStatusModeField->SetDivider(labelWidth);
	box->AddChild(fStatusModeField);

	BPopUpMenu *lookPopUp = new BPopUpMenu(B_EMPTY_STRING);
	const char *windowLookStrings[] = {
		MDR_DIALECT_CHOICE ("Normal, With Tab","タブ付通常"),
		MDR_DIALECT_CHOICE ("Normal, Border Only","ボーダーのみ通常"),
		MDR_DIALECT_CHOICE ("Floating","フローティング"),
		MDR_DIALECT_CHOICE ("Thin Border","細いボーダー"),
		MDR_DIALECT_CHOICE ("No Border","ボーダー無し")};
	for (int32 i = 0;i < 5;i++)
	{
		lookPopUp->AddItem(item = new BMenuItem(windowLookStrings[i],msg = new BMessage(kMsgStatusLookChanged)));
		msg->AddInt32("StatusWindowLook",i);
		if (i == 0)
			item->SetMarked(true);
	}
	rect.OffsetBy(0, height + 6);
	fStatusLookField = new BMenuField(rect,"status look",
		MDR_DIALECT_CHOICE ("Window Look:","ウィンドウ外観:"),lookPopUp);
	fStatusLookField->SetDivider(labelWidth);
	box->AddChild(fStatusLookField);

	BPopUpMenu *workspacesPopUp = new BPopUpMenu(B_EMPTY_STRING);
	workspacesPopUp->AddItem(item = new BMenuItem(
		MDR_DIALECT_CHOICE ("Current Workspace","使用中ワークスペース"),
		msg = new BMessage(kMsgStatusWorkspaceChanged)));
	msg->AddInt32("StatusWindowWorkSpace", 0);
	workspacesPopUp->AddItem(item = new BMenuItem(
		MDR_DIALECT_CHOICE ("All Workspaces","全てのワークスペース"),
		msg = new BMessage(kMsgStatusWorkspaceChanged)));
	msg->AddInt32("StatusWindowWorkSpace", -1);

	rect.OffsetBy(0,height + 6);
	fStatusWorkspaceField = new BMenuField(rect,"status workspace",
		MDR_DIALECT_CHOICE ("Window visible on:","表示場所:"),workspacesPopUp);
	fStatusWorkspaceField->SetDivider(labelWidth);
	box->AddChild(fStatusWorkspaceField);

	rect = box->Frame();  rect.bottom = rect.top + 3*height + 13;
	box = new BBox(rect);
	box->SetLabel(MDR_DIALECT_CHOICE ("Deskbar Icon","デスクバーアイコンリンク"));
	view->AddChild(box);

	rect = box->Bounds().InsetByCopy(8,8);
	rect.top += 7;	rect.bottom = rect.top + height + 5;
	BStringView *stringView = new BStringView(rect,B_EMPTY_STRING, MDR_DIALECT_CHOICE (
		"The menu links are links to folders in a real folder like the Be menu.",
		"デスクバーで表示する項目の設定"));
	box->AddChild(stringView);
	stringView->SetAlignment(B_ALIGN_CENTER);
	stringView->ResizeToPreferred();
	// BStringView::ResizeToPreferred() changes the width, so that the
	// alignment has no effect anymore
	stringView->ResizeTo(rect.Width(), stringView->Bounds().Height());

	rect.left += 100;  rect.right -= 100;
	rect.OffsetBy(0,height + 1);
	BButton *button = new BButton(rect,B_EMPTY_STRING,
		MDR_DIALECT_CHOICE ("Configure Menu Links","メニューリンクの設定"),
		msg = new BMessage(B_REFS_RECEIVED));
	box->AddChild(button);
	button->SetTarget(BMessenger("application/x-vnd.Be-TRAK"));

	BPath path;
	find_directory(B_USER_SETTINGS_DIRECTORY, &path);
	path.Append("Mail/Menu Links");
	BEntry entry(path.Path());
	if (entry.InitCheck() == B_OK && entry.Exists()) {
		entry_ref ref;
		entry.GetRef(&ref);
		msg->AddRef("refs", &ref);
	}
	else
		button->SetEnabled(false);

	rect = box->Frame();  rect.bottom = rect.top + 2*height + 6;
	box = new BBox(rect);
	box->SetLabel(MDR_DIALECT_CHOICE ("Misc.","その他の設定"));
	view->AddChild(box);

	rect = box->Bounds().InsetByCopy(8,8);
	rect.top += 7;	rect.bottom = rect.top + height + 5;
	fAutoStartCheckBox = new BCheckBox(rect,"start daemon",
		MDR_DIALECT_CHOICE ("Auto-Start Mail Daemon","Mail Daemonを自動起動"),NULL);
	box->AddChild(fAutoStartCheckBox);

	// about page

	rect = tabView->Bounds();	rect.bottom -= tabView->TabHeight() + 4;
	tabView->AddTab(view = new BView(rect,NULL,B_FOLLOW_ALL,0));
	tabView->TabAt(2)->SetLabel(MDR_DIALECT_CHOICE ("About","情報"));
	view->SetViewColor(top->ViewColor());

	AboutTextView *about = new AboutTextView(rect);
	about->SetViewColor(top->ViewColor());
	view->AddChild(about);

	// save/cancel/revert buttons

	top->AddChild(tabView);

	rect = tabView->Frame();
	rect.top = rect.bottom + 5;  rect.bottom = rect.top + height + 5;
	BButton *saveButton = new BButton(rect,"save",
		MDR_DIALECT_CHOICE ("Save","保存"),
		new BMessage(kMsgSaveSettings));
	float w,h;
	saveButton->GetPreferredSize(&w,&h);
	saveButton->ResizeTo(w,h);
	saveButton->MoveTo(rect.right - w, rect.top);
	top->AddChild(saveButton);

	BButton *cancelButton = new BButton(rect,"cancel",
		MDR_DIALECT_CHOICE ("Cancel","中止"),
		new BMessage(kMsgCancelSettings));
	cancelButton->GetPreferredSize(&w,&h);
	cancelButton->ResizeTo(w,h);
#ifdef HAVE_APPLY_BUTTON
	cancelButton->MoveTo(saveButton->Frame().left - w - 5,rect.top);
#else
	cancelButton->MoveTo(saveButton->Frame().left - w - 20,rect.top);
#endif
	top->AddChild(cancelButton);

#ifdef HAVE_APPLY_BUTTON
	BButton *applyButton = new BButton(rect,"apply",
		MDR_DIALECT_CHOICE ("Apply","適用"),
		new BMessage(kMsgApplySettings));
	applyButton->GetPreferredSize(&w,&h);
	applyButton->ResizeTo(w,h);
	applyButton->MoveTo(cancelButton->Frame().left - w - 20,rect.top);
	top->AddChild(applyButton);
#endif

	BButton *revertButton = new BButton(rect,"revert",
		MDR_DIALECT_CHOICE ("Revert","復元"),
		new BMessage(kMsgRevertSettings));
	revertButton->GetPreferredSize(&w,&h);
	revertButton->ResizeTo(w,h);
#ifdef HAVE_APPLY_BUTTON
	revertButton->MoveTo(applyButton->Frame().left - w - 5,rect.top);
#else
	revertButton->MoveTo(cancelButton->Frame().left - w - 6,rect.top);
#endif
	top->AddChild(revertButton);

	LoadSettings();

	fAccountsListView->SetSelectionMessage(new BMessage(kMsgAccountSelected));
}
Example #27
0
status_t MailInternal::WriteMessageFile(const BMessage& archive, const BPath& path, const char* name)
{
	status_t ret = B_OK;
	BString leaf = name;
	leaf << ".tmp";
	
	BEntry settings_entry;
	BFile tmpfile;
	bigtime_t now = system_time();
	
	create_directory(path.Path(), 0777);
	{
		BDirectory account_dir(path.Path());
		ret = account_dir.InitCheck();
		if (ret != B_OK)
		{
			fprintf(stderr, "Couldn't open '%s': %s\n",
				path.Path(), strerror(ret));
			return ret;
		}
		
		// get an entry for the tempfile
		// Get it here so that failure doesn't create any problems
		ret = settings_entry.SetTo(&account_dir,leaf.String());
		if (ret != B_OK)
		{
			fprintf(stderr, "Couldn't create an entry for '%s/%s': %s\n",
				path.Path(), leaf.String(), strerror(ret));
			return ret;
		}
	}
	
	//
	// Save to a temporary file
	//
	
	// Our goal is to write to a tempfile and then use 'rename' to
	// link that file into place once it contains valid contents.
	// Given the filesystem's guarantee of atomic "rename" oper-
	// ations this will guarantee that any non-temp files in the
	// config directory are valid configuration files.
	//
	// Ideally, we would be able to do the following:
	//   BFile tmpfile(&account_dir, "tmpfile", B_WRITE_ONLY|B_CREATE_FILE);
	//   // ...
	//   tmpfile.Relink(&account_dir,"realfile");
	// But this doesn't work because there is no way in the API
	// to link based on file descriptor.  (There should be, for
	// exactly this reason, and I see no reason that it can not
	// be added to the API, but as it is not present now so we'll
	// have to deal.)  It has to be file-descriptor based because
	// (a) all a BFile knows is its node/FD and (b) the file may
	// be unlinked at any time, at which point renaming the entry
	// to clobber the "realfile" will result in an invalid con-
	// figuration file being created.
	//
	// We can't count on not clobbering the tempfile to gain
	// exclusivity because, if the system crashes between when
	// we create the tempfile an when we rename it, we will have
	// a zombie tempfile that will prevent us from doing any more
	// saves.
	//
	// What we can do is:
	//
	//    Create or open the tempfile
	//    // At this point no one will *clobber* the file, but
	//    // others may open it
	//    Lock the tempfile
	//    // At this point, no one else may open it and we have
	//    // exclusive access to it.  Because of the above, we
	//    // know that our entry is still valid
	//
	//    Truncate the tempfile
	//    Write settings
	//    Sync
	//    Rename to the realfile
	//    // this does not affect the lock, but now open-
	//    // ing the realfile will fail with B_BUSY
	//    Unlock
	//
	// If this code is the only code that changes these files,
	// then we are guaranteed that all realfiles will be valid
	// settings files.  I think that's the best we can do unless
	// we get the Relink() api.  An implementation of the above
	// follows.
	//
	
	// Create or open
	ret = B_TIMED_OUT;
	while (system_time() - now < timeout) //-ATT-no timeout arg. Setting by #define
	{
		ret = tmpfile.SetTo(&settings_entry, B_WRITE_ONLY | B_CREATE_FILE);
		if (ret != B_BUSY) break;
		
		// wait 1/100th second
		snooze((bigtime_t)1e4);
	}
	if (ret != B_OK)
	{
		fprintf(stderr, "Couldn't open '%s/%s' within the timeout period (%fs): %s\n",
			path.Path(), leaf.String(), (float)timeout/1e6, strerror(ret));
		return ret==B_BUSY? B_TIMED_OUT:ret;
	}
	
	// lock
	ret = B_TIMED_OUT;
	while (system_time() - now < timeout)
	{
		ret = tmpfile.Lock(); //-ATT-changed account_file to tmpfile. Is that allowed?
		if (ret != B_BUSY) break;
		
		// wait 1/100th second
		snooze((bigtime_t)1e4);
	}
	if (ret != B_OK)
	{
		fprintf(stderr, "Couldn't lock '%s/%s' in within the timeout period (%fs): %s\n",
			path.Path(), leaf.String(), (float)timeout/1e6, strerror(ret));
		// Can't remove it here, since it might be someone else's.
		// Leaving a zombie shouldn't cause any problems tho so
		// that's OK.
		return ret==B_BUSY? B_TIMED_OUT:ret;
	}
	
	// truncate
	tmpfile.SetSize(0);
	
	// write
	ret = archive.Flatten(&tmpfile);
	if (ret != B_OK)
	{
		fprintf(stderr, "Couldn't flatten settings to '%s/%s': %s\n",
			path.Path(), leaf.String(), strerror(ret));
		return ret;
	}
	
	// ensure it's actually writen
	ret = tmpfile.Sync();
	if (ret != B_OK)
	{
		fprintf(stderr, "Couldn't sync settings to '%s/%s': %s\n",
			path.Path(), leaf.String(), strerror(ret));
		return ret;
	}
	
	// clobber old settings
	ret = settings_entry.Rename(name,true);
	if (ret != B_OK)
	{
		fprintf(stderr, "Couldn't clobber old settings '%s/%s': %s\n",
			path.Path(), name, strerror(ret));
		return ret;
	}
	
	return B_OK;
}
Example #28
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;
}
Example #29
0
void QHaikuApplication::RefsReceived(BMessage* message)
{
    uint32 type;
    int32 count;

    const status_t status = message->GetInfo("refs", &type, &count);
    if (status == B_OK && type == B_REF_TYPE) {
        entry_ref ref;
        for (int32 i = 0; i < count; ++i) {
            if (message->FindRef("refs", i, &ref) == B_OK) {
                const BPath path(&ref);
                QCoreApplication::postEvent(QCoreApplication::instance(), new QFileOpenEvent(QFile::decodeName(path.Path())));
            }
        }
    }

    BApplication::RefsReceived(message);
}
TypeItem*
TResourceSet::LoadResource(type_code type, int32 id, const char* name,
	TypeList** inOutList)
{
	TypeItem* item = NULL;

	if (name) {
		BEntry entry;

		// If a named resource, first look in directories.
		fLock.Lock();
		int32 count = fDirectories.CountItems();
		for (int32 i = 0; item == 0 && i < count; i++) {
			BPath* dir = (BPath*)fDirectories.ItemAt(i);
			if (dir) {
				fLock.Unlock();
				BPath path(dir->Path(), name);
				if (entry.SetTo(path.Path(), true) == B_OK ) {
					BFile file(&entry, B_READ_ONLY);
					if (file.InitCheck() == B_OK ) {
						item = new TypeItem(id, name, &file);
						item->SetSourceIsFile(true);
					}
				}
				fLock.Lock();
			}
		}
		fLock.Unlock();
	}

#if USE_RESOURCES
	if (!item) {
		// Look through resource objects for data.
		fLock.Lock();
		int32 count = fResources.CountItems();
		for (int32 i = 0; item == 0 && i < count; i++ ) {
			BResources* resource = (BResources*)fResources.ItemAt(i);
			if (resource) {
				const void* data = NULL;
				size_t size = 0;
				if (id >= 0)
					data = resource->LoadResource(type, id, &size);
				else if (name != NULL)
					data = resource->LoadResource(type, name, &size);

				if (data && size) {
					item = new TypeItem(id, name, data, size);
					item->SetSourceIsFile(false);
				}
			}
		}
		fLock.Unlock();
	}
#endif

	if (item) {
		TypeList* list = inOutList ? *inOutList : NULL;
		if (!list) {
			// Don't currently have a list for this type -- check if there is
			// already one.
			list = FindTypeList(type);
		}

		BAutolock lock(&fLock);

		if (!list) {
			// Need to make a new list for this type.
			list = new TypeList(type);
			fTypes.AddItem(list);
		}
		if (inOutList)
			*inOutList = list;

		list->AddItem(item);
	}

	return item;
}