dialCalendar::dialCalendar(const char *inidate, BTextControl *ptr, int32 msg, BHandler *hr) : BWindow( BRect(100+20, 100+20, 295+20, 320+20+25), NULL, B_TITLED_WINDOW, B_NOT_RESIZABLE ) { msgdc = msg; dateField = ptr; handler = hr; // split inidate into y/m/d BString tmp; tmp = inidate; tmp.Remove(4,tmp.Length()-4); year = toint(tmp.String()); tmp = inidate; tmp.Remove(0,5); tmp.Remove(2,tmp.Length()-2); month = toint(tmp.String()); tmp = inidate; tmp.Remove(0,8); day = toint(tmp.String()); this->SetTitle("Wybierz datę"); this->SetFeel(B_FLOATING_APP_WINDOW_FEEL); view = new BView(this->Bounds(), "calendarView", B_FOLLOW_ALL_SIDES, 0); view->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); this->AddChild(view); view->AddChild(monthyear = new BStringView(BRect(60,5,135,25), "calendarMonthYear", NULL)); monthyear->SetAlignment(B_ALIGN_CENTER); view->AddChild(but_prevy = new BButton(BRect(10,5,30,25), "calendarButPrevy", "<<", new BMessage(BUT_PREVY))); view->AddChild(but_prevm = new BButton(BRect(35,5,55,25), "calendarButPrevm", "<", new BMessage(BUT_PREVM))); view->AddChild(but_nextm = new BButton(BRect(140,5,160,25), "calendarButNextm", ">", new BMessage(BUT_NEXTM))); view->AddChild(but_nexty = new BButton(BRect(165,5,185,25), "calendarButNexty", ">>", new BMessage(BUT_NEXTY))); int i,j; for (i=0;i<=6;i++) { view->AddChild(new BStringView(BRect(10+i*25,30,30+i*25,50), NULL, shortweekdays[i])); } BMessage *msg; for (j=0;j<=5;j++) { for (i=0;i<=6;i++) { msg = new BMessage(BUT_CAL); msg->AddInt32("_x", i); msg->AddInt32("_y", j); view->AddChild(caltab[i][j] = new BButton(BRect(10+i*25,55+j*25,30+i*25,75+j*25), NULL, "33", msg)); } } view->AddChild(but_ok = new BButton(BRect(120,210,165,230), "calendarButOk", "OK", new BMessage(BUT_OK))); but_ok->MakeDefault(true); but_ok->ResizeToPreferred(); RefreshCalendar(); }
void StringTest::Prepare(BView* view) { // SetupClipping(view); font_height fh; view->GetFontHeight(&fh); fLineHeight = ceilf(fh.ascent) + ceilf(fh.descent) + ceilf(fh.leading); fStartHeight = ceilf(fh.ascent) + ceilf(fh.descent); fViewBounds = view->Bounds(); BString string; string.Append('M', fGlyphsPerLine); while (view->StringWidth(string.String()) < fViewBounds.Width() - 10) string.Append('M', 1); while (view->StringWidth(string.String()) > fViewBounds.Width() - 10) string.Remove(string.Length() - 1, 1); fGlyphsPerLine = 60; //string.Length(); fTestDuration = 0; fGlyphsRendered = 0; fIterations = 0; fTestStart = system_time(); }
void KeyboardLayout::_Trim(BString& string, bool stripComments) { // Strip leading spaces int32 i = 0; while (isspace(string[i])) { i++; } if (i > 0) string.Remove(0, i); // Remove comments if (stripComments) { i = string.FindFirst('#'); if (i >= 0) string.Truncate(i); } // Strip trailing spaces i = string.Length() - 1; while (i > 0 && isspace(string[i])) { i--; } string.Truncate(i + 1); }
/** * @brief Reads items array in menu design resource. * @return trigger character */ char BeSkinView::parseMenuItemTrigger( const char* sourceLabel, ///< source label string BString& outLabel ///< OUTPUT. label string without '&' prefix character. ) { char trigger = 0; outLabel = sourceLabel; int32 find = 0; while (true) { find = outLabel.FindFirst('~', find); if (B_ERROR == find) { break; } outLabel.Remove(find, 1); if (outLabel[find] != '~') { if (0 == trigger) { trigger = tolower(outLabel[find]); } } else { find++; } } return trigger; }
_EXPORT void extract_address(BString &address) { const char *string = address.String(); int32 first; // first, remove all quoted text if ((first = address.FindFirst('"')) >= 0) { int32 last = first + 1; while (string[last] && string[last] != '"') last++; if (string[last] == '"') address.Remove(first, last + 1 - first); } // try to extract the address now if ((first = address.FindFirst('<')) >= 0) { // the world likes us and we can just get the address the easy way... int32 last = address.FindFirst('>'); if (last >= 0) { address.Truncate(last); address.Remove(0, first + 1); return; } } // then, see if there is anything in parenthesis to throw away if ((first = address.FindFirst('(')) >= 0) { int32 last = first + 1; while (string[last] && string[last] != ')') last++; if (string[last] == ')') address.Remove(first, last + 1 - first); } // now, there shouldn't be much else left trim_white_space(address); }
void Emoticor::_findTokens(RunView *fTextView,BString text,int tokenstart, int16 cols ,int16 font ,int16 cols2 ,int16 font2) { //****************************************** // "Iteration is human, recursion is divine" //****************************************** int32 newindex = 0; BString cur; int i=tokenstart; while(config->FindString("face",i,&cur)==B_OK) //for(int i=tokenstart;i<config->numfaces;i++) { i++; //if(config->FindString("face",i,&cur)!=B_OK) return; newindex=0; while(true) { newindex=text.IFindFirst(cur.String(),0); //printf("Try %d %s -- match %d\n",i,cur->original.String(),newindex); if(newindex!=B_ERROR) { //take a walk on the left side ;) //printf("Found at %ld \n",newindex); if(newindex-1>=0) { BString left; text.CopyInto(left,0,newindex); //printf("ready to recourse! [%s]\n",left.String()); _findTokens(fTextView,left,tokenstart+1,cols,font,cols2,font2); } text.Remove(0,newindex+cur.Length()); //printf("remaning [%s] printed [%s]\n",text.String(),cur->original.String()); fTextView->Append(cur.String(),cols2,cols2,font2); if(text.Length()==0) return; //useless stack } else break; } } fTextView->Append(text.String(),cols,cols,font); }
void DataFile::RemoveComment(BString &result) //////////////////////////////////////////////////////////////////////// { int len = result.Length(); int x = result.FindFirst('#'); if (x>=0) result.Remove(x, len-x); }
void HaikuMailFormatFilter::_RemoveLeadingDots(BString& name) { int dots = 0; while (dots < name.Length() && name.ByteAt(dots) == '.') dots++; if (dots > 0) name.Remove(0, dots); }
static void CoerceFormatTo24HourClock(BString& format) { char* buffer = format.LockBuffer(format.Length()); char* currentPos = buffer; if (currentPos == NULL) return; // change the format to use H instead of h, K instead of k, and determine // and remove the am/pm marker (including leading whitespace) bool inQuote = false; bool lastWasWhitespace = false; uint32 ch; const char* amPmStartPos = NULL; const char* amPmEndPos = NULL; const char* lastWhitespaceStart = NULL; for (char* previousPos = currentPos; (ch = BUnicodeChar::FromUTF8( (const char**)¤tPos)) != 0; previousPos = currentPos) { switch (ch) { case '\'': inQuote = !inQuote; break; case 'h': if (!inQuote) *previousPos = 'H'; break; case 'k': if (!inQuote) *previousPos = 'K'; break; case 'a': if (!inQuote) { if (lastWasWhitespace) amPmStartPos = lastWhitespaceStart; else amPmStartPos = previousPos; amPmEndPos = currentPos; } break; default: if (!inQuote && BUnicodeChar::IsWhitespace(ch)) { if (!lastWasWhitespace) { lastWhitespaceStart = previousPos; lastWasWhitespace = true; } continue; } } lastWasWhitespace = false; } format.UnlockBuffer(format.Length()); if (amPmStartPos != NULL && amPmEndPos > amPmStartPos) format.Remove(amPmStartPos - buffer, amPmEndPos - amPmStartPos); }
void BAddressContactField::_PopValue(BString& str, BString& value) { int32 index = str.FindFirst(";", 0); if (index == B_ERROR) { fWellFormed = false; value.SetTo(""); return; } str.MoveInto(value, 0, index); str.Remove(0,1); }
void DataFile::Trim(BString &result) //////////////////////////////////////////////////////////////////////// { if (result.Length() == 0) return; // Elejen a space-ek... while (result.ByteAt(0) == ' ') { result.Remove(0, 1); } if (result.Length() == 0) return; // Vegen a space-ek... while (result.ByteAt(result.Length()-1) == ' ') { result.Remove(result.Length()-1, 1); } }
void BAddressContactField::_PopValue(BString& str, BString& value) { int32 index = str.FindFirst(fDivider, 0); printf("%s\n", str.String()); if (index == B_ERROR && str.Length() < 1) { value.SetTo(""); return; } str.MoveInto(value, 0, index); str.Remove(0,1); }
OpenPackageAction(PackageInfoRef package, Model* model, const DeskbarLink& link) : PackageAction(PACKAGE_ACTION_OPEN, package, model), fDeskbarLink(link), fLabel(B_TRANSLATE("Open %DeskbarLink%")) { BString target = fDeskbarLink.link; int32 lastPathSeparator = target.FindLast('/'); if (lastPathSeparator > 0 && lastPathSeparator + 1 < target.Length()) target.Remove(0, lastPathSeparator + 1); fLabel.ReplaceAll("%DeskbarLink%", target); }
BString HaikuMailFormatFilter::_ExtractName(const BString& from) { // extract name from something like "name" <*****@*****.**> // if name is empty return the mail address without "<>" BString name; int32 emailStart = from.FindFirst("<"); if (emailStart < 0) { name = from; return name.Trim(); } from.CopyInto(name, 0, emailStart); name.Trim(); if (name.Length() >= 2) { if (name[name.Length() - 1] == '\"') name.Truncate(name.Length() - 1, true); if (name[0] == '\"') name.Remove(0, 1); name.Trim(); } if (name != "") return name; // empty name extract email address name = from; name.Remove(0, emailStart + 1); name.Trim(); if (name.Length() < 1) return from; if (name[name.Length() - 1] == '>') name.Truncate(name.Length() - 1, true); name.Trim(); return name; }
status_t BLocaleRoster::_PrepareCatalogEntry(const entry_ref& ref, BString& signature, BString& context, BString& string, bool traverse) { BEntry entry(&ref, traverse); if (!entry.Exists()) return B_ENTRY_NOT_FOUND; BNode node(&entry); status_t status = node.InitCheck(); if (status != B_OK) return status; status = node.ReadAttrString("SYS:NAME", &signature); if (status != B_OK) return status; int32 first = signature.FindFirst(':'); int32 last = signature.FindLast(':'); if (first == last) return B_ENTRY_NOT_FOUND; context = signature; string = signature; signature.Truncate(first); context.Truncate(last); context.Remove(0, first + 1); string.Remove(0, last + 1); if (signature.Length() == 0 || context.Length() == 0 || string.Length() == 0) return B_ENTRY_NOT_FOUND; return B_OK; }
void VisionApp::LoadAliases(void) { BPath settingsPath; if (find_directory(B_USER_SETTINGS_DIRECTORY, &settingsPath) < B_OK) return; settingsPath.Append(kAliasPathName); if (settingsPath.InitCheck() < B_OK) return; BFile file(settingsPath.Path(), B_READ_ONLY); if (file.InitCheck() == B_OK) { BString data; char buffer[2048]; memset(buffer, 0, sizeof(buffer)); while (file.Read((void*)buffer, 2048) > 0) { data += buffer; memset(buffer, 0, sizeof(buffer)); } file.Unset(); while (data.Length() > 0) { BString cmd, value; int32 idx = data.IFindFirst("\t"); if (idx != B_ERROR) { data.MoveInto(cmd, 0, idx); data.Remove(0, 1); } else { break; } idx = data.IFindFirst("\n"); if (idx != B_ERROR) { data.MoveInto(value, 0, idx); data.Remove(0, 1); } else { break; } fAliases[cmd.ToUpper()] = value; } } }
BString DNSTools::ConvertFromDNSName(const BString& string) { BString outString = string; int32 dot = string[0]; int32 nextDot = dot; outString.Remove(0, sizeof(char)); while (true) { dot = outString[nextDot]; if (dot == 0) break; // set a "." outString[nextDot] = '.'; nextDot+= dot + 1; } return outString; }
void PanelView::GotoParent(void) //////////////////////////////////////////////////////////////////////// { // To set the cursor to the child entry where we came from... BString oldpath; SetPanelMode(PM_NORMAL); oldpath.SetTo(m_Path.String()); oldpath.Remove(0,oldpath.FindLast('/')+1); BPath path((const char *)m_Path.String()); if (path.GetParent(&path)==B_OK) m_Path.SetTo(path.Path()); SetPathStringView(); ClearFileList(); ReadDirectory(oldpath.String()); }
void BUrlProtocolHttp::_CopyChunkInBuffer(char** buffer, ssize_t* bytesReceived) { static ssize_t chunkSize = -1; BString chunkHeader; if (chunkSize >= 0) { if ((ssize_t)fInputBuffer.Size() >= chunkSize + 2) { // 2 more bytes to handle the closing CR+LF *bytesReceived = chunkSize; *buffer = new char[chunkSize+2]; fInputBuffer.RemoveData(*buffer, chunkSize+2); chunkSize = -1; } else { *bytesReceived = -1; *buffer = NULL; } } else { if (_GetLine(chunkHeader) == B_ERROR) { chunkSize = -1; *buffer = NULL; *bytesReceived = -1; return; } // Format of a chunk header: // <chunk size in hex>[; optional data] int32 semiColonIndex = chunkHeader.FindFirst(";", 0); // Cut-off optional data if present if (semiColonIndex != -1) chunkHeader.Remove(semiColonIndex, chunkHeader.Length() - semiColonIndex); chunkSize = strtol(chunkHeader.String(), NULL, 16); PRINT(("BHP[%p] Chunk %s=%d\n", this, chunkHeader.String(), chunkSize)); if (chunkSize == 0) { fContentReceived = true; } *bytesReceived = -1; *buffer = NULL; } }
status_t UrlWrapper::_DecodeUrlString(BString& string) { // TODO: check for %00 and bail out! int32 length = string.Length(); int i; for (i = 0; string[i] && i < length - 2; i++) { if (string[i] == '%' && isxdigit(string[i+1]) && isxdigit(string[i+2])) { int c; sscanf(string.String() + i + 1, "%02x", &c); string.Remove(i, 3); string.Insert((char)c, 1, i); length -= 2; } } return B_OK; }
status_t POP3Protocol::_RetrieveUniqueIDs() { fUniqueIDs.MakeEmpty(); fSizes.clear(); fTotalSize = 0; status_t status = SendCommand("UIDL" CRLF); if (status != B_OK) return status; BString result; int32 uidOffset; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; uidOffset = result.FindFirst(' ') + 1; result.Remove(0, uidOffset); fUniqueIDs.Add(result); } if (SendCommand("LIST" CRLF) != B_OK) return B_ERROR; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; int32 index = result.FindLast(" "); int32 size; if (index >= 0) size = atol(&result.String()[index]); else size = 0; fTotalSize += size; fSizes.push_back(size); } return B_OK; }
bool KeyboardLayout::_SubstituteVariables(BString& term, VariableMap& variables, BString& unknown) { while (true) { int32 index = term.FindFirst('$'); if (index < 0) break; // find variable name VariableMap::iterator iterator = variables.begin(); VariableMap::iterator best = variables.end(); int32 bestLength = 0; for (; iterator != variables.end(); iterator++) { const BString& name = iterator->first; if (!name.Compare(&term[index], name.Length()) && name.Length() > bestLength) { best = iterator; bestLength = name.Length(); } } if (best != variables.end()) { // got one, replace it term.Remove(index, bestLength); term.Insert(best->second.String(), index); } else { // variable has not been found unknown = &term[index]; int32 length = 1; while (isalpha(unknown[length])) { length++; } unknown.Truncate(length); return false; } } return true; }
status_t POP3Protocol::_UniqueIDs() { fUniqueIDs.MakeEmpty(); status_t ret = B_OK; ret = SendCommand("UIDL" CRLF); if (ret != B_OK) return ret; BString result; int32 uid_offset; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; uid_offset = result.FindFirst(' ') + 1; result.Remove(0,uid_offset); fUniqueIDs.AddItem(result.String()); } if (SendCommand("LIST" CRLF) != B_OK) return B_ERROR; int32 b; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; b = result.FindLast(" "); if (b >= 0) b = atol(&(result.String()[b])); else b = 0; fSizes.AddItem((void *)(b)); } return ret; }
status_t POP3Protocol::UniqueIDs() { status_t ret = B_OK; runner->ReportProgress(0, 0, MDR_DIALECT_CHOICE("Getting UniqueIDs...", "固有のIDを取得中...")); ret = SendCommand("UIDL" CRLF); if (ret != B_OK) return ret; BString result; int32 uid_offset; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; uid_offset = result.FindFirst(' ') + 1; result.Remove(0,uid_offset); unique_ids->AddItem(result.String()); } if (SendCommand("LIST" CRLF) != B_OK) return B_ERROR; int32 b; while (ReceiveLine(result) > 0) { if (result.ByteAt(0) == '.') break; b = result.FindLast(" "); if (b >= 0) b = atol(&(result.String()[b])); else b = 0; fSizes.AddItem((void *)(b)); } return ret; }
void HaikuMailFormatFilter::_RemoveExtraWhitespace(BString& name) { int spaces = 0; for (int i = 0; i <= name.Length();) { if (i < name.Length() && isspace(name.ByteAt(i))) { spaces++; i++; } else if (spaces > 0) { int remove = spaces - 1; // Also remove leading and trailing spaces if (i == remove + 1 || i == name.Length()) remove++; else name[i - spaces] = ' '; name.Remove(i - remove, remove); i -= remove; spaces = 0; } else i++; } }
void UrlWrapper::RefsReceived(BMessage* msg) { char buff[B_PATH_NAME_LENGTH]; int32 index = 0; entry_ref ref; char* args[] = { const_cast<char*>("urlwrapper"), buff, NULL }; status_t err; while (msg->FindRef("refs", index++, &ref) == B_OK) { BFile f(&ref, B_READ_ONLY); BNodeInfo ni(&f); BString mimetype; BString extension(ref.name); extension.Remove(0, extension.FindLast('.') + 1); if (f.InitCheck() == B_OK && ni.InitCheck() == B_OK) { ni.GetType(mimetype.LockBuffer(B_MIME_TYPE_LENGTH)); mimetype.UnlockBuffer(); // Internet Explorer Shortcut if (mimetype == "text/x-url" || extension == "url") { // http://filext.com/file-extension/URL // http://www.cyanwerks.com/file-format-url.html off_t size; if (f.GetSize(&size) < B_OK) continue; BString contents; BString url; if (f.ReadAt(0LL, contents.LockBuffer(size), size) < B_OK) continue; contents.UnlockBuffer(); while (contents.Length()) { BString line; int32 cr = contents.FindFirst('\n'); if (cr < 0) cr = contents.Length(); //contents.MoveInto(line, 0, cr); contents.CopyInto(line, 0, cr); contents.Remove(0, cr+1); line.RemoveAll("\r"); if (!line.Length()) continue; if (!line.ICompare("URL=", 4)) { line.MoveInto(url, 4, line.Length()); break; } } if (url.Length()) { BPrivate::Support::BUrl u(url.String()); args[1] = (char*)u.String(); mimetype = kURLHandlerSigBase; mimetype += u.Proto(); err = be_roster->Launch(mimetype.String(), 1, args + 1); if (err != B_OK && err != B_ALREADY_RUNNING) err = be_roster->Launch(kAppSig, 1, args + 1); continue; } } if (mimetype == "text/x-webloc" || extension == "webloc") { // OSX url shortcuts // XML file + resource fork off_t size; if (f.GetSize(&size) < B_OK) continue; BString contents; BString url; if (f.ReadAt(0LL, contents.LockBuffer(size), size) < B_OK) continue; contents.UnlockBuffer(); int state = 0; while (contents.Length()) { BString line; int32 cr = contents.FindFirst('\n'); if (cr < 0) cr = contents.Length(); contents.CopyInto(line, 0, cr); contents.Remove(0, cr+1); line.RemoveAll("\r"); if (!line.Length()) continue; int32 s, e; switch (state) { case 0: if (!line.ICompare("<?xml", 5)) state = 1; break; case 1: if (!line.ICompare("<plist", 6)) state = 2; break; case 2: if (!line.ICompare("<dict>", 6)) state = 3; break; case 3: if (line.IFindFirst("<key>URL</key>") > -1) state = 4; break; case 4: if ((s = line.IFindFirst("<string>")) > -1 && (e = line.IFindFirst("</string>")) > s) { state = 5; s += 8; line.MoveInto(url, s, e - s); break; } else state = 3; break; default: break; } if (state == 5) { break; } } if (url.Length()) { BPrivate::Support::BUrl u(url.String()); args[1] = (char*)u.String(); mimetype = kURLHandlerSigBase; mimetype += u.Proto(); err = be_roster->Launch(mimetype.String(), 1, args + 1); if (err != B_OK && err != B_ALREADY_RUNNING) err = be_roster->Launch(kAppSig, 1, args + 1); continue; } } // NetPositive Bookmark or any file with a META:url attribute if (f.ReadAttr("META:url", B_STRING_TYPE, 0LL, buff, B_PATH_NAME_LENGTH) > 0) { BPrivate::Support::BUrl u(buff); args[1] = (char*)u.String(); mimetype = kURLHandlerSigBase; mimetype += u.Proto(); err = be_roster->Launch(mimetype.String(), 1, args + 1); if (err != B_OK && err != B_ALREADY_RUNNING) err = be_roster->Launch(kAppSig, 1, args + 1); continue; } } } }
_EXPORT void SubjectToThread (BString &string) { // a regex that matches a non-ASCII UTF8 character: #define U8C \ "[\302-\337][\200-\277]" \ "|\340[\302-\337][\200-\277]" \ "|[\341-\357][\200-\277][\200-\277]" \ "|\360[\220-\277][\200-\277][\200-\277]" \ "|[\361-\367][\200-\277][\200-\277][\200-\277]" \ "|\370[\210-\277][\200-\277][\200-\277][\200-\277]" \ "|[\371-\373][\200-\277][\200-\277][\200-\277][\200-\277]" \ "|\374[\204-\277][\200-\277][\200-\277][\200-\277][\200-\277]" \ "|\375[\200-\277][\200-\277][\200-\277][\200-\277][\200-\277]" #define PATTERN \ "^ +" \ "|^(\\[[^]]*\\])(\\<| +| *(\\<(\\w|" U8C "){2,3} *(\\[[^\\]]*\\])? *:)+ *)" \ "|^( +| *(\\<(\\w|" U8C "){2,3} *(\\[[^\\]]*\\])? *:)+ *)" \ "| *\\(fwd\\) *$" if (gRebuf == NULL && atomic_add(&gLocker,1) == 0) { // the idea is to compile the regexp once to speed up testing for (int i=0; i<256; ++i) gTranslation[i]=i; for (int i='a'; i<='z'; ++i) gTranslation[i]=toupper(i); gRe.translate = gTranslation; gRe.regs_allocated = REGS_FIXED; re_syntax_options = RE_SYNTAX_POSIX_EXTENDED; const char *pattern = PATTERN; // count subexpressions in PATTERN for (unsigned int i=0; pattern[i] != 0; ++i) { if (pattern[i] == '\\') ++i; else if (pattern[i] == '(') ++gNsub; } const char *err = re_compile_pattern(pattern,strlen(pattern),&gRe); if (err == NULL) gRebuf = &gRe; else fprintf(stderr, "Failed to compile the regex: %s\n", err); } else { int32 tries = 200; while (gRebuf == NULL && tries-- > 0) snooze(10000); } if (gRebuf) { struct re_registers regs; // can't be static if this function is to be thread-safe regs.num_regs = gNsub; regs.start = (regoff_t*)malloc(gNsub*sizeof(regoff_t)); regs.end = (regoff_t*)malloc(gNsub*sizeof(regoff_t)); for (int start=0; (start=re_search(gRebuf, string.String(), string.Length(), 0, string.Length(), ®s)) >= 0; ) { // // we found something // // don't delete [bemaildaemon]... if (start == regs.start[1]) start = regs.start[2]; string.Remove(start,regs.end[0]-start); if (start) string.Insert(' ',1,start); } free(regs.start); free(regs.end); } // Finally remove leading and trailing space. Some software, like // tm-edit 1.8, appends a space to the subject, which would break // threading if we left it in. trim_white_space(string); }
_EXPORT void extract_address_name(BString &header) { BString name; const char *start = header.String(); const char *stop = start + strlen (start); // Find a string S in the header (email foo) that matches: // Old style name in brackets: [email protected] (S) // New style quotes: "S" <*****@*****.**> // New style no quotes if nothing else found: S <*****@*****.**> // If nothing else found then use the whole thing: S for (int i = 0; i <= 3; i++) { // Set p1 to the first letter in the name and p2 to just past the last // letter in the name. p2 stays NULL if a name wasn't found in this // pass. const char *p1 = NULL, *p2 = NULL; switch (i) { case 0: // [email protected] (S) if ((p1 = strchr(start,'(')) != NULL) { p1++; // Advance to first letter in the name. size_t nest = 1; // Handle nested brackets. for (p2 = p1; p2 < stop; ++p2) { if (*p2 == ')') --nest; else if (*p2 == '(') ++nest; if (nest <= 0) break; } if (nest != 0) p2 = NULL; // False alarm, no terminating bracket. } break; case 1: // "S" <*****@*****.**> if ((p1 = strchr(start, '\"')) != NULL) p2 = strchr(++p1, '\"'); break; case 2: // S <*****@*****.**> p1 = start; if (name.Length() == 0) p2 = strchr(start, '<'); break; case 3: // S p1 = start; if (name.Length() == 0) p2 = stop; break; } // Remove leading and trailing space-like characters and save the // result if it is longer than any other likely names found. if (p2 != NULL) { while (p1 < p2 && (isspace (*p1))) ++p1; while (p1 < p2 && (isspace (p2[-1]))) --p2; int newLength = p2 - p1; if (name.Length() < newLength) name.SetTo(p1, newLength); } } int32 lessIndex = name.FindFirst('<'); int32 greaterIndex = name.FindLast('>'); if (lessIndex == 0) { // Have an address of the form <address> and nothing else, so remove // the greater and less than signs, if any. if (greaterIndex > 0) name.Remove(greaterIndex, 1); name.Remove(lessIndex, 1); } else if (lessIndex > 0 && lessIndex < greaterIndex) { // Yahoo stupidly inserts the e-mail address into the name string, so // this bit of code fixes: "Joe <*****@*****.**>" <*****@*****.**> name.Remove(lessIndex, greaterIndex - lessIndex + 1); } trim_white_space(name); header = name; }
status_t BHttpRequest::_MakeRequest() { delete fSocket; if (fSSL) fSocket = new(std::nothrow) CheckedSecureSocket(this); else fSocket = new(std::nothrow) BSocket(); if (fSocket == NULL) return B_NO_MEMORY; _EmitDebug(B_URL_PROTOCOL_DEBUG_TEXT, "Connection to %s on port %d.", fUrl.Authority().String(), fRemoteAddr.Port()); status_t connectError = fSocket->Connect(fRemoteAddr); if (connectError != B_OK) { _EmitDebug(B_URL_PROTOCOL_DEBUG_ERROR, "Socket connection error %s", strerror(connectError)); return connectError; } //! ProtocolHook:ConnectionOpened if (fListener != NULL) fListener->ConnectionOpened(this); _EmitDebug(B_URL_PROTOCOL_DEBUG_TEXT, "Connection opened, sending request."); _SendRequest(); _SendHeaders(); fSocket->Write("\r\n", 2); _EmitDebug(B_URL_PROTOCOL_DEBUG_TEXT, "Request sent."); _SendPostData(); fRequestStatus = kRequestInitialState; // Receive loop bool receiveEnd = false; bool parseEnd = false; bool readByChunks = false; bool decompress = false; status_t readError = B_OK; ssize_t bytesRead = 0; ssize_t bytesReceived = 0; ssize_t bytesTotal = 0; off_t bytesUnpacked = 0; char* inputTempBuffer = new(std::nothrow) char[kHttpBufferSize]; ssize_t inputTempSize = kHttpBufferSize; ssize_t chunkSize = -1; DynamicBuffer decompressorStorage; BDataIO* decompressingStream; ObjectDeleter<BDataIO> decompressingStreamDeleter; while (!fQuit && !(receiveEnd && parseEnd)) { if (!receiveEnd) { fSocket->WaitForReadable(); BStackOrHeapArray<char, 4096> chunk(kHttpBufferSize); bytesRead = fSocket->Read(chunk, kHttpBufferSize); if (bytesRead < 0) { readError = bytesRead; break; } else if (bytesRead == 0) receiveEnd = true; fInputBuffer.AppendData(chunk, bytesRead); } else bytesRead = 0; if (fRequestStatus < kRequestStatusReceived) { _ParseStatus(); //! ProtocolHook:ResponseStarted if (fRequestStatus >= kRequestStatusReceived && fListener != NULL) fListener->ResponseStarted(this); } if (fRequestStatus < kRequestHeadersReceived) { _ParseHeaders(); if (fRequestStatus >= kRequestHeadersReceived) { _ResultHeaders() = fHeaders; //! ProtocolHook:HeadersReceived if (fListener != NULL) fListener->HeadersReceived(this); // Parse received cookies if (fContext != NULL) { for (int32 i = 0; i < fHeaders.CountHeaders(); i++) { if (fHeaders.HeaderAt(i).NameIs("Set-Cookie")) { fContext->GetCookieJar().AddCookie( fHeaders.HeaderAt(i).Value(), fUrl); } } } if (BString(fHeaders["Transfer-Encoding"]) == "chunked") readByChunks = true; BString contentEncoding(fHeaders["Content-Encoding"]); // We don't advertise "deflate" support (see above), but we // still try to decompress it, if a server ever sends a deflate // stream despite it not being in our Accept-Encoding list. if (contentEncoding == "gzip" || contentEncoding == "deflate") { decompress = true; readError = BZlibCompressionAlgorithm() .CreateDecompressingOutputStream(&decompressorStorage, NULL, decompressingStream); if (readError != B_OK) break; decompressingStreamDeleter.SetTo(decompressingStream); } int32 index = fHeaders.HasHeader("Content-Length"); if (index != B_ERROR) bytesTotal = atoi(fHeaders.HeaderAt(index).Value()); else bytesTotal = -1; } } if (fRequestStatus >= kRequestHeadersReceived) { // If Transfer-Encoding is chunked, we should read a complete // chunk in buffer before handling it if (readByChunks) { if (chunkSize >= 0) { if ((ssize_t)fInputBuffer.Size() >= chunkSize + 2) { // 2 more bytes to handle the closing CR+LF bytesRead = chunkSize; if (inputTempSize < chunkSize + 2) { delete[] inputTempBuffer; inputTempSize = chunkSize + 2; inputTempBuffer = new(std::nothrow) char[inputTempSize]; } if (inputTempBuffer == NULL) { readError = B_NO_MEMORY; break; } fInputBuffer.RemoveData(inputTempBuffer, chunkSize + 2); chunkSize = -1; } else { // Not enough data, try again later bytesRead = -1; } } else { BString chunkHeader; if (_GetLine(chunkHeader) == B_ERROR) { chunkSize = -1; bytesRead = -1; } else { // Format of a chunk header: // <chunk size in hex>[; optional data] int32 semiColonIndex = chunkHeader.FindFirst(';', 0); // Cut-off optional data if present if (semiColonIndex != -1) { chunkHeader.Remove(semiColonIndex, chunkHeader.Length() - semiColonIndex); } chunkSize = strtol(chunkHeader.String(), NULL, 16); PRINT(("BHP[%p] Chunk %s=%ld\n", this, chunkHeader.String(), chunkSize)); if (chunkSize == 0) fRequestStatus = kRequestContentReceived; bytesRead = -1; } } // A chunk of 0 bytes indicates the end of the chunked transfer if (bytesRead == 0) receiveEnd = true; } else { bytesRead = fInputBuffer.Size(); if (bytesRead > 0) { if (inputTempSize < bytesRead) { inputTempSize = bytesRead; delete[] inputTempBuffer; inputTempBuffer = new(std::nothrow) char[bytesRead]; } if (inputTempBuffer == NULL) { readError = B_NO_MEMORY; break; } fInputBuffer.RemoveData(inputTempBuffer, bytesRead); } } if (bytesRead >= 0) { bytesReceived += bytesRead; if (fListener != NULL) { if (decompress) { readError = decompressingStream->WriteExactly( inputTempBuffer, bytesRead); if (readError != B_OK) break; ssize_t size = decompressorStorage.Size(); BStackOrHeapArray<char, 4096> buffer(size); size = decompressorStorage.Read(buffer, size); if (size > 0) { fListener->DataReceived(this, buffer, bytesUnpacked, size); bytesUnpacked += size; } } else if (bytesRead > 0) { fListener->DataReceived(this, inputTempBuffer, bytesReceived - bytesRead, bytesRead); } fListener->DownloadProgress(this, bytesReceived, std::max((ssize_t)0, bytesTotal)); } if (bytesTotal >= 0 && bytesReceived >= bytesTotal) receiveEnd = true; if (decompress && receiveEnd) { readError = decompressingStream->Flush(); if (readError == B_BUFFER_OVERFLOW) readError = B_OK; if (readError != B_OK) break; ssize_t size = decompressorStorage.Size(); BStackOrHeapArray<char, 4096> buffer(size); size = decompressorStorage.Read(buffer, size); if (fListener != NULL && size > 0) { fListener->DataReceived(this, buffer, bytesUnpacked, size); bytesUnpacked += size; } } } } parseEnd = (fInputBuffer.Size() == 0); } fSocket->Disconnect(); delete[] inputTempBuffer; if (readError != B_OK) return readError; return fQuit ? B_INTERRUPTED : B_OK; }
void TimeZoneView::_BuildZoneMenu() { BTimeZone defaultTimeZone; BLocaleRoster::Default()->GetDefaultTimeZone(&defaultTimeZone); BLanguage language; BLocale::Default()->GetLanguage(&language); /* * Group timezones by regions, but filter out unwanted (duplicate) regions * and add an additional region with generic GMT-offset timezones at the end */ typedef std::map<BString, TimeZoneListItem*, TimeZoneItemLess> ZoneItemMap; ZoneItemMap zoneItemMap; const char* kOtherRegion = B_TRANSLATE_MARK("<Other>"); const char* kSupportedRegions[] = { B_TRANSLATE_MARK("Africa"), B_TRANSLATE_MARK("America"), B_TRANSLATE_MARK("Antarctica"), B_TRANSLATE_MARK("Arctic"), B_TRANSLATE_MARK("Asia"), B_TRANSLATE_MARK("Atlantic"), B_TRANSLATE_MARK("Australia"), B_TRANSLATE_MARK("Europe"), B_TRANSLATE_MARK("Indian"), B_TRANSLATE_MARK("Pacific"), kOtherRegion, NULL }; // Since the zone-map contains translated country-names (we get those from // ICU), we need to use translated region names in the zone-map, too: typedef std::map<BString, BString> TranslatedRegionMap; TranslatedRegionMap regionMap; for (const char** region = kSupportedRegions; *region != NULL; ++region) { BString translatedRegion = B_TRANSLATE_NOCOLLECT(*region); regionMap[*region] = translatedRegion; TimeZoneListItem* regionItem = new TimeZoneListItem(translatedRegion, NULL, NULL); regionItem->SetOutlineLevel(0); zoneItemMap[translatedRegion] = regionItem; } // Get all time zones BMessage zoneList; BLocaleRoster::Default()->GetAvailableTimeZonesWithRegionInfo(&zoneList); typedef std::map<BString, std::vector<const char*> > ZonesByCountyMap; ZonesByCountyMap zonesByCountryMap; const char *zoneID; BString countryCode; for (int tz = 0; zoneList.FindString("timeZone", tz, &zoneID) == B_OK && zoneList.FindString("region", tz, &countryCode) == B_OK; tz++) { // From the global ("001") timezones, we only accept the generic GMT // timezones, as all the other world-zones are duplicates of others. if (countryCode == "001" && strncmp(zoneID, "Etc/GMT", 7) != 0) continue; zonesByCountryMap[countryCode].push_back(zoneID); } ZonesByCountyMap::const_iterator countryIter = zonesByCountryMap.begin(); for (; countryIter != zonesByCountryMap.end(); ++countryIter) { BCountry country(countryIter->first.String()); BString countryName; country.GetName(countryName); size_t zoneCountInCountry = countryIter->second.size(); for (size_t tz = 0; tz < zoneCountInCountry; tz++) { BString zoneID(countryIter->second[tz]); int32 slashPos = zoneID.FindFirst('/'); BString region(zoneID, slashPos); if (region == "Etc") region = kOtherRegion; // just accept timezones from our supported regions, others are // aliases and would just make the list even longer TranslatedRegionMap::iterator regionIter = regionMap.find(region); if (regionIter == regionMap.end()) continue; BString fullCountryID = regionIter->second; bool countryIsRegion = countryName == regionIter->second || region == kOtherRegion; if (!countryIsRegion) fullCountryID << "/" << countryName; BTimeZone* timeZone = new BTimeZone(zoneID, &language); BString tzName; BString fullZoneID = fullCountryID; if (zoneCountInCountry > 1) { // we can't use the country name as timezone name, since there // are more than one timezones in this country - fetch the // localized name of the timezone and use that tzName = timeZone->Name(); int32 openParenthesisPos = tzName.FindFirst('('); if (openParenthesisPos >= 0) { tzName.Remove(0, openParenthesisPos + 1); int32 closeParenthesisPos = tzName.FindLast(')'); if (closeParenthesisPos >= 0) tzName.Truncate(closeParenthesisPos); } fullZoneID << "/" << tzName; } else { tzName = countryName; fullZoneID << "/" << zoneID; } // skip duplicates ZoneItemMap::iterator zoneIter = zoneItemMap.find(fullZoneID); if (zoneIter != zoneItemMap.end()) { delete timeZone; continue; } TimeZoneListItem* countryItem = NULL; TimeZoneListItem* zoneItem = NULL; if (zoneCountInCountry > 1) { ZoneItemMap::iterator countryIter = zoneItemMap.find(fullCountryID); if (countryIter == zoneItemMap.end()) { countryItem = new TimeZoneListItem(countryName, NULL, NULL); countryItem->SetOutlineLevel(1); zoneItemMap[fullCountryID] = countryItem; } else countryItem = countryIter->second; zoneItem = new TimeZoneListItem(tzName, NULL, timeZone); zoneItem->SetOutlineLevel(countryIsRegion ? 1 : 2); } else { zoneItem = new TimeZoneListItem(tzName, NULL, timeZone); zoneItem->SetOutlineLevel(1); } zoneItemMap[fullZoneID] = zoneItem; if (timeZone->ID() == defaultTimeZone.ID()) { fCurrentZoneItem = zoneItem; if (countryItem != NULL) countryItem->SetExpanded(true); ZoneItemMap::iterator regionItemIter = zoneItemMap.find(regionIter->second); if (regionItemIter != zoneItemMap.end()) regionItemIter->second->SetExpanded(true); } } } fOldZoneItem = fCurrentZoneItem; ZoneItemMap::iterator zoneIter; bool lastWasCountryItem = false; TimeZoneListItem* currentCountryItem = NULL; for (zoneIter = zoneItemMap.begin(); zoneIter != zoneItemMap.end(); ++zoneIter) { if (zoneIter->second->OutlineLevel() == 2 && lastWasCountryItem) { /* Some countries (e.g. Spain and Chile) have their timezones * spread across different regions. As a result, there might still * be country items with only one timezone below them. We manually * filter those country items here. */ ZoneItemMap::iterator next = zoneIter; ++next; if (next != zoneItemMap.end() && next->second->OutlineLevel() != 2) { fZoneList->RemoveItem(currentCountryItem); zoneIter->second->SetText(currentCountryItem->Text()); zoneIter->second->SetOutlineLevel(1); delete currentCountryItem; } } fZoneList->AddItem(zoneIter->second); if (zoneIter->second->OutlineLevel() == 1) { lastWasCountryItem = true; currentCountryItem = zoneIter->second; } else lastWasCountryItem = false; } }