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; }
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 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; }
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; }
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(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; }
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; }
// 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); }
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; }
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); }
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; };
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); }
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); }
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; }
/* * 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; }
/*! \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); }
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); } }
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); }
/*! 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; }
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); }
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; }
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); } }
/*! 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; }