Exemplo n.º 1
0
void MediaRoutingView::_changeBackground(
	entry_ref *ref)
{
	D_METHOD(("MediaRoutingView::_changeBackground()\n"));

	status_t error;
	BBitmap *background = 0; 
	BFile file(ref, B_READ_ONLY); 
	error = file.InitCheck();
	if (!error)
	{
		BTranslatorRoster *roster = BTranslatorRoster::Default(); 
		BBitmapStream stream; 
		error = roster->Translate(&file, NULL, NULL, &stream, B_TRANSLATOR_BITMAP);
		if (!error)
		{
			stream.DetachBitmap(&background); 
			setBackgroundBitmap(background);
			Invalidate();

			// [e.moon 1dec99] persistence, yay
			m_backgroundBitmapEntry.SetTo(ref);
		}
	}
	delete background;
}
Exemplo n.º 2
0
void
ImageView::SaveImageAtDropLocation(BMessage *pmsg)
{
	// Find the location and name of the drop and
	// write the image file there
	BBitmapStream stream(fpbitmap);

	StatusCheck chk;
		// throw an exception if this is assigned
		// anything other than B_OK

	try {
		entry_ref dirref;
		chk = pmsg->FindRef("directory", &dirref);
		const char *filename;
		chk = pmsg->FindString("name", &filename);

		BDirectory dir(&dirref);
		BFile file(&dir, filename, B_WRITE_ONLY | B_CREATE_FILE);
		chk = file.InitCheck();

		BTranslatorRoster *proster = BTranslatorRoster::Default();
		chk = proster->Translate(&stream, NULL, NULL, &file, B_TGA_FORMAT);

	} catch (StatusNotOKException) {
		BAlert *palert = new BAlert(NULL,
			B_TRANSLATE("Sorry, unable to write the image file."),
			B_TRANSLATE("OK"));
		palert->Go();
	}

	stream.DetachBitmap(&fpbitmap);
}
Exemplo n.º 3
0
status_t
SlideShowSaver::SetImage(const entry_ref *pref)
{
	entry_ref ref;
	if (!pref)
		ref = fCurrentRef;
	else
		ref = *pref;

	BTranslatorRoster *proster = BTranslatorRoster::Default();
	if (!proster)
		return B_ERROR;

	if (ent_is_dir(pref) != B_OK)
		// if ref is erroneous or a directory, return error
		return B_ERROR;

	BFile file(&ref, B_READ_ONLY);
	translator_info info;
	memset(&info, 0, sizeof(translator_info));
	BMessage ioExtension;
	//if (ref != fCurrentRef)
		// if new image, reset to first document
	//	fDocumentIndex = 1;
	if (ioExtension.AddInt32("/documentIndex", 1 /*fDocumentIndex*/) != B_OK)
		return B_ERROR;
	if (proster->Identify(&file, &ioExtension, &info, 0, NULL,
		B_TRANSLATOR_BITMAP) != B_OK)
		return B_ERROR;

	// Translate image data and create a new ShowImage window
	BBitmapStream outstream;
	if (proster->Translate(&file, &info, &ioExtension, &outstream,
		B_TRANSLATOR_BITMAP) != B_OK)
		return B_ERROR;
	BBitmap *newBitmap = NULL;
	if (outstream.DetachBitmap(&newBitmap) != B_OK)
		return B_ERROR;

	// Now that I've successfully loaded the new bitmap,
	// I can be sure it is safe to delete the old one,
	// and clear everything
	delete fBitmap;
	fBitmap = newBitmap;
	newBitmap = NULL;
	fCurrentRef = ref;

	// Get path to use in caption
	fCaption = "<< Unable to read the path >>";
	BEntry entry(&fCurrentRef);
	if (entry.InitCheck() == B_OK) {
		BPath path(&entry);
		if (path.InitCheck() == B_OK) {
			fCaption = path.Path();
		}
	}

	return B_OK;
}
Exemplo n.º 4
0
status_t
ThemeManager::SetThemeScreenShot(int32 id, BBitmap *bitmap)
{
	FENTRY;
	status_t err;
	BMessage msg;
	BString name;
	BString themepath;
	BMessage *theme;
	
	if (id < 0)
		return EINVAL;
	theme = (BMessage *)fThemeList.ItemAt(id);
	if (!theme)
		return EINVAL;
	
	// TODO
	err = theme->FindMessage(Z_THEME_INFO_MESSAGE, &msg);
	if (err) {
		msg.MakeEmpty();
		theme->AddMessage(Z_THEME_INFO_MESSAGE, &msg);
	}
	err = ThemeLocation(id, themepath);
	if (err)
		return err;
	err = msg.FindString(Z_THEME_SCREENSHOT_FILENAME, &name);
	if (!err) {
		BPath spath(themepath.String());
		spath.Append(name.String());
		BEntry ent(spath.Path());
		if (ent.InitCheck() == B_OK)
			ent.Remove();
	}
	
	name = "screenshot.png";
	err = msg.ReplaceString(Z_THEME_SCREENSHOT_FILENAME, name);
	if (err)
		err = msg.AddString(Z_THEME_SCREENSHOT_FILENAME, name);
	if (err)
		return err;
	
	// save the BBitmap to a png
	BPath spath(themepath.String());
	spath.Append(name.String());
	BFile shotfile(spath.Path(), B_WRITE_ONLY|B_CREATE_FILE);
	if (shotfile.InitCheck() != B_OK)
		return shotfile.InitCheck();
	BTranslatorRoster *troster = BTranslatorRoster::Default();
	BBitmapStream bmstream(bitmap);
	err = troster->Translate(&bmstream, NULL, NULL, &shotfile, 'PNG '/* XXX: hack, should find by mime type */);
	if (err)
		return err;
	
	err = theme->ReplaceMessage(Z_THEME_INFO_MESSAGE, &msg);
	msg.PrintToStream();
	return err;
}
Exemplo n.º 5
0
BBitmap * RBitmapLoader::TranslateBitmap(const char *name)
{
	 BPath path(&mAppDir, name);
	 BFile file(path.Path(), B_READ_ONLY); 
	 BTranslatorRoster *roster; 
	 BBitmapStream stream; 
	 BBitmap *result = NULL; 
	 roster = BTranslatorRoster::Default();
	 if (roster->Translate(&file, NULL, NULL, &stream,  B_TRANSLATOR_BITMAP) < B_OK) 
		 result = NULL; 
	 else stream.DetachBitmap(&result); 
	 return result; 
}
Exemplo n.º 6
0
/*=============================================================================================*\
|	FetchBitmap																					|
+-----------------------------------------------------------------------------------------------+
|	Effet: Converie une image en un BBitmap. La couleur de transparence est celle du pixel dans	|
|			le coin superieur gauche.															|
|	Entree:																						|
|		char *pzFileName: Le path du fichier image a convertir.									|
|		bool bTran: True si on utilise la transparence, false sinon.							|
|	Sortie:																						|
|		BBitmap *: Le pointeur le bitmap de l'image. NULL si la conversion a echouer.			|
\*=============================================================================================*/
BBitmap*
BitmapCatalog::FetchBitmap(char* pzFileName, bool bTrans) 
{ 


	BFile file(pzFileName, B_READ_ONLY); 
	BTranslatorRoster *roster = BTranslatorRoster::Default(); 
	BBitmapStream stream; 
	BBitmap *result = NULL; 
	if (roster->Translate(&file, NULL, NULL, &stream, B_TRANSLATOR_BITMAP) < B_OK) 
		return NULL; 
	stream.DetachBitmap(&result); 


//  OliverESP: 7 x 1 so -> #include <TranslationUtils.h> //OliverESP:
//			   less code and works
	//BBitmap *result = BTranslationUtils::GetBitmapFile(pzFileName);
	
	if (result == NULL)
		return NULL;

	if(!bTrans)
		return result;
	
	int32 iLenght = result->BitsLength() / 4;
	int32 i;
	int32 * cBit = (int32*)result->Bits();
	int32 backColor = cBit[result->Bounds().IntegerWidth() - 1];
	int32 iTrans = 0;
      
	//Determine le mode de definition de couleur
	switch(result->ColorSpace())
	{
	case B_RGB32:		iTrans = B_TRANSPARENT_MAGIC_RGBA32; break;
	case B_RGB32_BIG:	iTrans = B_TRANSPARENT_MAGIC_RGBA32_BIG; break;
	default:			break; //TODO: Major screwup here!
	}

	if (iTrans)
	{
		for(i = 0; i < iLenght; i++)
		{
			if(cBit[i] == backColor)
				cBit[i] = iTrans;
		}
	}

	return result; 
}
Exemplo n.º 7
0
status_t
PictureView::_LoadPicture(const entry_ref* ref)
{
	BFile file;
	status_t status = file.SetTo(ref, B_READ_ONLY);
	if (status != B_OK)
		return status;

	off_t fileSize;
	status = file.GetSize(&fileSize);
	if (status != B_OK)
		return status;

	// Check that we've at least some data to translate...
	if (fileSize < 1)
		return B_OK;

	translator_info info;
	memset(&info, 0, sizeof(translator_info));
	BMessage ioExtension;

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

	status = roster->Identify(&file, &ioExtension, &info, 0, NULL,
		B_TRANSLATOR_BITMAP);

	BBitmapStream stream;

	if (status == B_OK) {
		status = roster->Translate(&file, &info, &ioExtension, &stream,
			B_TRANSLATOR_BITMAP);
	}
	if (status != B_OK)
		return status;

	BBitmap* picture = NULL;
	if (stream.DetachBitmap(&picture) != B_OK
		|| picture == NULL)
		return B_ERROR;

	// Remember image format so we could store using the same
	fPictureMIMEType = info.MIME;
	fPictureType = info.type;

	_SetPicture(picture);
	return B_OK;
}
Exemplo n.º 8
0
void
PersonView::Save()
{
	BFile file(fRef, B_READ_WRITE);
	if (file.InitCheck() != B_NO_ERROR)
		return;

	fSaving = true;

	int32 count = fControls.CountItems();
	for (int32 i = 0; i < count; i++) {
		AttributeTextControl* control = fControls.ItemAt(i);
		const char* value = control->Text();
		file.WriteAttr(control->Attribute().String(), B_STRING_TYPE, 0,
			value, strlen(value) + 1);
		control->Update();
	}

	// Write the picture, if any, in the person file content
	if (fPictureView) {
		// Trim any previous content
		file.Seek(0, SEEK_SET);
		file.SetSize(0);

		BBitmap* picture = fPictureView->Bitmap();
		if (picture) {
			BBitmapStream stream(picture);
			// Detach *our* bitmap from stream to avoid its deletion
			// at stream object destruction
			stream.DetachBitmap(&picture);

			BTranslatorRoster* roster = BTranslatorRoster::Default();
			roster->Translate(&stream, NULL, NULL, &file,
				fPictureView->SuggestedType(), B_TRANSLATOR_BITMAP,
				fPictureView->SuggestedMIMEType());

		}

		fPictureView->Update();
	}

	file.GetModificationTime(&fLastModificationTime);

	fSaving = false;
}
Exemplo n.º 9
0
/*!
	Save the screenshot to the file with the specified filename and type.
	Note that any existing file with the same filename will be overwritten
	without warning.
*/
status_t
Utility::Save(BBitmap** screenshot, const char* fileName, uint32 imageType)
	const
{
	BString fileNameString(fileName);

	// Generate a default filename when none is given
	if (fileNameString.Compare("") == 0) {
		BPath homePath;
		if (find_directory(B_USER_DIRECTORY, &homePath) != B_OK)
			return B_ERROR;

		BEntry entry;
		int32 index = 1;
		BString extension = GetFileNameExtension(imageType);
		do {
			fileNameString.SetTo(homePath.Path());
			fileNameString << "/" << B_TRANSLATE(sDefaultFileNameBase) << index++ 
				<< extension;
			entry.SetTo(fileNameString.String());
		} while (entry.Exists());
	}

	// Create the file
	BFile file(fileNameString, B_CREATE_FILE | B_ERASE_FILE | B_WRITE_ONLY);
	if (file.InitCheck() != B_OK)
		return B_ERROR;

	// Write the screenshot bitmap to the file
	BBitmapStream stream(*screenshot);
	BTranslatorRoster* roster = BTranslatorRoster::Default();
	roster->Translate(&stream, NULL, NULL, &file, imageType,
		B_TRANSLATOR_BITMAP);
	*screenshot = NULL;

	// Set the file MIME attribute
	BNodeInfo nodeInfo(&file);
	if (nodeInfo.InitCheck() != B_OK)
		return B_ERROR;

	nodeInfo.SetType(_GetMimeString(imageType));

	return B_OK;
}
/*=============================================================================================*\
|	FetchBitmap																					|
+-----------------------------------------------------------------------------------------------+
|	Effet: Converie une image en un BBitmap. La couleur de transparence est celle du pixel dans	|
|			le coin superieur gauche.															|
|	Entree:																						|
|		char *pzFileName: Le path du fichier image a convertir.									|
|		bool bTran: True si on utilise la transparence, false sinon.							|
|	Sortie:																						|
|		BBitmap *: Le pointeur le bitmap de l'image. NULL si la conversion a echouer.			|
\*=============================================================================================*/
BBitmap * BeNetBitmapCatalog::FetchBitmap(char *pzFileName, bool bTrans) 
{ 
      BFile file(pzFileName, B_READ_ONLY); 
      BTranslatorRoster *roster = BTranslatorRoster::Default(); 
      BBitmapStream stream; 
      BBitmap *result = NULL; 
      if (roster->Translate(&file, NULL, NULL, &stream, 
            B_TRANSLATOR_BITMAP) < B_OK) 
         return NULL; 
      stream.DetachBitmap(&result); 
            
      
      if(!bTrans) return result;
      int32 iLenght = result->BitsLength() / 4;
      int32 i;
      int32 * cBit = (int32)result->Bits();
      int32 backColor = cBit[result->Bounds().IntegerWidth() - 1];
      int32 iTrans = 0;
      
      //Determine le mode de definition de couleur
      switch(result->ColorSpace())
      {
      		case B_RGB32:{
      				iTrans = B_TRANSPARENT_MAGIC_RGBA32;
      			}break;
      		case B_RGB32_BIG:{
      				iTrans = B_TRANSPARENT_MAGIC_RGBA32_BIG;
      			}break;
       }
      
      if(iTrans)
      {
     	for(i = 0; i < iLenght; i++)
      	{
      		if(cBit[i] == backColor)
      		{
     			cBit[i] = B_TRANSPARENT_MAGIC_RGBA32_BIG;
      		}
      	}
      }
      
      return result; 
}//Fin de FetchBitmap.
Exemplo n.º 11
0
ImageView::ImageView(BPositionIO *image)
	:
	BView(BRect(0, 0, 1, 1), "image_view", B_FOLLOW_NONE, B_WILL_DRAW),
	fSuccess(true)
{
	if (!image) {
		fSuccess = false;
		return;
	}
	// Initialize and translate the image
	BTranslatorRoster *roster = BTranslatorRoster::Default();
	BBitmapStream stream;
	if (roster->Translate(image, NULL, NULL, &stream, B_TRANSLATOR_BITMAP)
			< B_OK) {
		fSuccess = false;
		return;
	}
	stream.DetachBitmap(&fImage);
}
void PDocument::Load(void)
{
	TRACE();
	status_t			err				= B_OK;
	BFile				*file			= new BFile(entryRef,B_READ_ONLY);
	BMessage			*node			= NULL;
	BTranslatorRoster	*roster			= NULL;
	BMallocIO			*output			= new BMallocIO();
	BMessage			*loaded			= new BMessage();
	int32				i				= 0;
	translator_info		*indentifed		= new translator_info;
	bool locked = Lock();

	if (file->InitCheck() == B_OK)
	{
		roster	= BTranslatorRoster::Default();
		roster->Identify(file,NULL,indentifed,P_C_DOCUMENT_RAW_TYPE );
		err 	= roster->Translate(file,indentifed,NULL,output,P_C_DOCUMENT_RAW_TYPE);
		//buffer = (void *)output->Buffer();
		if (err == B_OK)
		{
			err = loaded->Unflatten(output);
			printf("%s",strerror(err));
			loaded->PrintToStream();
			ResetModified();
		}
	}
	else
	 //**error handling
	;
	//docloader handles the Format and Stuff also the input translation
	PDocLoader	*docLoader	= new PDocLoader(this,loaded);
	delete allNodes;
	delete allConnections;
	delete printerSetting;
	delete selected;

	allNodes 		= docLoader->GetAllNodes();
	for (i = 0; i<allNodes->CountItems(); i++)
	{
		node=((BMessage*)allNodes->ItemAt(i));
		node->AddPointer("ProjectConceptor::doc",this);
		valueChanged->AddItem(node);
	}
	allConnections	= docLoader->GetAllConnections();
	for (i = 0; i<allConnections->CountItems(); i++)
	{
		node= (BMessage *)allConnections->ItemAt(i);
		node->AddPointer("ProjectConceptor::doc",this);
		valueChanged->AddItem(node);
	}
	selected = docLoader->GetSelectedNodes();
	delete commandManager;
	commandManager= new PCommandManager(this);
	commandManager->SetMacroList(docLoader->GetMacroList());
	commandManager->SetUndoList(docLoader->GetUndoList());
	commandManager->SetUndoIndex(docLoader->GetUndoIndex());
//	commandManager->LoadMacros(docLoader->GetCommandManagerMessage());
//	commandManager->LoadUndo(docLoader->GetCommandManagerMessage());
	SetPrintSettings( docLoader->GetPrinterSetting());
	editorManager->BroadCast(new BMessage(P_C_VALUE_CHANGED));
	if (locked)
		Unlock();
}
Exemplo n.º 13
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);
}
status_t
OptiPNGTranslator::DerivedTranslate(BPositionIO *source,
	const translator_info *info, BMessage *ioExtension,
	uint32 outType, BPositionIO *target, int32 baseType)
{
	if(baseType == 1 && outType == OPTIPNG_PNG_FORMAT) {
		// create temp file
		int tempFileFD;
		BPath tempDir;
		BString tempFilePath;
		if(find_directory(B_SYSTEM_TEMP_DIRECTORY, &tempDir) != B_OK )
			return B_ERROR;
		
		tempFilePath.Append(tempDir.Path())
			.Append("/OptiPNGTranslator.XXXXXX");
		
		tempFileFD = mkstemp(tempFilePath.LockBuffer(0));
		tempFilePath.UnlockBuffer();
		
		if(tempFileFD == -1)
			return B_ERROR;
		close(tempFileFD);
		
		BFile tempFile = BFile(tempFilePath, O_WRONLY);
		
		// write PNG to file
		off_t sourceSize;
		source->GetSize(&sourceSize);
		unsigned char sourceChars[sourceSize];
		
		BTranslatorRoster *roster = BTranslatorRoster::Default();
		roster->Translate(source, NULL, NULL, &tempFile, (uint32)B_PNG_FORMAT);
		
		// optimize file
		BString optipng;
		if(system("optipng &> /dev/null") == 0) {
			optipng = "optipng";
		} else if(system("optipng-x86 &> /dev/null") == 0) {
			optipng = "optipng-x86";
		} else {
			return B_ERROR;
		}
		
		// optipng -clobber -out (file) (file)
		BString command;
		command = optipng;
		if(!fSettings->SetGetBool(OPTIPNG_SETTING_BIT_DEPTH_REDUCTION))
			command += " -nb"; // no bit-depth reduction
		if(!fSettings->SetGetBool(OPTIPNG_SETTING_COLOR_TYPE_REDUCTION))
			command += " -nc";
		if(!fSettings->SetGetBool(OPTIPNG_SETTING_PALETTE_REDUCTION))
			command += " -np";
		
		command.Append(" -o")
			.Append((char)(fSettings->
				SetGetInt32(OPTIPNG_SETTING_OPTIMIZATION_LEVEL)+'0'),1);
		// rest of command
		command.Append(" -clobber -out ")
			.Append(tempFilePath)
			.Append(" ")
			.Append(tempFilePath)
		;
		
		if(system(command) != 0) {
			return B_ERROR;
		}
		
		// read the file
		tempFile = BFile(tempFilePath, O_RDONLY);
		
		off_t fileSize;
		tempFile.GetSize(&fileSize);
		unsigned char *buffer;
		
		buffer = new unsigned char[fileSize];
		if(buffer == NULL)
			return B_ERROR;
		tempFile.ReadAt(0, buffer, fileSize);
		target->Write(buffer, fileSize);
		delete [] buffer;
		
		// delete the file
		BEntry entry = BEntry(tempFilePath);
		entry.Remove();
		
		return B_OK;
	}
	return B_NO_TRANSLATOR;
}
Exemplo n.º 15
0
void AppWindow::OnSaveGraph(BMessage *msg) {
entry_ref dir;
BString name, extension;
uint32 type; int i;
	msg->FindRef("directory", &dir);
	msg->FindString("name", &name);
	GetExtension(name, extension);
	for (i = 0; (file_types[i].extension != NULL) && 
				(extension != file_types[i].extension); i++);
	type = file_types[i].type;
	if (type != 0) {
		BDirectory dir2(&dir);
		BEntry file(&dir2, name.String());
		BPath path;
		file.GetPath(&path);

		BRect rect;
		BBitmap *bitmap = GetGraph(rect, B_CMAP8);
	
		if (bitmap != NULL) {
			BTranslatorRoster *roster = BTranslatorRoster::Default();
			BBitmapStream stream(bitmap);
			BFile file(path.Path(), B_CREATE_FILE | B_WRITE_ONLY);
			if (B_OK != roster->Translate(&stream, NULL, NULL, &file, type)) {
			BAlert *alert = new BAlert("Error", "Error in translator!\nCould not write file", "Ok");
				BEntry e(path.Path());
				e.Remove();
				alert->Go();
			}
			stream.DetachBitmap(&bitmap);
			delete bitmap;
		}
	} else {
		BAlert *alert = new BAlert("Error", "Unknown file format!", "Ok");
		alert->Go();
	}
/*	// print output translators to stdout
	translator_id *translators;
	int32 num_translators;
	BTranslatorRoster *roster = BTranslatorRoster::Default();
	
	roster->GetAllTranslators(&translators, &num_translators);

	for (int32 i = 0; i < num_translators; i++) {
		const translation_format *fmts;
		int32 num_fmts;
		const char *tname, *tinfo;
		int32 tversion;
		roster->GetTranslatorInfo(translators[i], &tname, &tinfo, &tversion);
		printf("%s: %s (%.2f)\n", tname, tinfo, tversion/100.0);
		roster->GetOutputFormats(translators[i], &fmts, &num_fmts);
		
		for (int32 j = 0; j < num_fmts; j++) {
			if (fmts[j].group == B_TRANSLATOR_BITMAP) { 
				if (fmts[j].type == B_TRANSLATOR_BITMAP) continue;
				printf("%d %d [%s] %s \"%4.4s\"\n", i, j, fmts[j].MIME, fmts[j].name,
						&fmts[j].type);
				break;
			}
		}
	}
	
	delete [] translators;
	fflush(stdout);
*/
}
Exemplo n.º 16
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);
    }
}
Exemplo n.º 17
0
BMallocIO *DragonView::_TranslateBitmap( BMessage *msg, char **type_out )
{
	// We'll need to access the Translation Kit's BTranslatorRoster...

	BTranslatorRoster *roster = BTranslatorRoster::Default();
	
	// We'll start by looking through be:types; if we need to look in
	// be:filetypes, we'll reset these.

	int type_idx = 0;
	const char *field_name = "be:types";

	const char *target_mime = msg->FindString( field_name, type_idx );
	if( !strcasecmp( target_mime, B_FILE_MIME_TYPE ) ) {
		// If target_mime == B_FILE_MIME_TYPE then we should be checking
		// in be:filetypes... this will end up being written to a file.

		field_name = "be:filetypes";
		target_mime = msg->FindString( field_name, type_idx );
	}

	while( target_mime ) {
		// Can any of the Translators give us data in this type?  First
		// we'll need to convert the MIME type to a Translation Kit type
		// code.

		uint32 target_code = _Mime2TypeCode( roster, target_mime );

		if( target_code != 0 ) {
			// We've found a translation type; let's try translating the
			// data.

			_bits_mutex.Lock();

			BMallocIO *bit_buff = new BMallocIO;
			BBitmapStream bit_stream( _bits );

			status_t retval = roster->Translate( &bit_stream, NULL, NULL,
												 bit_buff, target_code );

			BBitmap *detached;
			(void)bit_stream.DetachBitmap( &detached );

			_bits_mutex.Unlock();

			if( retval == B_OK ) {
				// Successful translation!  Woo-hoo!
				//
				// Make a copy of the MIME type we translated to, and then
				// send back the data.

				*type_out = new char[strlen( target_mime ) + 1];
				strcpy( *type_out, target_mime );

				return bit_buff;
			} else {
				delete bit_buff;
			}
		}

		// That didn't work... let's try the next one.

		type_idx++;
		target_mime = msg->FindString( field_name, type_idx );
	}

	// If you got here, we didn't manage to translate the data.  Dang.

	*type_out = NULL;
	return NULL;
}
Exemplo n.º 18
0
status_t
RAWTranslator::DerivedTranslate(BPositionIO* stream,
	const translator_info* info, BMessage* settings,
	uint32 outType, BPositionIO* target, int32 baseType)
{
	if (!outType)
		outType = B_TRANSLATOR_BITMAP;
	if (outType != B_TRANSLATOR_BITMAP || baseType != 0)
		return B_NO_TRANSLATOR;

	BBufferIO io(stream, 1024 * 1024, false);
	DCRaw raw(io);

	bool headerOnly = false;

	progress_data progressData;
	BMessenger monitor;

	if (settings != NULL) {
		settings->FindBool(B_TRANSLATOR_EXT_HEADER_ONLY, &headerOnly);

		bool half;
		if (settings->FindBool("raw:half_size", &half) == B_OK && half)
			raw.SetHalfSize(true);

		if (settings->FindMessenger(kProgressMonitor,
				&progressData.monitor) == B_OK
			&& settings->FindMessage(kProgressMessage,
				&progressData.message) == B_OK) {
			raw.SetProgressMonitor(&_ProgressMonitor, &progressData);
			_ProgressMonitor("Reading Image Data", 0, &progressData);
		}
	}

	int32 imageIndex = 0;
	uint8* buffer = NULL;
	size_t bufferSize;
	status_t status;

	try {
		status = raw.Identify();

		if (status == B_OK && settings) {
			// Check if a document index has been specified
			if (settings->FindInt32(kDocumentIndex, &imageIndex) == B_OK)
				imageIndex--;
			else
				imageIndex = 0;

			if (imageIndex < 0 || imageIndex >= (int32)raw.CountImages())
				status = B_BAD_VALUE;
		}
		if (status == B_OK && !headerOnly)
			status = raw.ReadImageAt(imageIndex, buffer, bufferSize);
	} catch (status_t error) {
		status = error;
	}

	if (status < B_OK)
		return B_NO_TRANSLATOR;

	FreeAllocation _(buffer);
		// frees the buffer on destruction

	image_meta_info meta;
	raw.GetMetaInfo(meta);

	image_data_info data;
	raw.ImageAt(imageIndex, data);

	if (!data.is_raw) {
		// let others handle embedded JPEG data
		BMemoryIO io(buffer, bufferSize);
		BMessage buffer;
		if (meta.flip != 1) {
			// preserve orientation
			if (settings == NULL)
				settings = &buffer;
			settings->AddInt32("exif:orientation", meta.flip);
		}

		BTranslatorRoster* roster = BTranslatorRoster::Default();
		return roster->Translate(&io, NULL, settings, target, outType);
	}

	// retrieve EXIF data
	off_t exifOffset;
	size_t exifLength;
	bool bigEndian;
	if (settings != NULL && raw.GetEXIFTag(exifOffset, exifLength, bigEndian) == B_OK) {
		uint8* exifBuffer = (uint8*)malloc(exifLength + 16);
		if (exifBuffer != NULL) {
			// add fake TIFF header to EXIF data
			struct {
				uint16	endian;
				uint16	tiff_marker;
				uint32	offset;
				uint16	null;
			} _PACKED header;
			header.endian = bigEndian ? 'MM' : 'II';
			header.tiff_marker = 42;
			header.offset = 16;
			header.null = 0;
			memcpy(exifBuffer, &header, sizeof(header));

			if (io.ReadAt(exifOffset, exifBuffer + 16, exifLength)
					== (ssize_t)exifLength)
				settings->AddData("exif", B_RAW_TYPE, exifBuffer, exifLength + 16);

			free(exifBuffer);
		}
	}
	uint32 dataSize = data.output_width * 4 * data.output_height;

	TranslatorBitmap header;
	header.magic = B_TRANSLATOR_BITMAP;
	header.bounds.Set(0, 0, data.output_width - 1, data.output_height - 1);
	header.rowBytes = data.output_width * 4;
	header.colors = B_RGB32;
	header.dataSize = dataSize;

	// write out Be's Bitmap header
	swap_data(B_UINT32_TYPE, &header, sizeof(TranslatorBitmap),
		B_SWAP_HOST_TO_BENDIAN);
	ssize_t bytesWritten = target->Write(&header, sizeof(TranslatorBitmap));
	if (bytesWritten < B_OK)
		return bytesWritten;

	if ((size_t)bytesWritten != sizeof(TranslatorBitmap))
		return B_IO_ERROR;

	if (headerOnly)
		return B_OK;

	bytesWritten = target->Write(buffer, dataSize);
	if (bytesWritten < B_OK)
		return bytesWritten;

	if ((size_t)bytesWritten != dataSize)
		return B_IO_ERROR;

	return B_OK;
}
Exemplo n.º 19
0
void
BitmapView::MessageReceived(BMessage *msg)
{
	if (msg->WasDropped() && AcceptsDrops()) {
		// We'll handle two types of drops: those from Tracker and those from ShowImage
		if (msg->what == B_SIMPLE_DATA) {
			int32 actions;
			if (msg->FindInt32("be:actions", &actions) == B_OK) {
				// ShowImage drop. This is a negotiated drag&drop, so send a reply
				BMessage reply(B_COPY_TARGET), response;
				reply.AddString("be:types", "image/jpeg");
				reply.AddString("be:types", "image/png");
				
				msg->SendReply(&reply, &response);
				
				// now, we've gotten the response
				if (response.what == B_MIME_DATA) {
					// Obtain and translate the received data
					uint8 *imagedata;
					ssize_t datasize;
										
					// Try JPEG first
					if (response.FindData("image/jpeg", B_MIME_DATA, 
						(const void **)&imagedata, &datasize) != B_OK) {
						// Try PNG next and piddle out if unsuccessful
						if (response.FindData("image/png", B_PNG_FORMAT, 
							(const void **)&imagedata, &datasize) != B_OK)
							return;
					}
					
					// Set up to decode into memory
					BMemoryIO memio(imagedata, datasize);
					BTranslatorRoster *roster = BTranslatorRoster::Default();
					BBitmapStream bstream;
					
					if (roster->Translate(&memio, NULL, NULL, &bstream, B_TRANSLATOR_BITMAP) == B_OK)
					{
						BBitmap *bmp;
						if (bstream.DetachBitmap(&bmp) != B_OK)
							return;
						SetBitmap(bmp);
						
						if (fConstrainDrops)
							ConstrainBitmap();
						Invoke();
					}
				}
				return;
			}
			
			entry_ref ref;
			if (msg->FindRef("refs", &ref) == B_OK) {
				// Tracker drop
				BBitmap *bmp = BTranslationUtils::GetBitmap(&ref);
				if (bmp) {
					SetBitmap(bmp);
					
					if (fConstrainDrops)
						ConstrainBitmap();
					Invoke();
				}
			}
		}
		return;
	}
	
	switch (msg->what)
	{
		case M_REMOVE_IMAGE: {
			BAlert *alert = new BAlert("ResEdit", "This cannot be undone. "
				"Remove the image?", "Remove", "Cancel");
			alert->SetShortcut(1, B_ESCAPE);
			int32 value = alert->Go();
			if (value == 0) {
				SetBitmap(NULL);
				
				if (Target()) {
					BMessenger msgr(Target());
					
					msgr.SendMessage(new BMessage(M_BITMAP_REMOVED));
					return;
				}
			}
		}
		case M_PASTE_IMAGE:
		{
			PasteBitmap();
			Invoke();
		}
	}
	BView::MessageReceived(msg);
}
Exemplo n.º 20
0
BBitmap *RBitmapLoader::LoadBitmap(const char *name)
{
	// Init App 
	if (!initied) init();
	// try to load image from ressource
	BBitmap *mImage32  = 0;
	app_info info;
	be_app->GetAppInfo(&info);
	BFile resFile(&info.ref, B_READ_WRITE);
	if (resFile.InitCheck() == B_NO_ERROR)
	{
		BResources res(&resFile);
		int32 idFound;
		size_t size;
		if (res.GetResourceInfo('IMAG', name, &idFound, &size))
		{
			// ressource exist, load it into a buffer
			char *image_data = new char[size];
             ASSERT(image_data);
			if (res.ReadResource('IMAG', idFound, image_data, 0, size) == B_NO_ERROR)
			{
				// map a BMemoryIO to point onto these data
				BMemoryIO mem(image_data, size);
				
				// read with translation kit from the data
				BTranslatorRoster *roster = BTranslatorRoster::Default(); 
				BBitmapStream stream; 
				if (roster->Translate(&mem, NULL, NULL, &stream,  B_TRANSLATOR_BITMAP) >= B_OK)
					stream.DetachBitmap(&mImage32); 
			}
			// delete buffer
			delete image_data;
		}
	}

	if (!mImage32)
	{
		printf("Load into resource %s\n",name);
		// if not in ressource, load from file and copy into ressources
		mImage32 = TranslateBitmap(name);
		if (!mImage32) 
		{
			return NULL;
		}
		// try to put into ressource
		BPath path(&mAppDir, name);
		BFile input(path.Path(), B_READ_ONLY);
		if (resFile.InitCheck() == B_NO_ERROR && input.InitCheck() == B_NO_ERROR)
		{
			BResources res(&resFile);
			input.Seek(0, SEEK_END);
			off_t insize = input.Position();
			input.Seek(0, SEEK_SET);
			char *data = new char[insize];
			if (data)
			{
				input.Read(data, insize);
				if (res.AddResource('IMAG',  g_current_id , data, insize, name)==B_OK)
				{
					g_current_id ++;
				}
				delete data;
			}
		}
	}
	return mImage32;
} 
void PDocument::Save(void)
{
	TRACE();
	status_t			err 				= B_OK;
	BTranslatorRoster	*roster				= BTranslatorRoster::Default();
	BMessage			*archived			= new BMessage();
	BMessage			*saveSettings		= new BMessage();
	char				*formatName			= NULL;
	translator_info		*translatorInfo		= new translator_info;
	int32				tmpInt				= 0;
	int32				outType				= 0;

	bool locked = Lock();
	documentSetting->FindMessage("saveSettings",saveSettings);
	if (saveSettings->FindInt32("translator_id",&tmpInt) == B_OK)
	{
		translatorInfo->translator	= tmpInt;
		saveSettings->FindString("format::name",(const char**)&formatName);
		//saveSettings->FindString("format::MIME",(const char**)&formatMIME);
		strcpy((translatorInfo->name),formatName);
		strcpy((translatorInfo->MIME),P_C_DOCUMENT_MIMETYPE);
		saveSettings->FindInt32("format::type",(int32 *)&outType);
		translatorInfo->type				= P_C_DOCUMENT_RAW_TYPE;
//		saveSettings->FindInt32("format::group",(int32 *)&tmpInt);
		translatorInfo->group				= P_C_DOCUMENT_RAW_TYPE;
//		saveSettings->FindFloat("format::quality",(float *)&tmpFloat);
		translatorInfo->quality				= 0.9;
//		saveSettings->FindFloat("format::capability",(float *)&tmpFloat);
		translatorInfo->capability			= 0.9;
		Archive(archived,true);
		BPositionIO		*input	= new BMallocIO();
		BFile			*file	= new BFile(entryRef,B_WRITE_ONLY | B_ERASE_FILE | B_CREATE_FILE);
		archived->Flatten(input);
		err=	roster->Translate(input,translatorInfo,NULL,file,outType);
		if (err == B_OK)
		{
			BNodeInfo nodeInfo(file);
			nodeInfo.SetType(P_C_DOCUMENT_MIMETYPE);
			nodeInfo.SetPreferredApp(APP_SIGNATURE);
		}
	}
	else
	{
		Archive(archived,true);
		if (entryRef)
		{
			BFile *file=	new BFile(entryRef,B_WRITE_ONLY | B_ERASE_FILE | B_CREATE_FILE);
			err=file->InitCheck();
			PRINT(("ERROR\tSave file error %s\n",strerror(err)));
			err = archived->Flatten(file);
			if (err == B_OK)
			{
				BNodeInfo nodeInfo(file);
				nodeInfo.SetType(P_C_DOCUMENT_MIMETYPE);
				nodeInfo.SetPreferredApp(APP_SIGNATURE);
			}
		}
	}
	if (err==B_OK)
	{
			ResetModified();
			window->SetTitle(Title());
	}
	else
		PRINT(("ERROR:\tPDocument","Save error %s\n",strerror(err)));
	if (locked)
		Unlock();
}