Пример #1
0
//---------------------- Private ---------------------------------//
status_t
JoyWin::_AddToList(BListView *list, uint32 command, const char* rootPath,
	BEntry *rootEntry)
{
	BDirectory root;

	if ( rootEntry != NULL )
		root.SetTo( rootEntry );
	else if ( rootPath != NULL )
		root.SetTo( rootPath );
	else
		return B_ERROR;

	BEntry entry;
	while ((root.GetNextEntry(&entry)) > B_ERROR ) {
		if (entry.IsDirectory()) {
			_AddToList(list, command, rootPath, &entry);
		} else {
			BPath path;
			entry.GetPath(&path);
			BString str(path.Path());
			str.RemoveFirst(rootPath);
			list->AddItem(new PortItem(str.String()));
		}
	}
	return B_OK;
}
Пример #2
0
void
ModuleManager::_FindModules(BDirectory &dir, const char *moduleDir,
	const char *suffix, module_name_list *list)
{
	BEntry entry;
	while (dir.GetNextEntry(&entry) == B_OK) {
		if (entry.IsFile()) {
			ModuleAddOn addon;
			BPath path;
			if (entry.GetPath(&path) == B_OK
				&& addon.Load(path.Path(), moduleDir) == B_OK) {
				module_info **infos = addon.ModuleInfos();
				for (int32 i = 0; infos[i]; i++) {
					if (infos[i]->name
						&& _MatchSuffix(infos[i]->name, suffix))
						list->names.insert(infos[i]->name);
				}
			}
		} else if (entry.IsDirectory()) {
			BDirectory subdir;
			if (subdir.SetTo(&entry) == B_OK)
				_FindModules(subdir, moduleDir, suffix, list);
		}
	}
}
Пример #3
0
void
OpenWindow::CollectDevices(BMenu *menu, BEntry *startEntry)
{
    BDirectory directory;
    if (startEntry != NULL)
        directory.SetTo(startEntry);
    else
        directory.SetTo("/dev/disk");

    BEntry entry;
    while (directory.GetNextEntry(&entry) == B_OK) {
        if (entry.IsDirectory()) {
            CollectDevices(menu, &entry);
            continue;
        }

        entry_ref ref;
        if (entry.GetRef(&ref) != B_OK)
            continue;

        BPath path;
        if (entry.GetPath(&path) != B_OK)
            continue;

        BMessage *message = new BMessage(B_REFS_RECEIVED);
        message->AddRef("refs", &ref);

        menu->AddItem(new BMenuItem(path.Path(), message));
    }
}
uint64 PanelView::GetDirectorySize(const char *path)
////////////////////////////////////////////////////////////////////////
{
	uint64 size = 0;
	BDirectory *dir;
		
	dir = new BDirectory(path);
	if (dir)
	{
		BEntry entry;
		
		if (dir->GetEntry(&entry)==B_OK)
		{	
			while (dir->GetNextEntry(&entry)==B_OK)			
			{
				BPath path;
				entry.GetPath(&path);
				
				if (entry.IsDirectory())
					size += GetDirectorySize(path.Path());
				else
				{
					struct stat statbuf;
					entry.GetStat(&statbuf);
					
					size += statbuf.st_size;
				}	
			}
		}
	
		delete dir;
	}

	return size;
}
Пример #5
0
/*
 * This function is lifted from Simple Directmedia Layer (SDL):
 *  http://www.libsdl.org/
 */
static void tryDir(const char *d, PHYSFS_StringCallback callback, void *data)
{
    BDirectory dir;
    dir.SetTo(d);
    if (dir.InitCheck() != B_NO_ERROR)
        return;

    dir.Rewind();
    BEntry entry;
    while (dir.GetNextEntry(&entry) >= 0)
    {
        BPath path;
        const char *name;
        entry_ref e;

        if (entry.GetPath(&path) != B_NO_ERROR)
            continue;

        name = path.Path();

        if (entry.GetRef(&e) != B_NO_ERROR)
            continue;

        if (entry.IsDirectory())
        {
            if (strcmp(e.name, "floppy") != 0)
                tryDir(name, callback, data);
        } /* if */

        else
        {
            bool add_it = false;
            int devfd;
            device_geometry g;

            if (strcmp(e.name, "raw") == 0)  /* ignore partitions. */
            {
                int devfd = open(name, O_RDONLY);
                if (devfd >= 0)
                {
                    if (ioctl(devfd, B_GET_GEOMETRY, &g, sizeof(g)) >= 0)
                    {
                        if (g.device_type == B_CD)
                        {
                            char *mntpnt = getMountPoint(name);
                            if (mntpnt != NULL)
                            {
                                callback(data, mntpnt);
                                allocator.Free(mntpnt);  /* !!! FIXME: lose this malloc! */
                            } /* if */
                        } /* if */
                    } /* if */
                } /* if */
            } /* if */

            close(devfd);
        } /* else */
    } /* while */
} /* tryDir */
Пример #6
0
// Scan directory for CD-ROM drives, add them to prefs
static void scan_for_cdrom_drives(const char *directory)
{
	// Set directory
	BDirectory dir;
	dir.SetTo(directory);
	if (dir.InitCheck() != B_NO_ERROR)
		return;
	dir.Rewind();

	// Scan each entry
	BEntry entry;
	while (dir.GetNextEntry(&entry) >= 0) {

		// Get path and ref for entry
		BPath path;
		if (entry.GetPath(&path) != B_NO_ERROR)
			continue;
		const char *name = path.Path();
		entry_ref e;
		if (entry.GetRef(&e) != B_NO_ERROR)
			continue;

		// Recursively enter subdirectories (except for floppy)
		if (entry.IsDirectory()) {
			if (!strcmp(e.name, "floppy"))
				continue;
			scan_for_cdrom_drives(name);
		} else {

			D(bug(" checking '%s'\n", name));

			// Ignore partitions
			if (strcmp(e.name, "raw"))
				continue;

			// Open device
			int fd = open(name, O_RDONLY);
			if (fd < 0)
				continue;

			// Get geometry and device type
			device_geometry g;
			if (ioctl(fd, B_GET_GEOMETRY, &g, sizeof(g)) < 0) {
				close(fd);
				continue;
			}

			// Insert to list if it is a CD drive
			if (g.device_type == B_CD)
				PrefsAddString("cdrom", name);
			close(fd);
		}
	}
}
Пример #7
0
void
InspectorApp::AddToTranslatorsList(const char *folder, int32 group)
{
	BDirectory dir;
	if (dir.SetTo(folder) == B_OK) {
	
		BEntry ent;
		while (dir.GetNextEntry(&ent) == B_OK) {
			BPath path;
			if (ent.GetPath(&path) == B_OK)
				flstTranslators.AddItem(
					new BTranslatorItem(path.Leaf(), path.Path(), group));
		}	
	}
}
Пример #8
0
    /*
     * This function is lifted from Simple Directmedia Layer (SDL):
     *  https://www.libsdl.org/  ... this is zlib-licensed code, too.
     */
static void tryDir(const char *d, PHYSFS_StringCallback callback, void *data)
{
    BDirectory dir;
    dir.SetTo(d);
    if (dir.InitCheck() != B_NO_ERROR)
        return;

    dir.Rewind();
    BEntry entry;
    while (dir.GetNextEntry(&entry) >= 0)
    {
        BPath path;
        const char *name;
        entry_ref e;

        if (entry.GetPath(&path) != B_NO_ERROR)
            continue;

        name = path.Path();

        if (entry.GetRef(&e) != B_NO_ERROR)
            continue;

        if (entry.IsDirectory())
        {
            if (strcmp(e.name, "floppy") != 0)
                tryDir(name, callback, data);
            continue;
        } /* if */

        const int devfd = open(name, O_RDONLY);
        if (devfd < 0)
            continue;

        device_geometry g;
        const int rc = ioctl(devfd, B_GET_GEOMETRY, &g, sizeof (g));
        close(devfd);
        if (rc < 0)
            continue;

        if (g.device_type != B_CD)
            continue;

        char mntpnt[B_FILE_NAME_LENGTH];
        if (getMountPoint(name, mntpnt, sizeof (mntpnt)))
            callback(data, mntpnt);
    } /* while */
} /* tryDir */
Пример #9
0
void InfoBox::GetFolder(BDirectory dir) {

	int32 c=dir.CountEntries();
	BEntry entry;
	
	if (c>0)
	for (int32 i=0; i<c; i++) {
		dir.GetNextEntry(&entry, true);
		if (entry.IsDirectory()) {
			folders++;
			GetFolder(BDirectory(&entry));
		}
		else
			files++;
	}
}
Пример #10
0
/*!	\brief Scan a folder for all valid fonts
	\param directoryPath Path of the folder to scan.
*/
status_t
FontManager::_ScanFontDirectory(font_directory& fontDirectory)
{
	// This bad boy does all the real work. It loads each entry in the
	// directory. If a valid font file, it adds both the family and the style.

	BDirectory directory;
	status_t status = directory.SetTo(&fontDirectory.directory);
	if (status != B_OK)
		return status;

	BEntry entry;
	while (directory.GetNextEntry(&entry) == B_OK) {
		if (entry.IsDirectory()) {
			// scan this directory recursively
			font_directory* newDirectory;
			if (_AddPath(entry, &newDirectory) == B_OK && newDirectory != NULL)
				_ScanFontDirectory(*newDirectory);

			continue;
		}

// TODO: Commenting this out makes my "Unicode glyph lookup"
// work with our default fonts. The real fix is to select the
// Unicode char map (if supported), and/or adjust the
// utf8 -> glyph-index mapping everywhere to handle other
// char maps. We could also ignore fonts that don't support
// the Unicode lookup as a temporary "solution".
#if 0
		FT_CharMap charmap = _GetSupportedCharmap(face);
		if (!charmap) {
		    FT_Done_Face(face);
		    continue;
    	}

		face->charmap = charmap;
#endif

		_AddFont(fontDirectory, entry);
			// takes over ownership of the FT_Face object
	}

	fontDirectory.revision = 1;
	return B_OK;
}
Пример #11
0
void BeCheckersWindow::SavedGames(BListView *list) {
	char name[B_FILE_NAME_LENGTH];

	BEntry entry;
	BDirectory dir;
	BPath p;
	find_directory(B_USER_DIRECTORY, &p);
	p.Append(APP_SGP);

	dir.SetTo(p.Path());
	dir.Rewind();

	while (dir.GetNextEntry(&entry) == B_OK) {
		entry.GetName(name);
		strtok(name, ".");	// Strip the filename extension
		list->AddItem(new BStringItem(name));
	}
}
Пример #12
0
void PanelView::DeleteDirectory(const char *dirname)
////////////////////////////////////////////////////////////////////////
{
	BDirectory *dir;
	key_info keyinfo;
	
	// Don't delete the parent directory!!!!!!
	if (strlen(dirname)>=3)
	{
		int len = strlen(dirname);
		if (dirname[len-1]=='.' && dirname[len-2]=='.' && dirname[len-3]=='/') return;
	}
		
	dir = new BDirectory(dirname);
	if (dir)
	{
		BEntry entry;
		
		if (dir->GetEntry(&entry)==B_OK)
		{	
			while (dir->GetNextEntry(&entry)==B_OK)			
			{
				get_key_info(&keyinfo);
				if (keyinfo.key_states[0] & 0x40)	// ESC
				{
					beep();
					delete dir;
					return;
				}

				BPath path;
				entry.GetPath(&path);
				
				if (entry.IsDirectory())
					DeleteDirectory(path.Path());

				entry.Remove();
			}
		}
	
		delete dir;
	}
}
Пример #13
0
// collect_folder_contents
void
collect_folder_contents( BDirectory& dir, BList& list, bool& deep, bool& asked, BEntry& entry )
{
    while ( dir.GetNextEntry( &entry, true ) == B_OK )
    {
        if ( !entry.IsDirectory() )
        {
            BPath path;
            // since the directory will give us the entries in reverse order,
            // we put them each at the same index, effectively reversing the
            // items while adding them
            if ( entry.GetPath( &path ) == B_OK )
            {
                BString* string = new BString( path.Path() );
                if ( !list.AddItem( string, 0 ) )
                    delete string;    // at least don't leak
            }
        }
        else
        {
            if ( !asked )
            {
                // ask user if we should parse sub-folders as well
                BAlert* alert = new BAlert( "sub-folders?",
                                            _("Open files from all sub-folders as well?"),
                                            _("Cancel"), _("Open"), NULL, B_WIDTH_AS_USUAL,
                                            B_IDEA_ALERT );
                int32 buttonIndex = alert->Go();
                deep = buttonIndex == 1;
                asked = true;
                // never delete BAlerts!!
            }
            if ( deep )
            {
                BDirectory subDir( &entry );
                if ( subDir.InitCheck() == B_OK )
                    collect_folder_contents( subDir, list,
                                             deep, asked, entry );
            }
        }
    }
}
Пример #14
0
status_t HModuleRoster::LoadModules( BPath *moduleDirectory )
{
	status_t		status;
	BDirectory		dir;
	
	if( (status = dir.SetTo( moduleDirectory->Path() )) == B_OK )
	{
		BEntry		entry;
		BPath		modulePath;
		
		while( dir.GetNextEntry( &entry, true ) != B_ENTRY_NOT_FOUND )
		{
			entry.GetPath( &modulePath );
			LoadModule( &modulePath );
		}
	}
	else
		return status;
	return B_OK;
}
bool
BTrashWatcher::CheckTrashDirs()
{
	BVolumeRoster volRoster;
	volRoster.Rewind();
	BVolume	volume;
	while (volRoster.GetNextVolume(&volume) == B_OK) {
		if (volume.IsReadOnly() || !volume.IsPersistent())
			continue;

		BDirectory trashDir;
		FSGetTrashDir(&trashDir, volume.Device());
		trashDir.Rewind();
		BEntry entry;
		if (trashDir.GetNextEntry(&entry) == B_OK)
			return true;
	}

	return false;
}
void
delete_directory_path(char *path,bool recur)
{
	BDirectory 	*dir;
	BPath		*pat,pt;
	BEntry		*ent;

	if ((pat = create_path(path)))
	{
		if	((dir = create_mydir((char *)pat->Path())))
		{
			if	(dir->Rewind() == B_OK)
			{
				if	((ent = new BEntry()))
				{
					while (dir->GetNextEntry(ent,false) == B_NO_ERROR)
					{
						if (ent->GetPath(&pt) == B_NO_ERROR)
						{
							if (recur)
							{
								if	(ent->IsDirectory())
								{
									delete_directory_path((char *)pt.Path(),recur);
								}
							}
						}

						ent->Remove();
					}

					delete ent;
				}
			}

			delete dir;
		}

		delete pat;
	}
}
Пример #17
0
void
DialUpView::LoadInterfaces()
{
	fInterfaceMenu->AddSeparatorItem();
	fInterfaceMenu->AddItem(new BMenuItem(kLabelCreateNewInterface,
		new BMessage(kMsgCreateNew)));
	fDeleterItem = new BMenuItem(kLabelDeleteCurrent,
		new BMessage(kMsgDeleteCurrent));
	fInterfaceMenu->AddItem(fDeleterItem);
	
	BDirectory settingsDirectory;
	BEntry entry;
	BPath path;
	GetPPPDirectories(&settingsDirectory, NULL);
	while(settingsDirectory.GetNextEntry(&entry) == B_OK) {
		if(entry.IsFile()) {
			entry.GetPath(&path);
			AddInterface(path.Leaf(), true);
		}
	}
}
Пример #18
0
void
TMailApp::_CheckForSpamFilterExistence()
{
	// Looks at the filter settings to see if the user is using a spam filter.
	// If there is one there, set fShowSpamGUI to TRUE, otherwise to FALSE.

	int32 addonNameIndex;
	const char *addonNamePntr;
	BDirectory inChainDir;
	BPath path;
	BEntry settingsEntry;
	BFile settingsFile;
	BMessage settingsMessage;

	fShowSpamGUI = false;

	if (find_directory(B_USER_SETTINGS_DIRECTORY, &path) != B_OK)
		return;
	// TODO use new settings
	path.Append("Mail/chains/inbound");
	if (inChainDir.SetTo(path.Path()) != B_OK)
		return;

	while (inChainDir.GetNextEntry (&settingsEntry, true /* traverse */) == B_OK) {
		if (!settingsEntry.IsFile())
			continue;
		if (settingsFile.SetTo (&settingsEntry, B_READ_ONLY) != B_OK)
			continue;
		if (settingsMessage.Unflatten (&settingsFile) != B_OK)
			continue;
		for (addonNameIndex = 0; B_OK == settingsMessage.FindString (
			"filter_addons", addonNameIndex, &addonNamePntr);
			addonNameIndex++) {
			if (strstr (addonNamePntr, "Spam Filter") != NULL) {
				fShowSpamGUI = true; // Found it!
				return;
			}
		}
	}
}
Пример #19
0
//---------------------------------------------------------------------
//	HandleDirectory
//---------------------------------------------------------------------
//	iterate through the directory and pass the resulting
//	refs and attempt to add the resulting file
//
status_t TQueueDialog::HandleDirectory(entry_ref &ref, struct stat &st, BDirectory &dir) 
{
	struct stat s; 
	BEntry entry; 
	
	dir.Rewind();
	while (true)
	{
		if (dir.GetNextEntry(&entry) == B_OK)
		{
			entry.GetStat(&s);
			
			entry_ref eRef;
			entry.GetRef(&eRef);
//			HandleFile(eRef, s);
			EvaluateRef(eRef);
		} else
			break;
	}
		

	return B_ERROR;
}
Пример #20
0
void PrefsWindow::add_serial_names(BPopUpMenu *menu, uint32 msg)
{
	BSerialPort *port = new BSerialPort;
	char name[B_PATH_NAME_LENGTH];
	for (int i=0; i<port->CountDevices(); i++) {
		port->GetDeviceName(i, name);
		menu->AddItem(new BMenuItem(name, new BMessage(msg)));
	}
	if (sys_info.platform_type == B_BEBOX_PLATFORM) {
		BDirectory dir;
		BEntry entry;
		dir.SetTo("/dev/parallel");
		if (dir.InitCheck() == B_NO_ERROR) {
			dir.Rewind();
			while (dir.GetNextEntry(&entry) >= 0) {
				if (!entry.IsDirectory()) {
					entry.GetName(name);
					menu->AddItem(new BMenuItem(name, new BMessage(msg)));
				}
			}
		}
	}
	delete port;
}
Пример #21
0
void
HWindow::SetupMenuField()
{
	BMenuField* menufield = dynamic_cast<BMenuField*>(FindView("filemenu"));
	if (menufield == NULL)
		return;
	BMenu* menu = menufield->Menu();
	int32 count = fEventList->CountRows();
	for (int32 i = 0; i < count; i++) {
		HEventRow* row = (HEventRow*)fEventList->RowAt(i);
		if (row == NULL)
			continue;

		BPath path(row->Path());
		if (path.InitCheck() != B_OK)
			continue;
		if (menu->FindItem(path.Leaf()))
			continue;

		BMessage* msg = new BMessage(M_ITEM_MESSAGE);
		entry_ref ref;
		::get_ref_for_path(path.Path(), &ref);
		msg->AddRef("refs", &ref);
		menu->AddItem(new BMenuItem(path.Leaf(), msg), 0);
	}

	BPath path;
	BDirectory dir;
	BEntry entry;
	BPath item_path;

	status_t err = find_directory(B_BEOS_SOUNDS_DIRECTORY, &path);
	if (err == B_OK)
		err = dir.SetTo(path.Path());
	while (err == B_OK) {
		err = dir.GetNextEntry(&entry, true);
		if (entry.InitCheck() != B_NO_ERROR)
			break;

		entry.GetPath(&item_path);

		if (menu->FindItem(item_path.Leaf()))
			continue;

		BMessage* msg = new BMessage(M_ITEM_MESSAGE);
		entry_ref ref;
		::get_ref_for_path(item_path.Path(), &ref);
		msg->AddRef("refs", &ref);
		menu->AddItem(new BMenuItem(item_path.Leaf(), msg), 0);
	}

	err = find_directory(B_USER_SOUNDS_DIRECTORY, &path);
	if (err == B_OK)
		err = dir.SetTo(path.Path());
	while (err == B_OK) {
		err = dir.GetNextEntry(&entry, true);
		if (entry.InitCheck() != B_NO_ERROR)
			break;

		entry.GetPath(&item_path);

		if (menu->FindItem(item_path.Leaf()))
			continue;

		BMessage* msg = new BMessage(M_ITEM_MESSAGE);
		entry_ref ref;

		::get_ref_for_path(item_path.Path(), &ref);
		msg->AddRef("refs", &ref);
		menu->AddItem(new BMenuItem(item_path.Leaf(), msg), 0);
	}

	err = find_directory(B_COMMON_SOUNDS_DIRECTORY, &path);
	if (err == B_OK)
		err = dir.SetTo(path.Path());
	while (err == B_OK) {
		err = dir.GetNextEntry(&entry, true);
		if (entry.InitCheck() != B_NO_ERROR)
			break;

		entry.GetPath(&item_path);

		if (menu->FindItem(item_path.Leaf()))
			continue;

		BMessage* msg = new BMessage(M_ITEM_MESSAGE);
		entry_ref ref;

		::get_ref_for_path(item_path.Path(), &ref);
		msg->AddRef("refs", &ref);
		menu->AddItem(new BMenuItem(item_path.Leaf(), msg), 0);
	}

}
Пример #22
0
/*! \brief Reads through the database and builds a complete set of installed types lists.

	An initial set of cached messages are also created.
*/
status_t
InstalledTypes::_BuildInstalledTypesList()
{
	status_t err = B_OK;
	_Unset();

	// Create empty "cached messages" so proper messages
	// will be built up as we add new types
	try {
		fCachedMessage = new BMessage();
		fCachedSupertypesMessage = new BMessage();
	} catch (std::bad_alloc) {
		err = B_NO_MEMORY;
	}

	BDirectory root;
	if (!err)
		err = root.SetTo(get_database_directory().c_str());
	if (!err) {
		root.Rewind();
		while (true) {
			BEntry entry;
			err = root.GetNextEntry(&entry);
			if (err) {
				// If we've come to the end of list, it's not an error
				if (err == B_ENTRY_NOT_FOUND)
					err = B_OK;
				break;
			} else {
				// Check that this entry is both a directory and a valid MIME string
				char supertype[B_PATH_NAME_LENGTH];
				if (entry.IsDirectory()
				      && entry.GetName(supertype) == B_OK
				         && BMimeType::IsValid(supertype))
				{
					// Make sure our string is all lowercase
					BPrivate::Storage::to_lower(supertype);

					// Add this supertype
					std::map<std::string, Supertype>::iterator i;
					if (_AddSupertype(supertype, i) != B_OK)
						DBG(OUT("Mime::InstalledTypes::BuildInstalledTypesList() -- Error adding supertype '%s': 0x%lx\n",
							supertype, err));
					Supertype &supertypeRef = fSupertypes[supertype];

					// Now iterate through this supertype directory and add
					// all of its subtypes
					BDirectory dir;
					if (dir.SetTo(&entry) == B_OK) {
						dir.Rewind();
						while (true) {
							BEntry subEntry;
							err = dir.GetNextEntry(&subEntry);
							if (err) {
								// If we've come to the end of list, it's not an error
								if (err == B_ENTRY_NOT_FOUND)
									err = B_OK;
								break;
							} else {
								// We need to preserve the case of the type name for
								// queries, so we can't use the file name directly
								BString type;
								int32 subStart;
								BNode node(&subEntry);
								if (node.InitCheck() == B_OK
									&& node.ReadAttrString(kTypeAttr, &type) >= B_OK
									&& (subStart = type.FindFirst('/')) > 0) {
									// Add the subtype
									if (_AddSubtype(supertypeRef, type.String()
											+ subStart + 1) != B_OK) {
										DBG(OUT("Mime::InstalledTypes::BuildInstalledTypesList() -- Error adding subtype '%s/%s': 0x%lx\n",
											supertype, type.String() + subStart + 1, err));
									}
								}
							}
						}
					} else {
						DBG(OUT("Mime::InstalledTypes::BuildInstalledTypesList(): "
						          "Failed opening supertype directory '%s'\n",
						            supertype));
					}
				}
			}
		}
	} else {
		DBG(OUT("Mime::InstalledTypes::BuildInstalledTypesList(): "
		          "Failed opening mime database directory '%s'\n",
		            get_database_directory().c_str()));
	}
	fHaveDoneFullBuild = true;
	return err;

}
Пример #23
0
status_t
CDDBDaemon::_WriteCDData(dev_t device, QueryResponseData* diskData,
	ReadResponseData* readResponse)
{
	// Rename volume.
	BVolume volume(device);
	
	status_t result;
	status_t error = B_OK;
	
	BString name = diskData->artist << " - " << diskData->title;
	name.ReplaceSet("/", " ");
	
	if ((result = volume.SetName(name.String())) != B_OK) {
		printf("Can't set volume name.\n");
		return result;
	}
	
	// Rename tracks and add relevant Audio attributes.	
	BDirectory cddaRoot;
	volume.GetRootDirectory(&cddaRoot);
	
	BEntry entry;
	int index = 0;
	while (cddaRoot.GetNextEntry(&entry) == B_OK) {
		TrackData* data = (TrackData*)((readResponse->tracks).ItemAt(index));
		
		// Update name.
		name = data->title;
		name.ReplaceSet("/", " ");
		
		if ((result = entry.Rename(name.String())) != B_OK) {
			printf("Failed renaming entry at index %d to \"%s\".\n", index,
				name.String());
			error = result;
				// User can benefit from continuing through all tracks.
				// Report error later.
		}
		
		// Add relevant attributes. We consider an error here as non-fatal.
		BNode node(&entry);
		node.WriteAttr("Audio:Title", B_STRING_TYPE, 0, (data->title).String(),
			(data->title).Length());
		node.WriteAttr("Audio:Album", B_STRING_TYPE, 0,
			(readResponse->title).String(),
			(readResponse->title).Length());
		node.WriteAttr("Audio:Genre", B_STRING_TYPE, 0,
			(readResponse->genre).String(),
			(readResponse->genre).Length());
		node.WriteAttr("Audio:Year", B_INT32_TYPE, 0, &(readResponse->year),
			sizeof(int32));

		if (data->artist == "") {
			node.WriteAttr("Audio:Artist", B_STRING_TYPE, 0,
				(readResponse->artist).String(),
				(readResponse->artist).Length());
		} else {
			node.WriteAttr("Audio:Artist", B_STRING_TYPE, 0,
				(data->artist).String(), (data->artist).Length());			
		}
			
		index++;
	}
	
	return error;
}	
Пример #24
0
status_t
CDDBLookup::_WriteCDData(dev_t device, const QueryResponseData& diskData,
	const ReadResponseData& readResponse)
{
	// Rename volume.
	BVolume volume(device);

	status_t error = B_OK;

	BString name = diskData.artist;
	name += " - ";
	name += diskData.title;
	name.ReplaceSet("/", " ");

	status_t result = volume.SetName(name.String());
	if (result != B_OK) {
		printf("Can't set volume name.\n");
		return result;
	}

	// Rename tracks and add relevant Audio attributes.
	BDirectory cddaRoot;
	volume.GetRootDirectory(&cddaRoot);

	BEntry entry;
	int index = 0;
	while (cddaRoot.GetNextEntry(&entry) == B_OK) {
		TrackData* track = readResponse.tracks.ItemAt(index);

		// Update name.
		int trackNum = index + 1; // index=0 is actually Track 1
		name.SetToFormat("%02d %s.wav", trackNum, track->title.String());
		name.ReplaceSet("/", " ");

		result = entry.Rename(name.String());
		if (result != B_OK) {
			fprintf(stderr, "%s: Failed renaming entry at index %d to "
				"\"%s\".\n", kProgramName, index, name.String());
			error = result;
				// User can benefit from continuing through all tracks.
				// Report error later.
		}

		// Add relevant attributes. We consider an error here as non-fatal.
		BNode node(&entry);
		node.WriteAttrString("Media:Title", &track->title);
		node.WriteAttrString("Audio:Album", &readResponse.title);
		if (readResponse.genre.Length() != 0)
			node.WriteAttrString("Media:Genre", &readResponse.genre);
		if (readResponse.year != 0) {
			node.WriteAttr("Media:Year", B_INT32_TYPE, 0,
				&readResponse.year, sizeof(int32));
		}

		if (track->artist == "")
			node.WriteAttrString("Audio:Artist", &readResponse.artist);
		else
			node.WriteAttrString("Audio:Artist", &track->artist);

		index++;
	}

	return error;
}
Пример #25
0
void
PairsView::_ReadRandomIcons()
{
	// TODO: maybe read the icons only once at startup

	// clean out any previous icons
	for (int i = 0; i < fCardBitmaps.CountItems(); i++)
		delete ((BBitmap*)fCardBitmaps.ItemAt(i));

	fCardBitmaps.MakeEmpty();

	BDirectory appsDirectory;
	BDirectory prefsDirectory;

	BPath path;
	if (find_directory(B_BEOS_APPS_DIRECTORY, &path) == B_OK)
		appsDirectory.SetTo(path.Path());
	if (find_directory(B_BEOS_PREFERENCES_DIRECTORY, &path) == B_OK)
		prefsDirectory.SetTo(path.Path());

	// read vector icons from apps and prefs folder and put them
	// into a BList as BBitmaps
	BList bitmaps;

	BEntry entry;
	while (appsDirectory.GetNextEntry(&entry) == B_OK
		|| prefsDirectory.GetNextEntry(&entry) == B_OK) {

		BNode node(&entry);
		BNodeInfo nodeInfo(&node);

		if (nodeInfo.InitCheck() < B_OK)
			continue;

		uint8* data;
		size_t size;
		type_code type;

		if (nodeInfo.GetIcon(&data, &size, &type) < B_OK)
			continue;

		if (type != B_VECTOR_ICON_TYPE) {
			delete[] data;
			continue;
		}

		BBitmap* bitmap = new BBitmap(
			BRect(0, 0, kBitmapSize - 1, kBitmapSize - 1), 0, B_RGBA32);
		if (BIconUtils::GetVectorIcon(data, size, bitmap) < B_OK) {
			delete[] data;
			delete bitmap;
			continue;
		}

		delete[] data;

		if (_HasBitmap(bitmaps, bitmap) || !bitmaps.AddItem(bitmap))
			delete bitmap;
		else if (bitmaps.CountItems() >= 128) {
			// this is enough to choose from, stop eating memory...
			break;
		}
	}

	// pick random bitmaps from the ones we got in the list
	srand((unsigned)time(0));

	for (int i = 0; i < fNumOfCards / 2; i++) {
		int32 index = rand() % bitmaps.CountItems();
		BBitmap* bitmap = ((BBitmap*)bitmaps.RemoveItem(index));
		if (bitmap == NULL) {
			char buffer[512];
			snprintf(buffer, sizeof(buffer), B_TRANSLATE("Pairs did not find "
				"enough vector icons in the system; it needs at least %d."),
				fNumOfCards / 2);
			BString msgStr(buffer);
			msgStr << "\n";
			BAlert* alert = new BAlert("Fatal", msgStr.String(),
				B_TRANSLATE("OK"), 	NULL, NULL, B_WIDTH_FROM_WIDEST,
				B_STOP_ALERT);
			alert->SetShortcut(0, B_ESCAPE);
			alert->Go();
			exit(1);
		}
		fCardBitmaps.AddItem(bitmap);
	}

	// delete the remaining bitmaps from the list
	while (BBitmap* bitmap = (BBitmap*)bitmaps.RemoveItem(0L))
		delete bitmap;
}
Пример #26
0
void PanelView::ReadDirectory(const char *itemname)
////////////////////////////////////////////////////////////////////////
{
	BDirectory *dir;
	CustomListItem *item;

	stop_watching(this);
//	SetMousePointer(CR_HOURGLASS);
	MAINWINDOW->SetMousePointer(GenesisWindow::CR_HOURGLASS);
	
	// If we are not in the root directory, simply start the dir with a '..' entry...
	if (strcmp(m_Path.String(),"/")!=0)
	{
		item = new CustomListItem("..", m_Path.String(), FT_PARENT, 0);
		m_CustomListView->AddItem(item);
		if (m_Setting_ShowIcons)
		{
			item->AddIcon(m_ParentIcon);
			item->SetHeight(15.0f);
		}
	}
	
	dir = new BDirectory(m_Path.String());
	if (dir)
	{
		BEntry entry;
		
		if (dir->GetEntry(&entry)==B_OK)
		{	
			while (dir->GetNextEntry(&entry)==B_OK)			
			{
				AddDirectoryEntry(&entry);
			}
		}
	
		delete dir;
	}
	
	m_CustomListView->DoSortList();
	
	// Always select the first item in the list or the child where we came from...
	if (itemname)
	{
		CustomListItem *item;
		int n = m_CustomListView->CountItems();
		
		for (int i=0;i<n;i++)
		{
			item = (CustomListItem *)m_CustomListView->ItemAt(i);

			if (strcasecmp(itemname,item->m_FileName.String())==0)
			{
				m_CustomListView->Select(i,false);
				m_CustomListView->ScrollToSelection();
				break;
			}			
		}
		
		// When the given file disappeared, we have to select the first entry...
		if (m_CustomListView->CountSelectedEntries(CT_WITHPARENT)==0)
			m_CustomListView->Select(0,false);	
	}
	else
		m_CustomListView->Select(0,false);

	m_CurrentTotalSize = m_CustomListView->GetCurrentTotalSize();

	// Probably we have to update the path of the command line...
	Parent()->Looper()->PostMessage(new BMessage(MSG_UPDATECOMMANDLINE_PATH));	// To update command line...

	EnableMonitoring();
	
//	SetMousePointer(CR_DEFAULT);
	MAINWINDOW->SetMousePointer(GenesisWindow::CR_DEFAULT);
}
Пример #27
0
/*------------------------------------------------------------------------------*\
	LoadAddons()
		-	loads all available filter-addons
\*------------------------------------------------------------------------------*/
void BmFilterList::LoadAddons() {
	BDirectory addonDir;
	BPath path;
	BEntry entry;
	status_t err;

	BM_LOG2( BM_LogFilter, BmString("Start of LoadAddons() for FilterList"));

	// determine the path to the user-config-directory:
	if (find_directory( B_USER_ADDONS_DIRECTORY, &path) != B_OK)
		BM_THROW_RUNTIME( "Sorry, could not determine user's addon-dir !?!");
	BmString addonPath = BmString(BeamRoster->AppPath()) + "/add-ons/Filters";
	SetupFolder( addonPath.String(), &addonDir);

	// ...and scan through all its entries for filter-add-ons:
	while ( addonDir.GetNextEntry( &entry, true) == B_OK) {
		if (entry.IsFile()) {
			char nameBuf[B_FILE_NAME_LENGTH];
			entry.GetName( nameBuf);
			// try to load addon:
			const char** filterKinds;
			const char** defaultFilterName;
			BmFilterAddonDescr ao;
			ao.name = nameBuf;
			ao.name.CapitalizeEachWord();
			entry.GetPath( &path);
			if ((ao.image = load_add_on( path.Path())) < 0) {
				BM_SHOWERR( BmString("Unable to load filter-addon\n\t")
									<<ao.name<<"\n\nError:\n\t"<<strerror( ao.image));
				continue;
			}
			if ((err = get_image_symbol( 
				ao.image, "InstantiateFilter", B_SYMBOL_TYPE_ANY, 
				(void**)&ao.instantiateFilterFunc
			)) != B_OK) {
				BM_SHOWERR( BmString("Unable to load filter-addon\n\t")
								<<ao.name<<"\n\nMissing symbol 'InstantiateFilter'");
				continue;
			}
			if ((err = get_image_symbol( 
				ao.image, "InstantiateFilterPrefs", B_SYMBOL_TYPE_ANY, 
				(void**)&ao.instantiateFilterPrefsFunc
			)) != B_OK) {
				BM_SHOWERR( BmString("Unable to load filter-addon\n\t")
								<<ao.name
								<<"\n\nMissing symbol 'InstantiateFilterPrefs'");
				continue;
			}
			if ((err = get_image_symbol( 
				ao.image, "FilterKinds", B_SYMBOL_TYPE_ANY, 
				(void**)&filterKinds
			)) != B_OK) {
				BM_SHOWERR( BmString("Unable to load filter-addon\n\t")
								<<ao.name<<"\n\nMissing symbol 'FilterKinds'");
				continue;
			}
			if ((err = get_image_symbol( 
				ao.image, "DefaultFilterName", B_SYMBOL_TYPE_ANY, 
				(void**)&defaultFilterName
			)) == B_OK)
				ao.defaultFilterName = *defaultFilterName;
			else
				ao.defaultFilterName = "new filter";
#if 0
			// we try to set TheBubbleHelper and TheLogHandler globals inside 
			// the addon to our current values:
			BubbleHelper** bhPtr;
			if (get_image_symbol( ao.image, "TheBubbleHelper", B_SYMBOL_TYPE_ANY, 
										 (void**)&bhPtr) == B_OK) {
				*bhPtr = TheBubbleHelper;
			}
			BmLogHandler** lhPtr;
			if (get_image_symbol( ao.image, "TheLogHandler", B_SYMBOL_TYPE_ANY, 
										 (void**)&lhPtr) == B_OK) {
				*lhPtr = TheLogHandler;
			}
#endif
			// now we add the addon to our map (one entry per filter-kind):
			while( *filterKinds) {
				BmString kind(*filterKinds);
				FilterAddonMap[*filterKinds++] = ao;
				if (kind.ICompare("Spam") == 0) {
					// a spam-filter requires two internal filters (learnAsSpam
					// and learnAsTofu) which don't appear as part of filter-list:
					mLearnAsSpamFilter 
						= new BmFilter( LEARN_AS_SPAM_NAME, "Spam", NULL);
					BMessage learnAsSpamJob;
					learnAsSpamJob.AddString("jobSpecifier", "LearnAsSpam");
					mLearnAsSpamFilter->JobSpecifier(learnAsSpamJob);
					mLearnAsTofuFilter 
						= new BmFilter( LEARN_AS_TOFU_NAME, "Spam", NULL);
					BMessage learnAsTofuJob;
					learnAsTofuJob.AddString("jobSpecifier", "LearnAsTofu");
					mLearnAsTofuFilter->JobSpecifier(learnAsTofuJob);
				}
			}
			BM_LOG( BM_LogFilter, BmString("Successfully loaded addon ") 
						<< ao.name);

		}
	}
	BM_LOG2( BM_LogFilter, BmString("End of LoadAddons() for FilterList"));
}
Пример #28
0
void BeHappy::SearchAddOns()
{
	// on vide les listes
	{
		BPath *p;
		while ((p=(BPath*)addOnsPaths.RemoveItem((int32)0))!=NULL)
			delete p;
			
		BString *s;
		while ((s=(BString*)addOnsNames.RemoveItem((int32)0))!=NULL)
			delete s;
	}
		
	// d'abord on cherche le dossier
	app_info myInfo;
	be_app->GetAppInfo(&myInfo);
	BEntry appEntry(&(myInfo.ref));
	BDirectory addOnsDir;
	appEntry.GetParent(&addOnsDir);
	
	// parcours de tous les fichiers du dossier
	if (addOnsDir.SetTo(&addOnsDir,"Add-ons")==B_OK)
	{
		BEntry addOn;
		while (addOnsDir.GetNextEntry(&addOn,true) == B_OK)
		{
			BPath *addOnPath = new BPath;
			addOn.GetPath(addOnPath);
			// extraction du type MIME
			{
				BNode myNode(&addOn);
								
				BNodeInfo myNodeInfo(&myNode);
				char mimeType[256];
				myNodeInfo.GetType(mimeType);
				if (BString("application/x-vnd.Be-elfexecutable") != mimeType)
					continue;
			}
			
			// on est sûrs que c'est un Add-on
			BString *projName = new BString;
			if (CheckAddOn(addOnPath->Path(),true,projName))
			{
				addOnsPaths.AddItem(addOnPath);
				addOnsNames.AddItem(projName);
			}
			else
			{
				delete addOnPath;
				delete projName;
			}
			
			// si c'est la première fois que SearchAddOns est appelé, on doit activer le node monitor
			if (!addOnsSearched)
			{
				addOnsSearched = true;
				
				node_ref myRef;
				addOnsDir.GetNodeRef(&myRef);
				watch_node(&myRef,B_WATCH_DIRECTORY,be_app_messenger);
			}
		}
	}
	else
	{
		BAlert *myAlert = new BAlert("BeHappy",T("Can't find Add-ons folder"),
			"Quit",NULL,NULL,B_WIDTH_AS_USUAL,B_STOP_ALERT);
		
		myAlert->Go();
		PostMessage(B_QUIT_REQUESTED);
	}
}
Пример #29
0
void 
BL_CDEngine::SearchForCdPlayer(const char* aDirName) 
{
  BDirectory lDirectory;
  if (lDirectory.SetTo(aDirName) != B_OK) {
    return;
  }
  lDirectory.Rewind();

  BEntry lEntry;
  while(lDirectory.GetNextEntry(&lEntry) >= 0) {

    BPath lPath;
    if(lEntry.GetPath(&lPath) != B_OK) {
      continue;
    } 
    
    const char* lpName = lPath.Path();

    entry_ref lRef;
    if(lEntry.GetRef(&lRef) != B_OK) {
      continue;
    }

    if(lEntry.IsDirectory()) {

      // Ignore floppy. It's worth to explicitly check for the floppy 
      // device and ignore it, because opening it to get its geometry
      // would just make a lot of noise, and not any sense.
      if(strcmp(lRef.name, "floppy") == 0) {
        continue;
      }
      SearchForCdPlayer(lpName);
    
    } else {

      // Ignore partitions.
      if(strcmp(lRef.name, "raw") != 0) {
        continue;
      }

      // Try to open the device.
      int lDevice = open(lpName, O_RDONLY);
      if(lDevice < 0) {
        continue;
      }

      // Figure out is the device is a CD-ROM drive.
      device_geometry lGeometry;
      if(ioctl(lDevice, 
               B_GET_GEOMETRY, 
               &lGeometry, 
               sizeof(lGeometry)) < 0) {
        close(lDevice);
        continue;
      }

      // Hooray, we've found a CD-ROM drive.
      if(lGeometry.device_type == B_CD) {

        // Store the device's name in the list and close the device. 
        mpDevices->AddItem(strdup(lpName));
        close(lDevice);        
      }
    }
  }
}
Пример #30
0
void
TMailApp::ReadyToRun()
{
	// Create needed indices for META:group, META:email, MAIL:draft,
	// INDEX_SIGNATURE, INDEX_STATUS on the boot volume

	BVolume volume;
	BVolumeRoster().GetBootVolume(&volume);

	fs_create_index(volume.Device(), "META:group", B_STRING_TYPE, 0);
	fs_create_index(volume.Device(), "META:email", B_STRING_TYPE, 0);
	fs_create_index(volume.Device(), "MAIL:draft", B_INT32_TYPE, 0);
	fs_create_index(volume.Device(), INDEX_SIGNATURE, B_STRING_TYPE, 0);
	fs_create_index(volume.Device(), INDEX_STATUS, B_STRING_TYPE, 0);
	fs_create_index(volume.Device(), B_MAIL_ATTR_FLAGS, B_INT32_TYPE, 0);

	// Start people queries
	fPeopleQueryList.Init("META:email=**");

	// Load dictionaries
	BPath indexDir;
	BPath dictionaryDir;
	BPath userDictionaryDir;
	BPath userIndexDir;
	BPath dataPath;
	BPath indexPath;
	BDirectory directory;
	BEntry entry;

	// Locate dictionaries directory
	find_directory(B_SYSTEM_DATA_DIRECTORY, &indexDir, true);
	indexDir.Append("spell_check");
	dictionaryDir = indexDir;

	//Locate user dictionary directory
	find_directory(B_USER_CONFIG_DIRECTORY, &userIndexDir, true);
	userIndexDir.Append("data/spell_check");
	userDictionaryDir = userIndexDir;

	// Create directory if needed
	directory.CreateDirectory(userIndexDir.Path(),  NULL);

	// Setup directory paths
	indexDir.Append(kIndexDirectory);
	dictionaryDir.Append(kDictDirectory);
	userIndexDir.Append(kIndexDirectory);
	userDictionaryDir.Append(kDictDirectory);

	// Create directories if needed
	directory.CreateDirectory(indexDir.Path(), NULL);
	directory.CreateDirectory(dictionaryDir.Path(), NULL);
	directory.CreateDirectory(userIndexDir.Path(), NULL);
	directory.CreateDirectory(userDictionaryDir.Path(), NULL);

	dataPath = dictionaryDir;
	dataPath.Append("words");

	// Only Load if Words Dictionary
	if (BEntry(kWordsPath).Exists() || BEntry(dataPath.Path()).Exists()) {
		// If "/boot/optional/goodies/words" exists but there is no
		// system dictionary, copy words
		if (!BEntry(dataPath.Path()).Exists() && BEntry(kWordsPath).Exists()) {
			BFile words(kWordsPath, B_READ_ONLY);
			BFile copy(dataPath.Path(), B_WRITE_ONLY | B_CREATE_FILE);
			char buffer[4096];
			ssize_t size;

			while ((size = words.Read( buffer, 4096)) > 0)
				copy.Write(buffer, size);
			BNodeInfo(&copy).SetType("text/plain");
		}

		// Load dictionaries
		directory.SetTo(dictionaryDir.Path());

		BString leafName;
		gUserDict = -1;

		while (gDictCount < MAX_DICTIONARIES
			&& directory.GetNextEntry(&entry) != B_ENTRY_NOT_FOUND) {
			dataPath.SetTo(&entry);

			indexPath = indexDir;
			leafName.SetTo(dataPath.Leaf());
			leafName.Append(kMetaphone);
			indexPath.Append(leafName.String());
			gWords[gDictCount] = new Words(dataPath.Path(), indexPath.Path(), true);

			indexPath = indexDir;
			leafName.SetTo(dataPath.Leaf());
			leafName.Append(kExact);
			indexPath.Append(leafName.String());
			gExactWords[gDictCount] = new Words(dataPath.Path(), indexPath.Path(), false);
			gDictCount++;
		}

		// Create user dictionary if it does not exist
		dataPath = userDictionaryDir;
		dataPath.Append("user");
		if (!BEntry(dataPath.Path()).Exists()) {
			BFile user(dataPath.Path(), B_WRITE_ONLY | B_CREATE_FILE);
			BNodeInfo(&user).SetType("text/plain");
		}

		// Load user dictionary
		if (BEntry(userDictionaryDir.Path()).Exists()) {
			gUserDictFile = new BFile(dataPath.Path(), B_WRITE_ONLY | B_OPEN_AT_END);
			gUserDict = gDictCount;

			indexPath = userIndexDir;
			leafName.SetTo(dataPath.Leaf());
			leafName.Append(kMetaphone);
			indexPath.Append(leafName.String());
			gWords[gDictCount] = new Words(dataPath.Path(), indexPath.Path(), true);

			indexPath = userIndexDir;
			leafName.SetTo(dataPath.Leaf());
			leafName.Append(kExact);
			indexPath.Append(leafName.String());
			gExactWords[gDictCount] = new Words(dataPath.Path(), indexPath.Path(), false);
			gDictCount++;
		}
	}

	// Create a new window if starting up without any extra arguments.

	if (!fPrintHelpAndExit && !fWindowCount) {
		TMailWindow	*window;
		window = NewWindow();
		window->Show();
	}
}