Example #1
0
	virtual bool Visit(BPartition* partition, int32 level)
	{
		if (!partition->Parent()
			|| !fViewMap.ContainsKey(partition->Parent()->ID()))
			return false;

		// calculate size factor within parent frame
		off_t offset = partition->Offset();
//		off_t parentOffset = partition->Parent()->Offset();
		off_t size = partition->Size();
		off_t parentSize = partition->Parent()->Size();
		double scale = (double)size / parentSize;

		BString name = partition->ContentName();
		if (name.Length() == 0) {
			if (partition->CountChildren() > 0)
				name << partition->Type();
			else {
				char buffer[64];
				snprintf(buffer, 64, B_TRANSLATE("Partition %ld"),
					partition->ID());
				name << buffer;
			}
		}
		partition_id id = partition->ID();
		PartitionView* view = new PartitionView(name.String(), scale, offset,
			level, id);
		view->SetSelected(id == fSelectedPartition);
		PartitionView* parent = fViewMap.Get(partition->Parent()->ID());
		BGroupLayout* layout = parent->GroupLayout();
		layout->AddView(_FindInsertIndex(view, layout), view, scale);

		fViewMap.Put(partition->ID(), view);
		_AddSpaces(partition, view);

		return false;
	}
Example #2
0
/*!	\brief Tells the BQuery to start fetching entries satisfying the predicate.
	After Fetch() has been called GetNextEntry(), GetNextRef() and
	GetNextDirents() can be used to retrieve the enties. Live query updates
	may be sent immediately after this method has been called.
	Fetch() fails, if it has already been called. To reuse a BQuery object it
	has to be reset via Clear().
	\return
	- \c B_OK: Everything went fine.
	- \c B_NO_INIT: The predicate or the volume aren't set.
	- \c B_BAD_VALUE: The predicate is invalid.
	- \c B_NOT_ALLOWED: Fetch() has already been called.
*/
status_t
BQuery::Fetch()
{
    if (_HasFetched())
        return B_NOT_ALLOWED;

    _EvaluateStack();

    if (!fPredicate || fDevice < 0)
        return B_NO_INIT;

    BString parsedPredicate;
    _ParseDates(parsedPredicate);

    fQueryFd = _kern_open_query(fDevice, parsedPredicate.String(),
                                parsedPredicate.Length(), fLive ? B_LIVE_QUERY : 0, fPort, fToken);
    if (fQueryFd < 0)
        return fQueryFd;

    // set close on exec flag
    fcntl(fQueryFd, F_SETFD, FD_CLOEXEC);

    return B_OK;
}
Example #3
0
/*static*/ BString
BUrl::_DoUrlEncodeChunk(const BString& chunk, bool strict, bool directory)
{
	BString result;

	for (int32 i = 0; i < chunk.Length(); i++) {
		if (_IsUnreserved(chunk[i])
				|| (directory && (chunk[i] == '/' || chunk[i] == '\\'))) {
			result << chunk[i];
		} else {
			if (chunk[i] == ' ' && !strict) {
				result << '+';
					// In non-strict mode, spaces are encoded by a plus sign
			} else {
				char hexString[5];
				snprintf(hexString, 5, "%X", chunk[i]);

				result << '%' << hexString;
			}
		}
	}

	return result;
}
Example #4
0
bool DataFile::GetEntry(BString key, BString &result)
////////////////////////////////////////////////////////////////////////
{
	if (key.Length() == 0)
		return false;
	
	unsigned char hashcode = GetHash(key);
	DataEntry *tempentry;

	for (int i=0; i<m_Entries.CountItems(); i++)
	{
		tempentry = (DataEntry *)m_Entries.ItemAt(i);
		if (tempentry)
		{
			if (tempentry->HashValue == hashcode && tempentry->Key == key)
			{
				result = tempentry->Value;
				return true;
			}
		}
	}	
	
	return false;
}
Example #5
0
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());
}
Example #6
0
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;
		}
	}
}
Example #7
0
status_t
FilePlaylistItem::SetAttribute(const Attribute& attribute,
	const BString& string)
{
	switch (attribute) {
		case ATTR_STRING_NAME:
		{
			BEntry entry(&fRefs[0], false);
			return entry.Rename(string.String(), false);
		}
	
		case ATTR_STRING_KEYWORDS:
			return _SetAttribute("Meta:Keywords", B_STRING_TYPE,
				string.String(), string.Length());

		case ATTR_STRING_ARTIST:
			return _SetAttribute("Audio:Artist", B_STRING_TYPE,
				string.String(), string.Length());
		case ATTR_STRING_AUTHOR:
			return _SetAttribute("Media:Author", B_STRING_TYPE,
				string.String(), string.Length());
		case ATTR_STRING_ALBUM:
			return _SetAttribute("Audio:Album", B_STRING_TYPE,
				string.String(), string.Length());
		case ATTR_STRING_TITLE:
			return _SetAttribute("Media:Title", B_STRING_TYPE,
				string.String(), string.Length());
		case ATTR_STRING_AUDIO_BITRATE:
			return _SetAttribute("Audio:Bitrate", B_STRING_TYPE,
				string.String(), string.Length());
		case ATTR_STRING_VIDEO_BITRATE:
			return _SetAttribute("Video:Bitrate", B_STRING_TYPE,
				string.String(), string.Length());

		default:
			return B_NOT_SUPPORTED;
	}
}
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;
}
Example #9
0
void
PDFWriter::DrawString(char *string, float escapementNoSpace,
	float escapementSpace)
{
	REPORT(kDebug, fPage, "DrawString string=\"%s\", escapementNoSpace=%f, "
		"escapementSpace=%f, at %f, %f", string, escapementNoSpace,
		escapementSpace, fState->penX, fState->penY);

	if (IsDrawing()) {
		// text color is always the high color and not the pattern!
		SetColor(fState->foregroundColor);
	}
	// convert string to UTF8
	BString utf8;
	if (fState->beFont.Encoding() == B_UNICODE_UTF8) {
		utf8 = string;
	} else {
		ToUtf8(fState->beFont.Encoding()-1, string, utf8);
	}

	// convert string in UTF8 to unicode UCS2
	BString unicode;
	ToUnicode(utf8.String(), unicode);
	// need font object to calculate width of utf8 code point
	BFont font = fState->beFont;
	font.SetEncoding(B_UNICODE_UTF8);
	// constants to calculate position of next character
	const double rotation = DEGREE2RAD(fState->beFont.Rotation());
	const bool rotate = rotation != 0.0;
	const double cos1 = rotate ? cos(rotation) : 1;
	const double sin1 = rotate ? -sin(rotation) : 0;

	BPoint start(fState->penX, fState->penY);

	BeginTransparency();
	// If !MakesPDF() all the effort below just for the bounding box!
	// draw each character
	const char *c = utf8.String();
	const unsigned char *u = (unsigned char*)unicode.String();
	for (int i = 0; i < unicode.Length(); i += 2) {
		int s = CodePointSize((char*)c);

		float w = font.StringWidth(c, s);

		if (MakesPDF() && IsClipping()) {
			ClipChar(&font, (char*)u, c, s, w);
		} else {
			DrawChar(u[0]*256+u[1], c, s);
		}

		// position of next character
		if (*(unsigned char*)c <= 0x20) { // should test if c is a white-space!
			w += escapementSpace;
		} else {
			w += escapementNoSpace;
		}

		fState->penX += w * cos1;
		fState->penY += w * sin1;

		// next character
		c += s; u += 2;
	}
	EndTransparency();

	// text line processing (for non rotated text only!)
	BPoint end(fState->penX, fState->penY);
	BRect bounds;
	font_height height;

	font.GetHeight(&height);

	bounds.left = start.x;
	bounds.right = end.x;
	bounds.top = start.y - height.ascent;
	bounds.bottom = end.y   + height.descent;

	TextSegment* segment = new TextSegment(utf8.String(), start, escapementSpace,
		escapementNoSpace, &bounds, &font, pdfSystem());

	fTextLine.Add(segment);
}
Example #10
0
int main(int argc, char* argv[])
{
	BApplication mailApp(APP_SIG);

	// No arguments, show usage
	if (argc < 2) {
		fprintf(stdout,"This program can only send mail, not read it.\n");
		fprintf(stdout,"usage: %s [-v] [-s subject] [-c cc-addr] "
			"[-b bcc-addr] to-addr ...\n", argv[0]);
		return 0;
	}

	char *subject = "No subject";
	char *cc = "";
	char *bcc = "";
	BString to;
	bool verbose = false;

	// Parse arguments
	for (int i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-v") == 0)
			verbose = true;
		else if (strcmp(argv[i], "-s") == 0) {
			subject = argv[i+1];
			i++;
		} else if (strcmp(argv[i], "-c") == 0) {
			cc = argv[i+1];
			i++;
 		} else if (strcmp(argv[i], "-b") == 0) {
 			bcc = argv[i+1];
 			i++;
		} else {
			if (to.Length() > 0)
				to.Append(", ");
			to.Append(argv[i]);
		}
	}

	if (verbose) {
		fprintf(stdout, "\n");
		fprintf(stdout, "To:\t%s\n", to.String());
		fprintf(stdout, "Cc:\t%s\n", cc);
		fprintf(stdout, "Bcc:\t%s\n", bcc);
		fprintf(stdout, "Subj:\t%s\n", subject);
		fprintf(stdout, "\n");
	}

	// Check if recipients are valid
	if (strcmp(to.String(), "") == 0 &&
		strcmp(cc, "") == 0 &&
		strcmp(bcc, "") == 0) {

		fprintf(stderr, "[Error]: You must specify at least one recipient "
			"in to, cc or bcc fields.\n");
		return -1;
	}

	bool isTerminal = isatty(STDIN_FILENO) != 0;
	if (isTerminal) {
		fprintf(stderr, "Now type your message.\n"
			"Type '.' alone on a line to end your text and send it.\n");
	}

	BString body;
	char line[32768] = "";

	// Read each line and collect the body text until we get an end of text
	// marker.  That's a single dot "." on a line typed in by the user,
	// or end of file when reading a file.
	do {
		if (fgets(line, sizeof(line), stdin) == NULL) {
			// End of file or an error happened, just send collected body text.
			break;
		}

		if (isTerminal && strcmp(line, ".\n") == 0)
			break;

		body.Append(line);
	} while (true);

	if (verbose)
		fprintf(stdout, "\nBody:\n%s\n", body.String());

	if (verbose)
		fprintf(stderr, "Sending E-mail...\n");
	fflush(stdout);

	BMailMessage mail;
	mail.AddHeaderField(B_MAIL_TO, to.String());
	mail.AddHeaderField(B_MAIL_CC, cc);
	mail.AddHeaderField(B_MAIL_BCC, bcc);
	mail.AddHeaderField(B_MAIL_SUBJECT, subject);
	mail.AddContent(body.String(), body.Length());
	status_t result = mail.Send();

	if (result == B_OK) {
		if (verbose)
			fprintf(stderr, "Message was sent successfully.\n");
		return 0;
	}

	fprintf(stderr, "Message failed to send: %s\n", strerror(result));
	return result;
}
Example #11
0
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();
	}
}
Example #12
0
float
TruncFileSizeBase(BString* outString, int64 value, const View* view,
	float width)
{
	// ToDo: If slow, replace float divisions with shifts
	//       if fast enough, try fitting more decimal places.

	// ToDo: Update string_for_size() in libshared to be able to
	//       handle this case.

	BString buffer;

	// format file size value
	if (value == kUnknownSize) {
		*outString = "-";
		return view->StringWidth("-");
	} else if (value < kKBSize) {
		static BStringFormat format(B_TRANSLATE(
			"{0, plural, one{# byte} other{# bytes}}"));
		format.Format(buffer, value);
		if (view->StringWidth(buffer.String()) > width)
			buffer.SetToFormat(B_TRANSLATE("%Ld B"), value);
	} else {
		const char* suffix;
		float doubleValue;
		if (value >= kTBSize) {
			suffix = B_TRANSLATE("TiB");
			doubleValue = (double)value / kTBSize;
		} else if (value >= kGBSize) {
			suffix = B_TRANSLATE("GiB");
			doubleValue = (double)value / kGBSize;
		} else if (value >= kMBSize) {
			suffix = B_TRANSLATE("MiB");
			doubleValue = (double)value / kMBSize;
		} else {
			ASSERT(value >= kKBSize);
			suffix = B_TRANSLATE("KiB");
			doubleValue = (double)value / kKBSize;
		}

		for (int32 index = 0; ; index++) {
			if (kSizeFormats[index] == 0)
				break;

			buffer.SetToFormat(kSizeFormats[index], doubleValue, suffix);
			// strip off an insignificant zero so we don't get readings
			// such as 1.00
			char* period = 0;
			for (char* tmp = const_cast<char*>(buffer.String()); *tmp != '\0';
					tmp++) {
				if (*tmp == '.')
					period = tmp;
			}
			if (period && period[1] && period[2] == '0')
				// move the rest of the string over the insignificant zero
				for (char* tmp = &period[2]; *tmp; tmp++)
					*tmp = tmp[1];

			float resultWidth = view->StringWidth(buffer);
			if (resultWidth <= width) {
				*outString = buffer.String();
				return resultWidth;
			}
		}
	}

	return TruncStringBase(outString, buffer.String(), buffer.Length(), view,
		width, (uint32)B_TRUNCATE_END);
}
Example #13
0
void
BJson::_Parse(BMessage& message, BString& JSON)
{
	BMessageBuilder builder(message);
	int32 pos = 0;
	int32 length = JSON.Length();
	
	/* Locals used by the parser. */
	// Keeps track of the hierarchy (e.g. "{[{{") that has
	// been read in. Allows the parser to verify that openbraces
	// match up to closebraces and so on and so forth.
	BString hierarchy("");
	// Stores the key that was just read by the string parser,
	// in the case that we are parsing a map.
	BString key("");
	
	// TODO: Check builder return codes and throw exception, or
	// change builder implementation/interface to throw exceptions
	// instead of returning errors.
	// TODO: Elimitate more duplicated code, for example by moving
	// more code into _ParseConstant().
	
	while (pos < length) {
		switch (JSON[pos]) {
		case '{':
			hierarchy += "{";
			
			if (hierarchy != "{") {
				if (builder.What() == JSON_TYPE_ARRAY)
					builder.PushObject(builder.CountNames());
				else {
					builder.PushObject(key.String());
					key = "";
				}
			}

			builder.SetWhat(JSON_TYPE_MAP);
			break;

		case '}':
			if (hierarchy.EndsWith("{") && hierarchy.Length() != 1) {
				hierarchy.Truncate(hierarchy.Length() - 1);
				builder.PopObject();
			} else if (hierarchy.Length() == 1)
				return; // End of the JSON data
			else
				throw ParseException(pos, "Unmatched closebrace }");

            break;

		case '[':
			hierarchy += "[";
			
			if (builder.What() == JSON_TYPE_ARRAY)
				builder.PushObject(builder.CountNames());
			else {
				builder.PushObject(key.String());
				key = "";
			}

			builder.SetWhat(JSON_TYPE_ARRAY);
			break;

		case ']':
			if (hierarchy.EndsWith("[")) {
				hierarchy.Truncate(hierarchy.Length() - 1);
				builder.PopObject();
			} else {
				BString error("Unmatched closebrace ] hierarchy: ");
				error << hierarchy;
				throw ParseException(pos, error);
			}

			break;

		case 't':
		{
			if (builder.What() != JSON_TYPE_ARRAY && key.Length() == 0) {
				throw ParseException(pos,
					"'true' cannot be a key, it can only be a value");
			}
			
			if (_ParseConstant(JSON, pos, "true")) {
				if (builder.What() == JSON_TYPE_ARRAY)
					key.SetToFormat("%" B_PRIu32, builder.CountNames());
				builder.AddBool(key.String(), true);
				key = "";
			} else
				throw ParseException(pos, "Unexpected 't'");

			break;
		}

		case 'f':
		{
			if (builder.What() != JSON_TYPE_ARRAY && key.Length() == 0) {
				throw ParseException(pos,
					"'false' cannot be a key, it can only be a value");
			}
			
			if (_ParseConstant(JSON, pos, "false")) {
				if (builder.What() == JSON_TYPE_ARRAY)
					key.SetToFormat("%" B_PRIu32, builder.CountNames());
				builder.AddBool(key.String(), false);
				key = "";
			} else
				throw ParseException(pos, "Unexpected 'f'");

			break;
		}

        case 'n':
        {
			if (builder.What() != JSON_TYPE_ARRAY && key.Length() == 0) {
				throw ParseException(pos,
					"'null' cannot be a key, it can only be a value");
			}
			
			if (_ParseConstant(JSON, pos, "null")) {
				if (builder.What() == JSON_TYPE_ARRAY)
					key.SetToFormat("%" B_PRIu32, builder.CountNames());
				builder.AddPointer(key.String(), (void*)NULL);
				key = "";
			} else
				throw ParseException(pos, "Unexpected 'n'");

			break;
		}

		case '"':
			if (builder.What() != JSON_TYPE_ARRAY && key.Length() == 0)
				key = _ParseString(JSON, pos);
			else if (builder.What() != JSON_TYPE_ARRAY && key.Length() > 0) {
				builder.AddString(key, _ParseString(JSON, pos));
				key = "";
			} else if (builder.What() == JSON_TYPE_ARRAY) {
				key << builder.CountNames();
				builder.AddString(key, _ParseString(JSON, pos));
				key = "";
			} else
				throw ParseException(pos, "Internal error at encountering \"");

			break;

		case '+':
		case '-':
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
		{
			if (builder.What() != JSON_TYPE_ARRAY && key.Length() == 0) {
				throw ParseException(pos,
					"Numbers cannot be keys, they can only be values");
			}
			
			if (builder.What() == JSON_TYPE_ARRAY)
				key << builder.CountNames();

			double number = _ParseNumber(JSON, pos);
			builder.AddDouble(key.String(), number);

			key = "";
			break;
		}

		case ':':
		case ',':
		default:
			// No need to do anything here.
			break;
		}
		pos++;
	}

	throw ParseException(pos, "Unexpected end of document");
}
Example #14
0
void
BUrl::SetAuthority(const BString& authority)
{
	fAuthority = authority;

	fHasPort = false;
	fHasUserName = false;
	fHasPassword = false;

	// An empty authority is still an authority, making it possible to have
	// URLs such as file:///path/to/file.
	// TODO however, there is no way to unset the authority once it is set...
	// We may want to take a const char* parameter and allow NULL.
	fHasHost = true;

	if (fAuthority.IsEmpty())
		return;

	int32 userInfoEnd = fAuthority.FindFirst('@');

	// URL contains userinfo field
	if (userInfoEnd != -1) {
		BString userInfo;
		fAuthority.CopyInto(userInfo, 0, userInfoEnd);

		int16 colonDelimiter = userInfo.FindFirst(':', 0);

		if (colonDelimiter == 0) {
			SetPassword(userInfo);
		} else if (colonDelimiter != -1) {
			userInfo.CopyInto(fUser, 0, colonDelimiter);
			userInfo.CopyInto(fPassword, colonDelimiter + 1,
				userInfo.Length() - colonDelimiter);
			SetUserName(fUser);
			SetPassword(fPassword);
		} else {
			SetUserName(fUser);
		}
	}


	// Extract the host part
	int16 hostEnd = fAuthority.FindFirst(':', userInfoEnd);
	userInfoEnd++;

	if (hostEnd < 0) {
		// no ':' found, the host extends to the end of the URL
		hostEnd = fAuthority.Length() + 1;
	}

	// The host is likely to be present if an authority is
	// defined, but in some weird cases, it's not.
	if (hostEnd != userInfoEnd) {
		fAuthority.CopyInto(fHost, userInfoEnd, hostEnd - userInfoEnd);
		SetHost(fHost);
	}

	// Extract the port part
	fPort = 0;
	if (fAuthority.ByteAt(hostEnd) == ':') {
		hostEnd++;
		int16 portEnd = fAuthority.Length();

		BString portString;
		fAuthority.CopyInto(portString, hostEnd, portEnd - hostEnd);
		fPort = atoi(portString.String());

		//  Even if the port is invalid, the URL is considered to
		// have a port.
		fHasPort = portString.Length() > 0;
	}
}
Example #15
0
_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;
}
Example #16
0
/**
 * Print() 
 *
 * @param BMessage*
 * @return status_t, any result from the operation
 */
status_t MessagePrinter::Print(BMessage* msg)
{
	status_t status;
	BFile file;
	BPath settingsPath;
	// char settingsPath[B_PATH_NAME_LENGTH];
	char  *name; 
	uint32  type; 
	int32   count; 

	// open a file to print message on the desktop
	status = find_directory(B_DESKTOP_DIRECTORY, &settingsPath);
	if (status != B_OK) {
		(new BAlert("","find directory error", "Doh!"))->Go();
		return status;
	}

	settingsPath.Append(msgFileName);
	status = file.SetTo(settingsPath.Path(), B_WRITE_ONLY | B_CREATE_FILE);
	if (status != B_OK) {
		(new BAlert("","file write error", "Doh!"))->Go();
		return status;
	}	
	
	// print the contents of the message to file
	for ( int32 i = 0; 
    	msg->GetInfo(B_ANY_TYPE, i, &name, &type, &count) == B_OK; 
     	i++ ) 
	{ 
		BString out;
		// count
		out << i;
		if (file.Write(out.String(), out.Length()) < 0) {
			(new BAlert("","count write error", "Doh!"))->Go();
			return B_ERROR;
		}	
		// name
		out = " ";
		out << name;
		if (file.Write(out.String(), out.Length()) < 0) {
			(new BAlert("","name write error", "Doh!"))->Go();
			return B_ERROR;
		}	
		
		// type
		switch (type) {
			case B_INT32_TYPE:
				{
				int32 v;
				out = " B_INT32_TYPE ";
				msg->FindInt32(name, 0, &v);
				out << v << '\n';
				}
				break;
			case B_UINT32_TYPE:
				{
				int32 v;
				out = " B_UINT32_TYPE ";
				msg->FindInt32(name, 0, &v);
				out << v << '\n';
				}
				break;
			case B_INT64_TYPE:
				{
				int64 v;
				out = " B_INT64_TYPE ";
				msg->FindInt64(name, 0, &v);
				out << v << '\n';
				}
				break;
			case B_FLOAT_TYPE:
				{
				float f;
				out = " B_FLOAT_TYPE ";
				msg->FindFloat(name, 0, &f);
				out << f << '\n';
				}
				break;
			case B_BOOL_TYPE:
				{
				bool b;
				out = " B_BOOL_TYPE ";
				msg->FindBool(name, 0, &b);
				out << (int)b << '\n';
				}
				break;
			case B_MESSAGE_TYPE:
				{
				BMessage *m = new BMessage(); 
				MessagePrinter *mp = new MessagePrinter(name);
				msg->FindMessage(name, m);
				mp->Print(m);
				out = " B_MESSAGE_TYPE \n";
				delete m;
				delete mp;
				}
				break;
			case B_RECT_TYPE:
				{
				BRect r;
				out = " B_RECT_TYPE ";
				msg->FindRect(name, 0, &r);
				out << "{ " 
					<< r.left <<" " 
					<< r.top <<" " 
					<< r.right <<" " 
					<< r.bottom <<" " 
					<< " }"
					<< '\n';
				}
				break;
			case B_STRING_TYPE:
				{
				BString s;
				out = " B_STRING_TYPE ";
				msg->FindString(name, 0, &s);
				out << s.String() << '\n';
				}
				break;
			default:
				out = " UNKNOWN TYPE \n";
				break;
		}
	    if (file.Write(out.String(), out.Length()) < 0) {
			(new BAlert("","value write error", "Doh!"))->Go();
			return B_ERROR;
		}	
	}
	return status;
}
static void get_bank_label(ArpCRef<AmBankI> bank, uint32 bankNumber, BString& out)
{
	if (bank) out = bank->Name().String();
	if (out.Length() < 1) out << "Bank " << bankNumber;
}
Example #18
0
	EntryPath(const BString& directory, const BString& name)
		:
		directory(directory.Length() > 0 ? directory.String() : NULL),
		name(name.String())
	{
	}
Example #19
0
void SeqPhraseMatrixView::DrawTopLevelPhrase(	BRect clip,
        BView* view,
        const AmTrack* track,
        const AmPhraseEvent* event,
        AmTime end,
        AmPhraseEvent* topPhrase,
        AmPhraseRendererI* renderer)
{
    ArpASSERT(event && topPhrase);
    if (!event || !event->Phrase() ) return;
    const AmPhrase*		phrase = event->Phrase();
    BRect				entireF(0, clip.top + 3, 0, clip.bottom - 3);
    AmTime				phraseEnd = event->EndTime();
    BString				n = event->Phrase()->Name();
    float				labelH = mCurLabelH + 3;
    bool				drawLabel = mCurLabelH > 0 && labelH < entireF.Height() && n.Length() > 0;

    entireF.left = mMtc.TickToPixel(event->StartTime()) - 2;
    entireF.right = mMtc.TickToPixel(phraseEnd) + 2;
    BRect				labelF = arp_invalid_rect();
    BRect				contentF = arp_invalid_rect();
    if (drawLabel) {
        if (entireF.Height() - 4 > labelH + 4) {
            labelF.Set(entireF.left + 2, entireF.top + 2, entireF.right - 2, entireF.bottom - 2);
            contentF = labelF;
            labelF.bottom = labelF.top + labelH - 1;
            contentF.top = labelF.bottom + 1;
        } else labelF.Set(entireF.left + 2, entireF.top + 2, entireF.right - 2, entireF.bottom - 2);
    } else contentF.Set(entireF.left + 2, entireF.top + 2, entireF.right - 2, entireF.bottom - 2);

    rgb_color			bgC = phrase->Color(phrase->BACKGROUND_C);
    rgb_color			fgC = phrase->Color(phrase->FOREGROUND_C);
    if (mDrawMuted) {
        bgC = shade_color(bgC, MUTE_SHADE);
        fgC = shade_color(fgC, MUTE_SHADE);
    }
    if (arp_is_valid_rect(contentF) ) {
        /* Fill the background.
         */
        if (!mDrawMuted) {
            view->SetHighColor(bgC);
            view->FillRect(contentF);
        }
        /* Draw the measure markers.
         */
        AmTrackMeasureBackground		bg(mSongRef, AmTrackRef(track), mMtc);
        if (mDrawMuted) bg.SetFlag(bg.DRAW_BEATS_FLAG, false);
        else {
            rgb_color	c = weighted_shade(bgC, Prefs().Color(AM_MEASURE_FG_C), 5);
            bg.SetBeatColor(c);
        }
        bg.LockedDraw(view, contentF, track->Signatures() );
    }

    mLines.BeginLineArray();
    if (arp_is_valid_rect(labelF) ) {
        rgb_color	c = weighted_shade(bgC, fgC, 3);
        view->SetHighColor(c);
        view->SetLowColor(c);
        view->FillRect(labelF);
        draw_label_border(view, labelF, c, mLines, mDrawMuted, !arp_is_valid_rect(contentF));
        view->SetHighColor(Prefs().Color(AM_MEASURE_FG_C) );
        BPoint		pt(labelF.left + 2, labelF.bottom - 2);
        if (arp_is_valid_rect(contentF) ) pt.y -= 2;
        view->TruncateString(&n, B_TRUNCATE_END, labelF.Width() );
        view->DrawString(n.String(), pt);
    }

    /* Shade the background.
     */
    rgb_color		c;
    c.red = c.green = c.blue = 0;
    if (mDrawMuted) c = shade_color(c, MUTE_SHADE);
    mLines.AddLine(BPoint(entireF.left + 1, entireF.top), BPoint(entireF.right - 1, entireF.top), c);
    mLines.AddLine(BPoint(entireF.left + 1, entireF.bottom), BPoint(entireF.right - 1, entireF.bottom), c);
    mLines.AddLine(BPoint(entireF.left, entireF.top + 1), BPoint(entireF.left, entireF.bottom - 1), c);
    mLines.AddLine(BPoint(entireF.right, entireF.top + 1), BPoint(entireF.right, entireF.bottom - 1), c);

    if (arp_is_valid_rect(contentF) ) {
        draw_content_border(view, contentF, bgC, mLines, mDrawMuted, !arp_is_valid_rect(labelF));
    }

    c = tint_color(Prefs().Color(AM_DATA_BACKDROP_C), B_DARKEN_1_TINT);
    if (mDrawMuted) c = shade_color(c, MUTE_SHADE);
    if (!gPhraseBg) {
        mLines.AddLine(BPoint(entireF.right + 1, entireF.top + 2), BPoint(entireF.right + 1, entireF.bottom + 0), c);
        mLines.AddLine(BPoint(entireF.left + 2, entireF.bottom + 1), BPoint(entireF.right + 0, entireF.bottom + 1), c);
        mLines.AddLine(BPoint(entireF.right + 0, entireF.bottom + 0), BPoint(entireF.right + 0, entireF.bottom + 0), c);
    }

    /* Indicate if this phrase is linked.
     */
    if (phrase->CountLinks() > 0) {
        view->SetHighColor(bgC);
        view->SetLowColor(0, 0, 0);
        view->StrokeRect(entireF, LINK_PATTERN);
    }

    if (arp_is_valid_rect(contentF) ) {
        /* Draw the events.
         */
        if (renderer) {
            BRect					trackR(clip.left, contentF.top, clip.right, contentF.bottom);
            view->SetHighColor(fgC);
            renderer->BeginTrack(trackR, view, track, mLines);
            renderer->DrawPhrase(contentF, view, track, event, end < phraseEnd ? end : phraseEnd, topPhrase, mLines);
            renderer->EndTrack(trackR, view, track, mLines);
        }
    }
    /* Finish.
     */
    mLines.EndLineArray();
}
/*
* Given a single line of the output of db_delta.py
* Figures out what to do and does it.
* (adds and removes files and directories)
*/
int
App::parse_command(BString command)
{
  command.RemoveAll("\n"); //remove trailing whitespace
  if(command.Compare("RESET") == 0)
  {
    printf("Burn Everything. 8D\n");

    status_t err = stop_watching(be_app_messenger);
    if(err != B_OK) printf("stop_watching error: %s\n",strerror(err));

    BDirectory dir = BDirectory(local_path_string);
    rm_rf(&dir);

    BString str = BString("/"); //create_local_path wants a remote path 
    create_local_directory(&str);

    this->recursive_watch(&dir);
  }
  else if(command.Compare("FILE ",5) == 0)
  {
    BString path, dirpath, partial_path;
    BPath *bpath;
    int32 last_space = command.FindLast(" ");
    command.CopyInto(path,5,last_space - 5);

    path.CopyInto(dirpath,0,path.FindLast("/"));

    create_local_directory(&dirpath);
    //TODO fix watching new dirs
    bpath = new BPath(db_to_local_filepath(path.String()).String());
    BEntry new_file = BEntry(bpath->Path());
    if(new_file.InitCheck() && new_file.Exists()) {
      this->new_paths.AddItem((void*)bpath);
    } else {
      this->edited_paths.AddItem((void*)bpath);
    }

    printf("create a file at |%s|\n",path.String());
    char *argv[3];
    argv[0] = "db_get.py";
    char not_const1[path.CountChars() + 1];
    strcpy(not_const1,path.String());
    argv[1] = not_const1;
    BString tmp = db_to_local_filepath(path.String());
    char not_const2[tmp.CountChars() + 1]; //plus one for null
    strcpy(not_const2,tmp.String());
    argv[2] = not_const2;

    //create/update file
    //potential problem: takes awhile to do this step
    // having watching for dir turned off is risky.    
    BString * b = run_python_script(argv,3);
    delete b;

    //start watching the new/updated file
    node_ref nref;
    new_file = BEntry(db_to_local_filepath(path.String()).String());
    new_file.GetNodeRef(&nref);
    status_t err = watch_node(&nref,B_WATCH_STAT,be_app_messenger);

    BString parent_rev;
    command.CopyInto(parent_rev,last_space + 1, command.CountChars() - (last_space+1));
    BNode node = BNode(db_to_local_filepath(path.String()).String());
    set_parent_rev(&node,&parent_rev);
  }
  else if(command.Compare("FOLDER ",7) == 0)
  {
    BString path;
    command.CopyInto(path,7,command.FindLast(" ") - 7);

    //ignore the creation message
    BPath bpath = BPath(db_to_local_filepath(path.String()).String());
    BPath *actually_exists = find_existing_subpath(&bpath);
    this->new_paths.AddItem((void*)actually_exists);

    //create all nescessary dirs in path
    printf("create a folder at |%s|\n", path.String());
    create_local_directory(&path);

    //start watching the new dir
    BDirectory existing_dir = BDirectory(actually_exists->Path());
    recursive_watch(&existing_dir);
  }
  else if(command.Compare("REMOVE ",7) == 0)
  {
    //TODO: deal with Dropbox file paths being case-insensitive
    //which here means all lower case
    BString path;
    command.CopyInto(path,7,command.Length() - 7);

    const char * pathstr = db_to_local_filepath(path.String()).String();
    BPath *bpath = new BPath(pathstr);
    //TODO: check if it exists...
    this->removed_paths.AddItem((void*)bpath);

    printf("Remove whatever is at |%s|\n", pathstr);

    BEntry entry = BEntry(pathstr);
    status_t err = entry.Remove();
    if(err != B_OK)
      printf("Removal error: %s\n", strerror(err));
  }
  else
  {
    printf("Did not recognize command.\n");
    return B_ERROR;
  }
  return B_OK;
}
Example #21
0
void FoldLineAtWhiteSpaceAndAddCRLF (BString &string)
{
	int			inputLength = string.Length();
	int			lineStartIndex;
	const int	maxLineLength = 78; // Doesn't include CRLF.
	BString		output;
	int			splitIndex;
	int			tempIndex;

	lineStartIndex = 0;
	while (true) {
		// If we don't need to wrap the text, just output the remainder, if any.

		if (lineStartIndex + maxLineLength >= inputLength) {
			if (lineStartIndex < inputLength) {
				output.Insert (string, lineStartIndex /* source offset */,
					inputLength - lineStartIndex /* count */,
					output.Length() /* insert at */);
				output.Append (CRLF);
			}
			break;
		}

		// Look ahead for a convenient spot to split it, between a comma and
		// space, which you often see between e-mail addresses like this:
		// "Joe Who" [email protected], "Someone Else" [email protected]

		tempIndex = lineStartIndex + maxLineLength;
		if (tempIndex > inputLength)
			tempIndex = inputLength;
		splitIndex = string.FindLast (", ", tempIndex);
		if (splitIndex >= lineStartIndex)
			splitIndex++; // Point to the space character.

		// If none of those exist, try splitting at any white space.

		if (splitIndex <= lineStartIndex)
			splitIndex = string.FindLast (" ", tempIndex);
		if (splitIndex <= lineStartIndex)
			splitIndex = string.FindLast ("\t", tempIndex);

		// If none of those exist, allow for a longer word - split at the next
		// available white space.

		if (splitIndex <= lineStartIndex)
			splitIndex = string.FindFirst (" ", lineStartIndex + 1);
		if (splitIndex <= lineStartIndex)
			splitIndex = string.FindFirst ("\t", lineStartIndex + 1);

		// Give up, the whole rest of the line can't be split, just dump it
		// out.

		if (splitIndex <= lineStartIndex) {
			if (lineStartIndex < inputLength) {
				output.Insert (string, lineStartIndex /* source offset */,
					inputLength - lineStartIndex /* count */,
					output.Length() /* insert at */);
				output.Append (CRLF);
			}
			break;
		}

		// Do the split.  The current line up to but not including the space
		// gets output, followed by a CRLF.  The space remains to become the
		// start of the next line (and that tells the message reader that it is
		// a continuation line).

		output.Insert (string, lineStartIndex /* source offset */,
			splitIndex - lineStartIndex /* count */,
			output.Length() /* insert at */);
		output.Append (CRLF);
		lineStartIndex = splitIndex;
	}
	string.SetTo (output);
}
Example #22
0
_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(), &regs)) >= 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);
}
Example #23
0
void
TemplateWindow::CheckTemplates(void)
{
	// This checks for the Templates folder in the Paladin application directory
	// and if it doesn't exist or it's empty, we make sure that it exists and
	// at least has empty project templates for each of the four basic types of projects
	
	DPath templatePath(gAppPath.GetFolder());
	templatePath << "Templates";
	
	bool needInit = false;
	if (!BEntry(templatePath.GetFullPath()).Exists())
		needInit = true;
	
	if (!needInit)
	{
		BDirectory dir(templatePath.GetFullPath());
		if (dir.CountEntries() == 0)
			needInit = true;
	}
	
	if (needInit)
	{
		create_directory(templatePath.GetFullPath(),0777);
		
		DPath tpath(templatePath);
		BFile file;
		BString filedata;
		
		tpath.Append("Addon");
		create_directory(tpath.GetFullPath(),0777);
		tpath.Append("TEMPLATEINFO");
		file.SetTo(tpath.GetFullPath(), B_READ_WRITE | B_CREATE_FILE);
		filedata = "TYPE=Shared\n";
		file.Write(filedata.String(),filedata.Length());
		
		tpath = templatePath;
		tpath.Append("Empty Application");
		create_directory(tpath.GetFullPath(),0777);
		tpath.Append("TEMPLATEINFO");
		file.SetTo(tpath.GetFullPath(), B_READ_WRITE | B_CREATE_FILE);
		filedata = "TYPE=Application\n";
		file.Write(filedata.String(),filedata.Length());
		
		tpath = templatePath;
		tpath.Append("Kernel Driver");
		create_directory(tpath.GetFullPath(),0777);
		tpath.Append("TEMPLATEINFO");
		file.SetTo(tpath.GetFullPath(), B_READ_WRITE | B_CREATE_FILE);
		filedata = "TYPE=Driver\n";
		file.Write(filedata.String(),filedata.Length());
		
		tpath = templatePath;
		tpath.Append("Shared Library");
		create_directory(tpath.GetFullPath(),0777);
		tpath.Append("TEMPLATEINFO");
		file.SetTo(tpath.GetFullPath(), B_READ_WRITE | B_CREATE_FILE);
		filedata = "TYPE=Shared\n";
		file.Write(filedata.String(),filedata.Length());
		
		tpath = templatePath;
		tpath.Append("Static Library");
		create_directory(tpath.GetFullPath(),0777);
		tpath.Append("TEMPLATEINFO");
		file.SetTo(tpath.GetFullPath(), B_READ_WRITE | B_CREATE_FILE);
		filedata = "TYPE=Static\n";
		file.Write(filedata.String(),filedata.Length());
		
	}
}
Example #24
0
status_t ExportContext::writeString(
	const BString&							string) {

	return writeString(string.String(), string.Length());
}
Example #25
0
status_t
TTracker::OpenRef(const entry_ref *ref, const node_ref *nodeToClose,
	const node_ref *nodeToSelect, OpenSelector selector,
	const BMessage *messageToBundle)
{
	Model *model = NULL;
	BEntry entry(ref, true);
	status_t result = entry.InitCheck();

	bool brokenLinkWithSpecificHandler = false;
	BString brokenLinkPreferredApp;

	if (result != B_OK) {
		model = new Model(ref, false);
		if (model->IsSymLink() && !model->LinkTo()) {
			model->GetPreferredAppForBrokenSymLink(brokenLinkPreferredApp);
			if (brokenLinkPreferredApp.Length() && brokenLinkPreferredApp != kTrackerSignature)
				brokenLinkWithSpecificHandler = true;
		}

		if (!brokenLinkWithSpecificHandler) {
			delete model;
			(new BAlert("", "There was an error resolving the link.",
				"Cancel", 0, 0,
				B_WIDTH_AS_USUAL, B_WARNING_ALERT))->Go();
			return result;
		}
	} else 
		model = new Model(&entry);

	result = model->InitCheck();
	if (result != B_OK) {
		delete model;
		return result;
	}

	bool openAsContainer = model->IsContainer();

	if (openAsContainer && selector != kOpenWith) {
		// if folder or query has a preferred handler and it's not the
		// Tracker, open it by sending refs to the handling app

		// if we are responding to the final open of OpenWith, just
		// skip this and proceed to opening the container with Tracker
		model->OpenNode();
		BNodeInfo nodeInfo(model->Node());
		char preferredApp[B_MIME_TYPE_LENGTH];
		if (nodeInfo.GetPreferredApp(preferredApp) == B_OK
			&& strcasecmp(preferredApp, kTrackerSignature) != 0)
			openAsContainer = false;
		model->CloseNode();
	}

	if (openAsContainer || selector == kRunOpenWithWindow) {
		// special case opening plain folders, queries or using open with
		OpenContainerWindow(model, 0, selector);	// window adopts model
		if (nodeToClose)
			CloseParentWaitingForChildSoon(ref, nodeToClose);
	} else if (model->IsQueryTemplate()) {
		// query template - open new find window
		(new FindWindow(model->EntryRef()))->Show();
		if (nodeToClose)
			CloseParentWaitingForChildSoon(ref, nodeToClose);
	} else {
		delete model;
		// run Launch in a separate thread
		// and close parent if successfull
		if (nodeToClose)
			Thread::Launch(new EntryAndNodeDoSoonWithMessageFunctor<TTracker,
				bool (TTracker::*)(const entry_ref *, const node_ref *,
				const BMessage *)>(&TTracker::LaunchAndCloseParentIfOK, this,
				ref, nodeToClose, messageToBundle));
		else {
			BMessage refsReceived(B_REFS_RECEIVED);
			if (messageToBundle) {
				refsReceived = *messageToBundle;
				refsReceived.what = B_REFS_RECEIVED;
			}
			refsReceived.AddRef("refs", ref);
			if (brokenLinkWithSpecificHandler)
				// This cruft is to support a hacky workaround for double-clicking
				// broken refs for cifs; should get fixed in R5
				LaunchBrokenLink(brokenLinkPreferredApp.String(), &refsReceived);
			else
				TrackerLaunch(&refsReceived, true);
		}
	}
	if (nodeToSelect)
		SelectChildInParentSoon(ref, nodeToSelect);

	return B_OK;
}
Example #26
0
status_t
WidgetAttributeText::AttrAsString(const Model* model, BString* outString,
	const char* attrName, int32 attrType, float width, BView* view,
	int64* resultingValue)
{
	int64 value;

	status_t error = model->InitCheck();
	if (error != B_OK)
		return error;

	switch (attrType) {
		case B_TIME_TYPE:
			if (strcmp(attrName, kAttrStatModified) == 0)
				value = model->StatBuf()->st_mtime;
			else if (strcmp(attrName, kAttrStatCreated) == 0)
				value = model->StatBuf()->st_crtime;
			else {
				TRESPASS();
				// not yet supported
				return B_ERROR;
			}
			TruncTimeBase(outString, value, view, width);
			if (resultingValue)
				*resultingValue = value;

			return B_OK;

		case B_STRING_TYPE:
			if (strcmp(attrName, kAttrPath) == 0) {
				BEntry entry(model->EntryRef());
				BPath path;
				BString tmp;

				if (entry.InitCheck() == B_OK
					&& entry.GetPath(&path) == B_OK) {
					tmp = path.Path();
					TruncateLeaf(&tmp);
				} else
					tmp = "-";

				if (width > 0) {
					TruncStringBase(outString, tmp.String(), tmp.Length(), view,
						width);
				} else
					*outString = tmp.String();

				return B_OK;
			}
			break;

		case kSizeType:
//			TruncFileSizeBase(outString, model->StatBuf()->st_size, view,
//				width);
			return B_OK;
			break;

		default:
			TRESPASS();
			// not yet supported
			return B_ERROR;

	}

	TRESPASS();
	return B_ERROR;
}
Example #27
0
int32 VisionApp::ThreadStates(void)
{
	thread_id team(Team());
	int32 cookie(0);
	thread_info info;

	BString buffer;
	int32 t_count(0);

	while (get_next_thread_info(team, &cookie, &info) == B_NO_ERROR) {
		// wake up any threads that're snoozing for their next reconnect run
		if (strstr(info.name, "s>") != NULL) {
			switch (info.state) {
			case B_THREAD_ASLEEP:
				suspend_thread(info.thread);
			// fall through
			case B_THREAD_SUSPENDED:
				resume_thread(info.thread);
				break;
			default:
				break;
			}
		}

		if (fDebugShutdown) {
			buffer += "thread: ";
			buffer << info.thread;
			buffer += " name:  ";
			buffer += info.name;
			buffer += " state: ";

			switch ((int32)info.state) {
			case B_THREAD_RUNNING:
				buffer += "running\n";
				break;

			case B_THREAD_READY:
				buffer += "ready\n";
				break;

			case B_THREAD_RECEIVING:
				buffer += "receiving\n";
				break;

			case B_THREAD_ASLEEP:
				buffer += "asleep\n";
				break;

			case B_THREAD_SUSPENDED:
				buffer += "suspended\n";
				break;

			case B_THREAD_WAITING:
				buffer += "waiting\n";
				break;

			default:
				buffer += "???\n";
			}
		}
		++t_count;
	}

	if (fDebugShutdown && buffer.Length()) {
		printf("%s\n", buffer.String());
#if 0
    BAlert *alert (new BAlert (
      "Too many threads",
      buffer.String(),
      t_count > 1 ? "Damn" : "Cool",
      0,
      0,
      B_WIDTH_AS_USUAL,
      t_count > 1 ? B_STOP_ALERT : B_INFO_ALERT));
      alert->Go();
#endif
	}

	return t_count;
}
Example #28
0
status_t
DwarfImageDebugInfo::GetFunctions(const BObjectList<SymbolInfo>& symbols,
	BObjectList<FunctionDebugInfo>& functions)
{
	TRACE_IMAGES("DwarfImageDebugInfo::GetFunctions()\n");
	TRACE_IMAGES("  %" B_PRId32 " compilation units\n",
		fFile->CountCompilationUnits());

	for (int32 i = 0; CompilationUnit* unit = fFile->CompilationUnitAt(i);
			i++) {
		DIECompileUnitBase* unitEntry = unit->UnitEntry();
//		printf("  %s:\n", unitEntry->Name());
//		printf("    address ranges:\n");
//		TargetAddressRangeList* rangeList = unitEntry->AddressRanges();
//		if (rangeList != NULL) {
//			int32 count = rangeList->CountRanges();
//			for (int32 i = 0; i < count; i++) {
//				TargetAddressRange range = rangeList->RangeAt(i);
//				printf("      %#llx - %#llx\n", range.Start(), range.End());
//			}
//		} else {
//			printf("      %#llx - %#llx\n", (target_addr_t)unitEntry->LowPC(),
//				(target_addr_t)unitEntry->HighPC());
//		}

//		printf("    functions:\n");
		for (DebugInfoEntryList::ConstIterator it
					= unitEntry->OtherChildren().GetIterator();
				DebugInfoEntry* entry = it.Next();) {
			if (entry->Tag() != DW_TAG_subprogram)
				continue;

			DIESubprogram* subprogramEntry = static_cast<DIESubprogram*>(entry);

			// ignore declarations and inlined functions
			if (subprogramEntry->IsDeclaration()
				|| subprogramEntry->Inline() == DW_INL_inlined
				|| subprogramEntry->Inline() == DW_INL_declared_inlined) {
				continue;
			}

			// get the name
			BString name;
			DwarfUtils::GetFullyQualifiedDIEName(subprogramEntry, name);
			if (name.Length() == 0)
				continue;

			// get the address ranges
			TargetAddressRangeList* rangeList = fFile->ResolveRangeList(unit,
				subprogramEntry->AddressRangesOffset());
			if (rangeList == NULL) {
				target_addr_t lowPC = subprogramEntry->LowPC();
				target_addr_t highPC = subprogramEntry->HighPC();
				if (highPC <= lowPC)
					continue;

				rangeList = new(std::nothrow) TargetAddressRangeList(
					TargetAddressRange(lowPC, highPC - lowPC));
				if (rangeList == NULL)
					return B_NO_MEMORY;
						// TODO: Clean up already added functions!
			}
			BReference<TargetAddressRangeList> rangeListReference(rangeList,
				true);

			// get the source location
			const char* directoryPath = NULL;
			const char* fileName = NULL;
			int32 line = -1;
			int32 column = -1;
			DwarfUtils::GetDeclarationLocation(fFile, subprogramEntry,
				directoryPath, fileName, line, column);

			LocatableFile* file = NULL;
			if (fileName != NULL) {
				file = fFileManager->GetSourceFile(directoryPath,
					fileName);
			}
			BReference<LocatableFile> fileReference(file, true);

			// create and add the functions
			DwarfFunctionDebugInfo* function
				= new(std::nothrow) DwarfFunctionDebugInfo(this, unit,
					subprogramEntry, rangeList, name, file,
					SourceLocation(line, std::max(column, (int32)0)));
			if (function == NULL || !functions.AddItem(function)) {
				delete function;
				return B_NO_MEMORY;
					// TODO: Clean up already added functions!
			}

//			BString name;
//			DwarfUtils::GetFullyQualifiedDIEName(subprogramEntry, name);
//			printf("      subprogram entry: %p, name: %s, declaration: %d\n",
//				subprogramEntry, name.String(),
//				subprogramEntry->IsDeclaration());
//
//			rangeList = subprogramEntry->AddressRanges();
//			if (rangeList != NULL) {
//				int32 count = rangeList->CountRanges();
//				for (int32 i = 0; i < count; i++) {
//					TargetAddressRange range = rangeList->RangeAt(i);
//					printf("        %#llx - %#llx\n", range.Start(), range.End());
//				}
//			} else {
//				printf("        %#llx - %#llx\n",
//					(target_addr_t)subprogramEntry->LowPC(),
//					(target_addr_t)subprogramEntry->HighPC());
//			}
		}
	}

	if (fFile->CountCompilationUnits() != 0)
		return B_OK;

	// if we had no compilation units, fall back to providing basic
	// debug infos with DWARF-supported call frame unwinding,
	// if available.
	if (fFile->HasFrameInformation()) {
		return SpecificImageDebugInfo::GetFunctionsFromSymbols(symbols,
			functions, fDebuggerInterface, fImageInfo, this);
	}

	return B_OK;
}
Example #29
0
void ChannelAgent::TabExpansion(void)
{
	/*
	 * Function purpose: Get the characters before the caret's current position,
	 *                   and update the fInput VTextControl with a relevant match
	 *                   from the ChannelAgent's NamesView
	 */

	int32 start, finish;
	static int32 lastindex;
	static BString lastNick;
	fInput->TextView()->GetSelection(&start, &finish);

	if (fInput->TextView()->TextLength() && start == finish &&
		start == fInput->TextView()->TextLength()) {
		const char* fInputText(fInput->TextView()->Text() + fInput->TextView()->TextLength());
		const char* place(fInputText);

		while (place > fInput->TextView()->Text()) {
			if (*(place - 1) == '\x20') break;

			--place;
		}

		if (fLastExpansion.Length() == 0 ||
			fLastExpansion.ICompare(place, fLastExpansion.Length()) != 0 || lastNick != place) {
			lastindex = 0;
			fLastExpansion = place;

			while (!fCompletionNicks.IsEmpty()) delete fCompletionNicks.RemoveItemAt(0L);

			int32 count(fNamesList->CountItems()), i(0);

			for (i = 0; i < count; i++) {
				BString* name(new BString(static_cast<NameItem*>(fNamesList->ItemAt(i))->Name()));
				if (!(name->ICompare(fLastExpansion.String(), strlen(fLastExpansion.String()))))
					fCompletionNicks.AddItem(name);
				else
					delete name;
			}
			// sort items alphabetically
			fCompletionNicks.SortItems(AlphaSortNames);

			count = fRecentNicks.CountItems();
			// parse recent nicks in reverse to ensure that they're pushed onto the completion
			// list in the correct order
			for (i = 0; i < count; i++) {
				BString* name(new BString(*fRecentNicks.ItemAt(i)));
				if (!(name->ICompare(fLastExpansion.String(), strlen(fLastExpansion.String())))) {
					// parse through list and nuke duplicate if present
					for (int32 j = fCompletionNicks.CountItems() - 1; j >= 0; j--) {
						if (!(name->ICompare(*fCompletionNicks.ItemAt(j)))) {
							delete fCompletionNicks.RemoveItemAt(j);
							break;
						}
					}
					fCompletionNicks.AddItem(name, 0);
				} else
					delete name;
			}
		}

		// We first check if what the user typed matches the channel
		// If that doesn't match, we check the names
		BString insertion;

		if (!fId.ICompare(place, strlen(place)))
			insertion = fId;
		else {
			int32 count = fCompletionNicks.CountItems();
			if (count > 0) {
				insertion = *(fCompletionNicks.ItemAt(lastindex++));

				if (lastindex == count) lastindex = 0;
				lastNick = insertion;
			}
		}

		if (insertion.Length()) {
// check if we are at the beginning of a line
// (ignoring whitespace). if we are, prepend a colon to the nick being
// inserted
#if 0
      const char *place2 = place;
      while (place2 > fInput->TextView()->Text())
      {
        --place2;
        if (*place2 != 0x20)
          break;
      }
      if (place2 == fInput->TextView()->Text())
	insertion += ": ";
#endif
			fInput->TextView()->Delete(place - fInput->TextView()->Text(),
									   fInput->TextView()->TextLength());

			fInput->TextView()->Insert(insertion.String());
			fInput->TextView()->Select(fInput->TextView()->TextLength(),
									   fInput->TextView()->TextLength());
		}
	}
}
Example #30
0
int32 VisionApp::Identity(void*)
{
	int32 identSock(0), accepted(0);
	BString ident;
	char received[64];

	struct sockaddr_in localAddr;
	localAddr.sin_family = AF_INET;
	localAddr.sin_port = htons(113);
	localAddr.sin_addr.s_addr = INADDR_ANY;

	if ((identSock = socket(AF_INET, SOCK_STREAM, 0)) >= 0 &&
		bind(identSock, (struct sockaddr*)&localAddr, sizeof(localAddr)) == 0) {
		vision_app->fIdentSocket = identSock;

		struct linger lng = {0, 0};
		setsockopt(identSock, SOL_SOCKET, SO_LINGER, &lng, sizeof(linger));
		listen(identSock, 1);

		while (!vision_app->fShuttingDown) {
			struct fd_set rset, eset;
			struct sockaddr_in remoteSock;
			int size(sizeof(sockaddr_in));
			struct timeval tv = {10, 0};
			FD_ZERO(&rset);
			FD_ZERO(&eset);
			FD_SET(identSock, &rset);
			FD_SET(identSock, &eset);

			if (select(identSock + 1, &rset, 0, &eset, NULL) < 0 || FD_ISSET(identSock, &eset))
				break;
			else if (FD_ISSET(identSock, &rset)) {
				accepted = accept(identSock, (struct sockaddr*)&remoteSock, (socklen_t*)&size);
				if (accepted >= 0) {
					FD_ZERO(&rset);
					FD_ZERO(&eset);

					BString remoteIP(inet_ntoa(remoteSock.sin_addr));
					ident = vision_app->GetIdent(remoteIP.String());

					if (ident.Length() > 0) {
						memset(received, 0, 64);
						FD_SET(accepted, &rset);
						FD_SET(accepted, &eset);
						if (select(accepted + 1, &rset, 0, &eset, &tv) > 0 &&
							FD_ISSET(accepted, &rset) && !FD_ISSET(accepted, &eset)) {

							recv(accepted, received, 64, 0);
							int32 len(0);

							received[63] = 0;
							while ((len = strlen(received)) && isspace(received[len - 1]))
								received[len - 1] = 0;

							BString string;

							string.Append(received);
							string.Append(" : USERID : BeOS : ");
							string.Append(ident);
							string.Append("\r\n");

							send(accepted, string.String(), string.Length(), 0);
						}
					} else {
						BString string("0 , 0 : UNKNOWN : UNKNOWN-ERROR");
						send(accepted, string.String(), string.Length(), 0);
					}
					close(accepted);
				}
			}
		}
	}

	close(identSock);
	return 0;
}