status_t StyledEditView::GetStyledText(BPositionIO* stream) { fSuppressChanges = true; status_t result = BTranslationUtils::GetStyledText(stream, this, fEncoding.String()); fSuppressChanges = false; if (result != B_OK) return result; BNode* node = dynamic_cast<BNode*>(stream); if (node != NULL) { // get encoding if (node->ReadAttrString("be:encoding", &fEncoding) != B_OK) { // try to read as "int32" int32 encoding; ssize_t bytesRead = node->ReadAttr("be:encoding", B_INT32_TYPE, 0, &encoding, sizeof(encoding)); if (bytesRead == (ssize_t)sizeof(encoding)) { if (encoding == 65535) { fEncoding = "UTF-8"; } else { const BCharacterSet* characterSet = BCharacterSetRoster::GetCharacterSetByConversionID(encoding); if (characterSet != NULL) fEncoding = characterSet->GetName(); } } } // TODO: move those into BTranslationUtils::GetStyledText() as well? // restore alignment int32 align; ssize_t bytesRead = node->ReadAttr("alignment", 0, 0, &align, sizeof(align)); if (bytesRead == (ssize_t)sizeof(align)) SetAlignment((alignment)align); // restore wrapping bool wrap; bytesRead = node->ReadAttr("wrap", 0, 0, &wrap, sizeof(wrap)); if (bytesRead == (ssize_t)sizeof(wrap)) { SetWordWrap(wrap); if (wrap == false) { BRect textRect; textRect = Bounds(); textRect.OffsetTo(B_ORIGIN); textRect.InsetBy(TEXT_INSET, TEXT_INSET); // the width comes from stylededit R5. TODO: find a better way textRect.SetRightBottom(BPoint(1500.0, textRect.RightBottom().y)); SetTextRect(textRect); } } } return result; }
/* copy atribytes */ bool BF_GUI_FilesPanel_CopyTask::Copy_Atributes(BNode & o_NodeSrc,BNode & o_NodeDest) { char pcName[B_ATTR_NAME_LENGTH]; attr_info uAttrInfo; uint32 iBufMaxSize=255; char *pcBuf = (char*)malloc(iBufMaxSize); o_NodeSrc.RewindAttrs(); // while(B_OK==o_NodeSrc.GetNextAttrName(pcName)) { if(B_OK==o_NodeSrc.GetAttrInfo(pcName,&uAttrInfo)) { /* check buffer size */ if(uAttrInfo.size>iBufMaxSize) { DELETE(pcBuf); iBufMaxSize = uAttrInfo.size; pcBuf = (char*)malloc(iBufMaxSize); } /* read attr */ o_NodeSrc.ReadAttr(pcName,uAttrInfo.type,0, (void*)pcBuf,uAttrInfo.size); /* write attr */ o_NodeDest.WriteAttr(pcName,uAttrInfo.type, 0,(void*)pcBuf,uAttrInfo.size); /* check for cancel_process */ if(Canceled()) return false; } } DELETE(pcBuf); return true; }/* end of atributes */
bool ResourceData::SetFromAttribute(const char *name, BNode &node) { attr_info info; if (node.GetAttrInfo(name, &info) != B_OK) { *this = ResourceData(); return false; } fType = info.type; fID = -1; fIDString = "(attr)"; fName = name; fLength = info.size; fAttr = true; fTypeString = MakeTypeString(fType); fData = (char *)malloc(fLength); if (fData) { ssize_t size = node.ReadAttr(name, info.type, 0, (void*)fData, fLength); if (size >= 0) { fLength = (size_t) size; return true; } } *this = ResourceData(); return false; }
/* * this method is not currently being used, but it may be useful in the future... */ status_t DefaultCatalog::ReadFromAttribute(const entry_ref &appOrAddOnRef) { BNode node; status_t res = node.SetTo(&appOrAddOnRef); if (res != B_OK) return B_ENTRY_NOT_FOUND; attr_info attrInfo; res = node.GetAttrInfo(BLocaleRoster::kEmbeddedCatAttr, &attrInfo); if (res != B_OK) return B_NAME_NOT_FOUND; if (attrInfo.type != B_MESSAGE_TYPE) return B_BAD_TYPE; size_t size = attrInfo.size; auto_ptr<char> buf(new(std::nothrow) char [size]); if (buf.get() == NULL) return B_NO_MEMORY; res = node.ReadAttr(BLocaleRoster::kEmbeddedCatAttr, B_MESSAGE_TYPE, 0, buf.get(), size); if (res < (ssize_t)size) return res < B_OK ? res : B_BAD_DATA; BMemoryIO memIO(buf.get(), size); res = Unflatten(&memIO); return res; }
void app_sig_for_pathname(const char * path, BString * signature) { *signature = ZK_APP_SIG; BNode node (path); attr_info info; char buffer [B_MIME_TYPE_LENGTH]; if (node.GetAttrInfo("BEOS:APP_SIG", & info) == B_OK) { PRINT(("node.GetAttrInfo(BEOS:APP_SIG, & info) == B_OK\n")); if (node.ReadAttr("BEOS:APP_SIG", info.type, 0, & buffer, info.size) == info.size) { PRINT(("node.ReadAttr(BEOS:APP_SIG, info.type, 0, & buffer, info.size) == B_OK\n")); PRINT(("attribute: %s \n", buffer)); *signature = buffer; } else PRINT(("No BEOS:APP_SIG attribute. Fallback to default.\n")); } else PRINT(("No BEOS:APP_SIG attribute. Fallback to default.\n")); }
void BepdfApplication::UpdateAttr(BNode &node, const char *name, type_code type, off_t offset, void *buffer, size_t length) { char dummy[10]; if (B_ENTRY_NOT_FOUND == node.ReadAttr(name, type, offset, (char*)dummy, sizeof(dummy))) { node.WriteAttr(name, type, offset, buffer, length); } }
void ActivityView::_LoadBackgroundInfo(bool watch) { fCachedOutline = false; fCachedWorkspace = -1; BPath path; if (find_directory(B_DESKTOP_DIRECTORY, &path) == B_OK) { BNode desktopNode = BNode(path.Path()); attr_info info; if (desktopNode.GetAttrInfo(kDesktopAttrName, &info) != B_OK) return; char* buffer = new char[info.size]; if (desktopNode.ReadAttr(kDesktopAttrName, B_MESSAGE_TYPE, 0, buffer, (size_t)info.size) == info.size) { BMessage message; if (message.Unflatten(buffer) == B_OK) fBackgroundInfo = message; } delete[] buffer; if (watch) { node_ref nref; desktopNode.GetNodeRef(&nref); watch_node(&nref, B_WATCH_ATTR, this); } } }
/*! Work-around for a broken index that contains out-of-date information. */ /*static*/ bool MailDaemonApp::_IsPending(BNode& node) { int32 flags; if (node.ReadAttr(B_MAIL_ATTR_FLAGS, B_INT32_TYPE, 0, &flags, sizeof(int32)) != (ssize_t)sizeof(int32)) return false; return (flags & B_MAIL_PENDING) != 0; }
uint32 IMAPFolder::_ReadUInt32(BNode& node, const char* attribute) const { uint32 value; ssize_t bytesRead = node.ReadAttr(attribute, B_UINT32_TYPE, 0, &value, sizeof(uint32)); if (bytesRead == (ssize_t)sizeof(uint32)) return value; return 0; }
/*! \brief Fetches the vector icon used by an application of this type for files of the given type. The type of the \c BMimeType object is not required to actually be a subtype of \c "application/"; that is the intended use however, and calling \c get_icon_for_type() on a non-application type will likely return \c B_ENTRY_NOT_FOUND. The icon data is allocated and returned in \a data. \param type The MIME type \param fileType Pointer to a pre-allocated string containing the MIME type whose custom icon you wish to fetch. If NULL, works just like get_icon(). \param data Pointer in which the icon data is returned on success. \param size Pointer in which the size of the icon data is returned. \return - \c B_OK: Success - \c B_ENTRY_NOT_FOUND: No vector icon exists for the given type - "error code": Failure */ status_t get_icon_for_type(const char* type, const char* fileType, uint8** data, size_t* size) { if (!type || !data || !size) return B_BAD_VALUE; // open the node for the given type BNode node; ssize_t err = open_type(type, &node); if (err < B_OK) return (status_t)err; // construct our attribute name std::string iconAttrName; if (fileType) iconAttrName = kIconAttrPrefix + BPrivate::Storage::to_lower(fileType); else iconAttrName = kIconAttr; // get info about attribute for that name attr_info info; if (!err) err = node.GetAttrInfo(iconAttrName.c_str(), &info); // validate attribute type if (!err) err = (info.type == B_VECTOR_ICON_TYPE) ? B_OK : B_BAD_VALUE; // allocate a buffer and read the attribute data into it if (!err) { uint8* buffer = new(std::nothrow) uint8[info.size]; if (!buffer) err = B_NO_MEMORY; if (!err) { err = node.ReadAttr(iconAttrName.c_str(), B_VECTOR_ICON_TYPE, 0, buffer, info.size); } if (err >= 0) err = (err == info.size) ? (ssize_t)B_OK : (ssize_t)B_FILE_ERROR; if (!err) { // success, set data pointer and size *data = buffer; *size = info.size; } else { delete[] buffer; } } return err; }
status_t IMAPStorage::ReadUniqueID(BNode& node, int32& uid) { const uint32 kMaxUniqueLength = 32; char uidString[kMaxUniqueLength]; memset(uidString, 0, kMaxUniqueLength); if (node.ReadAttr("MAIL:unique_id", B_STRING_TYPE, 0, uidString, kMaxUniqueLength) < 0) return B_ERROR; uid = atoi(uidString); return B_OK; }
/* * this method is not currently being used, but it may be useful in the future... */ status_t DefaultCatalog::ReadFromAttribute(entry_ref *appOrAddOnRef) { BNode node; status_t res = node.SetTo(appOrAddOnRef); if (res != B_OK) { log_team(LOG_ERR, "couldn't find app or add-on (dev=%lu, dir=%Lu, name=%s)", appOrAddOnRef->device, appOrAddOnRef->directory, appOrAddOnRef->name); return B_ENTRY_NOT_FOUND; } log_team(LOG_DEBUG, "looking for embedded catalog-attribute in app/add-on" "(dev=%lu, dir=%Lu, name=%s)", appOrAddOnRef->device, appOrAddOnRef->directory, appOrAddOnRef->name); attr_info attrInfo; res = node.GetAttrInfo(BLocaleRoster::kEmbeddedCatAttr, &attrInfo); if (res != B_OK) { log_team(LOG_DEBUG, "no embedded catalog found"); return B_NAME_NOT_FOUND; } if (attrInfo.type != B_MESSAGE_TYPE) { log_team(LOG_ERR, "attribute %s has incorrect type and is ignored!", BLocaleRoster::kEmbeddedCatAttr); return B_BAD_TYPE; } size_t size = attrInfo.size; auto_ptr<char> buf(new(std::nothrow) char [size]); if (buf.get() == NULL) { log_team(LOG_ERR, "couldn't allocate array of %d chars", size); return B_NO_MEMORY; } res = node.ReadAttr(BLocaleRoster::kEmbeddedCatAttr, B_MESSAGE_TYPE, 0, buf.get(), size); if (res < (ssize_t)size) { log_team(LOG_ERR, "unable to read embedded catalog from attribute"); return res < B_OK ? res : B_BAD_DATA; } BMemoryIO memIO(buf.get(), size); res = Unflatten(&memIO); return res; }
status_t read_read_attr(BNode& node, read_flags& flag) { if (node.ReadAttr(B_MAIL_ATTR_READ, B_INT32_TYPE, 0, &flag, sizeof(int32)) == sizeof(int32)) return B_OK; #if R5_COMPATIBLE BString statusString; if (node.ReadAttrString(B_MAIL_ATTR_STATUS, &statusString) == B_OK) { if (statusString.ICompare("New")) flag = B_UNREAD; else flag = B_READ; return B_OK; } #endif return B_ERROR; }
/* isProject * checks if an selected folder is a lava project folder. */ bool ProjectTypeSelector::isProject() { BNode objNode; BString *Project = (BString*)FileList->FirstItem(); objNode.SetTo(Project->String()); char buffer[500]; memset(buffer, 0, sizeof(buffer)); if(objNode.ReadAttr("LAVA:Type", B_STRING_TYPE, 0, buffer, sizeof(buffer)) == B_ENTRY_NOT_FOUND) return false; else { BDirectory objDir; objDir.SetTo(Project->String()); if(objDir.InitCheck() != B_OK) return false; else return true; } }
bool EventFileRefFilter::Filter( const entry_ref* ref, BNode* node, struct stat_beos* st, const char* filetype ) { BString fileType( filetype ); BDirectory testDir( ref ); BEntry tempEntry; BNode tempNode; char buffer[ B_MIME_TYPE_LENGTH ]; // All directories are allowed - else the user won't be able to travel if ( testDir.InitCheck() == B_OK ) { return true; } // All Event files are allowed if ( fileType.IFindFirst( kEventFileMIMEType ) == 0 ) { return true; } // Symlinks are traversed and allowed only if they point to audio file while ( fileType.IFindFirst( "application/x-vnd.Be-symlink" ) == 0 ) { if ( ( B_OK == tempEntry.SetTo( ref, true ) ) && // Find the entry referenced by symlink ( B_OK == tempNode.SetTo( &tempEntry ) ) && // Access the attributes (needed to read file type) ( 0 != tempNode.ReadAttr( "BEOS:TYPE", B_STRING_TYPE, 0, buffer, 255 ) ) && ( NULL != fileType.SetTo( buffer ) ) && // This check is really unnecessary ( fileType.IFindFirst( kEventFileMIMEType ) == 0 ) ) { return true; } } return false; } // <-- end of function EventFileRefFilter::Filter
/*********************************************************** * Fetching ***********************************************************/ void HQueryItem::Fetching() { bool some_success = false; BVolume volume; BVolumeRoster roster; while (fQueries.CountItems()) { delete static_cast<BQuery *>(fQueries.RemoveItem((int32)0)); } uint32 count_items = 0; while (roster.GetNextVolume(&volume) == B_OK) { BQuery *query = new BQuery; fQueries.AddItem((void*)query); query->Clear(); query->SetTarget(*fMessenger); query->SetVolume(&volume); query->SetPredicate(fPredicate.String()); char type[B_MIME_TYPE_LENGTH+1]; BNode node; HMailItem *item(NULL); if(query->Fetch() == B_OK) { some_success = true; entry_ref ref; char buf[4096]; dirent *dent; int32 count; int32 offset; while (((count = query->GetNextDirents((dirent *)buf, 4096)) > 0) && (!fCancel)) { offset = 0; /* Now we step through the dirents. */ while (count-- > 0) { dent = (dirent *)buf + offset; offset += dent->d_reclen; /* Skip . and .. directory */ if(::strcmp(dent->d_name,".") == 0 || ::strcmp(dent->d_name,"..")== 0) continue; ref.device = dent->d_pdev; ref.directory = dent->d_pino; ref.set_name(dent->d_name); if(node.SetTo(&ref) != B_OK) continue; node.ReadAttr("BEOS:TYPE",'MIMS',0,type,B_MIME_TYPE_LENGTH); if(::strcmp(type,B_MAIL_TYPE) == 0) { fMailList.AddItem(item = new HMailItem(ref)); if(item && !item->IsRead() ) count_items++; } } } }DEBUG_ONLY( else{ PRINT(("Query fetching was failed\n")); } ); }
void MailDaemonApp::SendPendingMessages(BMessage* msg) { BVolumeRoster roster; BVolume volume; map<int32, send_mails_info> messages; int32 account = -1; if (msg->FindInt32("account", &account) != B_OK) account = -1; if (!msg->HasString("message_path")) { while (roster.GetNextVolume(&volume) == B_OK) { BQuery query; query.SetVolume(&volume); query.PushAttr(B_MAIL_ATTR_FLAGS); query.PushInt32(B_MAIL_PENDING); query.PushOp(B_EQ); query.PushAttr(B_MAIL_ATTR_FLAGS); query.PushInt32(B_MAIL_PENDING | B_MAIL_SAVE); query.PushOp(B_EQ); if (account >= 0) { query.PushAttr(B_MAIL_ATTR_ACCOUNT_ID); query.PushInt32(account); query.PushOp(B_EQ); query.PushOp(B_AND); } query.PushOp(B_OR); query.Fetch(); BEntry entry; while (query.GetNextEntry(&entry) == B_OK) { if (_IsEntryInTrash(entry)) continue; BNode node; while (node.SetTo(&entry) == B_BUSY) snooze(1000); if (!_IsPending(node)) continue; int32 messageAccount; if (node.ReadAttr(B_MAIL_ATTR_ACCOUNT_ID, B_INT32_TYPE, 0, &messageAccount, sizeof(int32)) < 0) messageAccount = -1; off_t size = 0; node.GetSize(&size); entry_ref ref; entry.GetRef(&ref); messages[messageAccount].files.push_back(ref); messages[messageAccount].totalSize += size; } } } else { const char* path; if (msg->FindString("message_path", &path) != B_OK) return; off_t size = 0; if (BNode(path).GetSize(&size) != B_OK) return; BEntry entry(path); entry_ref ref; entry.GetRef(&ref); messages[account].files.push_back(ref); messages[account].totalSize += size; } map<int32, send_mails_info>::iterator iter = messages.begin(); for (; iter != messages.end(); iter++) { OutboundProtocolThread* protocolThread = _FindOutboundProtocol( iter->first); if (!protocolThread) continue; send_mails_info& info = iter->second; if (info.files.size() == 0) continue; MailProtocol* protocol = protocolThread->Protocol(); protocolThread->Lock(); protocol->SetTotalItems(info.files.size()); protocol->SetTotalItemsSize(info.totalSize); protocolThread->Unlock(); protocolThread->SendMessages(iter->second.files, info.totalSize); } }
BMenuItem* BRecentItemsList::GetNextMenuItem(const BMessage* fileOpenInvokeMessage, const BMessage* containerOpenInvokeMessage, BHandler* target, entry_ref* currentItemRef) { entry_ref ref; if (GetNextRef(&ref) != B_OK) return NULL; Model model(&ref, true); if (model.InitCheck() != B_OK) return NULL; bool container = false; if (model.IsSymLink()) { Model* newResolvedModel = NULL; Model* result = model.LinkTo(); if (result == NULL) { newResolvedModel = new Model(model.EntryRef(), true, true); if (newResolvedModel->InitCheck() != B_OK) { // broken link, still can show though, bail delete newResolvedModel; result = NULL; } else result = newResolvedModel; } else { BModelOpener opener(result); // open the model, if it ain't open already PoseInfo poseInfo; BNode* resultNode = result->Node(); if (resultNode != NULL) { resultNode->ReadAttr(kAttrPoseInfo, B_RAW_TYPE, 0, &poseInfo, sizeof(poseInfo)); } result->CloseNode(); ref = *result->EntryRef(); container = result->IsContainer(); } model.SetLinkTo(result); } else { ref = *model.EntryRef(); container = model.IsContainer(); } // if user asked for it, return the current item ref if (currentItemRef != NULL) *currentItemRef = ref; BMessage* message; if (container && containerOpenInvokeMessage) message = new BMessage(*containerOpenInvokeMessage); else if (!container && fileOpenInvokeMessage) message = new BMessage(*fileOpenInvokeMessage); else message = new BMessage(B_REFS_RECEIVED); message->AddRef("refs", model.EntryRef()); // Truncate the name if necessary BString truncatedString(model.Name()); be_plain_font->TruncateString(&truncatedString, B_TRUNCATE_END, BNavMenu::GetMaxMenuWidth()); ModelMenuItem* item = NULL; if (!container || !fNavMenuFolders) item = new ModelMenuItem(&model, truncatedString.String(), message); else { // add another nav menu item if it's a directory BNavMenu* menu = new BNavMenu(truncatedString.String(), message->what, target, 0); menu->SetNavDir(&ref); item = new ModelMenuItem(&model, menu); item->SetMessage(message); } if (item != NULL && target != NULL) item->SetTarget(target); return item; }
/*! Convert the plain text (UTF8) from inSource to plain or styled text in outDestination */ status_t translate_from_text(BPositionIO* source, const char* encoding, bool forceEncoding, BPositionIO* destination, uint32 outType) { if (outType != B_TRANSLATOR_TEXT && outType != B_STYLED_TEXT_FORMAT) return B_BAD_VALUE; // find the length of the text off_t size = source->Seek(0, SEEK_END); if (size < 0) return (status_t)size; if (size > UINT32_MAX && outType == B_STYLED_TEXT_FORMAT) return B_NOT_SUPPORTED; status_t status = source->Seek(0, SEEK_SET); if (status < B_OK) return status; if (outType == B_STYLED_TEXT_FORMAT) { // output styled text headers status = output_headers(destination, (uint32)size); if (status != B_OK) return status; } class MallocBuffer { public: MallocBuffer() : fBuffer(NULL), fSize(0) {} ~MallocBuffer() { free(fBuffer); } void* Buffer() { return fBuffer; } size_t Size() const { return fSize; } status_t Allocate(size_t size) { fBuffer = malloc(size); if (fBuffer != NULL) { fSize = size; return B_OK; } return B_NO_MEMORY; } private: void* fBuffer; size_t fSize; } encodingBuffer; BMallocIO encodingIO; uint32 encodingID = 0; // defaults to UTF-8 or no encoding BNode* node = dynamic_cast<BNode*>(source); if (node != NULL) { // determine encoding, if available const BCharacterSet* characterSet = NULL; bool hasAttribute = false; if (encoding != NULL && !forceEncoding) { BString name; if (node->ReadAttrString("be:encoding", &name) == B_OK) { encoding = name.String(); hasAttribute = true; } else { int32 value; ssize_t bytesRead = node->ReadAttr("be:encoding", B_INT32_TYPE, 0, &value, sizeof(value)); if (bytesRead == (ssize_t)sizeof(value)) { hasAttribute = true; if (value != 65535) characterSet = BCharacterSetRoster::GetCharacterSetByConversionID(value); } } } else { hasAttribute = true; // we don't write the encoding in this case } if (characterSet == NULL && encoding != NULL) characterSet = BCharacterSetRoster::FindCharacterSetByName(encoding); if (characterSet != NULL) { encodingID = characterSet->GetConversionID(); encodingBuffer.Allocate(READ_BUFFER_SIZE * 4); } if (!hasAttribute && encoding != NULL) { // add encoding attribute, so that someone opening the file can // retrieve it for persistance node->WriteAttr("be:encoding", B_STRING_TYPE, 0, encoding, strlen(encoding)); } } off_t outputSize = 0; ssize_t bytesRead; int32 state = 0; // output the actual text part of the data do { uint8 buffer[READ_BUFFER_SIZE]; bytesRead = source->Read(buffer, READ_BUFFER_SIZE); if (bytesRead < B_OK) return bytesRead; if (bytesRead == 0) break; if (encodingBuffer.Size() == 0) { // default, no encoding ssize_t bytesWritten = destination->Write(buffer, bytesRead); if (bytesWritten != bytesRead) { if (bytesWritten < B_OK) return bytesWritten; return B_ERROR; } outputSize += bytesRead; } else { // decode text file to UTF-8 char* pos = (char*)buffer; int32 encodingLength = encodingIO.BufferLength(); int32 bytesLeft = bytesRead; int32 bytes; do { encodingLength = READ_BUFFER_SIZE * 4; bytes = bytesLeft; status = convert_to_utf8(encodingID, pos, &bytes, (char*)encodingBuffer.Buffer(), &encodingLength, &state); if (status < B_OK) return status; ssize_t bytesWritten = destination->Write(encodingBuffer.Buffer(), encodingLength); if (bytesWritten < encodingLength) { if (bytesWritten < B_OK) return bytesWritten; return B_ERROR; } pos += bytes; bytesLeft -= bytes; outputSize += encodingLength; } while (encodingLength > 0 && bytesLeft > 0); } } while (bytesRead > 0); if (outType != B_STYLED_TEXT_FORMAT) return B_OK; if (encodingBuffer.Size() != 0 && size != outputSize) { if (outputSize > UINT32_MAX) return B_NOT_SUPPORTED; // we need to update the header as the decoded text size has changed status = destination->Seek(0, SEEK_SET); if (status == B_OK) status = output_headers(destination, (uint32)outputSize); if (status == B_OK) status = destination->Seek(0, SEEK_END); if (status < B_OK) return status; } // Read file attributes if outputting styled data // and source is a BNode object if (node == NULL) return B_OK; // Try to read styles - we only propagate an error if the actual on-disk // data is likely to be okay const char *kAttrName = "styles"; attr_info info; if (node->GetAttrInfo(kAttrName, &info) != B_OK) return B_OK; if (info.type != B_RAW_TYPE || info.size < 160) { // styles seem to be broken, but since we got the text, // we don't propagate the error return B_OK; } uint8* flatRunArray = new (std::nothrow) uint8[info.size]; if (flatRunArray == NULL) return B_NO_MEMORY; bytesRead = node->ReadAttr(kAttrName, B_RAW_TYPE, 0, flatRunArray, info.size); if (bytesRead != info.size) return B_OK; output_styles(destination, size, flatRunArray, info.size); delete[] flatRunArray; return B_OK; }
/* 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; }
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; }
QueryEntryListCollection::QueryEntryListCollection(Model* model, BHandler* target, PoseList* oldPoseList) : fQueryListRep(new QueryListRep(new BObjectList<BQuery>(5, true))) { Rewind(); attr_info info; BQuery query; BNode* modelNode = model->Node(); if (modelNode == NULL) { fStatus = B_ERROR; return; } // read the actual query string fStatus = modelNode->GetAttrInfo(kAttrQueryString, &info); if (fStatus != B_OK) return; BString buffer; if (modelNode->ReadAttr(kAttrQueryString, B_STRING_TYPE, 0, buffer.LockBuffer((int32)info.size), (size_t)info.size) != info.size) { fStatus = B_ERROR; return; } buffer.UnlockBuffer(); // read the extra options MoreOptionsStruct saveMoreOptions; if (ReadAttr(modelNode, kAttrQueryMoreOptions, kAttrQueryMoreOptionsForeign, B_RAW_TYPE, 0, &saveMoreOptions, sizeof(MoreOptionsStruct), &MoreOptionsStruct::EndianSwap) != kReadAttrFailed) { fQueryListRep->fShowResultsFromTrash = saveMoreOptions.searchTrash; } fStatus = query.SetPredicate(buffer.String()); fQueryListRep->fOldPoseList = oldPoseList; fQueryListRep->fDynamicDateQuery = false; fQueryListRep->fRefreshEveryHour = false; fQueryListRep->fRefreshEveryMinute = false; if (modelNode->ReadAttr(kAttrDynamicDateQuery, B_BOOL_TYPE, 0, &fQueryListRep->fDynamicDateQuery, sizeof(bool)) != sizeof(bool)) { fQueryListRep->fDynamicDateQuery = false; } if (fQueryListRep->fDynamicDateQuery) { // only refresh every minute on debug builds fQueryListRep->fRefreshEveryMinute = buffer.IFindFirst("second") != -1 || buffer.IFindFirst("minute") != -1; fQueryListRep->fRefreshEveryHour = fQueryListRep->fRefreshEveryMinute || buffer.IFindFirst("hour") != -1; #if !DEBUG // don't refresh every minute unless we are running debug build fQueryListRep->fRefreshEveryMinute = false; #endif } if (fStatus != B_OK) return; bool searchAllVolumes = true; status_t result = B_OK; // get volumes to perform query on if (modelNode->GetAttrInfo(kAttrQueryVolume, &info) == B_OK) { char* buffer = NULL; if ((buffer = (char*)malloc((size_t)info.size)) != NULL && modelNode->ReadAttr(kAttrQueryVolume, B_MESSAGE_TYPE, 0, buffer, (size_t)info.size) == info.size) { BMessage message; if (message.Unflatten(buffer) == B_OK) { for (int32 index = 0; ;index++) { ASSERT(index < 100); BVolume volume; // match a volume with the info embedded in // the message result = MatchArchivedVolume(&volume, &message, index); if (result == B_OK) { // start the query on this volume result = FetchOneQuery(&query, target, fQueryListRep->fQueryList, &volume); if (result != B_OK) continue; searchAllVolumes = false; } else if (result != B_DEV_BAD_DRIVE_NUM) { // if B_DEV_BAD_DRIVE_NUM, the volume just isn't // mounted this time around, keep looking for more // if other error, bail break; } } } } free(buffer); } if (searchAllVolumes) { // no specific volumes embedded in query, search everything BVolumeRoster roster; BVolume volume; roster.Rewind(); while (roster.GetNextVolume(&volume) == B_OK) if (volume.IsPersistent() && volume.KnowsQuery()) { result = FetchOneQuery(&query, target, fQueryListRep->fQueryList, &volume); if (result != B_OK) continue; } } fStatus = B_OK; return; }
/* ReadSetting * this method can read attributes from a File, just give the name of the * attribute to the method (const char) and it returns a pointer to the content of the attribute. * It's importent that you know the type of the content because the method returns * a void pointer and you have to make a typ caste to the return value to the expected * type of the attribute. * If there are errors the method throws exceptions */ void *IOSettings::ReadSetting(const char* Setting) { if(!SettingsFileExists()) CreateSettingsFile(); BNode objNode; char buffer[500]; attr_info info; memset(buffer, 0, sizeof(buffer)); //content pointer BString *strCont; int32 *int32Cont; int64 *int64Cont; double *dbCont; bool *blCont; objNode.SetTo(fSettingsFile.String()); objNode.GetAttrInfo(Setting, &info); switch(info.type) { case B_STRING_TYPE: { if(objNode.ReadAttr(Setting, info.type, 0, buffer, sizeof(buffer)) == B_ENTRY_NOT_FOUND) throw new IOSettingsException(new BString("an Attr. doesn't exsist by some folder (LavaProjectManager::_readPorject)")); strCont = new BString(buffer); return strCont; } break; case B_INT32_TYPE: { int32Cont = new int32(); if(objNode.ReadAttr(Setting, info.type, 0, int32Cont, sizeof(int32Cont)) == B_ENTRY_NOT_FOUND) throw new IOSettingsException(new BString("an Attr. doesn't exsist by some folder (LavaProjectManager::_readPorject)")); return int32Cont; } break; case B_INT64_TYPE: { int64Cont = new int64(); if(objNode.ReadAttr(Setting, info.type, 0, int64Cont, sizeof(int64Cont)) == B_ENTRY_NOT_FOUND) throw new IOSettingsException(new BString("an Attr. doesn't exsist by some folder (LavaProjectManager::_readPorject)")); return int64Cont; } break; case B_DOUBLE_TYPE: { dbCont = new double(); if(objNode.ReadAttr(Setting, info.type, 0, dbCont, sizeof(dbCont)) == B_ENTRY_NOT_FOUND) throw new IOSettingsException(new BString("an Attr. doesn't exsist by some folder (LavaProjectManager::_readPorject)")); return dbCont; } break; case B_BOOL_TYPE: { blCont = new bool(); if(objNode.ReadAttr(Setting, info.type, 0, blCont, sizeof(blCont)) == B_ENTRY_NOT_FOUND) throw new IOSettingsException(new BString("an Attr. doesn't exsist by some folder (LavaProjectManager::_readPorject)")); return blCont; } break; default: throw new IOSettingsException(new BString("not supported attribute type was read")); break; } }
/* iterate over add-on-folders and collect information about each catalog-add-ons (types of catalogs) into fCatalogAddOnInfos. */ status_t LocaleRosterData::_InitializeCatalogAddOns() { BAutolock lock(fLock); if (!lock.IsLocked()) return B_ERROR; // add info about embedded default catalog: CatalogAddOnInfo* defaultCatalogAddOnInfo = new(std::nothrow) CatalogAddOnInfo("Default", "", DefaultCatalog::kDefaultCatalogAddOnPriority); if (!defaultCatalogAddOnInfo) return B_NO_MEMORY; defaultCatalogAddOnInfo->fInstantiateFunc = DefaultCatalog::Instantiate; defaultCatalogAddOnInfo->fCreateFunc = DefaultCatalog::Create; fCatalogAddOnInfos.AddItem((void*)defaultCatalogAddOnInfo); BStringList folders; BPathFinder::FindPaths(B_FIND_PATH_ADD_ONS_DIRECTORY, "locale/catalogs/", B_FIND_PATH_EXISTING_ONLY, folders); BPath addOnPath; BDirectory addOnFolder; char buf[4096]; status_t err; for (int32 f = 0; f < folders.CountStrings(); f++) { BString addOnFolderName = folders.StringAt(f); err = addOnFolder.SetTo(addOnFolderName.String()); if (err != B_OK) continue; // scan through all the folder's entries for catalog add-ons: int32 count; int8 priority; entry_ref eref; BNode node; BEntry entry; dirent* dent; while ((count = addOnFolder.GetNextDirents((dirent*)buf, sizeof(buf))) > 0) { dent = (dirent*)buf; while (count-- > 0) { if (strcmp(dent->d_name, ".") != 0 && strcmp(dent->d_name, "..") != 0 && strcmp(dent->d_name, "x86") != 0 && strcmp(dent->d_name, "x86_gcc2") != 0) { // we have found (what should be) a catalog-add-on: eref.device = dent->d_pdev; eref.directory = dent->d_pino; eref.set_name(dent->d_name); entry.SetTo(&eref, true); // traverse through any links to get to the real thang! node.SetTo(&entry); priority = -1; if (node.ReadAttr(kPriorityAttr, B_INT8_TYPE, 0, &priority, sizeof(int8)) <= 0) { // add-on has no priority-attribute yet, so we load it // to fetch the priority from the corresponding // symbol... BString fullAddOnPath(addOnFolderName); fullAddOnPath << "/" << dent->d_name; image_id image = load_add_on(fullAddOnPath.String()); if (image >= B_OK) { uint8* prioPtr; if (get_image_symbol(image, "gCatalogAddOnPriority", B_SYMBOL_TYPE_DATA, (void**)&prioPtr) == B_OK) { priority = *prioPtr; node.WriteAttr(kPriorityAttr, B_INT8_TYPE, 0, &priority, sizeof(int8)); } unload_add_on(image); } } if (priority >= 0) { // add-ons with priority < 0 will be ignored CatalogAddOnInfo* addOnInfo = new(std::nothrow) CatalogAddOnInfo(dent->d_name, addOnFolderName, priority); if (addOnInfo) fCatalogAddOnInfos.AddItem((void*)addOnInfo); } } // Bump the dirent-pointer by length of the dirent just handled: dent = (dirent*)((char*)dent + dent->d_reclen); } } } fCatalogAddOnInfos.SortItems(CompareInfos); return B_OK; }