コード例 #1
0
status_t
WebAppInterface::_SendJsonRequest(BString jsonString, BMessage& reply) const
{
    BUrl url("https://depot.haiku-os.org/api/v1/pkg");

    ProtocolListener listener;
    BUrlContext context;
    BHttpHeaders headers;
    // Content-Type
    headers.AddHeader("Content-Type", "application/json");
    headers.AddHeader("User-Agent", "X-HDS-Client");

    BHttpRequest request(url, true, "HTTP", &listener, &context);

    // Authentication
    if (!fUsername.IsEmpty() && !fPassword.IsEmpty()) {
        request.SetUserName(fUsername);
        request.SetPassword(fPassword);
    }

    request.SetMethod(B_HTTP_POST);
    request.SetHeaders(headers);

    BMemoryIO* data = new BMemoryIO(
        jsonString.String(), jsonString.Length() - 1);

    request.AdoptInputData(data, jsonString.Length() - 1);

    BMallocIO replyData;
    listener.SetDownloadIO(&replyData);
//	listener.SetDebug(true);

    thread_id thread = request.Run();
    wait_for_thread(thread, NULL);

    const BHttpResult& result = dynamic_cast<const BHttpResult&>(
                                    request.Result());

    int32 statusCode = result.StatusCode();
    if (statusCode != 200) {
        printf("Response code: %" B_PRId32 "\n", statusCode);
        return B_ERROR;
    }

    jsonString.SetTo(static_cast<const char*>(replyData.Buffer()),
                     replyData.BufferLength());
    if (jsonString.Length() == 0)
        return B_ERROR;

    BJson parser;
    status_t status = parser.Parse(reply, jsonString);
    if (status == B_BAD_DATA) {
//		printf("Parser choked on JSON:\n%s\n", jsonString.String());
    }
    return status;
}
コード例 #2
0
ファイル: RDefExporter.cpp プロジェクト: yunxiaoxiao110/haiku
// Export
status_t
RDefExporter::Export(const Icon* icon, BPositionIO* stream)
{
    BMallocIO buffer;
    status_t ret = FlatIconExporter::Export(icon, &buffer);
    if (ret < B_OK)
        return ret;

    return _Export((const uint8*)buffer.Buffer(), buffer.BufferLength(), stream);
}
コード例 #3
0
ファイル: ServerPicture.cpp プロジェクト: simonsouth/haiku
void
ServerPicture::Play(DrawingContext* target)
{
	// TODO: for now: then change PicturePlayer
	// to accept a BPositionIO object
	BMallocIO* mallocIO = dynamic_cast<BMallocIO*>(fData);
	if (mallocIO == NULL)
		return;

	BPrivate::PicturePlayer player(mallocIO->Buffer(),
		mallocIO->BufferLength(), PictureList::Private(fPictures).AsBList());
	player.Play(kPicturePlayerCallbacks, sizeof(kPicturePlayerCallbacks),
		target);
}
コード例 #4
0
ファイル: ServerPicture.cpp プロジェクト: mmanley/Antares
void
ServerPicture::Play(View* view)
{
	// TODO: for now: then change PicturePlayer
	// to accept a BPositionIO object
	BMallocIO* mallocIO = dynamic_cast<BMallocIO*>(fData);
	if (mallocIO == NULL)
		return;

	BPrivate::PicturePlayer player(mallocIO->Buffer(),
		mallocIO->BufferLength(), fPictures->AsBList());
	player.Play(const_cast<void**>(kTableEntries),
		sizeof(kTableEntries) / sizeof(void*), view);
}
コード例 #5
0
BEmailMessage *
BEmailMessage::ForwardMessage(bool accountFromMail, bool includeAttachments)
{
	BString header = "------ Forwarded Message: ------\n";
	header << "To: " << To() << '\n';
	header << "From: " << From() << '\n';
	if (CC() != NULL) {
		// Can use CC rather than "Cc" since display only.
		header << "CC: " << CC() << '\n';
	}
	header << "Subject: " << Subject() << '\n';
	header << "Date: " << Date() << "\n\n";
	if (_text_body != NULL)
		header << _text_body->Text() << '\n';
	BEmailMessage *message = new BEmailMessage();
	message->SetBodyTextTo(header.String());

	// set the subject
	BString subject = Subject();
	if (subject.IFindFirst("fwd") == B_ERROR
		&& subject.IFindFirst("forward") == B_ERROR
		&& subject.FindFirst("FW") == B_ERROR)
		subject << " (fwd)";
	message->SetSubject(subject.String());

	if (includeAttachments) {
		for (int32 i = 0; i < CountComponents(); i++) {
			BMailComponent *cmpt = GetComponent(i);
			if (cmpt == _text_body || cmpt == NULL)
				continue;

			//---I am ashamed to have the written the code between here and the next comment
			// ... and you still managed to get it wrong ;-)), axeld.
			// we should really move this stuff into copy constructors
			// or something like that

			BMallocIO io;
			cmpt->RenderToRFC822(&io);
			BMailComponent *clone = cmpt->WhatIsThis();
			io.Seek(0, SEEK_SET);
			clone->SetToRFC822(&io, io.BufferLength(), true);
			message->AddComponent(clone);
		}
	}
	if (accountFromMail)
		message->SendViaAccountFrom(this);

	return message;
}
コード例 #6
0
/*!	\brief Delivers a message to the supplied targets.

	The method tries to send the message right now to each of the given targets
	(if there are not already messages pending for a target port). If that
	fails due to a full target port, the message is queued for later delivery.

	\param message The message to be delivered.
	\param targets MessagingTargetSet providing the the delivery targets.
	\param timeout If given, the message will be dropped, when it couldn't be
		   delivered after this amount of microseconds.
	\return
	- \c B_OK, if for each of the given targets sending the message succeeded
	  or if the target port was full and the message has been queued,
	- another error code otherwise.
*/
status_t
MessageDeliverer::DeliverMessage(BMessage *message, MessagingTargetSet &targets,
	bigtime_t timeout)
{
	if (!message)
		return B_BAD_VALUE;

	// flatten the message
	BMallocIO mallocIO;
	status_t error = message->Flatten(&mallocIO, NULL);
	if (error < B_OK)
		return error;

	return DeliverMessage(mallocIO.Buffer(), mallocIO.BufferLength(), targets,
		timeout);
}
コード例 #7
0
ファイル: PictureTest.cpp プロジェクト: SummerSnail2014/haiku
BPicture *
FlattenPictureTest::SaveAndRestore(BPicture *picture)
{
	BMallocIO *data = new BMallocIO();
	AutoDelete<BMallocIO> _data(data);
	TEST_AND_RETURN(data == NULL, "BMallocIO could not be allocated for flattening the picture!" , NULL);
	
	picture->Flatten(data);
	
	data->Seek(0, SEEK_SET);
	BPicture *archivedPicture = new BPicture();
	TEST_AND_RETURN(archivedPicture == NULL, "BPicture could not be allocated for unflattening the picture!" , NULL);
	archivedPicture->Unflatten(data);
		
	return archivedPicture;
}
コード例 #8
0
status_t 
Shelf::SaveState(BMessage *state) const
{
	status_t status;

	PRINT(("%p:%s()\n", this, __FUNCTION__));
	state->PrintToStream();

	if (fInConfig)
		state->AddBool(kInConfigName, fInConfig);
	if (!fInConfig)
		state->RemoveData(kInConfigName);
	if (fInConfig && fShelf) {
		status = state->AddBool("got it", true);

		fShelf->LockLooper();
		status = fShelf->Save();
		fShelf->UnlockLooper();
		if (status < B_OK)
			return status;
		status = state->AddData(kShelfArchiveName, 'shlf', fShelfData.Buffer(), 
			fShelfData.BufferLength());

//		return B_OK;
//fShelfData.SetSize(0LL);
#if 0
		BMallocIO mio;
		status = fShelf->SetSaveLocation(&mio);
		if (status < B_OK)
			return status;
		status = fShelf->Save();
		fShelf->SetSaveLocation((BDataIO *)NULL);
		if (status < B_OK)
			return status;
		status = state->AddData(kShelfArchiveName, 'shlf', mio.Buffer(), 
			mio.BufferLength());
#endif
		if (status < B_OK)
			return status;
	}
	return B_OK;
}
コード例 #9
0
ファイル: download.cpp プロジェクト: pombredanne/NetSurf
void
NSDownloadWindow::MessageReceived(BMessage* message)
{
	switch(message->what)
	{
		case B_SAVE_REQUESTED:
		{
			entry_ref directory;
			const char* name;
			struct gui_download_window* dw;
			BFilePanel* source;

			message->FindRef("directory", &directory);
			message->FindString("name", &name);
			message->FindPointer("dw", (void**)&dw);

			BDirectory dir(&directory);
			BFile* storage = new BFile(&dir, name,
				B_WRITE_ONLY | B_CREATE_FILE | B_ERASE_FILE);
			dw->storageLock->Lock();

			BMallocIO* tempstore = dynamic_cast<BMallocIO*>(dw->storage);

			storage->Write(tempstore->Buffer(), tempstore->BufferLength());
			delete dw->storage;

			if (success)
				delete storage; // File is already finished downloading !
			else
				dw->storage = storage;
			dw->storageLock->Unlock();

			message->FindPointer("source", (void**)&source);
			delete source;			

			break;
		}
		default:
			BWindow::MessageReceived(message);
	}
}
コード例 #10
0
static size_t
mkColumnsBits(BMallocIO& stream, const ColumnData* src, int32 nelm,
	const char* context)
{
	for (int32 i = 0; i < nelm; i++) {
		BColumn c(
			B_TRANSLATE_CONTEXT(src[i].title, context),
			src[i].offset, src[i].width, src[i].align, src[i].attributeName,
			src[i].attrType, src[i].statField, src[i].editable);
		c.ArchiveToStream(&stream);
	}

	return stream.Position();
}
コード例 #11
0
ファイル: PictureTest.cpp プロジェクト: looncraz/haiku
void
PictureView::AllAttached()
{	
	BeginPicture(new BPicture);
	
	DrawStuff(this);

	BPicture *picture = EndPicture();
	if (picture == NULL)
		return;

	BMessage message;
	picture->Archive(&message);
	message.PrintToStream();

	BMallocIO stream;
	
	status_t status = picture->Flatten(&stream);
	delete picture;

	if (status != B_OK)
		printf("Error flattening BPicture: %s\n", strerror(status));
	
	if (status == B_OK) {
		stream.Seek(0, SEEK_SET);
		fPicture = new BPicture();
		status = fPicture->Unflatten(&stream);
		if (status != B_OK) {
			printf("Error unflattening BPicture: %s\n", strerror(status));
			return;
		}
	}

	BMessage message2;
	fPicture->Archive(&message2);
	message2.PrintToStream();
}
コード例 #12
0
ファイル: SSO.cpp プロジェクト: HaikuArchives/IMKit
int32 DeriveKey(const void *key, int32 keyLen, const uchar *magic, int32 magicLen, uchar **result) {
	uchar hash1[EVP_MAX_MD_SIZE];
	uchar hash2[EVP_MAX_MD_SIZE];
	uchar hash3[EVP_MAX_MD_SIZE];
	uchar hash4[EVP_MAX_MD_SIZE];
	unsigned int hash1Len = 0;
	unsigned int hash2Len = 0;
	unsigned int hash3Len = 0;
	unsigned int hash4Len = 0;
	int32 length = B_ERROR;
	BMallocIO temp;
	
	// HMAC-SHA1(magic)
	HMAC(EVP_sha1(), key, keyLen, magic, magicLen, hash1, &hash1Len);

	// Key 2 is HMAC-SHA1(HMAC-SHA1(magic) + magic)
	temp.Write(hash1, hash1Len);
	temp.Write(magic, magicLen);
	HMAC(EVP_sha1(), key, keyLen, (uchar *)temp.Buffer(), temp.BufferLength(), hash2, &hash2Len);

	// HMAC-SHA1(HMAC-SHA1(magic))
	HMAC(EVP_sha1(), key, keyLen, hash1, hash1Len, hash3, &hash3Len);
			
	// Clear the BMallocIO and reset the position to 0
	temp.SetSize(0);
	temp.Seek(0, SEEK_SET);

	// Key 4 is HMAC-SHA1(HMAC-SHA1(HMAC-SHA1(magic)) + magic)
	temp.Write(hash3, hash3Len);
	temp.Write(magic, magicLen);
	HMAC(EVP_sha1(), key, keyLen, (uchar *)temp.Buffer(), temp.BufferLength(), hash4, &hash4Len);

	// The key is Hash2 followed by the first four bytes of Hash4
	length = hash2Len + 4;
	*result = (uchar *)calloc(length, sizeof(uchar));

	memcpy(*result, hash2, hash2Len);
	memcpy(*result + hash2Len, hash4, 4);
	
	return length;
};
コード例 #13
0
/*
 * this method is not currently being used, but it may be useful in the
 * future...
 */
status_t
DefaultCatalog::WriteToAttribute(entry_ref *appOrAddOnRef)
{
	BNode node;
	status_t res = node.SetTo(appOrAddOnRef);
	if (res != B_OK)
		return res;

	BMallocIO mallocIO;
	mallocIO.SetBlockSize(max(fCatMap.Size() * 20, 256L));
		// set a largish block-size in order to avoid reallocs
	res = Flatten(&mallocIO);

	if (res == B_OK) {
		ssize_t wsz;
		wsz = node.WriteAttr(BLocaleRoster::kEmbeddedCatAttr, B_MESSAGE_TYPE, 0,
			mallocIO.Buffer(), mallocIO.BufferLength());
		if (wsz < B_OK)
			res = wsz;
		else if (wsz != (ssize_t)mallocIO.BufferLength())
			res = B_ERROR;
	}
	return res;
}
コード例 #14
0
status_t 
Shelf::StartSaver(BView *view, bool preview)
{
	PRINT(("%p:%s(, %d)\n", this, __FUNCTION__, preview));
	if (!preview) {
		view->SetViewColor(216, 216, 216, 0);
		fShelfData.Seek(SEEK_SET, 0LL);
		fShelf = new BShelf(&fShelfData, view);
		
	}
	BString s;
	s << "preview: " << preview << " ";
	s << "BView:Name: " << view->Name() << " ";
	s << "BApp:Name: " << be_app->Name();
	
	PRINT(("%p:%s:%s\n", this, __FUNCTION__, s.String()));
	//BAlert *a = new BAlert("debug", s.String(), "Ok");
	//a->Go();
	return B_ERROR;
#if 0
	float width = view->Bounds().Width();
	float height = view->Bounds().Height();
	
	BFont font;
	view->GetFont(&font);
	font.SetSize(height / 2.5);
	view->SetFont(&font);
	
	BRect rect;
	escapement_delta delta;
	delta.nonspace = 0;
	delta.space = 0;
	// If anyone has suggestions for how to clean this up, speak up
	font.GetBoundingBoxesForStrings(&fLine1, 1, B_SCREEN_METRIC, &delta, &rect);
	float y = ((height - (rect.Height() * 2 + height / 10)) / 2) + rect.Height();
	fLine1Start.Set((width - rect.Width()) / 2, y);
	font.GetBoundingBoxesForStrings(&fLine2, 1, B_SCREEN_METRIC, &delta, &rect);
	fLine2Start.Set((width - rect.Width()) / 2, y + rect.Height() + height / 10);
	
#endif
	return B_OK;
}
コード例 #15
0
ファイル: PictureView.cpp プロジェクト: AmirAbrams/haiku
void
PictureView::_HandleDrop(BMessage* msg)
{
	entry_ref dirRef;
	BString name, type;
	bool saveToFile = msg->FindString("be:filetypes", &type) == B_OK
		&& msg->FindRef("directory", &dirRef) == B_OK
		&& msg->FindString("name", &name) == B_OK;

	bool sendInMessage = !saveToFile
		&& msg->FindString("be:types", &type) == B_OK;

	if (!sendInMessage && !saveToFile)
		return;

	BBitmap* bitmap = fPicture;
	if (bitmap == NULL)
		return;

	BTranslatorRoster* roster = BTranslatorRoster::Default();
	if (roster == NULL)
		return;

	BBitmapStream stream(bitmap);

	// find translation format we're asked for
	translator_info* outInfo;
	int32 outNumInfo;
	bool found = false;
	translation_format format;

	if (roster->GetTranslators(&stream, NULL, &outInfo, &outNumInfo) == B_OK) {
		for (int32 i = 0; i < outNumInfo; i++) {
			const translation_format* formats;
			int32 formatCount;
			roster->GetOutputFormats(outInfo[i].translator, &formats,
					&formatCount);
			for (int32 j = 0; j < formatCount; j++) {
				if (strcmp(formats[j].MIME, type.String()) == 0) {
					format = formats[j];
					found = true;
					break;
				}
			}
		}
	}

	if (!found) {
		stream.DetachBitmap(&bitmap);
		return;
	}

	if (sendInMessage) {

		BMessage reply(B_MIME_DATA);
		BMallocIO memStream;
		if (roster->Translate(&stream, NULL, NULL, &memStream,
			format.type) == B_OK) {
			reply.AddData(format.MIME, B_MIME_TYPE, memStream.Buffer(),
				memStream.BufferLength());
			msg->SendReply(&reply);
		}

	} else {

		BDirectory dir(&dirRef);
		BFile file(&dir, name.String(), B_WRITE_ONLY | B_CREATE_FILE
			| B_ERASE_FILE);

		if (file.InitCheck() == B_OK
			&& roster->Translate(&stream, NULL, NULL, &file,
				format.type) == B_OK) {
			BNodeInfo nodeInfo(&file);
			if (nodeInfo.InitCheck() == B_OK)
				nodeInfo.SetType(type.String());
		} else {
			BString text = B_TRANSLATE("The file '%name%' could not "
				"be written.");
			text.ReplaceFirst("%name%", name);
			BAlert* alert = new BAlert(B_TRANSLATE("Error"), text.String(),
				B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT);
			alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
			alert->Go();
		}
	}

	// Detach, as we don't want our fPicture to be deleted
	stream.DetachBitmap(&bitmap);
}
コード例 #16
0
void 
MallocBufferLengthTest::PerformTest(void)
{
	BMallocIO mem;
	size_t size;
	size_t bufLen;
	status_t error;
	off_t offset;
	char writeBuf[11] = "0123456789";
	
	NextSubTest();
	bufLen = mem.BufferLength();
	CPPUNIT_ASSERT(bufLen == 0);
	
	NextSubTest();
	size = mem.Write(writeBuf, 10);
	bufLen = mem.BufferLength();
	CPPUNIT_ASSERT(bufLen == 10);
	CPPUNIT_ASSERT(size = 10);
	
	NextSubTest();
	error = mem.SetSize(0);
	bufLen = mem.BufferLength();
	CPPUNIT_ASSERT(bufLen == 0);
	CPPUNIT_ASSERT(error == B_OK);
	
	//This is for the BResource crashing bug
	NextSubTest();
	error = mem.SetSize(200);
	bufLen = mem.BufferLength();
	offset = mem.Seek(0, SEEK_END);
	CPPUNIT_ASSERT(bufLen == 200);
	CPPUNIT_ASSERT(error == B_OK);
	CPPUNIT_ASSERT(offset == 200);	
	
	NextSubTest();
	offset = mem.Seek(0, SEEK_END);
	error = mem.SetSize(100);
	bufLen = mem.BufferLength();
	CPPUNIT_ASSERT(bufLen == 100);
	CPPUNIT_ASSERT(mem.Position() == offset);
}
コード例 #17
0
ファイル: TranslationUtils.cpp プロジェクト: mmanley/Antares
/*!
	This function translates the styled text in fromStream and 
	inserts it at the end of the text in intoView, using the
	BTranslatorRoster *roster to do the translation. The structs
	that make it possible to work with the translated data are
	defined in
	/boot/develop/headers/be/translation/TranslatorFormats.h
	
	\param source the stream with the styled text
	\param intoView the view where the test will be inserted
		roster, BTranslatorRoster used to do the translation
	\param the encoding to use, defaults to UTF-8

	\return B_BAD_VALUE, if fromStream or intoView is NULL
	\return B_ERROR, if any other error occurred
	\return B_OK, if successful
*/
status_t
BTranslationUtils::GetStyledText(BPositionIO* source, BTextView* intoView,
	const char* encoding, BTranslatorRoster* roster)
{
	if (source == NULL || intoView == NULL)
		return B_BAD_VALUE;

	// Use default Translator if none is specified 
	if (roster == NULL) {
		roster = BTranslatorRoster::Default();
		if (roster == NULL)
			return B_ERROR;
	}

	BMessage config;
	if (encoding != NULL && encoding[0])
		config.AddString("be:encoding", encoding);

	// Translate the file from whatever format it is to B_STYLED_TEXT_FORMAT
	// we understand
	BMallocIO mallocIO;
	if (roster->Translate(source, NULL, &config, &mallocIO,
			B_STYLED_TEXT_FORMAT) < B_OK)
		return B_BAD_TYPE;

	const uint8* buffer = (const uint8*)mallocIO.Buffer();

	// make sure there is enough data to fill the stream header
	const size_t kStreamHeaderSize = sizeof(TranslatorStyledTextStreamHeader);
	if (mallocIO.BufferLength() < kStreamHeaderSize)
		return B_BAD_DATA;

	// copy the stream header from the mallio buffer
	TranslatorStyledTextStreamHeader header =
		*(reinterpret_cast<const TranslatorStyledTextStreamHeader *>(buffer));

	// convert the stm_header.header struct to the host format
	const size_t kRecordHeaderSize = sizeof(TranslatorStyledTextRecordHeader);
	swap_data(B_UINT32_TYPE, &header.header, kRecordHeaderSize, B_SWAP_BENDIAN_TO_HOST);
	swap_data(B_INT32_TYPE, &header.version, sizeof(int32), B_SWAP_BENDIAN_TO_HOST);

	if (header.header.magic != 'STXT')
		return B_BAD_TYPE;

	// copy the text header from the mallocIO buffer

	uint32 offset = header.header.header_size + header.header.data_size;
	const size_t kTextHeaderSize = sizeof(TranslatorStyledTextTextHeader);
	if (mallocIO.BufferLength() < offset + kTextHeaderSize)
		return B_BAD_DATA;

	TranslatorStyledTextTextHeader textHeader = 
		*(const TranslatorStyledTextTextHeader *)(buffer + offset);

	// convert the stm_header.header struct to the host format
	swap_data(B_UINT32_TYPE, &textHeader.header, kRecordHeaderSize, B_SWAP_BENDIAN_TO_HOST);
	swap_data(B_INT32_TYPE, &textHeader.charset, sizeof(int32), B_SWAP_BENDIAN_TO_HOST);

	if (textHeader.header.magic != 'TEXT' || textHeader.charset != B_UNICODE_UTF8)
		return B_BAD_TYPE;

	offset += textHeader.header.header_size;
	if (mallocIO.BufferLength() < offset + textHeader.header.data_size) {
		// text buffer misses its end; handle this gracefully
		textHeader.header.data_size = mallocIO.BufferLength() - offset;
	}

	const char* text = (const char*)buffer + offset;
		// point text pointer at the actual character data
	bool hasStyles = false;

	if (mallocIO.BufferLength() > offset + textHeader.header.data_size) {
		// If the stream contains information beyond the text data
		// (which means that this data is probably styled text data)

		offset += textHeader.header.data_size;
		const size_t kStyleHeaderSize =
			sizeof(TranslatorStyledTextStyleHeader);
		if (mallocIO.BufferLength() >= offset + kStyleHeaderSize) {
			TranslatorStyledTextStyleHeader styleHeader = 
				*(reinterpret_cast<const TranslatorStyledTextStyleHeader *>(buffer + offset));
			swap_data(B_UINT32_TYPE, &styleHeader.header, kRecordHeaderSize, B_SWAP_BENDIAN_TO_HOST);
			swap_data(B_UINT32_TYPE, &styleHeader.apply_offset, sizeof(uint32), B_SWAP_BENDIAN_TO_HOST);
			swap_data(B_UINT32_TYPE, &styleHeader.apply_length, sizeof(uint32), B_SWAP_BENDIAN_TO_HOST);
			if (styleHeader.header.magic == 'STYL') {
				offset += styleHeader.header.header_size;
				if (mallocIO.BufferLength() >= offset + styleHeader.header.data_size)
					hasStyles = true;
			}
		}
	}

	text_run_array *runArray = NULL;
	if (hasStyles)
		runArray = BTextView::UnflattenRunArray(buffer + offset);

	if (runArray != NULL) {
		intoView->Insert(intoView->TextLength(),
			text, textHeader.header.data_size, runArray);
#ifdef ANTARES_TARGET_PLATFORM_ANTARES
		BTextView::FreeRunArray(runArray);
#else
		free(runArray);
#endif
	} else {
		intoView->Insert(intoView->TextLength(), text,
			textHeader.header.data_size);
	}

	return B_OK;
}
コード例 #18
0
void
TTracker::InstallDefaultTemplates()
{
	// the following templates are in big endian and we rely on the Tracker
	// translation support to swap them on little endian machines
	//
	// in case there is an attribute (B_RECT_TYPE) that gets swapped by the media
	// (unzip, file system endianness swapping, etc., the correct endianness for
	// the correct machine has to be used here

	static AttributeTemplate sDefaultQueryTemplate[] =
		/* /boot/home/config/settings/Tracker/DefaultQueryTemplates/
		   application_octet-stream */
	{
		{
			// default frame
			kAttrWindowFrame,
			B_RECT_TYPE,
			16,
			(const char*)&kDefaultFrame
		},
		{
			// attr: _trk/viewstate
			kAttrViewState_be,
			B_RAW_TYPE,
			49,
			"o^\365R\000\000\000\012Tlst\000\000\000\000\000\000\000\000\000\000"
				"\000\000\000\000\000\000\000\000\000\000\357\323\335RCSTR\000\000"
				"\000\000\000\000\000\000\000"
		},
		{
			// attr: _trk/columns
			kAttrColumns_be,
			B_RAW_TYPE,
			0,
			NULL
		}
	};

#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Default Query Columns"

	static const ColumnData defaultQueryColumns[] =
	{
		{ B_TRANSLATE_MARK("Name"), 40, 145, B_ALIGN_LEFT, "_stat/name",
			B_STRING_TYPE, true, true },
		{ B_TRANSLATE_MARK("Path"), 200, 225, B_ALIGN_LEFT, "_trk/path",
			B_STRING_TYPE, false, false },
		{ B_TRANSLATE_MARK("Size"), 440, 41, B_ALIGN_LEFT, "_stat/size",
			B_OFF_T_TYPE, true, false },
		{ B_TRANSLATE_MARK("Modified"), 496, 138, B_ALIGN_LEFT, "_stat/modified",
			B_TIME_TYPE, true, false }
	};


	static AttributeTemplate sBookmarkQueryTemplate[] =
		/* /boot/home/config/settings/Tracker/DefaultQueryTemplates/
		   application_x-vnd.Be-bookmark */
	{
		{
			// default frame
			kAttrWindowFrame,
			B_RECT_TYPE,
			16,
			(const char*)&kDefaultFrame
		},
		{
			// attr: _trk/viewstate
			kAttrViewState_be,
			B_RAW_TYPE,
			49,
			"o^\365R\000\000\000\012Tlst\000\000\000\000\000\000\000\000\000\000"
				"\000\000\000\000\000\000\000\000\000\000w\373\175RCSTR\000\000\000"
				"\000\000\000\000\000\000"
		},
		{
			// attr: _trk/columns
			kAttrColumns_be,
			B_RAW_TYPE,
			0,
			NULL
		}
	};


#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Bookmark Query Columns"


	static const ColumnData bookmarkQueryColumns[] =
	{
		{ B_TRANSLATE_MARK("Title"), 40, 171, B_ALIGN_LEFT, "META:title",
			B_STRING_TYPE, false, true },
		{ B_TRANSLATE_MARK("URL"), 226, 287, B_ALIGN_LEFT, kAttrURL,
			B_STRING_TYPE, false, true },
		{ B_TRANSLATE_MARK("Keywords"), 528, 130, B_ALIGN_LEFT, "META:keyw",
			B_STRING_TYPE, false, true }
	};


	static AttributeTemplate sPersonQueryTemplate[] =
		/* /boot/home/config/settings/Tracker/DefaultQueryTemplates/
		   application_x-vnd.Be-bookmark */
	{
		{
			// default frame
			kAttrWindowFrame,
			B_RECT_TYPE,
			16,
			(const char*)&kDefaultFrame
		},
		{
			// attr: _trk/viewstate
			kAttrViewState_be,
			B_RAW_TYPE,
			49,
			"o^\365R\000\000\000\012Tlst\000\000\000\000\000\000\000\000\000\000"
				"\000\000\000\000\000\000\000\000\000\000\357\323\335RCSTR\000\000"
				"\000\000\000\000\000\000\000"
		},
		{
			// attr: _trk/columns
			kAttrColumns_be,
			B_RAW_TYPE,
			0,
			NULL
		},
	};


#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Person Query Columns"


	static const ColumnData personQueryColumns[] =
	{
		{ B_TRANSLATE_MARK("Name"), 40, 115, B_ALIGN_LEFT, "_stat/name",
			B_STRING_TYPE, true, true },
		{ B_TRANSLATE_MARK("Work Phone"), 170, 90, B_ALIGN_LEFT, kAttrWorkPhone,
			B_STRING_TYPE, false, true },
		{ B_TRANSLATE_MARK("E-mail"), 275, 93, B_ALIGN_LEFT, kAttrEmail,
			B_STRING_TYPE, false, true },
		{ B_TRANSLATE_MARK("Company"), 383, 120, B_ALIGN_LEFT, kAttrCompany,
			B_STRING_TYPE, false, true }
	};


	static AttributeTemplate sEmailQueryTemplate[] =
		/* /boot/home/config/settings/Tracker/DefaultQueryTemplates/
		   text_x-email */
	{
		{
			// default frame
			kAttrWindowFrame,
			B_RECT_TYPE,
			16,
			(const char*)&kDefaultFrame
		},
		{
			// attr: _trk/viewstate
			kAttrViewState_be,
			B_RAW_TYPE,
			49,
			"o^\365R\000\000\000\012Tlst\000\000\000\000\000\000\000\000\000\000"
				"\000\000\000\000\000\000\000\000\000\000\366_\377ETIME\000\000\000"
				"\000\000\000\000\000\000"
		},
		{
			// attr: _trk/columns
			kAttrColumns_be,
			B_RAW_TYPE,
			0,
			NULL
		},
	};


#undef B_TRANSLATION_CONTEXT
#define B_TRANSLATION_CONTEXT "Email Query Columns"


	static const ColumnData emailQueryColumns[] =
	{
		{ B_TRANSLATE_MARK("Subject"), 40, 110, B_ALIGN_LEFT, "MAIL:subject",
			B_STRING_TYPE, false, false },
		{ B_TRANSLATE_MARK("From"), 165, 153, B_ALIGN_LEFT, "MAIL:from",
			B_STRING_TYPE, false, false },
		{ B_TRANSLATE_MARK("When"), 333, 120, B_ALIGN_LEFT, "MAIL:when",
			B_STRING_TYPE, false, false },
		{ B_TRANSLATE_MARK("Status"), 468, 50, B_ALIGN_RIGHT, "MAIL:status",
			B_STRING_TYPE, false, true }
	};


	BNode node;
	BString query(kQueryTemplates);
	query += "/application_octet-stream";

	if (!BContainerWindow::DefaultStateSourceNode(query.String(),
			&node, false)) {
		if (BContainerWindow::DefaultStateSourceNode(query.String(),
				&node, true)) {
			BMallocIO stream;
			size_t n = mkColumnsBits(stream,
					defaultQueryColumns, 4, "Default Query Columns");
			sDefaultQueryTemplate[2].fSize = n;
			sDefaultQueryTemplate[2].fBits = (const char*)stream.Buffer();

			AttributeStreamFileNode fileNode(&node);
			AttributeStreamTemplateNode tmp(sDefaultQueryTemplate, 3);
			fileNode << tmp;
		}
	}

	(query = kQueryTemplates) += "/application_x-vnd.Be-bookmark";
	if (!BContainerWindow::DefaultStateSourceNode(query.String(),
			&node, false)) {
		if (BContainerWindow::DefaultStateSourceNode(query.String(),
				&node, true)) {
			BMallocIO stream;
			size_t n = mkColumnsBits(stream,
				bookmarkQueryColumns, 3, "Bookmark Query Columns");
			sBookmarkQueryTemplate[2].fSize = n;
			sBookmarkQueryTemplate[2].fBits = (const char*)stream.Buffer();

			AttributeStreamFileNode fileNode(&node);
			AttributeStreamTemplateNode tmp(sBookmarkQueryTemplate, 3);
			fileNode << tmp;
		}
	}

	(query = kQueryTemplates) += "/application_x-person";
	if (!BContainerWindow::DefaultStateSourceNode(query.String(),
			&node, false)) {
		if (BContainerWindow::DefaultStateSourceNode(query.String(),
				&node, true)) {
			BMallocIO stream;
			size_t n = mkColumnsBits(stream,
				personQueryColumns, 4, "Person Query Columns");
			sPersonQueryTemplate[2].fSize = n;
			sPersonQueryTemplate[2].fBits = (const char*)stream.Buffer();

			AttributeStreamFileNode fileNode(&node);
			AttributeStreamTemplateNode tmp(sPersonQueryTemplate, 3);
			fileNode << tmp;
		}
	}

	(query = kQueryTemplates) += "/text_x-email";
	if (!BContainerWindow::DefaultStateSourceNode(query.String(),
			&node, false)) {
		if (BContainerWindow::DefaultStateSourceNode(query.String(),
				&node, true)) {
			BMallocIO stream;
			size_t n = mkColumnsBits(stream,
				emailQueryColumns, 4, "Email Query Columns");
			sEmailQueryTemplate[2].fSize = n;
			sEmailQueryTemplate[2].fBits = (const char*)stream.Buffer();

			AttributeStreamFileNode fileNode(&node);
			AttributeStreamTemplateNode tmp(sEmailQueryTemplate, 3);
			fileNode << tmp;
		}
	}
}
コード例 #19
0
ファイル: CellView.IO.cpp プロジェクト: ModeenF/OpenSumIt
void CCellView::Write(BPositionIO& stream)
{
// Collect the information needed to write the file, fonts first...
	int *fontList, usedFonts;
	fontList = (int *)MALLOC(gFontSizeTable.Count() * sizeof(int));
	FailNil(fontList);
	usedFonts = fContainer->CollectFontList(fontList);
	if (GetOffsetOf(fontList, fBorderFontID, usedFonts) == -1)
		fontList[usedFonts++] = fBorderFontID;

// ...then the styles
	int *styleList, usedStyles;
	styleList = (int *)CALLOC(gStyleTable.Count(), sizeof(int));
	FailNil(styleList);
	usedStyles = fContainer->CollectStyles(styleList);

// Write the version number
	scVersion vers;
	vers.major = 3;
	vers.minor = 0;
	WriteChunk(stream, kscVersion, sizeof(vers), &vers);

// Write some header info, global to the document
	scHeader head;
	head.defaultFormat = 0;
	head.flags = htonl(fAutoRecalc ? kscAutoRecalc : 0);
	head.functionCount = htons(gFuncCount);
	head.cellCount = htonl(fContainer->GetCellCount());
	WriteChunk(stream, kscHeader, sizeof(head), &head);

// Write a view 
	scView view;
	view.windowRect = Window()->Frame();			swap_order(view.windowRect);
	view.position = fPosition;								swap_order(view.position);
	view.frozen = fFrozen;								swap_order(view.frozen);
	view.curCell = fCurCell;								swap_order(view.curCell);
	view.selection = fSelection;							swap_order(view.selection);
	view.headingFont = htons(GetOffsetOf(fontList, fBorderFontID, usedFonts));
	if (fShowGrid) view.flags |= kscShowGrid;
	if (fShowBorders) view.flags |= kscShowHeadings;
	if (fDisplayZero) view.flags |= kscDisplayZero;	swap_order(view.flags);
	WriteChunk(stream, kscView, sizeof(view), &view);

	short size;

// Write the widths of the last view	
	size = fCellWidths.Count() * sizeof(short) * 2;
	void *p = MALLOC(size);
	FailNil(p);
	fCellWidths.Write(p);
	WriteChunk(stream, kscWidths, size, p);
	FREE(p);
	
// And the heights of course
	size = fCellHeights.Count() * sizeof(short) * 2;
	p = MALLOC(size);
	FailNil(p);
	fCellHeights.Write(p);
	WriteChunk(stream, kscHeights, size, p);
	FREE(p);

// Then write the styles for the columns
	size = fContainer->GetColumnStyles().Count() * sizeof(short) * 2;
	p = MALLOC(size);
	FailNil(p);
	scCSElement *sp = (scCSElement *)p;
	fContainer->GetColumnStyles().Write(p);
	for (int i = 0; i < fContainer->GetColumnStyles().Count(); i++)
	{
		swap_order(sp[i].index);
		sp[i].style = htons(GetOffsetOf(styleList, sp[i].style, usedStyles));
	}
	WriteChunk(stream, kscColStyles, size, p);
	FREE(p);

// Continue with the names
	namemap::iterator ni;
	for (ni = fNames->begin(); ni != fNames->end(); ni++)
	{
		scName name;
		char c;
		ushort k = htons(kscName);
		memset(name.name, 0, 32);
		
		CHECKWRITE(stream, &k, 2);
		
		strcpy(name.name, (*ni).first);
		
		if ((*ni).second.BotRight() == (*ni).second.TopLeft())
		{
			k = htons(32 + 6);
			CHECKWRITE(stream, &k, 2);
			CHECKWRITE(stream, name.name, 32);

			c = valCell;
			CHECKWRITE(stream, &c, sizeof(c));
			cell C = (*ni).second.BotRight();
			swap_order(C);
			CHECKWRITE(stream, &C, sizeof(cell));
		}
		else
		{
			k = htons(32 + 10);
			CHECKWRITE(stream, &k, 2);
			CHECKWRITE(stream, name.name, 32);

			c = valRange;
			CHECKWRITE(stream, &c, sizeof(c));
			range r = (*ni).second;
			swap_order(r);
			CHECKWRITE(stream, &r, sizeof(range));
		}
		c = opEnd;
		CHECKWRITE(stream, &c, sizeof(c));
	}

// Then there are the functions used in this document
	CSet funcs;
	fContainer->CollectFunctionNrs(funcs);
	for (int i = kFunctionCount; i < gFuncCount; i++)
		if (funcs[i])
		{
			scFunc func;
			memset(func.name, 0, 10);
			strcpy(func.name, gFuncArrayByNr[i].funcName);
			func.argCnt = htons(gFuncArrayByNr[i].argCnt);
			func.funcNr = htons(gFuncArrayByNr[i].funcNr);
			WriteChunk(stream, kscFunc, sizeof(func), &func);
		}

// Followed by the formatting information. Fonts first
	for (int i = 0; i < usedFonts; i++)
	{
		CFontMetrics fm = gFontSizeTable[fontList[i]];
		scFont *font;
		
		font_family fam;
		font_style sty;
		fm.Font().GetFamilyAndStyle(&fam, &sty);

		ulong size = sizeof(scFont) + strlen(fam) + strlen(sty) + 2;
		
		font = (scFont *)CALLOC(1, size);
		FailNil(font);
		
		font->size = B_HOST_TO_BENDIAN_FLOAT(fm.Font().Size());
		font->color = fm.FontColor();
		
		char *p = (char *)font + sizeof(scFont);
		strcpy(p, sty);
		p += strlen(sty) + 1;
		strcpy(p, fam);

		WriteChunk(stream, kscFont, size, font);
		FREE(font);
	}
	
// Then we get the number formats
	int *formatList, usedFormats;
	formatList = (int *)MALLOC(gFormatTable.Count() * sizeof(int));
	FailNil(formatList);
	usedFormats = fContainer->CollectFormats(formatList);
	for (int i = 0; i < usedFormats; i++)
	{
		CFormatter nf;
		if (formatList[i] < eFirstNewFormat)
			nf = CFormatter(formatList[i]);
		else
			nf = gFormatTable[formatList[i]];
		
		scFormat format;
		format.nr = htons(nf.FormatID());
		format.info[0] = 0;
		format.info[1] = 0;
		format.info[2] = 0;
		format.info[3] = 0;
		
		WriteChunk(stream, kscFormat, sizeof(format)-1, &format);
	}
	
// The style table
	for (int i = 0; i < usedStyles; i++)
	{
		CellStyle cs = gStyleTable[styleList[i]];

		scStyle style;
		memset(&style, 0, sizeof(style));
		style.font = htons(GetOffsetOf(fontList, cs.fFont, usedFonts));
		style.format = htons(GetOffsetOf(formatList, cs.fFormat, usedFormats));
		style.align = cs.fAlignment;
		style.lowColor = cs.fLowColor;
		
		WriteChunk(stream, kscStyle, sizeof(style), &style);
	}
	FREE(fontList);
	FREE(formatList);
	
	int *t = (int *)CALLOC(gStyleTable.Count(), sizeof(int));
	FailNil(t);
	for (int i = 0; i < usedStyles; i++)
		t[styleList[i]] = i;
	
	FREE(styleList);
	styleList = t;
	
// And now its time for some data
	StProgress progress(this, fContainer->GetCellCount(), pColorYellow, false);

	CCellIterator iter(fContainer);
	cell c;
	while (iter.NextExisting(c))
	{
		scCell cl;
		cl.loc = c;							swap_order(cl.loc);
		cl.style = htons(styleList[fContainer->GetCellStyleNr(c)]);
		Value val;
		fContainer->GetValue(c, val);
		
		switch (val.fType)
		{
			case eNoData:
				WriteChunk(stream, kscCellEmpty, kscCellSize, &cl);
				break;
			case eNumData:
			{
				double d = B_HOST_TO_BENDIAN_DOUBLE(val.fDouble);
				memcpy(cl.num, &d, sizeof(double));
				WriteChunk(stream, kscCellNumber, kscCellSize+sizeof(double), &cl);
				break;
			}
			case eBoolData:
				memcpy(cl.num, &val.fBool, sizeof(bool));
				WriteChunk(stream, kscCellBool, kscCellSize+sizeof(bool), &cl);
				break;
			case eTimeData:
			{
				time_t t = htonl(val.fTime);	
				memcpy(cl.num, &t, sizeof(time_t));
				WriteChunk(stream, kscCellDateTime, kscCellSize+sizeof(time_t), &cl);
				break;
			}
			case eTextData:
			{
				WriteChunk(stream, kscCellText, kscCellSize, &cl);
				const char *t = val;
				WriteChunk(stream, kscString, strlen(t) + 1, t);
				break;
			}
			default:
				// there was a warning about not all enum values handled in 
				// switch statement.
				break;
		}
		
		CFormula form = fContainer->GetCellFormula(c);
		if (form.IsFormula())
		{
			BMallocIO buf;
			form.Write(buf);
			
			WriteChunk(stream, kscFormula, buf.BufferLength(), buf.Buffer());
		}
		progress.Step();
	}
	
	WriteCharts(stream);
	
// cleanup the mess
	
	WriteChunk(stream, kscEnd, 0, NULL);

	FREE(styleList);
}
コード例 #20
0
ファイル: pictureViewer.cpp プロジェクト: HaikuArchives/Peek
void PictureViewer::HandleCopyTarget(BMessage *e) {
  entry_ref targetRef;
   
  BBitmap *toSend;
  if (clipping == true) toSend = GetClipping();
                   else toSend = thePic;
  


  // memory or file transfer ?
  if (e->FindRef("directory",&targetRef) == B_OK)  {

      BDirectory *targetDir = new BDirectory( &targetRef );
      if (targetDir->InitCheck() == B_OK) {
         BFile *targetFile = new BFile(targetDir,e->FindString("name"),B_WRITE_ONLY | B_CREATE_FILE | B_ERASE_FILE);
         if (targetFile->InitCheck() == B_OK) {

          BBitmap *dragImage = NULL;
          BBitmapStream *strm;
          strm = new BBitmapStream(toSend);

          translator_id trans_id;
          uint32 type;

          GetTranslatorInfo(e->FindString("be:filetypes"),&trans_id,&type);
          BTranslatorRoster::Default()->Translate(trans_id,strm,NULL,targetFile,type);
          BNodeInfo *ni = new BNodeInfo(targetFile);
          ni->SetType(e->FindString("be:filetypes"));
          if (dragImage == NULL) strm->DetachBitmap(&toSend);
           else {
            strm->DetachBitmap(&dragImage);
            delete dragImage;
           }
          delete ni;
          delete strm;
         } 
        delete targetFile;
       }   
     delete targetDir;
     return;
   } 
   
  else {
     BMallocIO *data = new BMallocIO;
     BBitmapStream *imageSrc;
     imageSrc = new BBitmapStream(toSend);

     BMessage *package = new BMessage(B_MIME_DATA);
     translator_id trans_id;
     uint32 type;

     GetTranslatorInfo(e->FindString("be:types"),&trans_id,&type);
     if (BTranslatorRoster::Default()->Translate( trans_id, imageSrc, NULL, data, type ) != B_OK) return;
     package->AddData( e->FindString("be:types"),  B_MIME_DATA, data->Buffer(), data->BufferLength());
     e->SendReply(package);        

     imageSrc->DetachBitmap(&toSend);

     delete data;
     delete imageSrc;
     delete package;
  } 

 if (clipping) delete toSend;

}
コード例 #21
0
void VBoxClipboardService::MessageReceived(BMessage *message)
{
    uint32_t formats = 0;
    message->PrintToStream();
    switch (message->what)
    {
        case VBOX_GUEST_CLIPBOARD_HOST_MSG_FORMATS:
        {
            int rc;
            uint32_t cb;
            void *pv;
            bool commit = false;

            if (message->FindInt32("Formats", (int32 *)&formats) != B_OK)
                break;

            if (!formats)
                break;

            if (!be_clipboard->Lock())
                break;

            be_clipboard->Clear();
            BMessage *clip = be_clipboard->Data();
            if (!clip)
            {
                be_clipboard->Unlock();
                break;
            }

            if (formats & VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
            {
                pv = _VBoxReadHostClipboard(VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT, &cb);
                if (pv)
                {
                    char *text;
                    rc = RTUtf16ToUtf8((PCRTUTF16)pv, &text);
                    if (RT_SUCCESS(rc))
                    {
                        BString str(text);
                        /** @todo user vboxClipboardUtf16WinToLin() */
                        // convert Windows CRLF to LF
                        str.ReplaceAll("\r\n", "\n");
                        // don't include the \0
                        clip->AddData("text/plain", B_MIME_TYPE, str.String(), str.Length());
                        RTStrFree(text);
                        commit = true;
                    }
                    free(pv);
                }
            }

            if (formats & VBOX_SHARED_CLIPBOARD_FMT_BITMAP)
            {
                pv = _VBoxReadHostClipboard(VBOX_SHARED_CLIPBOARD_FMT_BITMAP, &cb);
                if (pv)
                {
                    void  *pBmp  = NULL;
                    size_t cbBmp = 0;
                    rc = vboxClipboardDibToBmp(pv, cb, &pBmp, &cbBmp);
                    if (RT_SUCCESS(rc))
                    {
                        BMemoryIO mio(pBmp, cbBmp);
                        BBitmap *bitmap = BTranslationUtils::GetBitmap(&mio);
                        if (bitmap)
                        {
                            BMessage bitmapArchive;

                            /** @todo r=ramshankar: split this into functions with error checking as
                             *        neccessary. */
                            if (   bitmap->IsValid()
                                && bitmap->Archive(&bitmapArchive) == B_OK
                                && clip->AddMessage("image/bitmap", &bitmapArchive) == B_OK)
                            {
                                commit = true;
                            }
                            delete bitmap;
                        }
                        RTMemFree(pBmp);
                    }
                    free(pv);
                }
            }

            /*
             * Make sure we don't bounce this data back to the host, it's impolite. It can also
             * be used as a hint to applications probably.
             */
            clip->AddBool("FromVirtualBoxHost", true);
            if (commit)
                be_clipboard->Commit();
            be_clipboard->Unlock();
            break;
        }

        case VBOX_GUEST_CLIPBOARD_HOST_MSG_READ_DATA:
        {
            int rc;

            if (message->FindInt32("Formats", (int32 *)&formats) != B_OK)
                break;

            if (!formats)
                break;
            if (!be_clipboard->Lock())
                break;

            BMessage *clip = be_clipboard->Data();
            if (!clip)
            {
                be_clipboard->Unlock();
                break;
            }
            clip->PrintToStream();

            if (formats & VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
            {
                const char *text;
                int32 textLen;
                if (clip->FindData("text/plain", B_MIME_TYPE, (const void **)&text, &textLen) == B_OK)
                {
                    // usually doesn't include the \0 so be safe
                    BString str(text, textLen);
                    // convert from LF to Windows CRLF
                    str.ReplaceAll("\n", "\r\n");
                    PRTUTF16 pwsz;
                    rc = RTStrToUtf16(str.String(), &pwsz);
                    if (RT_SUCCESS(rc))
                    {
                        uint32_t cb = (RTUtf16Len(pwsz) + 1) * sizeof(RTUTF16);

                        rc = VbglR3ClipboardWriteData(fClientId, VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT, pwsz, cb);
                        //printf("VbglR3ClipboardWriteData: %d\n", rc);
                        RTUtf16Free(pwsz);
                    }
                }
            }
            else if (formats & VBOX_SHARED_CLIPBOARD_FMT_BITMAP)
            {
                BMessage archivedBitmap;
                if (clip->FindMessage("image/bitmap", &archivedBitmap) == B_OK ||
                    clip->FindMessage("image/x-be-bitmap", &archivedBitmap) == B_OK)
                {
                    BBitmap *bitmap = new(std::nothrow) BBitmap(&archivedBitmap);
                    if (bitmap)
                    {
                        // Don't delete bitmap, BBitmapStream will.
                        BBitmapStream stream(bitmap);
                        BTranslatorRoster *roster = BTranslatorRoster::Default();
                        if (roster && bitmap->IsValid())
                        {
                            BMallocIO bmpStream;
                            if (roster->Translate(&stream, NULL, NULL, &bmpStream, B_BMP_FORMAT) == B_OK)
                            {
                                const void *pDib;
                                size_t cbDibSize;
                                /* Strip out the BM header */
                                rc = vboxClipboardBmpGetDib(bmpStream.Buffer(), bmpStream.BufferLength(), &pDib, &cbDibSize);
                                if (RT_SUCCESS(rc))
                                {
                                    rc = VbglR3ClipboardWriteData(fClientId, VBOX_SHARED_CLIPBOARD_FMT_BITMAP, (void *)pDib,
                                                                  cbDibSize);
                                }
                            }
                        }
                    }
                }
            }

            be_clipboard->Unlock();
            break;
        }

        case B_CLIPBOARD_CHANGED:
        {
            printf("B_CLIPBOARD_CHANGED\n");
            const void *data;
            int32 dataLen;
            if (!be_clipboard->Lock())
                break;

            BMessage *clip = be_clipboard->Data();
            if (!clip)
            {
                be_clipboard->Unlock();
                break;
            }

            bool fromVBox;
            if (clip->FindBool("FromVirtualBoxHost", &fromVBox) == B_OK && fromVBox)
            {
                // It already comes from the host, discard.
                be_clipboard->Unlock();
                break;
            }

            if (clip->FindData("text/plain", B_MIME_TYPE, &data, &dataLen) == B_OK)
                formats |= VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT;

            if (   clip->HasMessage("image/bitmap")
                || clip->HasMessage("image/x-be-bitmap"))
            {
                formats |= VBOX_SHARED_CLIPBOARD_FMT_BITMAP;
            }

            be_clipboard->Unlock();

            VbglR3ClipboardReportFormats(fClientId, formats);
            break;
        }

        case B_QUIT_REQUESTED:
            fExiting = true;
            break;

        default:
            BHandler::MessageReceived(message);
    }
}
コード例 #22
0
ssize_t
CamStreamingDeframer::Write(const void *buffer, size_t size)
{
	int i = -1;
	int j;
	int end = size;
	int which;
	const uint8 *buf = (const uint8 *)buffer;
	int bufsize = size;
	bool detach = false;
	bool discard = false;
	//PRINT((CH "(%p, %d); state=%s framesz=%u queued=%u" CT, buffer, size, (fState==ST_SYNC)?"sync":"frame", (size_t)(fCurrentFrame?(fCurrentFrame->Position()):-1), (size_t)fInputBuff.Position()));
	if (!fCurrentFrame) {
		BAutolock l(fLocker);
		if (fFrames.CountItems() < MAXFRAMEBUF)
			fCurrentFrame = AllocFrame();
		else {
			PRINT((CH "DROPPED %d bytes! (too many queued frames)" CT, size));
			return size; // drop XXX
		}
	}

	// update in case resolution changed
	fMinFrameSize = fDevice->MinRawFrameSize();
	fMaxFrameSize = fDevice->MaxRawFrameSize();

	if (fInputBuff.Position()) {
		// residual data ? append to it
		fInputBuff.Write(buffer, size);
		// and use it as input buf
		buf = (uint8 *)fInputBuff.Buffer();
		bufsize = fInputBuff.BufferLength();
		end = bufsize;
	}
	// whole buffer belongs to a frame, simple
	if ((fState == ST_FRAME) && (fCurrentFrame->Position() + bufsize < fMinFrameSize)) {
		// no residual data, and
		fCurrentFrame->Write(buf, bufsize);
		fInputBuff.Seek(0LL, SEEK_SET);
		fInputBuff.SetSize(0);
		return size;
	}

	// waiting for a frame...
	if (fState == ST_SYNC) {
		i = 0;
		while ((j = FindSOF(buf+i, bufsize-i, &which)) > -1) {
			i += j;
			if (fDevice->ValidateStartOfFrameTag(buf+i, fSkipSOFTags))
				break;
			i++;
		}
		// got one
		if (j >= 0) {
			PRINT((CH ": SOF[%d] at offset %d" CT, which, i));
			//PRINT((CH ": SOF: ... %02x %02x %02x %02x %02x %02x" CT, buf[i+6], buf[i+7], buf[i+8], buf[i+9], buf[i+10], buf[i+11]));
			int start = i + fSkipSOFTags;
			buf += start;
			bufsize -= start;
			end = bufsize;
			fState = ST_FRAME;
		}
	}

	// check for end of frame
	if (fState == ST_FRAME) {
#if 0
		int j, k;
		i = -1;
		k = 0;
		while ((j = FindEOF(buf + k, bufsize - k, &which)) > -1) {
			k += j;
			//PRINT((CH "| EOF[%d] at offset %d; pos %Ld" CT, which, k, fCurrentFrame->Position()));
			if (fCurrentFrame->Position()+k >= fMinFrameSize) {
				i = k;
				break;
			}
			k++;
			if (k >= bufsize)
				break;
		}
#endif
#if 1
		i = 0;
		if (fCurrentFrame->Position() < fMinFrameSize) {
			if (fCurrentFrame->Position() + bufsize >= fMinFrameSize)
				i = (fMinFrameSize - (size_t)fCurrentFrame->Position());
			else
				i = bufsize;
		}
		PRINT((CH ": checking for EOF; bufsize=%d i=%d" CT, bufsize, i));

		if (i + (int)fSkipEOFTags > bufsize) { // not enough room to check for EOF, leave it for next time
			end = i;
			i = -1; // don't detach yet
		} else {
			PRINT((CH ": EOF? %02x [%02x %02x %02x %02x] %02x" CT, buf[i-1], buf[i], buf[i+1], buf[i+2], buf[i+3], buf[i+4]));
			while ((j = FindEOF(buf + i, bufsize - i, &which)) > -1) {
				i += j;
				PRINT((CH "| EOF[%d] at offset %d; pos %Ld" CT, which, i, fCurrentFrame->Position()));
				if (fCurrentFrame->Position()+i >= fMaxFrameSize) {
					// too big: discard
					//i = -1;
					discard = true;
					break;
				}
				if (fDevice->ValidateEndOfFrameTag(buf+i, fSkipEOFTags, fCurrentFrame->Position()+i))
					break;
				i++;
				if (i >= bufsize) {
					i = -1;
					break;
				}
			}
			if (j < 0)
				i = -1;
		}
#endif
		if (i >= 0) {
			PRINT((CH ": EOF[%d] at offset %d" CT, which, i));
			end = i;
			detach = true;
		}
		PRINT((CH ": writing %d bytes" CT, end));
		if (end <= bufsize)
			fCurrentFrame->Write(buf, end);
		if (fCurrentFrame->Position() > fMaxFrameSize) {
			fCurrentFrame->SetSize(fMaxFrameSize);
			detach = true;
		}
		if (detach) {
			BAutolock f(fLocker);
			PRINT((CH ": Detaching a frame (%d bytes, end = %d, )" CT, (size_t)fCurrentFrame->Position(), end));
			fCurrentFrame->Seek(0LL, SEEK_SET);
			if (discard) {
				delete fCurrentFrame;
			} else {
				fFrames.AddItem(fCurrentFrame);
				release_sem(fFrameSem);
			}
			fCurrentFrame = NULL;
			if (fFrames.CountItems() < MAXFRAMEBUF) {
				fCurrentFrame = AllocFrame();
			}
			fState = ST_SYNC;
		}
	}




	// put the remainder in input buff, discarding old data
#if 0
	fInputBuff.Seek(0LL, SEEK_SET);
	if (bufsize - end > 0)
		fInputBuff.Write(buf+end, bufsize - end);
#endif
	BMallocIO m;
	m.Write(buf+end, bufsize - end);
	fInputBuff.Seek(0LL, SEEK_SET);
	if (bufsize - end > 0)
		fInputBuff.Write(m.Buffer(), bufsize - end);
	fInputBuff.SetSize(bufsize - end);
	return size;
}
コード例 #23
0
ファイル: STXTTranslator.cpp プロジェクト: mmanley/Antares
/*!
	Convert the plain text (UTF8) from inSource to plain or
	styled text in outDestination
*/
status_t
translate_from_text(BPositionIO* source, const char* encoding, bool forceEncoding,
                    BPositionIO* destination, uint32 outType)
{
    if (outType != B_TRANSLATOR_TEXT && outType != B_STYLED_TEXT_FORMAT)
        return B_BAD_VALUE;

    // find the length of the text
    off_t size = source->Seek(0, SEEK_END);
    if (size < 0)
        return (status_t)size;
    if (size > UINT32_MAX && outType == B_STYLED_TEXT_FORMAT)
        return B_NOT_SUPPORTED;

    status_t status = source->Seek(0, SEEK_SET);
    if (status < B_OK)
        return status;

    if (outType == B_STYLED_TEXT_FORMAT) {
        // output styled text headers
        status = output_headers(destination, (uint32)size);
        if (status != B_OK)
            return status;
    }

    class MallocBuffer {
    public:
        MallocBuffer() : fBuffer(NULL), fSize(0) {}
        ~MallocBuffer() {
            free(fBuffer);
        }

        void* Buffer() {
            return fBuffer;
        }
        size_t Size() const {
            return fSize;
        }

        status_t
        Allocate(size_t size)
        {
            fBuffer = malloc(size);
            if (fBuffer != NULL) {
                fSize = size;
                return B_OK;
            }
            return B_NO_MEMORY;
        }

    private:
        void*	fBuffer;
        size_t	fSize;
    } encodingBuffer;
    BMallocIO encodingIO;
    uint32 encodingID = 0;
    // defaults to UTF-8 or no encoding

    BNode* node = dynamic_cast<BNode*>(source);
    if (node != NULL) {
        // determine encoding, if available
        const BCharacterSet* characterSet = NULL;
        bool hasAttribute = false;
        if (encoding != NULL && !forceEncoding) {
            BString name;
            if (node->ReadAttrString("be:encoding", &name) == B_OK) {
                encoding = name.String();
                hasAttribute = true;
            } else {
                int32 value;
                ssize_t bytesRead = node->ReadAttr("be:encoding", B_INT32_TYPE, 0,
                                                   &value, sizeof(value));
                if (bytesRead == (ssize_t)sizeof(value)) {
                    hasAttribute = true;
                    if (value != 65535)
                        characterSet = BCharacterSetRoster::GetCharacterSetByConversionID(value);
                }
            }
        } else {
            hasAttribute = true;
            // we don't write the encoding in this case
        }
        if (characterSet == NULL && encoding != NULL)
            characterSet = BCharacterSetRoster::FindCharacterSetByName(encoding);

        if (characterSet != NULL) {
            encodingID = characterSet->GetConversionID();
            encodingBuffer.Allocate(READ_BUFFER_SIZE * 4);
        }

        if (!hasAttribute && encoding != NULL) {
            // add encoding attribute, so that someone opening the file can
            // retrieve it for persistance
            node->WriteAttr("be:encoding", B_STRING_TYPE, 0, encoding,
                            strlen(encoding));
        }
    }

    off_t outputSize = 0;
    ssize_t bytesRead;
    int32 state = 0;

    // output the actual text part of the data
    do {
        uint8 buffer[READ_BUFFER_SIZE];
        bytesRead = source->Read(buffer, READ_BUFFER_SIZE);
        if (bytesRead < B_OK)
            return bytesRead;
        if (bytesRead == 0)
            break;

        if (encodingBuffer.Size() == 0) {
            // default, no encoding
            ssize_t bytesWritten = destination->Write(buffer, bytesRead);
            if (bytesWritten != bytesRead) {
                if (bytesWritten < B_OK)
                    return bytesWritten;

                return B_ERROR;
            }

            outputSize += bytesRead;
        } else {
            // decode text file to UTF-8
            char* pos = (char*)buffer;
            int32 encodingLength = encodingIO.BufferLength();
            int32 bytesLeft = bytesRead;
            int32 bytes;
            do {
                encodingLength = READ_BUFFER_SIZE * 4;
                bytes = bytesLeft;

                status = convert_to_utf8(encodingID, pos, &bytes,
                                         (char*)encodingBuffer.Buffer(), &encodingLength, &state);
                if (status < B_OK)
                    return status;

                ssize_t bytesWritten = destination->Write(encodingBuffer.Buffer(),
                                       encodingLength);
                if (bytesWritten < encodingLength) {
                    if (bytesWritten < B_OK)
                        return bytesWritten;

                    return B_ERROR;
                }

                pos += bytes;
                bytesLeft -= bytes;
                outputSize += encodingLength;
            } while (encodingLength > 0 && bytesLeft > 0);
        }
    } while (bytesRead > 0);

    if (outType != B_STYLED_TEXT_FORMAT)
        return B_OK;

    if (encodingBuffer.Size() != 0 && size != outputSize) {
        if (outputSize > UINT32_MAX)
            return B_NOT_SUPPORTED;

        // we need to update the header as the decoded text size has changed
        status = destination->Seek(0, SEEK_SET);
        if (status == B_OK)
            status = output_headers(destination, (uint32)outputSize);
        if (status == B_OK)
            status = destination->Seek(0, SEEK_END);

        if (status < B_OK)
            return status;
    }

    // Read file attributes if outputting styled data
    // and source is a BNode object

    if (node == NULL)
        return B_OK;

    // Try to read styles - we only propagate an error if the actual on-disk
    // data is likely to be okay

    const char *kAttrName = "styles";
    attr_info info;
    if (node->GetAttrInfo(kAttrName, &info) != B_OK)
        return B_OK;

    if (info.type != B_RAW_TYPE || info.size < 160) {
        // styles seem to be broken, but since we got the text,
        // we don't propagate the error
        return B_OK;
    }

    uint8* flatRunArray = new (std::nothrow) uint8[info.size];
    if (flatRunArray == NULL)
        return B_NO_MEMORY;

    bytesRead = node->ReadAttr(kAttrName, B_RAW_TYPE, 0, flatRunArray, info.size);
    if (bytesRead != info.size)
        return B_OK;

    output_styles(destination, size, flatRunArray, info.size);

    delete[] flatRunArray;
    return B_OK;
}
コード例 #24
0
ファイル: MP4Parser.cpp プロジェクト: AmirAbrams/haiku
void
CMOVAtom::OnProcessMetaData()
{
	BMallocIO *theUncompressedData;
	uint8 *outBuffer;
	CMVDAtom *aCMVDAtom = NULL;
	uint32	compressionID = 0;
	uint64	descBytesLeft;
	uint32	Size;
	
	descBytesLeft = GetAtomSize();
	
	// Check for Compression Type
	while (descBytesLeft > 0) {
		AtomBase *aAtomBase = GetAtom(theStream);
	
		aAtomBase->OnProcessMetaData();

		if (aAtomBase->GetAtomSize() > 0) {
			descBytesLeft = descBytesLeft - aAtomBase->GetAtomSize();
		} else {
			printf("Invalid Atom found when reading Compressed Headers\n");
			descBytesLeft = 0;
		}

		if (dynamic_cast<DCOMAtom *>(aAtomBase)) {
			// DCOM atom
			compressionID = dynamic_cast<DCOMAtom *>(aAtomBase)->GetCompressionID();
			delete aAtomBase;
		} else {
			if (dynamic_cast<CMVDAtom *>(aAtomBase)) {
				// CMVD atom
				aCMVDAtom = dynamic_cast<CMVDAtom *>(aAtomBase);
				descBytesLeft = 0;
			}
		}
	}

	// Decompress data
	if (compressionID == 'zlib') {
		Size = aCMVDAtom->GetUncompressedSize();
		
		outBuffer = (uint8 *)(malloc(Size));
		
		printf("Decompressing %ld bytes to %ld bytes\n",aCMVDAtom->GetBufferSize(),Size);
		int result = uncompress(outBuffer, &Size, aCMVDAtom->GetCompressedData(), aCMVDAtom->GetBufferSize());
		
		if (result != Z_OK) {
			printf("Failed to decompress headers uncompress returned ");
			switch (result) {
				case Z_MEM_ERROR:
					DEBUGGER("Lack of Memory Error\n");
					break;
				case Z_BUF_ERROR:
					DEBUGGER("Lack of Output buffer space Error\n");
					break;
				case Z_DATA_ERROR:
					DEBUGGER("Input Data is corrupt or not a compressed set Error\n");
					break;
			}
		}

		// Copy uncompressed data into BMAllocIO
		theUncompressedData = new BMallocIO();
		theUncompressedData->SetSize(Size);
		theUncompressedData->WriteAt(0L,outBuffer,Size);
		
		free(outBuffer);
		delete aCMVDAtom;
		
		// reset position on BMAllocIO
		theUncompressedData->Seek(SEEK_SET,0L);
		// Assign to Stream
		theUncompressedStream = theUncompressedData;
		
		// All subsequent reads should use theUncompressedStream
	}

}