Esempio n. 1
0
// Import
status_t
StyledTextImporter::Import(Icon* icon, const entry_ref* ref)
{
	CALLED();
	status_t err;
	BFile file(ref, B_READ_ONLY);
	err = file.InitCheck();
	if (err < B_OK)
		return err;

	BNodeInfo info(&file);
	char mime[B_MIME_TYPE_LENGTH];
	err = info.GetType(mime);
	if (err < B_OK)
		return err;

	if (strncmp(mime, "text/plain", B_MIME_TYPE_LENGTH))
		return EINVAL;

	off_t size;
	err = file.GetSize(&size);
	if (err < B_OK)
		return err;
	if (size > 1 * 1024 * 1024) // Don't load files that big
		return E2BIG;

	BMallocIO mio;
	mio.SetSize((size_t)size + 1);
	memset((void *)mio.Buffer(), 0, (size_t)size + 1);

	// TODO: read runs from attribute

	return _Import(icon, (const char *)mio.Buffer(), NULL);
}
Esempio n. 2
0
status_t
DefaultCatalog::WriteToResource(entry_ref *appOrAddOnRef)
{
	BFile file;
	status_t res = file.SetTo(appOrAddOnRef, B_READ_WRITE);
	if (res != B_OK)
		return res;

	BResources rsrc;
	res = rsrc.SetTo(&file);
	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) {
		res = rsrc.AddResource(B_MESSAGE_TYPE, BLocaleRoster::kEmbeddedCatResId,
			mallocIO.Buffer(), mallocIO.BufferLength(), "embedded catalog");
	}

	return res;
}
Esempio n. 3
0
status_t HTMLProject::Archive(BMessage *archive,bool deep)
{
	archive->AddInt16(hpV,bhv_application);	// version

	BEntry dirEntry;
	entry_ref dirRef;
	filesDir.GetEntry(&dirEntry);
	dirEntry.GetRef(&dirRef);
	
	archive->AddRef(hpD,&dirRef);

	BMallocIO happyArchive;
	happyList->Archive(&happyArchive);
	archive->AddData(hpH,B_RAW_TYPE,happyArchive.Buffer(),happyArchive.BufferLength());
	
	unsigned int n = fileList->CountItems();
	for (unsigned int i=0; i<n; i++)
		archive->AddString(hpF,((HTMLFile*)fileList->ItemAt(i))->name.String());
		
	n = labelList->CountItems();
	for (unsigned int i=0; i<n; i++)
	{
		smallLabel *lab = (smallLabel*)labelList->ItemAt(i);
		archive->AddString(hpLn,lab->label.String());
		archive->AddInt32(hpLf,lab->file);
	}
	
	return B_OK;
}
Esempio n. 4
0
status_t
DefaultCatalog::WriteToFile(const char *path)
{
	BFile catalogFile;
	if (path)
		fPath = path;
	status_t res = catalogFile.SetTo(fPath.String(),
		B_WRITE_ONLY | B_CREATE_FILE | B_ERASE_FILE);
	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 = catalogFile.Write(mallocIO.Buffer(), mallocIO.BufferLength());
		if (wsz != (ssize_t)mallocIO.BufferLength())
			return B_FILE_ERROR;

		// set mimetype-, language- and signature-attributes:
		UpdateAttributes(catalogFile);
	}
	if (res == B_OK)
		UpdateAttributes(catalogFile);
	return res;
}
Esempio n. 5
0
void CCellView::StartDrag(BPoint where, bool copy)
{
	ClearAnts();
	BMessage msg(B_SIMPLE_DATA);
	msg.AddPointer("container", fContainer);
	msg.AddPointer("cellview", this);
	msg.AddData("range", 'rang', &fSelection, sizeof(range));
	msg.AddBool("dragacopy", copy);
	
	BRegion rgn;
	SelectionToRegion(rgn);
	cell c;
	GetCellHitBy(where, c);
	BRect dragRect = rgn.Frame();
	dragRect.OffsetBy(fCellWidths[c.h] - fCellWidths[fSelection.left],
		fCellHeights[c.v] - fCellHeights[fSelection.top]);
	
	BMallocIO buf;
	CTextConverter conv(buf, fContainer);
	conv.ConvertToText(&fSelection);
	msg.AddData("text/plain", B_MIME_DATA,
		buf.Buffer(), buf.BufferLength());

// and add a nice picture
	BPicture pic;
	BRect r;
	GetPictureOfSelection(&pic, r);
	pic.Archive(&msg);
//	msg.AddData("picture", 'PICT', pic.Data(), pic.DataSize());
	msg.AddData("rect of pict", 'RECT', &r, sizeof(BRect));
	
	fDragIsAcceptable = true;
	DragMessage(&msg, dragRect, this);
} /* CCellView::StartDrag */
status_t
DefaultCatalog::WriteToResource(const entry_ref &appOrAddOnRef)
{
	BFile file;
	status_t res = file.SetTo(&appOrAddOnRef, B_READ_WRITE);
	if (res != B_OK)
		return res;

	BResources rsrc;
	res = rsrc.SetTo(&file);
	if (res != B_OK)
		return res;

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

	int mangledLanguage = CatKey::HashFun(fLanguageName.String(), 0);

	if (res == B_OK) {
		res = rsrc.AddResource('CADA', mangledLanguage,
			mallocIO.Buffer(), mallocIO.BufferLength(),
			BString(fLanguageName));
	}

	return res;
}
Esempio n. 7
0
ServerPicture::ServerPicture(const ServerPicture& picture)
	:
	fFile(NULL),
	fData(NULL),
	fPictures(NULL),
	fPushed(NULL),
	fOwner(NULL)
{
	fToken = gTokenSpace.NewToken(kPictureToken, this);

	BMallocIO* mallocIO = new(std::nothrow) BMallocIO();
	if (mallocIO == NULL)
		return;

	fData = mallocIO;

	const off_t size = picture.DataLength();
	if (mallocIO->SetSize(size) < B_OK)
		return;

	picture.fData->ReadAt(0, const_cast<void*>(mallocIO->Buffer()),
		size);

	PictureDataWriter::SetTo(fData);
}
Esempio n. 8
0
status_t
DefaultCatalog::WriteToFile(const char *path)
{
	BFile catalogFile;
	if (path)
		fPath = path;
	status_t status = catalogFile.SetTo(fPath.String(),
		B_WRITE_ONLY | B_CREATE_FILE | B_ERASE_FILE);
	if (status != B_OK)
		return status;

	BMallocIO mallocIO;
	mallocIO.SetBlockSize(max_c(fCatMap.Size() * 20, 256));
		// set a largish block-size in order to avoid reallocs
	status = Flatten(&mallocIO);
	if (status != B_OK)
		return status;

	ssize_t bytesWritten
		= catalogFile.Write(mallocIO.Buffer(), mallocIO.BufferLength());
	if (bytesWritten < 0)
		return bytesWritten;
	if (bytesWritten != (ssize_t)mallocIO.BufferLength())
		return B_IO_ERROR;

	// set mimetype-, language- and signature-attributes:
	UpdateAttributes(catalogFile);

	return B_OK;
}
status_t
BPhotoContactField::Flatten(void* buffer, ssize_t size) const
{
	if (size < FlattenedSize())
		return B_ERROR;

	BMemoryIO flatData(buffer, size);
	status_t ret = BContactField::Flatten(&flatData);
	if (ret != B_OK)
		return ret;

	ssize_t destSize;

	if (fBitmap != NULL) {
		BMessage msg;
		BMallocIO dest;

		fBitmap->Archive(&msg);
		destSize = msg.FlattenedSize();
		msg.Flatten(&dest);

		flatData.Write(&destSize, sizeof(destSize));
		flatData.Write(dest.Buffer(), destSize);
	} else {
		size = 0;
		flatData.Write(&size, sizeof(destSize));
	}

	return B_OK;
}
Esempio n. 10
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;
}
Esempio n. 11
0
// 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);
}
Esempio n. 12
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;
}
Esempio n. 13
0
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;
};
Esempio n. 14
0
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);
}
Esempio n. 15
0
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);
}
Esempio n. 16
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);
}
Esempio n. 17
0
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);
	}
}
Esempio n. 18
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;
}
Esempio n. 19
0
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);
}
Esempio n. 20
0
/*!
	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;
}
Esempio n. 21
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;
		}
	}
}
Esempio n. 22
0
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);
}
Esempio n. 23
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;
}
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);
    }
}
Esempio n. 25
0
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;

}