本文整理汇总了C++中BString::Append方法的典型用法代码示例。如果您正苦于以下问题:C++ BString::Append方法的具体用法?C++ BString::Append怎么用?C++ BString::Append使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BString
的用法示例。
在下文中一共展示了BString::Append方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: Run
void MatrixControl::Run(alNormalWindow *win)
{
//Optimizer Section
int i ,k, x;
int counted_zeros[matrix_dimension];
int bestline,val;
float value;
for (i=0; i < matrix_dimension; ++i)
{
counted_zeros[i] = 0;
for (x=0; x < matrix_dimension; ++x)
{
value = float_matrix[i*matrix_dimension +x];
if (value == 0.0) ++counted_zeros[i];
}
}
for (i=0; i < matrix_dimension; ++i)
{
bestline = -1;
val = 0;
for (k = i; k < matrix_dimension; ++k)
{
if (counted_zeros[k] > val)
{
val = counted_zeros[k];
bestline = k;
}
}
if (bestline > i)
SwitchRows(bestline, i);
}
//Optimizer End
oneisrunning = true;
MasterMatrix = this;
loaded_threads = 0;
answers = 0;
MatrixResult = 0.0;
BString nam ("Progress ");
nam += extra::StringOutOf(matrix_dimension);
nam.Append("x");
nam += extra::StringOutOf(matrix_dimension);
alLooper *master_matrix_calculator = new alLooper(&MasterMatrixReceiver,"Master Matrix Calculator",B_LOW_PRIORITY);
theone = new ShowProgressWin(400,100,nam.String(),100);
theone->stat_bar->SetMaxValue( (float) matrix_dimension );
theone->tonotify = win;
theone->toshutLooper = master_matrix_calculator;
theone->Show();
master_matrix_calculator->Parent = (char *) this;
master_matrix_calculator->Run();
master_matrix_calculator->PostMessage(1);
}
示例2: MainLoop
//---------------------------------------------------------------
void ExportWindow::MainLoop()
{
BString fFilePath;
BString fFolderPath;
BString fFileName;
BPath Path;
BEntry Entry("/boot/home");
MSave Load("Load");
find_directory(B_COMMON_SETTINGS_DIRECTORY, &Path);
fFolderPath.SetTo(Path.Path());
fFolderPath.Append(SAVE_NOTE_PATH);
for (int a = 1; a <= 31; a++)
{
fFileName.SetTo("");
fFileName << a << "-" << fMonth << fYear << "-";
for (int b = 1; b <= INT_MAXFILES; b++)
{
fFileName << b;
fFilePath.SetTo(fFolderPath);
fFilePath << fFileName.String();
Entry.SetTo(fFilePath.String());
if (Entry.Exists())
{
Load.FindString(fFilePath.String(), SAVE_FILE_TYPE, &fType, "M_ERROR");
if (!strcmp(fType.String(), "Note") || !strcmp(fType.String(), "Apointment"))
{
//Add the date if it is the first note/apointment of this day
if (fFirstNoteOfTheDay)
{
fContent << "<table width=450 color=\"#FFFFFF\">\n";
fContent << "<h2>" << a << "." << fMonth << "-" << fYear << "</h2>\n";
fFirstNoteOfTheDay = false;
}
//Change the color
if (!strcmp(TableColor.String(), TableBGColor1.String()))
{
TableColor.SetTo(TableBGColor2);
}
else
{
TableColor.SetTo(TableBGColor1);
}
}
//Its a note
if (!strcmp(fType.String(), "Note") && _ExportView->mNoteCheckBox->Value())
{
Load.FindString(fFilePath.String(), SAVE_FILE_NOTE, &fNote, "M_ERROR");
Load.FindString(fFilePath.String(), SAVE_FILE_TITLE, &fTitle, "M_ERROR");
fContent << "<tr><td bgcolor=\"" << TableColor.String() << "\" width=430>\n";
fContent << "<h4>"<< fTitle.String() << "</h4>";
fNote.ReplaceAll("\n", "<br>");
fContent << fNote.String() << "\n";
fContent << "</tr></td>\n";
}
//Its an apointment
if (!strcmp(fType.String(), "Apointment") && _ExportView->mApointmentCheckBox->Value())
{
Load.FindString(fFilePath.String(), SAVE_FILE_NOTE, &fNote, "M_ERROR");
Load.FindString(fFilePath.String(), SAVE_FILE_TITLE, &fTitle, "M_ERROR");
Load.FindString(fFilePath.String(), SAVE_FILE_TIME, &fTime, "M_ERROR");
fContent << "<tr><td bgcolor=\"" << TableColor.String() << "\" width=430>\n";
fContent << "<h4>"<< fTitle.String() << "";
tmpString.SetTo(fTime);
tmpString.Remove(0, tmpString.FindFirst(":") + 1);
if (tmpString.CountChars() == 1)
{
fTime.RemoveLast(tmpString.String());
fTime.Append("0");
fTime.Append(tmpString.String());
}
fContent << " "<< fTime.String() << "</h4>\n";
fNote.ReplaceAll("\n", "<br>");
fContent << fNote.String() << "\n";
fContent << "</tr></td>\n";
}
}
tmpString.SetTo("");
tmpString << b;
fFileName.RemoveLast(tmpString.String());
}
if (!fFirstNoteOfTheDay)
{
fContent << "</table>\n";
fContent << "<br>";
}
fFirstNoteOfTheDay = true;
}
}
示例3: LoadStatusses
status_t LoadStatusses(BPath statFilePath)
{
status_t error = B_OK;
//open file
BFile statFile(statFilePath.Path(), B_READ_ONLY);
error = statFile.InitCheck();
if (error != B_ERROR)
{
StringList *tokenList = new StringList();
//read line
off_t fileSize;
if (statFile.GetSize(&fileSize) == B_OK)
{
ssize_t bytesRead = 0;
BString* token = new BString("");
bool newToken = false;
do
{
char c[2];
bytesRead += statFile.Read(c,1);
c[1] = '\0';
if (c[0] == '\t' || c[0] == '\n')
{
//clear token
if (!newToken)
{
//add token to list
tokenList->AddItem(token);
token = new BString("");
newToken = true;
}
}
else
{
token->Append(c);
newToken = false;
}
}
while (bytesRead < fileSize);
}
int32 startIndex = -1;
int32 endIndex = -1;
for (int32 i = 0; i < tokenList->CountItems(); i++)
{
if ((*tokenList)[i].ICompare("<status>") == 0)
startIndex = i;
else if ((*tokenList)[i].ICompare("</status>") == 0)
{
endIndex = i;
break;
}
}
if (startIndex != -1 && endIndex != -1)
{
//start past the <status> tag
startIndex++;
for (int32 i = startIndex; i < endIndex; i++)
{
int32 lastLineIndex = i + 4;
if (lastLineIndex < endIndex)
{
//parse lines
BString bitmapString = (*tokenList)[i];
BString statusName = (*tokenList)[i+1];
BString abbreviation = (*tokenList)[i+2];
bool userChoice = atoi((*tokenList)[i+3].String());
BString colourString = (*tokenList)[i+4];
i += 4;
//construct bitmap path
BPath bitmapPath;
statFilePath.GetParent(&bitmapPath);
bitmapPath.Append(bitmapString.String());
BBitmap *icon = BTranslationUtils::GetBitmap(bitmapPath.Path());
//construct status object
Status *status = FindStatus(abbreviation);
if (status != NULL)
{
status->AddIcon(icon);
}
else
{
//remove brackets from colourString
colourString.RemoveAll("{");
colourString.RemoveAll("}");
int32 colours[4];
int32 startIndex = 0;
for (int i = 0; i < 4; i++)
{
int32 commaIndex = colourString.FindFirst(",",startIndex);
if (commaIndex != B_ERROR)
{
BString colourValue;
colourString.CopyInto(colourValue,startIndex, commaIndex-startIndex);
colours[i] = atoi(colourValue.String());
startIndex = commaIndex + 1;
//.........这里部分代码省略.........
示例4: if
void
TMailApp::RefsReceived(BMessage *msg)
{
bool have_names = false;
BString names;
char type[B_FILE_NAME_LENGTH];
int32 item = 0;
BFile file;
TMailWindow *window;
entry_ref ref;
//
// If a tracker window opened me, get a messenger from it.
//
BMessenger messenger;
if (msg->HasMessenger("TrackerViewToken"))
msg->FindMessenger("TrackerViewToken", &messenger);
while (msg->HasRef("refs", item)) {
msg->FindRef("refs", item++, &ref);
if ((window = FindWindow(ref)) != NULL)
window->Activate(true);
else {
file.SetTo(&ref, O_RDONLY);
if (file.InitCheck() == B_NO_ERROR) {
BNodeInfo node(&file);
node.GetType(type);
if (strcmp(type, B_MAIL_TYPE) == 0
|| strcmp(type, B_PARTIAL_MAIL_TYPE) == 0) {
window = NewWindow(&ref, NULL, false, &messenger);
window->Show();
} else if(strcmp(type, "application/x-person") == 0) {
/* Got a People contact info file, see if it has an Email address. */
BString name;
BString email;
attr_info info;
char *attrib;
if (file.GetAttrInfo("META:email", &info) == B_NO_ERROR) {
attrib = (char *) malloc(info.size + 1);
file.ReadAttr("META:email", B_STRING_TYPE, 0, attrib, info.size);
attrib[info.size] = 0; // Just in case it wasn't NUL terminated.
email << attrib;
free(attrib);
/* we got something... */
if (email.Length() > 0) {
/* see if we can get a username as well */
if(file.GetAttrInfo("META:name", &info) == B_NO_ERROR) {
attrib = (char *) malloc(info.size + 1);
file.ReadAttr("META:name", B_STRING_TYPE, 0, attrib, info.size);
attrib[info.size] = 0; // Just in case it wasn't NUL terminated.
name << "\"" << attrib << "\" ";
email.Prepend("<");
email.Append(">");
free(attrib);
}
if (names.Length() == 0) {
names << name << email;
} else {
names << ", " << name << email;
}
have_names = true;
email.SetTo("");
name.SetTo("");
}
}
}
else if (strcmp(type, kDraftType) == 0) {
window = NewWindow();
// If it's a draft message, open it
window->OpenMessage(&ref);
window->Show();
}
} /* end of else(file.InitCheck() == B_NO_ERROR */
}
}
if (have_names) {
window = NewWindow(NULL, names.String());
window->Show();
}
}
示例5: rawCnonce
status_t
SMTPProtocol::Login(const char *_login, const char *password)
{
if (fAuthType == 0)
return B_OK;
const char *login = _login;
char hex_digest[33];
BString out;
int32 loginlen = ::strlen(login);
int32 passlen = ::strlen(password);
if (fAuthType & DIGEST_MD5) {
//******* DIGEST-MD5 Authentication ( tested. works fine [with Cyrus SASL] )
// this implements only the subpart of DIGEST-MD5 which is
// required for authentication to SMTP-servers. Integrity-
// and confidentiality-protection are not implemented, as
// they are provided by the use of OpenSSL.
SendCommand("AUTH DIGEST-MD5"CRLF);
const char *res = fLog.String();
if (strncmp(res, "334", 3) != 0)
return B_ERROR;
int32 baselen = ::strlen(&res[4]);
char *base = new char[baselen+1];
baselen = ::decode_base64(base, &res[4], baselen);
base[baselen] = '\0';
D(bug("base: %s\n", base));
map<BString,BString> challengeMap;
SplitChallengeIntoMap(base, challengeMap);
delete[] base;
BString rawResponse = BString("username=") << '"' << login << '"';
rawResponse << ",realm=" << '"' << challengeMap["realm"] << '"';
rawResponse << ",nonce=" << '"' << challengeMap["nonce"] << '"';
rawResponse << ",nc=00000001";
char temp[33];
for( int i=0; i<32; ++i)
temp[i] = 1+(rand()%254);
temp[32] = '\0';
BString rawCnonce(temp);
BString cnonce;
char* cnoncePtr = cnonce.LockBuffer(rawCnonce.Length()*2);
baselen = ::encode_base64(cnoncePtr, rawCnonce.String(), rawCnonce.Length(), true /* headerMode */);
cnoncePtr[baselen] = '\0';
cnonce.UnlockBuffer(baselen);
rawResponse << ",cnonce=" << '"' << cnonce << '"';
rawResponse << ",qop=auth";
BString digestUriValue = BString("smtp/") << fServerName;
rawResponse << ",digest-uri=" << '"' << digestUriValue << '"';
char sum[17], hex_digest2[33];
BString a1,a2,kd;
BString t1 = BString(login) << ":"
<< challengeMap["realm"] << ":"
<< password;
MD5Sum(sum, (unsigned char*)t1.String(), t1.Length());
a1 << sum << ":" << challengeMap["nonce"] << ":" << cnonce;
MD5Digest(hex_digest, (unsigned char*)a1.String(), a1.Length());
a2 << "AUTHENTICATE:" << digestUriValue;
MD5Digest(hex_digest2, (unsigned char*)a2.String(), a2.Length());
kd << hex_digest << ':' << challengeMap["nonce"]
<< ":" << "00000001" << ':' << cnonce << ':' << "auth"
<< ':' << hex_digest2;
MD5Digest(hex_digest, (unsigned char*)kd.String(), kd.Length());
rawResponse << ",response=" << hex_digest;
BString postResponse;
char *resp = postResponse.LockBuffer(rawResponse.Length() * 2 + 10);
baselen = ::encode_base64(resp, rawResponse.String(), rawResponse.Length(), true /* headerMode */);
resp[baselen] = 0;
postResponse.UnlockBuffer();
postResponse.Append(CRLF);
SendCommand(postResponse.String());
res = fLog.String();
if (atol(res) >= 500)
return B_ERROR;
// actually, we are supposed to check the rspauth sent back
// by the SMTP-server, but that isn't strictly required,
// so we skip that for now.
SendCommand(CRLF); // finish off authentication
res = fLog.String();
if (atol(res) < 500)
return B_OK;
}
if (fAuthType & CRAM_MD5) {
//******* CRAM-MD5 Authentication ( tested. works fine [with Cyrus SASL] )
SendCommand("AUTH CRAM-MD5"CRLF);
const char *res = fLog.String();
if (strncmp(res, "334", 3) != 0)
return B_ERROR;
int32 baselen = ::strlen(&res[4]);
char *base = new char[baselen+1];
baselen = ::decode_base64(base, &res[4], baselen);
//.........这里部分代码省略.........
示例6: expression
void
CalcView::Paste(BMessage* message)
{
// handle files first
int32 count;
if (message->GetInfo("refs", NULL, &count) == B_OK) {
entry_ref ref;
ssize_t read;
BFile file;
char buffer[256];
memset(buffer, 0, sizeof(buffer));
for (int32 i = 0; i < count; i++) {
if (message->FindRef("refs", i, &ref) == B_OK) {
if (file.SetTo(&ref, B_READ_ONLY) == B_OK) {
read = file.Read(buffer, sizeof(buffer) - 1);
if (read <= 0)
continue;
BString expression(buffer);
int32 j = expression.Length();
while (j > 0 && expression[j - 1] == '\n')
j--;
expression.Truncate(j);
if (expression.Length() > 0)
fExpressionTextView->Insert(expression.String());
}
}
}
return;
}
// handle color drops
// read incoming color
const rgb_color* dropColor = NULL;
ssize_t dataSize;
if (message->FindData("RGBColor", B_RGB_COLOR_TYPE,
(const void**)&dropColor, &dataSize) == B_OK
&& dataSize == sizeof(rgb_color)) {
// calculate view relative drop point
BPoint dropPoint = ConvertFromScreen(message->DropPoint());
// calculate current keypad area
float sizeDisp = fHeight * kDisplayScaleY;
BRect keypadRect(0.0, sizeDisp, fWidth, fHeight);
// check location of color drop
if (keypadRect.Contains(dropPoint) && dropColor != NULL) {
fBaseColor = *dropColor;
fHasCustomBaseColor =
fBaseColor != ui_color(B_PANEL_BACKGROUND_COLOR);
_Colorize();
// redraw
Invalidate();
}
} else {
// look for text/plain MIME data
const char* text;
ssize_t numBytes;
if (message->FindData("text/plain", B_MIME_TYPE,
(const void**)&text, &numBytes) == B_OK) {
BString temp;
temp.Append(text, numBytes);
fExpressionTextView->Insert(temp.String());
}
}
}
示例7: enclosure
void
TMailApp::ArgvReceived(int32 argc, char **argv)
{
BEntry entry;
BString names;
BString ccNames;
BString bccNames;
BString subject;
BString body;
BMessage enclosure(B_REFS_RECEIVED);
// a "mailto:" with no name should open an empty window
// so remember if we got a "mailto:" even if there isn't a name
// that goes along with it (this allows deskbar replicant to open
// an empty message even when Mail is already running)
bool gotmailto = false;
for (int32 loop = 1; loop < argc; loop++)
{
if (strcmp(argv[loop], "-h") == 0
|| strcmp(argv[loop], "--help") == 0)
{
printf(" usage: %s [ mailto:<address> ] [ -subject \"<text>\" ] [ ccto:<address> ] [ bccto:<address> ] "
"[ -body \"<body text>\" ] [ enclosure:<path> ] [ <message to read> ...] \n",
argv[0]);
fPrintHelpAndExit = true;
be_app->PostMessage(B_QUIT_REQUESTED);
return;
}
else if (strncmp(argv[loop], "mailto:", 7) == 0)
{
if (names.Length())
names += ", ";
char *options;
if ((options = strchr(argv[loop],'?')) != NULL)
{
names.Append(argv[loop] + 7, options - argv[loop] - 7);
if (!strncmp(++options,"subject=",8))
subject = options + 8;
}
else
names += argv[loop] + 7;
gotmailto = true;
}
else if (strncmp(argv[loop], "ccto:", 5) == 0)
{
if (ccNames.Length())
ccNames += ", ";
ccNames += argv[loop] + 5;
}
else if (strncmp(argv[loop], "bccto:", 6) == 0)
{
if (bccNames.Length())
bccNames += ", ";
bccNames += argv[loop] + 6;
}
else if (strcmp(argv[loop], "-subject") == 0)
subject = argv[++loop];
else if (strcmp(argv[loop], "-body") == 0 && argv[loop + 1])
body = argv[++loop];
else if (strncmp(argv[loop], "enclosure:", 10) == 0)
{
BEntry tmp(argv[loop] + 10, true);
if (tmp.InitCheck() == B_OK && tmp.Exists())
{
entry_ref ref;
tmp.GetRef(&ref);
enclosure.AddRef("refs", &ref);
}
}
else if (entry.SetTo(argv[loop]) == B_NO_ERROR)
{
BMessage msg(B_REFS_RECEIVED);
entry_ref ref;
entry.GetRef(&ref);
msg.AddRef("refs", &ref);
RefsReceived(&msg);
}
}
if (gotmailto || names.Length() || ccNames.Length() || bccNames.Length() || subject.Length()
|| body.Length() || enclosure.HasRef("refs"))
{
TMailWindow *window = NewWindow(NULL, names.String());
window->SetTo(names.String(), subject.String(), ccNames.String(), bccNames.String(),
&body, &enclosure);
window->Show();
}
}
示例8: messenger
void
NotificationView::SetText(const char* app, const char* title, const char* text,
float newMaxWidth)
{
if (newMaxWidth < 0)
newMaxWidth = Bounds().Width() - (kEdgePadding * 2);
// Delete old lines
LineInfoList::iterator lIt;
for (lIt = fLines.begin(); lIt != fLines.end(); lIt++)
delete (*lIt);
fLines.clear();
fApp = app;
fTitle = title;
fText = text;
float iconRight = kEdgePadding + kEdgePadding;
if (fBitmap != NULL)
iconRight += fParent->IconSize();
font_height fh;
be_bold_font->GetHeight(&fh);
float fontHeight = ceilf(fh.leading) + ceilf(fh.descent)
+ ceilf(fh.ascent);
float y = fontHeight;
// Title
LineInfo* titleLine = new LineInfo;
titleLine->text = fTitle;
titleLine->font = *be_bold_font;
if (fParent->Layout() == AllTextRightOfIcon)
titleLine->location = BPoint(iconRight, y);
else
titleLine->location = BPoint(kEdgePadding, y);
fLines.push_front(titleLine);
y += fontHeight;
// Rest of text is rendered with be_plain_font.
be_plain_font->GetHeight(&fh);
fontHeight = ceilf(fh.leading) + ceilf(fh.descent)
+ ceilf(fh.ascent);
// Split text into chunks between certain characters and compose the lines.
const char kSeparatorCharacters[] = " \n-\\/";
BString textBuffer = fText;
textBuffer.ReplaceAll("\t", " ");
const char* chunkStart = textBuffer.String();
float maxWidth = newMaxWidth - kEdgePadding - iconRight;
LineInfo* line = NULL;
ssize_t length = textBuffer.Length();
while (chunkStart - textBuffer.String() < length) {
size_t chunkLength = strcspn(chunkStart, kSeparatorCharacters) + 1;
// Start a new line if either we didn't start one before,
// the current offset
BString tempText;
if (line != NULL)
tempText.SetTo(line->text);
tempText.Append(chunkStart, chunkLength);
if (line == NULL || chunkStart[0] == '\n'
|| StringWidth(tempText) > maxWidth) {
line = new LineInfo;
line->font = *be_plain_font;
line->location = BPoint(iconRight + kEdgePadding, y);
fLines.push_front(line);
y += fontHeight;
// Skip the eventual new-line character at the beginning of this
// chunk.
if (chunkStart[0] == '\n') {
chunkStart++;
chunkLength--;
}
// Skip more new-line characters and move the line further down.
while (chunkStart[0] == '\n') {
chunkStart++;
chunkLength--;
line->location.y += fontHeight;
y += fontHeight;
}
// Strip space at beginning of a new line.
while (chunkStart[0] == ' ') {
chunkLength--;
chunkStart++;
}
}
if (chunkStart[0] == '\0')
break;
// Append the chunk to the current line, which was either a new
// line or the one from the previous iteration.
line->text.Append(chunkStart, chunkLength);
chunkStart += chunkLength;
//.........这里部分代码省略.........
示例9: nick
//.........这里部分代码省略.........
if (client)
{
BMessage msg (M_CHANNEL_MODE);
msg.AddString("nick", theNick.String());
msg.AddString("mode", theMode.String());
msg.AddString("target", theTarget.String());
client->PostMessage (&msg);
}
else
{
BMessage msg (M_DISPLAY);
BString buffer;
theMode.RemoveFirst(":");
buffer << "*** User mode changed: " << theMode << "\n";
PackDisplay (&msg, buffer.String(), 0, 0, true);
PostActive (&msg);
}
return true;
}
if(firstWord == "NOTICE") // _server_ notice
{
BString theNotice (RestOfString(data, 3));
const char *expansions[1];
theNotice.RemoveFirst(":");
expansions[0] = theNotice.String();
theNotice = ExpandKeyed (events[E_SNOTICE], "R", expansions);
Display (theNotice.String(), 0, 0, true);
return true;
}
if (firstWord == "ERROR") // server error (on connect?)
{
BString theError (RestOfString (data, 2));
theError.RemoveAll (":");
theError.Append ("\n");
Display (theError.String(), &quitColor);
isConnecting = false;
return true;
}
if(secondWord == "NOTICE") // _user_ notice
{
BString theNick (GetNick (data)),
ident (GetIdent (data)),
address (GetAddress (data)),
addy;
addy << theNick << "@" << address;
BMessage aMsg (M_IS_IGNORED), reply;
bool ignored;
aMsg.AddString ("server", serverName.String());
aMsg.AddString ("nick", theNick.String());
aMsg.AddString ("address", addy.String());
be_app_messenger.SendMessage (&aMsg, &reply);
reply.FindBool ("ignored", &ignored);
if (ignored) return true;
BString theNotice = RestOfString(data, 4);
theNotice.RemoveFirst(":");
if(theNotice[0] == '\1')
{
ParseCTCPResponse(theNick, theNotice);
return true;
}
const char *expansions[4];
BString tempString;
expansions[0] = theNick.String();
expansions[1] = theNotice.String();
expansions[2] = ident.String();
expansions[3] = address.String();
tempString = ExpandKeyed (events[E_UNOTICE], "NRIA", expansions);
BMessage display (M_DISPLAY);
PackDisplay (&display, tempString.String(), ¬iceColor, 0, true);
PostActive (&display);
return true;
}
return ParseENums (data, secondWord.String());
}
示例10: upFile
BString
BHttpForm::RawData() const
{
BString result;
if (fType == B_HTTP_FORM_URL_ENCODED) {
for (FormStorage::const_iterator it = fFields.begin();
it != fFields.end(); it++) {
const BHttpFormData* currentField = &it->second;
switch (currentField->Type()) {
case B_HTTPFORM_UNKNOWN:
break;
case B_HTTPFORM_STRING:
result << '&' << BUrl::UrlEncode(currentField->Name())
<< '=' << BUrl::UrlEncode(currentField->String());
break;
case B_HTTPFORM_FILE:
break;
case B_HTTPFORM_BUFFER:
// Send the buffer only if its not marked as a file
if (!currentField->IsFile()) {
result << '&' << BUrl::UrlEncode(currentField->Name())
<< '=';
result.Append(
reinterpret_cast<const char*>(currentField->Buffer()),
currentField->BufferSize());
}
break;
}
}
result.Remove(0, 1);
} else if (fType == B_HTTP_FORM_MULTIPART) {
// Very slow and memory consuming method since we're caching the
// file content, this should be preferably handled by the protocol
for (FormStorage::const_iterator it = fFields.begin();
it != fFields.end(); it++) {
const BHttpFormData* currentField = &it->second;
result << _GetMultipartHeader(currentField);
switch (currentField->Type()) {
case B_HTTPFORM_UNKNOWN:
break;
case B_HTTPFORM_STRING:
result << currentField->String();
break;
case B_HTTPFORM_FILE:
{
BFile upFile(currentField->File().Path(), B_READ_ONLY);
char readBuffer[1024];
ssize_t readSize;
readSize = upFile.Read(readBuffer, 1024);
while (readSize > 0) {
result.Append(readBuffer, readSize);
readSize = upFile.Read(readBuffer, 1024);
}
break;
}
case B_HTTPFORM_BUFFER:
result.Append(
reinterpret_cast<const char*>(currentField->Buffer()),
currentField->BufferSize());
break;
}
result << "\r\n";
}
result << "--" << fMultipartBoundary << "--\r\n";
}
return result;
}
示例11: Parent
void
NotificationView::SetText(float newMaxWidth)
{
if (newMaxWidth < 0 && Parent())
newMaxWidth = Parent()->Bounds().IntegerWidth();
if (newMaxWidth <= 0)
newMaxWidth = kDefaultWidth;
// Delete old lines
LineInfoList::iterator lIt;
for (lIt = fLines.begin(); lIt != fLines.end(); lIt++)
delete (*lIt);
fLines.clear();
float iconRight = kIconStripeWidth;
if (fBitmap != NULL)
iconRight += fParent->IconSize();
else
iconRight += 32;
font_height fh;
be_bold_font->GetHeight(&fh);
float fontHeight = ceilf(fh.leading) + ceilf(fh.descent)
+ ceilf(fh.ascent);
float y = 2 * fontHeight;
// Title
LineInfo* titleLine = new LineInfo;
titleLine->text = fNotification->Title();
titleLine->font = *be_bold_font;
titleLine->location = BPoint(iconRight + kEdgePadding, y);
fLines.push_front(titleLine);
y += fontHeight;
// Rest of text is rendered with be_plain_font.
be_plain_font->GetHeight(&fh);
fontHeight = ceilf(fh.leading) + ceilf(fh.descent)
+ ceilf(fh.ascent);
// Split text into chunks between certain characters and compose the lines.
const char kSeparatorCharacters[] = " \n-\\";
BString textBuffer = fNotification->Content();
textBuffer.ReplaceAll("\t", " ");
const char* chunkStart = textBuffer.String();
float maxWidth = newMaxWidth - kEdgePadding - iconRight;
LineInfo* line = NULL;
ssize_t length = textBuffer.Length();
while (chunkStart - textBuffer.String() < length) {
size_t chunkLength = strcspn(chunkStart, kSeparatorCharacters) + 1;
// Start a new line if we didn't start one before
BString tempText;
if (line != NULL)
tempText.SetTo(line->text);
tempText.Append(chunkStart, chunkLength);
if (line == NULL || chunkStart[0] == '\n'
|| StringWidth(tempText) > maxWidth) {
line = new LineInfo;
line->font = *be_plain_font;
line->location = BPoint(iconRight + kEdgePadding, y);
fLines.push_front(line);
y += fontHeight;
// Skip the eventual new-line character at the beginning of this chunk
if (chunkStart[0] == '\n') {
chunkStart++;
chunkLength--;
}
// Skip more new-line characters and move the line further down
while (chunkStart[0] == '\n') {
chunkStart++;
chunkLength--;
line->location.y += fontHeight;
y += fontHeight;
}
// Strip space at beginning of a new line
while (chunkStart[0] == ' ') {
chunkLength--;
chunkStart++;
}
}
if (chunkStart[0] == '\0')
break;
// Append the chunk to the current line, which was either a new
// line or the one from the previous iteration
line->text.Append(chunkStart, chunkLength);
chunkStart += chunkLength;
}
fHeight = y + (kEdgePadding * 2);
//.........这里部分代码省略.........
示例12: if
bool
fetchStr(const char *&in, BString &str, bool lookForID)
{
int parLevel = 0;
while (isspace(*in) || *in == '(') {
if (*in == '(')
parLevel++;
in++;
}
if (*in == '"') {
bool inString = true;
bool quoted = false;
in++;
while (parLevel >= 0 && inString)
{
// Collect string content until we find a quote marking end of
// string (skip escaped quotes)
while (*in != '"' || quoted)
{
str.Append(in,1);
if (*in == '\\' && !quoted)
quoted = true;
else
quoted = false;
in++;
}
in++;
inString = false;
// Strip all whitespace until we find a closing parenthesis, or the
// beginning of another string
while (isspace(*in) || *in == ')') {
if (*in == ')') {
if (parLevel == 0)
return true;
parLevel--;
}
in++;
}
if (*in == '"') {
inString = true;
in++;
}
}
} else {
if (!memcmp(in, "__null", 6)) {
// NULL is preprocessed into __null, which we parse as ""
in += 6;
} else if (lookForID && (isdigit(*in) || *in == '-' || *in == '+')) {
// try to parse an ID (a long):
errno = 0;
char *next;
id = strtol(in, &next, 10);
if (id != 0 || errno == 0) {
haveID = true;
in = next;
}
} else
return false;
while (isspace(*in) || *in == ')') {
if (*in == ')') {
if (!parLevel)
return true;
parLevel--;
}
in++;
}
}
return true;
}
示例13: mkstemp
status_t
OptiPNGTranslator::DerivedTranslate(BPositionIO *source,
const translator_info *info, BMessage *ioExtension,
uint32 outType, BPositionIO *target, int32 baseType)
{
if(baseType == 1 && outType == OPTIPNG_PNG_FORMAT) {
// create temp file
int tempFileFD;
BPath tempDir;
BString tempFilePath;
if(find_directory(B_SYSTEM_TEMP_DIRECTORY, &tempDir) != B_OK )
return B_ERROR;
tempFilePath.Append(tempDir.Path())
.Append("/OptiPNGTranslator.XXXXXX");
tempFileFD = mkstemp(tempFilePath.LockBuffer(0));
tempFilePath.UnlockBuffer();
if(tempFileFD == -1)
return B_ERROR;
close(tempFileFD);
BFile tempFile = BFile(tempFilePath, O_WRONLY);
// write PNG to file
off_t sourceSize;
source->GetSize(&sourceSize);
unsigned char sourceChars[sourceSize];
BTranslatorRoster *roster = BTranslatorRoster::Default();
roster->Translate(source, NULL, NULL, &tempFile, (uint32)B_PNG_FORMAT);
// optimize file
BString optipng;
if(system("optipng &> /dev/null") == 0) {
optipng = "optipng";
} else if(system("optipng-x86 &> /dev/null") == 0) {
optipng = "optipng-x86";
} else {
return B_ERROR;
}
// optipng -clobber -out (file) (file)
BString command;
command = optipng;
if(!fSettings->SetGetBool(OPTIPNG_SETTING_BIT_DEPTH_REDUCTION))
command += " -nb"; // no bit-depth reduction
if(!fSettings->SetGetBool(OPTIPNG_SETTING_COLOR_TYPE_REDUCTION))
command += " -nc";
if(!fSettings->SetGetBool(OPTIPNG_SETTING_PALETTE_REDUCTION))
command += " -np";
command.Append(" -o")
.Append((char)(fSettings->
SetGetInt32(OPTIPNG_SETTING_OPTIMIZATION_LEVEL)+'0'),1);
// rest of command
command.Append(" -clobber -out ")
.Append(tempFilePath)
.Append(" ")
.Append(tempFilePath)
;
if(system(command) != 0) {
return B_ERROR;
}
// read the file
tempFile = BFile(tempFilePath, O_RDONLY);
off_t fileSize;
tempFile.GetSize(&fileSize);
unsigned char *buffer;
buffer = new unsigned char[fileSize];
if(buffer == NULL)
return B_ERROR;
tempFile.ReadAt(0, buffer, fileSize);
target->Write(buffer, fileSize);
delete [] buffer;
// delete the file
BEntry entry = BEntry(tempFilePath);
entry.Remove();
return B_OK;
}
return B_NO_TRANSLATOR;
}
示例14: GetToolVersion
const char* VersionControl::GetToolVersion(const char* path)
{
thread_id thread;
int in, out, err;
const char** argv;
int argc = 0;
const char* threadname = "Helios:GetToolVersion()";
char buffer[1000];
size_t bytesread;
BString version = "";
buffer[0] = 0;
argv = (const char**)malloc(sizeof(char*) * (5));
argv[argc++] = strdup(path);
argv[argc++] = strdup("--version");
argv[argc] = NULL;
thread = pipe_command(argc, argv, in, out, err);
rename_thread(thread, threadname);
resume_thread(thread);
while ((bytesread = read(err, (void*)buffer, 1000)) > 0) {
buffer[bytesread] = 0;
version.Append(buffer);
// printf("%s: %s\n",path, buffer);
snooze(10000);
}
while ((bytesread = read(out, (void*)buffer, 1000)) > 0) {
buffer[bytesread] = 0;
version.Append(buffer);
// printf("%s: %s\n",path, buffer);
snooze(10000);
}
free(argv);
close(in);
close(out);
close(err);
char str[1024];
int32 length = 1024;
int32 state = 0;
int32 srclen = version.Length();
convert_to_utf8(B_ISO1_CONVERSION, version.String(), &srclen, str, &length, &state);
str[length] = 0;
version = str;
// --version option not supported?
if (version.FindFirst("--version") != B_ERROR) {
version = path;
version << ": "
<< _T("(could not get version info)"); // "STR:(could not get version info)"
} else {
version.RemoveAll("\n");
version.RemoveAll("\t");
// for case-insensitivity replace instead of remove...
version.IReplaceAll("Copyright ", "");
version.IReplaceAll("(c) ", B_UTF8_COPYRIGHT);
version.IReplaceAll("(c)", B_UTF8_COPYRIGHT);
}
return strdup(version.String());
}
示例15: Filter
filter_result ClientAgentInputFilter::Filter(BMessage* msg, BHandler** target)
{
filter_result result(B_DISPATCH_MESSAGE);
switch (msg->what) {
case B_MOUSE_MOVED:
break;
case B_COPY: {
int32 start, finish;
fWindow->fInput->TextView()->GetSelection(&start, &finish);
if (start == finish) *target = fWindow->fText;
} break;
case B_SELECT_ALL: {
if (fWindow->fInput->TextView()->TextLength() == 0) *target = fWindow->fText;
} break;
case B_KEY_DOWN: {
result = HandleKeys(msg);
} break;
case B_MOUSE_UP: {
if (fHandledDrop) {
fHandledDrop = false;
result = B_SKIP_MESSAGE;
}
} break;
case B_MIME_TYPE: {
if (msg->HasData("text/plain", B_MIME_TYPE)) {
const char* buffer;
ssize_t size;
msg->FindData("text/plain", B_MIME_TYPE, 0, reinterpret_cast<const void**>(&buffer),
&size);
// We copy it, because B_MIME_TYPE
// might not be \0 terminated
BString string;
string.Append(buffer, size);
HandleDrop(string.String());
fHandledDrop = true;
result = B_SKIP_MESSAGE;
}
} break;
case B_SIMPLE_DATA: {
if (msg->HasRef("refs")) {
for (int32 i = 0; msg->HasRef("refs", i); ++i) {
entry_ref ref;
msg->FindRef("refs", &ref);
char mime[B_MIME_TYPE_LENGTH];
BFile file(&ref, B_READ_ONLY);
BNodeInfo info(&file);
off_t size;
if (file.InitCheck() == B_NO_ERROR && file.GetSize(&size) == B_NO_ERROR &&
info.InitCheck() == B_NO_ERROR && info.GetType(mime) == B_NO_ERROR &&
strncasecmp(mime, "text/", 5) == 0) {
char* buffer(new char[size + 1]);
if (buffer) {
// Oh baby!
file.Read(buffer, size);
buffer[size] = 0;
HandleDrop(buffer);
delete[] buffer;
break;
}
}
}
// Give the fWindow a chance to handle non
// text files. If it's a message window, it'll
// kick off a dcc send
fWindow->DroppedFile(msg);
}
} break;
case B_PASTE: {
// we have our own pasting code so we can catch multiple lines
BClipboard clipboard("system");
const char* fText;
ssize_t textLen;
BMessage* clip((BMessage*)NULL);
if (clipboard.Lock()) {
if ((clip = clipboard.Data()))
if (clip->FindData("text/plain", B_MIME_TYPE, (const void**)&fText, &textLen) !=
B_OK) {
clipboard.Unlock();
break;
}
}
//.........这里部分代码省略.........