status_t POP3Protocol::SyncMessages() { bool leaveOnServer; if (fSettings.FindBool("leave_mail_on_server", &leaveOnServer) != B_OK) leaveOnServer = true; // create directory if not exist create_directory(fDestinationDir, 0777); printf("POP3Protocol::SyncMessages()\n"); _ReadManifest(); SetTotalItems(2); ReportProgress(0, 1, "Connect to server..."); status_t error = Connect(); if (error < B_OK) { ResetProgress(); return error; } ReportProgress(0, 1, MDR_DIALECT_CHOICE("Getting UniqueIDs...", "固有のIDを取得中...")); error = _UniqueIDs(); if (error < B_OK) { ResetProgress(); return error; } BStringList toDownload; fManifest.NotHere(fUniqueIDs, &toDownload); int32 numMessages = toDownload.CountItems(); if (numMessages == 0) { CheckForDeletedMessages(); ResetProgress(); return B_OK; } ResetProgress(); SetTotalItems(toDownload.CountItems()); printf("POP3: Messages to download: %i\n", (int)toDownload.CountItems()); for (int32 i = 0; i < toDownload.CountItems(); i++) { const char* uid = toDownload.ItemAt(i); int32 toRetrieve = fUniqueIDs.IndexOf(uid); if (toRetrieve < 0) { // should not happen! error = B_NAME_NOT_FOUND; printf("POP3: uid %s index %i not found in fUniqueIDs!\n", uid, (int)toRetrieve); continue; } BPath path(fDestinationDir); BString fileName = "Downloading file... uid: "; fileName += uid; fileName.ReplaceAll("/", "_SLASH_"); path.Append(fileName); BEntry entry(path.Path()); BFile file(&entry, B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE); error = file.InitCheck(); if (error != B_OK) { printf("POP3: Can't create file %s\n ", path.Path()); break; } BMailMessageIO mailIO(this, &file, toRetrieve); entry_ref ref; entry.GetRef(&ref); // the ref becomes invalid after renaming the file thus we already // write the status here MarkMessageAsRead(ref, B_UNREAD); int32 size = MessageSize(toRetrieve); if (fFetchBodyLimit < 0 || size <= fFetchBodyLimit) { error = mailIO.Seek(0, SEEK_END); if (error < 0) { printf("POP3: Failed to download body %s\n ", uid); break; } NotifyHeaderFetched(ref, &file); NotifyBodyFetched(ref, &file); if (!leaveOnServer) Delete(toRetrieve); } else { int32 dummy; error = mailIO.ReadAt(0, &dummy, 1); if (error < 0) { printf("POP3: Failed to download header %s\n ", uid); break; } NotifyHeaderFetched(ref, &file); } ReportProgress(0, 1); if (file.WriteAttr("MAIL:unique_id", B_STRING_TYPE, 0, uid, strlen(uid)) < 0) { error = B_ERROR; } file.WriteAttr("MAIL:size", B_INT32_TYPE, 0, &size, sizeof(int32)); // save manifest in case we get disturbed fManifest += uid; _WriteManifest(); } ResetProgress(); CheckForDeletedMessages(); Disconnect(); return error; }
BString VisionApp::ParseAlias(const char* cmd, const BString& channel) { BString command(GetWord(cmd, 1).ToUpper()); BString newcmd = fAliases[command]; const char* parse = newcmd.String(); int32 replidx(0); int32 varidx(0); newcmd.ReplaceAll("$C", channel.String()); while (*parse != '\0') { if (*parse != '$') { ++parse; continue; } else { replidx = parse - newcmd.String(); ++parse; if (isdigit(*parse)) { varidx = atoi(parse); BString replString = "$"; replString << varidx; if (*(parse + replString.Length() - 1) != '-') { newcmd.ReplaceAll(replString.String(), GetWord(cmd, varidx + 1).String()); } else { replString += "-"; newcmd.ReplaceAll(replString.String(), RestOfString(cmd, varidx + 1).String()); } } } } return newcmd; }
// Note: \xNN is not replaced back, so you get the unescaped value in the catkey // file. This is fine for regular unicode chars (B_UTF8_ELLIPSIS) but may be // dangerous if you use \x10 as a newline... void escapeQuotedChars(BString& stringToEscape) { stringToEscape.ReplaceAll("\\","\\\\"); stringToEscape.ReplaceAll("\n","\\n"); stringToEscape.ReplaceAll("\t","\\t"); stringToEscape.ReplaceAll("\"","\\\""); }
static void EscapeWord(BString& word) { word.ReplaceAll("\\", "\\\\"); word.ReplaceAll("#", "\\#"); word.ReplaceAll("\"", "\\\""); word.ReplaceAll("\'", "\\\'"); }
void THeaderView::InitEmailCompletion() { // get boot volume BVolume volume; BVolumeRoster().GetBootVolume(&volume); BQuery query; query.SetVolume(&volume); query.SetPredicate("META:email=**"); // Due to R5 BFS bugs, you need two stars, META:email=** for the query. // META:email="*" will just return one entry and stop, same with // META:email=* and a few other variations. Grumble. query.Fetch(); entry_ref ref; while (query.GetNextRef (&ref) == B_OK) { BNode file; if (file.SetTo(&ref) == B_OK) { // Add the e-mail address as an auto-complete string. BString email; if (file.ReadAttrString("META:email", &email) >= B_OK) fEmailList.AddChoice(email.String()); // Also add the quoted full name as an auto-complete string. Can't // do unquoted since auto-complete isn't that smart, so the user // will have to type a quote mark if he wants to select someone by // name. BString fullName; if (file.ReadAttrString("META:name", &fullName) >= B_OK) { if (email.FindFirst('<') < 0) { email.ReplaceAll('>', '_'); email.Prepend("<"); email.Append(">"); } fullName.ReplaceAll('\"', '_'); fullName.Prepend("\""); fullName << "\" " << email; fEmailList.AddChoice(fullName.String()); } // support for 3rd-party People apps. Looks like a job for // multiple keyword (so you can have several e-mail addresses in // one attribute, perhaps comma separated) indices! Which aren't // yet in BFS. for (int16 i = 2; i < 6; i++) { char attr[16]; sprintf(attr, "META:email%d", i); if (file.ReadAttrString(attr, &email) >= B_OK) fEmailList.AddChoice(email.String()); } } } }
void AIMNetManager::ReceiveWarning( SNAC_Object& snac ) { BString warnMessage; char strNewWLevel[15]; unsigned short wLevel, i=0; DataContainer screenName; bool anon = false; char snLength; wLevel = (unsigned short)( rint( (double)GetWord(snac.data,i) / 10.0 ) ); i += 2; printf( "New warning level: %u%%\n", wLevel ); printf( "... came from " ); // 'twas an anonymous warning if( i >= snac.data.length() ) { anon = true; printf( "Anonymous\n" ); } // grab the length, and then the screen name if( !anon ) { snLength = snac.data[i++]; screenName = DataContainer( snac.data.getrange(i,snLength) ); i += snLength; screenName << char(0); printf( "%s\n", screenName.c_ptr() ); } // is our warning level going DOWN? if so, don't annoy the user by telling them about it if( wLevel < client->WarningLevel() ) { client->SetWarningLevel( wLevel ); return; } // make the "warned" message client->SetWarningLevel( wLevel ); sprintf( strNewWLevel, "%u%%", wLevel ); warnMessage = BString( Language.get("ERR_GOT_WARNED") ); warnMessage.ReplaceAll( "%WLEVEL", strNewWLevel ); if( anon ) { BString anonLabel = "["; anonLabel.Append( Language.get("ANONYMOUS_LABEL") ); anonLabel.Append( "]" ); warnMessage.ReplaceAll( "%USER", anonLabel.String() ); } else warnMessage.ReplaceAll( "%USER", screenName.c_ptr() ); // now display it windows->ShowMessage( warnMessage, B_STOP_ALERT, Language.get("BEHAVE_LABEL"), WS_WARNED ); }
void MainWindow::_UpdateAuthorization() { BString username(fModel.Username()); bool hasUser = !username.IsEmpty(); if (fLogOutItem != NULL) fLogOutItem->SetEnabled(hasUser); if (fLogInItem != NULL) { if (hasUser) fLogInItem->SetLabel(B_TRANSLATE("Switch account" B_UTF8_ELLIPSIS)); else fLogInItem->SetLabel(B_TRANSLATE("Log in" B_UTF8_ELLIPSIS)); } if (fUserMenu != NULL) { BString label; if (username.Length() == 0) { label = B_TRANSLATE("Not logged in"); } else { label = B_TRANSLATE("Logged in as %User%"); label.ReplaceAll("%User%", username); } fUserMenu->Superitem()->SetLabel(label); } }
void MainWindow::_DisplayPartitionError(BString _message, const BPartition* partition, status_t error) const { char message[1024]; if (partition && _message.FindFirst("%s") >= 0) { BString name; name << "\"" << partition->ContentName() << "\""; snprintf(message, sizeof(message), _message.String(), name.String()); } else { _message.ReplaceAll("%s", ""); snprintf(message, sizeof(message), _message.String()); } if (error < B_OK) { BString helper = message; const char* errorString = B_TRANSLATE_COMMENT("Error: ", "in any error alert"); snprintf(message, sizeof(message), "%s\n\n%s%s", helper.String(), errorString, strerror(error)); } BAlert* alert = new BAlert("error", message, B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_FROM_WIDEST, error < B_OK ? B_STOP_ALERT : B_INFO_ALERT); alert->Go(NULL); }
status_t CDDBServer::_SendCommand(const BString& command, BString& output) { if (!fConnected) return B_ERROR; // Assemble full command string. BString fullCommand; fullCommand << command << "&hello=" << fLocalUserName << " " << fLocalHostName << " cddb_lookup 1.0&proto=6"; // Replace spaces by + signs. fullCommand.ReplaceAll(" ", "+"); // And now add command header and footer. fullCommand.Prepend("GET /~cddb/cddb.cgi?cmd="); fullCommand << " HTTP 1.0\n\n"; int32 result = fConnection.Send((void*)fullCommand.String(), fullCommand.Length()); if (result == fullCommand.Length()) { BNetBuffer netBuffer; while (fConnection.Receive(netBuffer, 1024) != 0) { // Do nothing. Data is automatically appended to the NetBuffer. } // AppendString automatically adds the terminating \0. netBuffer.AppendString(""); output.SetTo((char*)netBuffer.Data(), netBuffer.Size()); return B_OK; } return B_ERROR; }
status_t ExpanderThread::ThreadStartup() { status_t status = B_OK; entry_ref srcRef; entry_ref destRef; BString cmd; if ((status = GetDataStore()->FindRef("srcRef", &srcRef)) != B_OK) return status; if ((status = GetDataStore()->FindRef("destRef", &destRef)) == B_OK) { BPath path(&destRef); chdir(path.Path()); } if ((status = GetDataStore()->FindString("cmd", &cmd)) != B_OK) return status; BPath path(&srcRef); BString pathString(path.Path()); pathString.CharacterEscape("\\\"$`", '\\'); pathString.Prepend("\""); pathString.Append("\""); cmd.ReplaceAll("%s", pathString.String()); int32 argc = 3; const char** argv = new const char * [argc + 1]; argv[0] = strdup("/bin/sh"); argv[1] = strdup("-c"); argv[2] = strdup(cmd.String()); argv[argc] = NULL; fThreadId = PipeCommand(argc, argv, fStdIn, fStdOut, fStdErr); delete [] argv; if (fThreadId < 0) return fThreadId; // lower the command priority since it is a background task. set_thread_priority(fThreadId, B_LOW_PRIORITY); resume_thread(fThreadId); int flags = fcntl(fStdOut, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(fStdOut, F_SETFL, flags); flags = fcntl(fStdErr, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(fStdErr, F_SETFL, flags); fExpanderOutput = fdopen(fStdOut, "r"); fExpanderError = fdopen(fStdErr, "r"); return B_OK; }
void PackageManager::JobFailed(BJob* job) { BString error = job->ErrorString(); if (error.Length() > 0) { error.ReplaceAll("\n", "\n*** "); fprintf(stderr, "%s", error.String()); } }
bool UploadFromUser(LogWindow* logWindow, const char* filename, uint32 iFileLength) { uint32 iBytesReceived; BString fileString; BFile* bfMp3; DownloadWindow* myDownloadWindow; unsigned char* pBuffer; BString status; BString tmp; DownloadView* dlView; pBuffer = (unsigned char *) malloc(4096); fileString = filename; fileString.ReplaceAll("\\", "/"); tmp << logWindow->myPreferences->GetDownloadPath() << "/"; fileString.Prepend(tmp); bfMp3 = new BFile(fileString.String(), B_WRITE_ONLY|B_CREATE_FILE|B_OPEN_AT_END); if (bfMp3->InitCheck() == B_OK) { logWindow->netEndpoint->Send("0",1); // I think this is the start position, other values may be resumes myDownloadWindow = new DownloadWindow(BRect(100,100, 400, 200), "Upload From User", B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_NOT_RESIZABLE, B_CURRENT_WORKSPACE); myDownloadWindow->Show(); dlView = myDownloadWindow->AddTransfer(filename, (float)iFileLength); uint32 iDataLength = 0; while(iDataLength < iFileLength) { iBytesReceived = logWindow->netEndpoint->Receive((unsigned char*)pBuffer, 4096); if (iBytesReceived < 0) { break; } bfMp3->Write(pBuffer, iBytesReceived); iDataLength += iBytesReceived; myDownloadWindow->Lock(); dlView->AddBytesReceived(iBytesReceived); myDownloadWindow->Unlock(); } dlView->SetFinished(true); bfMp3->Unset(); myDownloadWindow->Refresh(); } else { //logWindow->LogMessage("Could Not Open The File", BN_ERROR); } return true; }
status_t SVNSourceControl::GetCheckinHeader(BString &out) { GetChangeStatus(out); out.Prepend("SVN: \nAll lines starting with 'SVN:' will be ignored.\n" "----------------------------------------------------\n"); out.ReplaceAll("\n", "\nSVN: "); return B_OK; }
// Format the message into HTML, and return it char* HTMLView::GetFormattedMessage() { BString theText = Text(); // replace all linebreaks with <br>'s theText.ReplaceAll( "\n", "<br>" ); message = (char*)malloc( theText.Length() + 1 ); theText.CopyInto( message, 0, theText.Length() ); message[theText.Length()] = '\0'; return message; }
void VisionApp::VisionVersion(int typebit, BString& result) { switch (typebit) { case VERSION_VERSION: result = VERSION_STRING; break; case VERSION_DATE: result = __DATE__ " " __TIME__; result.ReplaceAll("_", " "); break; } }
void MediaConverterApp::RefsReceived(BMessage* msg) { entry_ref ref; int32 i = 0; BString errorFiles; int32 errors = 0; // from Open dialog or drag & drop while (msg->FindRef("refs", i++, &ref) == B_OK) { uint32 flags = 0; // B_MEDIA_FILE_NO_READ_AHEAD BMediaFile* file = new(std::nothrow) BMediaFile(&ref, flags); if (file == NULL || file->InitCheck() != B_OK) { errorFiles << ref.name << "\n"; errors++; delete file; continue; } if (fWin->Lock()) { if (!fWin->AddSourceFile(file, ref)) delete file; fWin->Unlock(); } } if (errors) { BString alertText; if (errors > 1) { alertText = B_TRANSLATE( "%amountOfFiles files were not recognized" " as supported media files:"); BString amount; amount << errors; alertText.ReplaceAll("%amountOfFiles", amount); } else { alertText = B_TRANSLATE( "The file was not recognized as a supported media file:"); } alertText << "\n" << errorFiles; BAlert* alert = new BAlert((errors > 1) ? B_TRANSLATE("Error loading files") : B_TRANSLATE("Error loading a file"), alertText.String(), B_TRANSLATE("Continue"), NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); alert->Go(); } }
void GrepWindow::_SetWindowTitle() { BEntry entry(&fModel->fDirectory, true); BString title; if (entry.InitCheck() == B_OK) { BPath path; if (entry.GetPath(&path) == B_OK) { if (fOldPattern.Length()) { title = B_TRANSLATE("%appname% : %path% : %searchtext%"); title.ReplaceAll("%searchtext%", fOldPattern.String()); } else title = B_TRANSLATE("%appname% : %path%"); title.ReplaceAll("%appname%", B_TRANSLATE(APP_NAME)); title.ReplaceAll("%path%", path.Path()); } } if (!title.Length()) title = B_TRANSLATE(APP_NAME); SetTitle(title.String()); }
void encode_html( BString &msg ) { // BStrings are slow and sucky, but this is real easy msg.ReplaceAll("&","&"); msg.ReplaceAll("\"","""); msg.ReplaceAll("<","<"); msg.ReplaceAll(">",">"); msg.ReplaceAll("[b]","<b>"); msg.ReplaceAll("[/b]","</b>"); msg.ReplaceAll("[i]","<i>"); msg.ReplaceAll("[/i]","</i>"); msg.Prepend("<html>"); msg.Append("</html>"); }
void AwayEditorWindow::LoadMessage( BString name ) { BString message; if( !(prefs->GetAwayMessage(name, message)) ) return; // correct the line breaks and stuff message.ReplaceAll( "<br>", "\n" ); // set the textviews and stuff genView->messageName->SetModificationMessage( NULL ); genView->messageName->SetText( name.String() ); genView->messageName->SetModificationMessage( new BMessage(AWAY_CHANGED) ); genView->textview->SetText( message.String() ); EnableMessageStuff( true ); hasSelection = true; currentMsg = name; }
BString AIMProtocol::NormalizeNick(const char *nick) { BString normal = nick; normal.ReplaceAll(" ", ""); normal.ToLower(); map<string,BString>::iterator i = fNickMap.find(normal.String()); if ( i == fNickMap.end() ) { // add 'real' nick if it's not already there LOG(fManager->Protocol(), liDebug, "Adding normal (%s) vs screen (%s)", normal.String(), nick ); fNickMap[string(normal.String())] = BString(nick); } LOG(fManager->Protocol(), liDebug, "Screen (%s) to normal (%s)", nick, normal.String() ); return normal; };
void AIMNetManager::FailedMessage( SNAC_Object& snac ) { BString errorMessage; unsigned short targetReqID; bool found = false, kg; userRequestID rid; targetReqID = snac.GetRequestID(); kg = pendingNRRequests.First(rid); while( kg ) { if( targetReqID == rid.reqID ) { found = true; break; } kg = pendingNRRequests.Next(rid); } // if we didn't find it, stay quiet for now if( !found ) return; // aha! Found it! Send an error message printf( ">>> Failed Message: %s\n", rid.userid.UserString() ); // failure to send a message if( rid.type == RID_SEND_MESSAGE ) { if( users->IsUserBlocked(rid.userid) ) errorMessage = BString( Language.get("ERR_NO_SEND_BLOCKED") ); else errorMessage = BString( Language.get("ERR_NO_SEND_OFFLINE") ); } // failure to send a warning else if( rid.type == RID_WARN_EM ) errorMessage = BString( Language.get("ERR_BAD_WARN_ATTEMPT") ); // none of the above else return; // replace %USER with the username and show the warning errorMessage.ReplaceAll( "%USER", rid.userid.UserString() ); windows->ShowMessage( errorMessage, B_STOP_ALERT ); }
void Paragraph::PrintToStream() const { int32 spanCount = fTextSpans.CountItems(); if (spanCount == 0) { printf(" <p/>\n"); return; } printf(" <p>\n"); for (int32 i = 0; i < spanCount; i++) { const TextSpan& span = fTextSpans.ItemAtFast(i); if (span.CountChars() == 0) printf(" <span/>\n"); else { BString text = span.Text(); text.ReplaceAll("\n", "\\n"); printf(" <span>%s<span/>\n", text.String()); } } printf(" </p>\n"); }
status_t BEntry::SetTo(const char *dir, const char *leaf, bool traverse) { if (dir == NULL) return B_BAD_VALUE; BString str; if (path_expound(str, dir, leaf, NULL) != B_OK) return B_BAD_VALUE; BString parent; status_t status = path_get_parent(parent, str.String()); if (status == B_ENTRY_NOT_FOUND) parent = str; else if (status != B_OK) return B_BAD_VALUE; #ifdef _WIN32 parent.ReplaceAll("/", "\\"); #endif bool parentExists; #ifndef _WIN32 struct stat st; parentExists = (stat(parent.String(), &st) == 0); #else struct _stat st; parentExists = (_stat(parent.String(), &st) == 0); #endif if (!parentExists) return B_ENTRY_NOT_FOUND; // TODO: traverse char *name = EStrdup(str.String()); if (name == NULL) return B_NO_MEMORY; if (fName != NULL) delete[] fName; fName = name; return B_OK; }
bool AwayEditorWindow::SaveMessage() { if( client->AwayMode() == AM_STANDARD_MESSAGE ) { if( client->CurrentAwayMessageName() == currentMsg ) { windows->ShowMessage( Language.get("AME_ERR1"), B_INFO_ALERT ); return false; } } BString text = genView->messageName->Text(); if( text == BString(Language.get("AME_NEW_MESSAGE")) || text == BString("") ) { windows->ShowMessage( Language.get("AME_ERR2"), B_WARNING_ALERT ); Revert(); genView->messageName->MakeFocus(true); return false; } if( (text != currentMsg) && (prefs->FindAwayMessage(text) != -1) ) { windows->ShowMessage( Language.get("AME_ERR3"), B_WARNING_ALERT ); Revert(); genView->messageName->MakeFocus(true); return false; } int32 selected = genView->listview->CurrentSelection(); BString message = genView->textview->Text(); message.ReplaceAll( "\n", "<br>" ); prefs->SetAwayMessage( genView->messageName->Text(), currentMsg, message ); BuildList(); isDirty = false; genView->textview->MakeDirty(false); genView->listview->Select( selected ); PostAppMessage( new BMessage(BEAIM_LOAD_AWAY_MENU) ); return true; }
bool App::_LaunchPackageDaemon() { status_t ret = be_roster->Launch(kPackageDaemonSignature); if (ret != B_OK) { BString errorMessage = B_TRANSLATE("Starting the package daemon failed:\n\n%Error%"); errorMessage.ReplaceAll("%Error%", strerror(ret)); BAlert* alert = new BAlert("package_daemon_problem", errorMessage, B_TRANSLATE("Quit HaikuDepot"), B_TRANSLATE("Try again"), NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT); alert->SetShortcut(0, B_ESCAPE); if (alert->Go() == 0) return false; } // TODO: Would be nice to send a message to the package daemon instead // and get a reply once it is ready. snooze(2000000); return true; }
void PackageView::AttachedToWindow() { status_t ret = fInfo.InitCheck(); if (ret != B_OK && ret != B_NO_INIT) { BAlert* warning = new BAlert("parsing_failed", B_TRANSLATE("The package file is not readable.\nOne of the " "possible reasons for this might be that the requested file " "is not a valid BeOS .pkg package."), B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT); warning->SetFlags(warning->Flags() | B_CLOSE_ON_ESCAPE); warning->Go(); Window()->PostMessage(B_QUIT_REQUESTED); return; } // Set the window title BWindow* parent = Window(); BString title; BString name = fInfo.GetName(); if (name.CountChars() == 0) { title = B_TRANSLATE("Package installer"); } else { title = B_TRANSLATE("Install %name%"); title.ReplaceAll("%name%", name); } parent->SetTitle(title.String()); fBeginButton->SetTarget(this); fOpenPanel->SetTarget(BMessenger(this)); fInstallTypes->SetTargetForItems(this); if (ret != B_OK) return; // If the package is valid, we can set up the default group and all // other things. If not, then the application will close just after // attaching the view to the window _InstallTypeChanged(0); fStatusWindow = new PackageStatus(B_TRANSLATE("Installation progress"), NULL, NULL, this); // Show the splash screen, if present BMallocIO* image = fInfo.GetSplashScreen(); if (image != NULL) { PackageImageViewer* imageViewer = new PackageImageViewer(image); imageViewer->Go(); } // Show the disclaimer/info text popup, if present BString disclaimer = fInfo.GetDisclaimer(); if (disclaimer.Length() != 0) { PackageTextViewer* text = new PackageTextViewer( disclaimer.String()); int32 selection = text->Go(); // The user didn't accept our disclaimer, this means we cannot // continue. if (selection == 0) parent->Quit(); } }
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; }
void THeaderView::InitGroupCompletion() { // get boot volume BVolume volume; BVolumeRoster().GetBootVolume(&volume); // Build a list of all unique groups and the addresses they expand to. BQuery query; query.SetVolume(&volume); query.SetPredicate("META:group=**"); query.Fetch(); map<BString *, BString *, CompareBStrings> groupMap; entry_ref ref; BNode file; while (query.GetNextRef(&ref) == B_OK) { if (file.SetTo(&ref) != B_OK) continue; BString groups; if (file.ReadAttrString("META:group", &groups) < B_OK || groups.Length() == 0) continue; BString address; file.ReadAttrString("META:email", &address); // avoid adding an empty address if (address.Length() == 0) continue; char *group = groups.LockBuffer(groups.Length()); char *next = strchr(group, ','); for (;;) { if (next) *next = 0; while (*group && *group == ' ') group++; BString *groupString = new BString(group); BString *addressListString = NULL; // nobody is in this group yet, start it off if (groupMap[groupString] == NULL) { addressListString = new BString(*groupString); addressListString->Append(" "); groupMap[groupString] = addressListString; } else { addressListString = groupMap[groupString]; addressListString->Append(", "); delete groupString; } // Append the user's address to the end of the string with the // comma separated list of addresses. If not present, add the // < and > brackets around the address. if (address.FindFirst ('<') < 0) { address.ReplaceAll ('>', '_'); address.Prepend ("<"); address.Append(">"); } addressListString->Append(address); if (!next) break; group = next + 1; next = strchr(group, ','); } } map<BString *, BString *, CompareBStrings>::iterator iter; for (iter = groupMap.begin(); iter != groupMap.end();) { BString *group = iter->first; BString *addr = iter->second; fEmailList.AddChoice(addr->String()); ++iter; groupMap.erase(group); delete group; delete addr; } }
PanelView::PanelView(BRect rect, char *name) : BView( rect, name , 0, B_WILL_DRAW ) //////////////////////////////////////////////////////////////////////// { BPath dirPath; // To query some paths... BString tempstring; // Ebben lehet kotoraszni a replace-eleshez // Default view color... SetViewColor(216, 216, 216, 0); // Default settings... m_Setting_ShowIcons = true; m_Setting_ShowFileSize = true; m_Setting_ShowFileDate = false; m_MonitoringPath.SetTo(""); // Empty string... // Resources LoadResources(); // Main Box m_Box = new BBox(Bounds(),"box",B_FOLLOW_ALL,B_WILL_DRAW,B_FANCY_BORDER); AddChild(m_Box); // Path m_PathMenu = new BMenu("cd",B_ITEMS_IN_COLUMN); m_CD_Parent = new BMenuItem(LANGS("CD_PARENT"),new BMessage(PATH_MSG_CD_PARENT),0,0); m_PathMenu->AddItem(m_CD_Parent); m_PathMenu->AddSeparatorItem(); m_CD_Root = new BMenuItem(LANGS("CD_ROOT"),new BMessage(PATH_MSG_CD_ROOT),0,0); m_PathMenu->AddItem(m_CD_Root); find_directory(B_USER_DIRECTORY, &dirPath, true); tempstring = LANG("CD_HOME"); tempstring.ReplaceAll("<DIR>", dirPath.Path()); m_CD_Home = new BMenuItem(tempstring.String(),new BMessage(PATH_MSG_CD_HOME),0,0); m_PathMenu->AddItem(m_CD_Home); find_directory(B_DESKTOP_DIRECTORY, &dirPath, true); tempstring = LANG("CD_DESKTOP"); tempstring.ReplaceAll("<DIR>", dirPath.Path()); m_CD_Desktop = new BMenuItem(tempstring.String(),new BMessage(PATH_MSG_CD_DESKTOP),0,0); m_PathMenu->AddItem(m_CD_Desktop); m_PathMenu->AddSeparatorItem(); m_CD_Disks = new BMenuItem(LANGS("CD_DISKS"),new BMessage(PATH_MSG_CD_DISKS),0,0); m_PathMenu->AddItem(m_CD_Disks); // CD BMenuField in the upper left area... m_PathField = new BMenuField(BRect(3,2,20,8*3),"cd","",m_PathMenu, false, 0, B_WILL_DRAW); m_PathField->ResizeToPreferred(); m_PathField->SetDivider(0); m_Box->AddChild(m_PathField); // Menu in the top right corner... m_PanelMenu = new BMenu("",B_ITEMS_IN_COLUMN); m_PanelMenu_Find = new BMenuItem(LANGS("PANELMENU_FIND"),new BMessage(PANELMENU_MSG_FIND),0,0); m_PanelMenu_Find->SetEnabled(false); m_PanelMenu->AddItem(m_PanelMenu_Find); m_PanelMenu->AddSeparatorItem(); m_PanelMenu_ShowIcons = new BMenuItem(LANGS("PANELMENU_SHOWICONS"),new BMessage(PANELMENU_MSG_SHOWICONS),0,0); if (m_Setting_ShowIcons) m_PanelMenu_ShowIcons->SetMarked(true); else m_PanelMenu_ShowIcons->SetMarked(false); m_PanelMenu->AddItem(m_PanelMenu_ShowIcons); // Panel menu BMenuField in the upper right area... m_PanelMenuField = new BMenuField(BRect(Bounds().right-24,2,Bounds().right-4,8*3),"Menu","",m_PanelMenu, false, B_FOLLOW_TOP | B_FOLLOW_RIGHT, B_WILL_DRAW); m_PanelMenuField->ResizeToPreferred(); m_PanelMenuField->SetDivider(0); m_Box->AddChild(m_PanelMenuField); // Path text in the upper area... m_PathStringView = new BStringView(BRect(38,2,280,20),"path",""); m_PathStringView->SetAlignment(B_ALIGN_CENTER); m_Box->AddChild(m_PathStringView); m_Bevel_1 = new BBox(BRect(2,26,180,27), "bevel1"); m_Box->AddChild(m_Bevel_1); m_Bevel_2 = new BBox(BRect(2,26,180,27), "bevel2", B_FOLLOW_BOTTOM); m_Bevel_2->MoveTo(2,Bounds().bottom-27); m_Box->AddChild(m_Bevel_2); // Status bar in the bottom area... m_StatusStringView = new BStringView(BRect(2,2,180,20),"status","No file(s) selected.", B_FOLLOW_LEFT | B_FOLLOW_BOTTOM); m_StatusStringView->MoveTo(4,Bounds().bottom-25); m_StatusStringView->SetAlignment(B_ALIGN_LEFT); m_Box->AddChild(m_StatusStringView); // Seek TextControl m_SeekTextControl = NULL; m_SeekMode = false; BRect r = Bounds(); r.right-=20; r.left+=6; r.top+=32; r.bottom-=32; m_CustomListView = new CustomListView(r, "file_list", this); m_pScrollView = new BScrollView("rep_scroll_view", m_CustomListView, B_FOLLOW_ALL, B_WILL_DRAW, false, true); m_Box->AddChild(m_pScrollView); m_CustomListView->SetSelectionMessage(new BMessage(MSG_FILELISTVIEW_SELECTION)); m_PanelMode = -1; SetPanelMode(PM_NORMAL); }
BMailFilterAction HaikuMailFormatFilter::HeaderFetched(entry_ref& ref, BFile& file, BMessage& attributes) { file.Seek(0, SEEK_SET); // TODO: attributes.AddInt32(B_MAIL_ATTR_CONTENT, length); attributes.AddInt32(B_MAIL_ATTR_ACCOUNT_ID, fAccountID); attributes.AddString(B_MAIL_ATTR_ACCOUNT, fAccountName); BString header; off_t size; if (file.GetSize(&size) == B_OK) { char* buffer = header.LockBuffer(size); if (buffer == NULL) return B_NO_MEMORY; ssize_t bytesRead = file.Read(buffer, size); if (bytesRead < 0) return bytesRead; if (bytesRead != size) return B_IO_ERROR; header.UnlockBuffer(size); } for (int i = 0; gDefaultFields[i].rfc_name; ++i) { BString target; status_t status = extract_from_header(header, gDefaultFields[i].rfc_name, target); if (status != B_OK) continue; switch (gDefaultFields[i].attr_type){ case B_STRING_TYPE: sanitize_white_space(target); attributes.AddString(gDefaultFields[i].attr_name, target); break; case B_TIME_TYPE: { time_t when; when = ParseDateWithTimeZone(target); if (when == -1) when = time(NULL); // Use current time if it's undecodable. attributes.AddData(B_MAIL_ATTR_WHEN, B_TIME_TYPE, &when, sizeof(when)); break; } } } BString senderName = _ExtractName(attributes.FindString(B_MAIL_ATTR_FROM)); attributes.AddString(B_MAIL_ATTR_NAME, senderName); // Generate a file name for the incoming message. See also // Message::RenderTo which does a similar thing for outgoing messages. BString name = attributes.FindString(B_MAIL_ATTR_SUBJECT); SubjectToThread(name); // Extract the core subject words. if (name.Length() <= 0) name = "No Subject"; attributes.AddString(B_MAIL_ATTR_THREAD, name); // Convert the date into a year-month-day fixed digit width format, so that // sorting by file name will give all the messages with the same subject in // order of date. time_t dateAsTime = 0; const time_t* datePntr; ssize_t dateSize; char numericDateString[40]; struct tm timeFields; if (attributes.FindData(B_MAIL_ATTR_WHEN, B_TIME_TYPE, (const void**)&datePntr, &dateSize) == B_OK) dateAsTime = *datePntr; localtime_r(&dateAsTime, &timeFields); snprintf(numericDateString, sizeof(numericDateString), "%04d%02d%02d%02d%02d%02d", timeFields.tm_year + 1900, timeFields.tm_mon + 1, timeFields.tm_mday, timeFields.tm_hour, timeFields.tm_min, timeFields.tm_sec); name << " " << numericDateString; BString workerName = attributes.FindString(B_MAIL_ATTR_FROM); extract_address_name(workerName); name << " " << workerName; name.Truncate(222); // reserve space for the unique number // Get rid of annoying characters which are hard to use in the shell. name.ReplaceAll('/', '_'); name.ReplaceAll('\'', '_'); name.ReplaceAll('"', '_'); name.ReplaceAll('!', '_'); name.ReplaceAll('<', '_'); name.ReplaceAll('>', '_'); _RemoveExtraWhitespace(name); _RemoveLeadingDots(name); // Avoid files starting with a dot. if (!attributes.HasString(B_MAIL_ATTR_STATUS)) attributes.AddString(B_MAIL_ATTR_STATUS, "New"); _SetType(attributes, B_PARTIAL_MAIL_TYPE); ref.set_name(name.String()); return B_MOVE_MAIL_ACTION; }