// write string to output: inline static void OutputString(wxOutputStream& stream, const wxString& str, wxMBConv *convMem = NULL, wxMBConv *convFile = NULL) { if (str.empty()) return; #if wxUSE_UNICODE wxUnusedVar(convMem); const wxWX2MBbuf buf(str.mb_str(*(convFile ? convFile : &wxConvUTF8))); if ( !buf ) return; stream.Write((const char*)buf, strlen((const char*)buf)); #else // !wxUSE_UNICODE if ( convFile && convMem ) { wxString str2(str.wc_str(*convMem), *convFile); stream.Write(str2.mb_str(), str2.Len()); } else // no conversions to do { stream.Write(str.mb_str(), str.Len()); } #endif // wxUSE_UNICODE/!wxUSE_UNICODE }
void ArchiveTestCase<ClassFactoryT>::CreateArchive(wxOutputStream& out, const wxString& archiver) { // for an external archiver the test data need to be written to // temp files TempDir tmpdir; // write the files TestEntries::iterator i; for (i = m_testEntries.begin(); i != m_testEntries.end(); ++i) { wxFileName fn(i->first, wxPATH_UNIX); TestEntry& entry = *i->second; if (fn.IsDir()) { fn.Mkdir(0777, wxPATH_MKDIR_FULL); } else { wxFileName::Mkdir(fn.GetPath(), 0777, wxPATH_MKDIR_FULL); wxFFileOutputStream fileout(fn.GetFullPath()); fileout.Write(entry.GetData(), entry.GetSize()); } } for (i = m_testEntries.begin(); i != m_testEntries.end(); ++i) { wxFileName fn(i->first, wxPATH_UNIX); TestEntry& entry = *i->second; wxDateTime dt = entry.GetDateTime(); #ifdef __WXMSW__ if (fn.IsDir()) entry.SetDateTime(wxDateTime()); else #endif fn.SetTimes(NULL, &dt, NULL); } if ((m_options & PipeOut) == 0) { wxFileName fn(tmpdir.GetName()); fn.SetExt(_T("arc")); wxString tmparc = fn.GetPath(wxPATH_GET_SEPARATOR) + fn.GetFullName(); // call the archiver to create an archive file system(wxString::Format(archiver, tmparc.c_str()).mb_str()); // then load the archive file { wxFFileInputStream in(tmparc); if (in.Ok()) out.Write(in); } wxRemoveFile(tmparc); } else { // for the non-seekable test, have the archiver output to "-" // and read the archive via a pipe PFileInputStream in(wxString::Format(archiver, _T("-"))); if (in.Ok()) out.Write(in); } }
static inline bool WriteAsciiString(wxOutputStream& ostr, const wxString& s) { #if wxUSE_UNICODE wxCharBuffer name(s.mb_str()); ostr.Write(name, strlen(name)); #else ostr.Write(s.mb_str(), s.length()); #endif return ostr.IsOk(); }
/* static */ bool IStateStore::WriteLine(wxOutputStream& output, const wxString& txt) { wxInt32 len = txt.Len(); output.Write(txt.c_str(), len ); bool ret = CheckLastWrite(output, len); if (ret) { output.Write("\r", 1); } return ret; }
Void CFxLine::SavePoints(wxOutputStream& stream) { vPointIter Iter; wxPoint Point; for (Iter = _NodeVector.begin(); (Iter != _NodeVector.end()) && !(_NodeVector.empty()); Iter++) { (*Iter)->GetPoint(&Point); stream.Write((Char*)&(Point.x), sizeof(int)); stream.Write((Char*)&(Point.y), sizeof(int)); int sdwPointType = (*Iter)->GetType(); stream.Write((Char*)&(sdwPointType), sizeof(int)); } return; }
/*! This function is called for every value objects of INT type. This function uses the \n snprintf function to get the US-ASCII representation of the integer and simply copy it to the output stream. Returns -1 on stream errors or ZERO if no errors. */ int wxJSONWriter::WriteIntValue( wxOutputStream& os, const wxJSONValue& value ) { int r = 0; char buffer[32]; // need to store 64-bits integers (max 20 digits) size_t len; wxJSONRefData* data = value.GetRefData(); wxASSERT( data ); #if defined( wxJSON_64BIT_INT ) // this is for wxW 2.8 Unicode: in order to use the cross-platform // format specifier, we use the wxString's sprintf() function and then // convert to UTF-8 before writing to the stream wxString s; s.Printf( _T("%") wxLongLongFmtSpec _T("d"), data->m_value.m_valInt64 ); wxCharBuffer cb = s.ToUTF8(); const char* cbData = cb.data(); len = strlen( cbData ); wxASSERT( len < 32 ); memcpy( buffer, cbData, len ); buffer[len] = 0; #else snprintf( buffer, 32, "%ld", data->m_value.m_valLong ); #endif len = strlen( buffer ); os.Write( buffer, len ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { r = -1; } return r; }
/** @brief Write the database to an output stream * * @param tokenDatabase The database to write * @param out Were to write the database to * @return true if the operation was successful, false otherwise * */ bool ClTokenDatabase::WriteOut( const ClTokenDatabase& tokenDatabase, wxOutputStream& out ) { int i; int cnt; out.Write("CbCc", 4); // Magic number WriteInt(out, 1); // Version number WriteInt(out, ClTokenPacketType_filenames); if (!ClFilenameDatabase::WriteOut(tokenDatabase.m_FileDB, out)) return false; wxMutexLocker(tokenDatabase.m_Mutex); WriteInt(out, ClTokenPacketType_tokens); cnt = tokenDatabase.m_pTokens->GetCount(); WriteInt(out, cnt); uint32_t written_count = 0; for (i = 0; i < cnt; ++i) { ClAbstractToken tok = tokenDatabase.m_pTokens->GetValue(i); if (!ClAbstractToken::WriteOut(tok, out)) return false; written_count++; } CCLogger::Get()->DebugLog(F(_T("Wrote token database: %d tokens"), written_count)); return true; }
/*! An invalid wxJSONValue is a value that was not initialized and it is an error. You should never write invalid values to JSON text because the output is not valid JSON text. Note that the NULL value is a legal JSON text and it is written: \code null \endcode This function writes a non-JSON text to the output stream: \code <invalid JSON value> \endcode In debug mode, the function always fails with an wxFAIL_MSG failure. */ int wxJSONWriter::WriteInvalid( wxOutputStream& os ) { wxFAIL_MSG( _T("wxJSONWriter::WriteInvalid() cannot be called (not a valid JSON text")); int lastChar = 0; os.Write( "<invalid JSON value>", 9 ); return lastChar; }
/*! The function writes the \b null literal string to the output stream. */ int wxJSONWriter::WriteNullValue( wxOutputStream& os ) { os.Write( "null", 4 ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { return -1; } return 0; }
//! Write the key of a key/value element to the output stream. int wxJSONWriter::WriteKey( wxOutputStream& os, const wxString& key ) { wxLogTrace( writerTraceMask, _T("(%s) key write=%s"), __PRETTY_FUNCTION__, key.c_str() ); int lastChar = WriteStringValue( os, key ); os.Write( " : ", 3 ); return lastChar; }
/*! This function is called for every value objects of DOUBLE type. This function uses the \n snprintf function to get the US-ASCII representation of the integer and simply copy it to the output stream. Returns -1 on stream errors or ZERO if no errors. Note that writing a double to a decimal ASCII representation could lay to unexpected results depending on the format string used in the conversion. See SetDoubleFmtString for details. */ int wxJSONWriter::WriteDoubleValue( wxOutputStream& os, const wxJSONValue& value ) { int r = 0; wxJSONRefData* data = value.GetRefData(); wxASSERT( data ); char* writeBuff = 0; // the buffer that has to be written is either UTF-8 or ANSI c_str() depending // on the 'm_noUtf8' flag wxCharBuffer utf8CB = wxString::FromCDouble(data->m_value.m_valDouble, 10).ToUTF8(); // the UTF-8 buffer #if !defined(wxJSON_USE_UNICODE) wxCharBuffer ansiCB(str.c_str()); // the ANSI buffer if (m_noUtf8) { writeBuff = ansiCB.data(); } else { writeBuff = utf8CB.data(); } #else writeBuff = utf8CB.data(); #endif // NOTE: in ANSI builds UTF-8 conversion may fail (see samples/test5.cpp, // test 7.3) although I do not know why if (writeBuff == 0) { const char* err = "<wxJSONWriter::WriteComment(): error converting the double to UTF-8>"; os.Write(err, strlen(err)); return 0; } size_t len = strlen(writeBuff); os.Write(writeBuff, len); if (os.GetLastError() != wxSTREAM_NO_ERROR) { r = -1; } return r; }
/*! The function writes the wxString object \c str to the output object. The string is written as is; you cannot use it to write JSON strings to the output text. The function converts the string \c str to UTF-8 and writes the buffer.. */ int wxJSONWriter::WriteString( wxOutputStream& os, const wxString& str ) { wxLogTrace( writerTraceMask, _T("(%s) string to write=%s"), __PRETTY_FUNCTION__, str.c_str() ); int lastChar = 0; char* writeBuff = 0; // the buffer that has to be written is either UTF-8 or ANSI c_str() depending // on the 'm_noUtf8' flag wxCharBuffer utf8CB = str.ToUTF8(); // the UTF-8 buffer #if !defined( wxJSON_USE_UNICODE ) wxCharBuffer ansiCB( str.c_str()); // the ANSI buffer if ( m_noUtf8 ) { writeBuff = ansiCB.data(); } else { writeBuff = utf8CB.data(); } #else writeBuff = utf8CB.data(); #endif // NOTE: in ANSI builds UTF-8 conversion may fail (see samples/test5.cpp, // test 7.3) although I do not know why if ( writeBuff == 0 ) { const char* err = "<wxJSONWriter::WriteComment(): error converting the string to UTF-8>"; os.Write( err, strlen( err )); return 0; } size_t len = strlen( writeBuff ); os.Write( writeBuff, len ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { return -1; } wxLogTrace( writerTraceMask, _T("(%s) result=%d"), __PRETTY_FUNCTION__, lastChar ); return lastChar; }
bool wxPNMHandler::SaveFile( wxImage *image, wxOutputStream& stream, bool WXUNUSED(verbose) ) { wxTextOutputStream text_stream(stream); //text_stream << "P6" << endl //<< image->GetWidth() << " " << image->GetHeight() << endl //<< "255" << endl; text_stream << wxT("P6\n") << image->GetWidth() << wxT(" ") << image->GetHeight() << wxT("\n255\n"); stream.Write(image->GetData(),3*image->GetWidth()*image->GetHeight()); return stream.IsOk(); }
/* static */ bool IStateStore::SaveString(wxOutputStream& output, const wxString& txt) { wxInt32 len = txt.Len(); if ( SaveSimpleType<wxInt32>(output, len) ) { len *= sizeof(wchar_t); output.Write(txt.c_str().AsWChar(), len ); return CheckLastWrite(output, len); } return false; }
/** @brief Write a string to an output stream * * @param out wxOutputStream& * @param str const char* * @return bool * */ static bool WriteString( wxOutputStream& out, const char* str ) { int len = 0; if (str != nullptr) len = strlen(str); // Need size in amount of bytes if (!WriteInt(out, len)) return false; if (len > 0) out.Write((const void*)str, len); return true; }
// write string to output: inline static void OutputString(wxOutputStream& stream, const wxString& str, #if wxUSE_UNICODE wxMBConv * WXUNUSED(convMem), #else wxMBConv *convMem, #endif wxMBConv *convFile) { if (str.empty()) return; #if wxUSE_UNICODE const wxWX2MBbuf buf(str.mb_str(*(convFile ? convFile : &wxConvUTF8))); stream.Write((const char*)buf, strlen((const char*)buf)); #else if ( convFile == NULL ) stream.Write(str.mb_str(), str.Len()); else { wxString str2(str.wc_str(*convMem), *convFile); stream.Write(str2.mb_str(), str2.Len()); } #endif }
/*! This function is called for every value objects of DOUBLE type. This function uses the \n snprintf function to get the US-ASCII representation of the integer and simply copy it to the output stream. Returns -1 on stream errors or ZERO if no errors. Note that writing a double to a decimal ASCII representation could lay to unexpected results depending on the format string used in the conversion. See SetDoubleFmtString for details. */ int wxJSONWriter::WriteDoubleValue( wxOutputStream& os, const wxJSONValue& value ) { int r = 0; char buffer[32]; wxJSONRefData* data = value.GetRefData(); wxASSERT( data ); snprintf( buffer, 32, m_fmt, data->m_value.m_valDouble ); size_t len = strlen( buffer ); os.Write( buffer, len ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { r = -1; } return r; }
/*! This function is called for every value objects of UINT type. This function uses the \n snprintf function to get the US-ASCII representation of the integer and simply copy it to the output stream. The function prepends a \b plus \b sign if the \c wxJSONWRITER_RECOGNIZE_UNSIGNED flag is set in the \c m_flags data member. Returns -1 on stream errors or ZERO if no errors. */ int wxJSONWriter::WriteUIntValue( wxOutputStream& os, const wxJSONValue& value ) { int r = 0; size_t len; // prepend a plus sign if the style specifies that unsigned integers // have to be recognized by the JSON reader if ( m_style & wxJSONWRITER_RECOGNIZE_UNSIGNED ) { os.PutC( '+' ); } char buffer[32]; // need to store 64-bits integers (max 20 digits) wxJSONRefData* data = value.GetRefData(); wxASSERT( data ); #if defined( wxJSON_64BIT_INT ) #if wxCHECK_VERSION(2, 9, 0 ) || !defined( wxJSON_USE_UNICODE ) // this is fine for wxW 2.9 and for wxW 2.8 ANSI snprintf( buffer, 32, "%" wxLongLongFmtSpec "u", data->m_value.m_valUInt64 ); #elif wxCHECK_VERSION(3, 0, 0) || !defined( wxJSON_USE_UNICODE ) snprintf( buffer, 32, "%" wxLongLongFmtSpec "u", data->m_value.m_valUInt64 ); #else // this is for wxW 2.8 Unicode: in order to use the cross-platform // format specifier, we use the wxString's sprintf() function and then // convert to UTF-8 before writing to the stream wxString s; s.Printf( _T("%") wxLongLongFmtSpec _T("u"), data->m_value.m_valInt64 ); wxCharBuffer cb = s.ToUTF8(); const char* cbData = cb.data(); len = strlen( cbData ); wxASSERT( len < 32 ); memcpy( buffer, cbData, len ); buffer[len] = 0; #endif #else snprintf( buffer, 32, "%lu", data->m_value.m_valULong ); #endif len = strlen( buffer ); os.Write( buffer, len ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { r = -1; } return r; }
bool wxSVGBitmapEmbedHandler::ProcessBitmap(const wxBitmap& bmp, wxCoord x, wxCoord y, wxOutputStream& stream) const { static int sub_images = 0; if ( wxImage::FindHandler(wxBITMAP_TYPE_PNG) == NULL ) wxImage::AddHandler(new wxPNGHandler); // write the bitmap as a PNG to a memory stream and Base64 encode wxMemoryOutputStream mem; bmp.ConvertToImage().SaveFile(mem, wxBITMAP_TYPE_PNG); wxString data = wxBase64Encode(mem.GetOutputStreamBuffer()->GetBufferStart(), mem.GetSize()); // write image meta information wxString s; s += wxString::Format(" <image x=\"%d\" y=\"%d\" " "width=\"%dpx\" height=\"%dpx\" " "title=\"Image from wxSVG\"\n", x, y, bmp.GetWidth(), bmp.GetHeight()); s += wxString::Format(" id=\"image%d\" " "xlink:href=\"data:image/png;base64,\n", sub_images++); // Wrap Base64 encoded data on 76 columns boundary (same as Inkscape). const unsigned WRAP = 76; for ( size_t i = 0; i < data.size(); i += WRAP ) { if (i < data.size() - WRAP) s += data.Mid(i, WRAP) + "\n"; else s += data.Mid(i, s.size() - i) + "\"\n/>"; // last line } // write to the SVG file const wxCharBuffer buf = s.utf8_str(); stream.Write(buf, strlen((const char *)buf)); return stream.IsOk(); }
/*! This function is called for every value objects of BOOL type. This function prints the literals \b true or \b false depending on the value in \c value. Returns -1 on stream errors or ZERO if no errors. */ int wxJSONWriter::WriteBoolValue( wxOutputStream& os, const wxJSONValue& value ) { int r = 0; const char* f = "false"; const char* t = "true"; wxJSONRefData* data = value.GetRefData(); wxASSERT( data ); const char* c = f; // defaults to FALSE if ( data->m_value.m_valBool ) { c = t; } size_t len = strlen( c ); os.Write( c, len ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { r = -1; } return r; }
bool wxSVGBitmapFileHandler::ProcessBitmap(const wxBitmap& bmp, wxCoord x, wxCoord y, wxOutputStream& stream) const { static int sub_images = 0; if ( wxImage::FindHandler(wxBITMAP_TYPE_PNG) == NULL ) wxImage::AddHandler(new wxPNGHandler); // find a suitable file name wxString sPNG; do { sPNG = wxString::Format("image%d.png", sub_images++); } while (wxFile::Exists(sPNG)); if ( !bmp.SaveFile(sPNG, wxBITMAP_TYPE_PNG) ) return false; // reference the bitmap from the SVG doc using only filename & ext sPNG = sPNG.AfterLast(wxFileName::GetPathSeparator()); // reference the bitmap from the SVG doc wxString s; s += wxString::Format(" <image x=\"%d\" y=\"%d\" " "width=\"%dpx\" height=\"%dpx\" " "title=\"Image from wxSVG\"\n", x, y, bmp.GetWidth(), bmp.GetHeight()); s += wxString::Format(" xlink:href=\"%s\">\n</image>\n", sPNG); // write to the SVG file const wxCharBuffer buf = s.utf8_str(); stream.Write(buf, strlen((const char *)buf)); return stream.IsOk(); }
/*! The function writes the string \c str to the output object that was specified in the wxJSONWriter::Write() function. The function may split strings in two or more lines if the string contains LF characters if the \c m_style data member contains the wxJSONWRITER_SPLIT_STRING flag. The function does not actually write the string: for every character in the provided string the function calls WriteChar() which does the actual character output. The function returns ZERO on success or -1 in case of errors. */ int wxJSONWriter::WriteStringValue( wxOutputStream& os, const wxString& str ) { // JSON values of type STRING are written by converting the whole string // to UTF-8 and then copying the UTF-8 buffer to the 'os' stream // one byte at a time and processing them os.PutC( '\"' ); // open quotes // the buffer that has to be written is either UTF-8 or ANSI c_str() depending // on the 'm_noUtf8' flag char* writeBuff = 0; wxCharBuffer utf8CB = str.ToUTF8(); // the UTF-8 buffer #if !defined( wxJSON_USE_UNICODE ) wxCharBuffer ansiCB( str.c_str()); // the ANSI buffer if ( m_noUtf8 ) { writeBuff = ansiCB.data(); } else { writeBuff = utf8CB.data(); } #else writeBuff = utf8CB.data(); #endif // NOTE: in ANSI builds UTF-8 conversion may fail (see samples/test5.cpp, // test 7.3) although I do not know why if ( writeBuff == 0 ) { const char* err = "<wxJSONWriter::WriteStringValue(): error converting the string to a UTF8 buffer>"; os.Write( err, strlen( err )); return 0; } size_t len = strlen( writeBuff ); int lastChar = 0; // store the column at which the string starts // splitting strings only happen if the string starts within // column wxJSONWRITER_LAST_COL (default 50) // see 'include/wx/json_defs.h' for the defines int tempCol = m_colNo; // now write the UTF8 buffer processing the bytes size_t i; for ( i = 0; i < len; i++ ) { bool shouldEscape = false; unsigned char ch = *writeBuff; ++writeBuff; // point to the next byte // the escaped character char escCh = 0; // for every character we have to check if it is a character that // needs to be escaped: note that characters that should be escaped // may be not if some writer's flags are specified switch ( ch ) { case '\"' : // quotes shouldEscape = true; escCh = '\"'; break; case '\\' : // reverse solidus shouldEscape = true; escCh = '\\'; break; case '/' : // solidus shouldEscape = true; escCh = '/'; break; case '\b' : // backspace shouldEscape = true; escCh = 'b'; break; case '\f' : // formfeed shouldEscape = true; escCh = 'f'; break; case '\n' : // newline shouldEscape = true; escCh = 'n'; break; case '\r' : // carriage-return shouldEscape = true; escCh = 'r'; break; case '\t' : // horizontal tab shouldEscape = true; escCh = 't'; break; default : shouldEscape = false; break; } // end switch // if the character is a control character that is not identified by a // lowercase letter, we should escape it if ( !shouldEscape && ch < 32 ) { char b[8]; snprintf( b, 8, "\\u%04X", (int) ch ); os.Write( b, 6 ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { return -1; } } // the char is not a control character else { // some characters that should be escaped are not escaped // if the writer was constructed with some flags if ( shouldEscape && !( m_style & wxJSONWRITER_ESCAPE_SOLIDUS) ) { if ( ch == '/' ) { shouldEscape = false; } } if ( shouldEscape && (m_style & wxJSONWRITER_MULTILINE_STRING)) { if ( ch == '\n' || ch == '\t' ) { shouldEscape = false; } } // now write the character prepended by ESC if it should be escaped if ( shouldEscape ) { os.PutC( '\\' ); os.PutC( escCh ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { return -1; } } else { // a normal char or a UTF-8 units: write the character os.PutC( ch ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { return -1; } } } // check if SPLIT_STRING flag is set and if the string has to // be splitted if ( (m_style & wxJSONWRITER_STYLED) && (m_style & wxJSONWRITER_SPLIT_STRING)) { // split the string if the character written is LF if ( ch == '\n' ) { // close quotes and CR os.Write( "\"\n", 2 ); lastChar = WriteIndent( os, m_level + 2 ); // write indentation os.PutC( '\"' ); // reopen quotes if ( lastChar < 0 ) { return lastChar; } } // split the string only if there is at least wxJSONWRITER_MIN_LENGTH // character to write and the character written is a punctuation or space // BUG: the following does not work because the columns are not counted else if ( (m_colNo >= wxJSONWRITER_SPLIT_COL) && (tempCol <= wxJSONWRITER_LAST_COL )) { if ( IsSpace( ch ) || IsPunctuation( ch )) { if ( len - i > wxJSONWRITER_MIN_LENGTH ) { // close quotes and CR os.Write( "\"\n", 2 ); lastChar = WriteIndent( os, m_level + 2 ); // write indentation os.PutC( '\"' ); // reopen quotes if ( lastChar < 0 ) { return lastChar; } } } } } } // end for os.PutC( '\"' ); // close quotes return 0; }
static inline bool WriteAsciiString(wxOutputStream& ostr, const char *p) { return ostr.Write(p, strlen(p)).IsOk(); }
inline bool wxTarHeaderBlock::WriteField(wxOutputStream& out, int id) { return out.Write(Get(id), Len(id)).LastWrite() == Len(id); }
bool wxBMPHandler::SaveDib(wxImage *image, wxOutputStream& stream, bool verbose, bool IsBmp, bool IsMask) { wxCHECK_MSG( image, false, wxT("invalid pointer in wxBMPHandler::SaveFile") ); if ( !image->Ok() ) { if ( verbose ) { wxLogError(_("BMP: Couldn't save invalid image.")); } return false; } // get the format of the BMP file to save, else use 24bpp unsigned format = wxBMP_24BPP; if ( image->HasOption(wxIMAGE_OPTION_BMP_FORMAT) ) format = image->GetOptionInt(wxIMAGE_OPTION_BMP_FORMAT); wxUint16 bpp; // # of bits per pixel int palette_size; // # of color map entries, ie. 2^bpp colors // set the bpp and appropriate palette_size, and do additional checks if ( (format == wxBMP_1BPP) || (format == wxBMP_1BPP_BW) ) { bpp = 1; palette_size = 2; } else if ( format == wxBMP_4BPP ) { bpp = 4; palette_size = 16; } else if ( (format == wxBMP_8BPP) || (format == wxBMP_8BPP_GREY) || (format == wxBMP_8BPP_RED) || (format == wxBMP_8BPP_PALETTE) ) { // need to set a wxPalette to use this, HOW TO CHECK IF VALID, SIZE? if ((format == wxBMP_8BPP_PALETTE) #if wxUSE_PALETTE && !image->HasPalette() #endif // wxUSE_PALETTE ) { if ( verbose ) { wxLogError(_("BMP: wxImage doesn't have own wxPalette.")); } return false; } bpp = 8; palette_size = 256; } else // you get 24bpp { format = wxBMP_24BPP; bpp = 24; palette_size = 0; } unsigned width = image->GetWidth(); unsigned row_padding = (4 - int(width*bpp/8.0) % 4) % 4; // # bytes to pad to dword unsigned row_width = int(width * bpp/8.0) + row_padding; // # of bytes per row struct { // BitmapHeader: wxUint16 magic; // format magic, always 'BM' wxUint32 filesize; // total file size, inc. headers wxUint32 reserved; // for future use wxUint32 data_offset; // image data offset in the file // BitmapInfoHeader: wxUint32 bih_size; // 2nd part's size wxUint32 width, height; // bitmap's dimensions wxUint16 planes; // num of planes wxUint16 bpp; // bits per pixel wxUint32 compression; // compression method wxUint32 size_of_bmp; // size of the bitmap wxUint32 h_res, v_res; // image resolution in pixels-per-meter wxUint32 num_clrs; // number of colors used wxUint32 num_signif_clrs;// number of significant colors } hdr; wxUint32 hdr_size = 14/*BitmapHeader*/ + 40/*BitmapInfoHeader*/; hdr.magic = wxUINT16_SWAP_ON_BE(0x4D42/*'BM'*/); hdr.filesize = wxUINT32_SWAP_ON_BE( hdr_size + palette_size*4 + row_width * image->GetHeight() ); hdr.reserved = 0; hdr.data_offset = wxUINT32_SWAP_ON_BE(hdr_size + palette_size*4); hdr.bih_size = wxUINT32_SWAP_ON_BE(hdr_size - 14); hdr.width = wxUINT32_SWAP_ON_BE(image->GetWidth()); if ( IsBmp ) { hdr.height = wxUINT32_SWAP_ON_BE(image->GetHeight()); } else { hdr.height = wxUINT32_SWAP_ON_BE(2 * image->GetHeight()); } hdr.planes = wxUINT16_SWAP_ON_BE(1); // always 1 plane hdr.bpp = wxUINT16_SWAP_ON_BE(bpp); hdr.compression = 0; // RGB uncompressed hdr.size_of_bmp = wxUINT32_SWAP_ON_BE(row_width * image->GetHeight()); // get the resolution from the image options or fall back to 72dpi standard // for the BMP format if not specified int hres, vres; switch ( GetResolutionFromOptions(*image, &hres, &vres) ) { default: wxFAIL_MSG( wxT("unexpected image resolution units") ); // fall through case wxIMAGE_RESOLUTION_NONE: hres = vres = 72; // fall through to convert it to correct units case wxIMAGE_RESOLUTION_INCHES: // convert resolution in inches to resolution in centimeters hres = (int)(10*mm2inches*hres); vres = (int)(10*mm2inches*vres); // fall through to convert it to resolution in meters case wxIMAGE_RESOLUTION_CM: // convert resolution in centimeters to resolution in meters hres *= 100; vres *= 100; break; } hdr.h_res = wxUINT32_SWAP_ON_BE(hres); hdr.v_res = wxUINT32_SWAP_ON_BE(vres); hdr.num_clrs = wxUINT32_SWAP_ON_BE(palette_size); // # colors in colormap hdr.num_signif_clrs = 0; // all colors are significant if ( IsBmp ) { if (// VS: looks ugly but compilers tend to do ugly things with structs, // like aligning hdr.filesize's ofset to dword :( // VZ: we should add padding then... !stream.Write(&hdr.magic, 2) || !stream.Write(&hdr.filesize, 4) || !stream.Write(&hdr.reserved, 4) || !stream.Write(&hdr.data_offset, 4) ) { if (verbose) { wxLogError(_("BMP: Couldn't write the file (Bitmap) header.")); } return false; } } if ( !IsMask ) { if ( !stream.Write(&hdr.bih_size, 4) || !stream.Write(&hdr.width, 4) || !stream.Write(&hdr.height, 4) || !stream.Write(&hdr.planes, 2) || !stream.Write(&hdr.bpp, 2) || !stream.Write(&hdr.compression, 4) || !stream.Write(&hdr.size_of_bmp, 4) || !stream.Write(&hdr.h_res, 4) || !stream.Write(&hdr.v_res, 4) || !stream.Write(&hdr.num_clrs, 4) || !stream.Write(&hdr.num_signif_clrs, 4) ) { if (verbose) { wxLogError(_("BMP: Couldn't write the file (BitmapInfo) header.")); } return false; } } wxPalette *palette = NULL; // entries for quantized images wxUint8 *rgbquad = NULL; // for the RGBQUAD bytes for the colormap wxImage *q_image = NULL; // destination for quantized image // if <24bpp use quantization to reduce colors for *some* of the formats if ( (format == wxBMP_1BPP) || (format == wxBMP_4BPP) || (format == wxBMP_8BPP) || (format == wxBMP_8BPP_PALETTE) ) { // make a new palette and quantize the image if (format != wxBMP_8BPP_PALETTE) { q_image = new wxImage(); // I get a delete error using Quantize when desired colors > 236 int quantize = ((palette_size > 236) ? 236 : palette_size); // fill the destination too, it gives much nicer 4bpp images wxQuantize::Quantize( *image, *q_image, &palette, quantize, 0, wxQUANTIZE_FILL_DESTINATION_IMAGE ); } else { #if wxUSE_PALETTE palette = new wxPalette(image->GetPalette()); #endif // wxUSE_PALETTE } int i; unsigned char r, g, b; rgbquad = new wxUint8 [palette_size*4]; for (i = 0; i < palette_size; i++) { #if wxUSE_PALETTE if ( !palette->GetRGB(i, &r, &g, &b) ) #endif // wxUSE_PALETTE r = g = b = 0; rgbquad[i*4] = b; rgbquad[i*4+1] = g; rgbquad[i*4+2] = r; rgbquad[i*4+3] = 0; } } // make a 256 entry greyscale colormap or 2 entry black & white else if ( (format == wxBMP_8BPP_GREY) || (format == wxBMP_8BPP_RED) || (format == wxBMP_1BPP_BW) ) { rgbquad = new wxUint8 [palette_size*4]; for ( int i = 0; i < palette_size; i++ ) { // if 1BPP_BW then the value should be either 0 or 255 wxUint8 c = (wxUint8)((i > 0) && (format == wxBMP_1BPP_BW) ? 255 : i); rgbquad[i*4] = rgbquad[i*4+1] = rgbquad[i*4+2] = c; rgbquad[i*4+3] = 0; } } // if the colormap was made, then it needs to be written if (rgbquad) { if ( !IsMask ) { if ( !stream.Write(rgbquad, palette_size*4) ) { if (verbose) { wxLogError(_("BMP: Couldn't write RGB color map.")); } delete[] rgbquad; #if wxUSE_PALETTE delete palette; #endif // wxUSE_PALETTE delete q_image; return false; } } delete []rgbquad; } // pointer to the image data, use quantized if available wxUint8 *data = (wxUint8*) image->GetData(); if (q_image) if (q_image->Ok()) data = (wxUint8*) q_image->GetData(); wxUint8 *buffer = new wxUint8[row_width]; memset(buffer, 0, row_width); int y; unsigned x; long int pixel; for (y = image->GetHeight() -1; y >= 0; y--) { if ( format == wxBMP_24BPP ) // 3 bytes per pixel red,green,blue { for ( x = 0; x < width; x++ ) { pixel = 3*(y*width + x); buffer[3*x ] = data[pixel+2]; buffer[3*x + 1] = data[pixel+1]; buffer[3*x + 2] = data[pixel]; } } else if ((format == wxBMP_8BPP) || // 1 byte per pixel in color (format == wxBMP_8BPP_PALETTE)) { for (x = 0; x < width; x++) { pixel = 3*(y*width + x); #if wxUSE_PALETTE buffer[x] = (wxUint8)palette->GetPixel( data[pixel], data[pixel+1], data[pixel+2] ); #else // FIXME: what should this be? use some std palette maybe? buffer[x] = 0; #endif // wxUSE_PALETTE } } else if ( format == wxBMP_8BPP_GREY ) // 1 byte per pix, rgb ave to grey { for (x = 0; x < width; x++) { pixel = 3*(y*width + x); buffer[x] = (wxUint8)(.299*data[pixel] + .587*data[pixel+1] + .114*data[pixel+2]); } } else if ( format == wxBMP_8BPP_RED ) // 1 byte per pixel, red as greys { for (x = 0; x < width; x++) { buffer[x] = (wxUint8)data[3*(y*width + x)]; } } else if ( format == wxBMP_4BPP ) // 4 bpp in color { for (x = 0; x < width; x+=2) { pixel = 3*(y*width + x); // fill buffer, ignore if > width #if wxUSE_PALETTE buffer[x/2] = (wxUint8)( ((wxUint8)palette->GetPixel(data[pixel], data[pixel+1], data[pixel+2]) << 4) | (((x+1) > width) ? 0 : ((wxUint8)palette->GetPixel(data[pixel+3], data[pixel+4], data[pixel+5]) )) ); #else // FIXME: what should this be? use some std palette maybe? buffer[x/2] = 0; #endif // wxUSE_PALETTE } } else if ( format == wxBMP_1BPP ) // 1 bpp in "color" { for (x = 0; x < width; x+=8) { pixel = 3*(y*width + x); #if wxUSE_PALETTE buffer[x/8] = (wxUint8)( ((wxUint8)palette->GetPixel(data[pixel], data[pixel+1], data[pixel+2]) << 7) | (((x+1) > width) ? 0 : ((wxUint8)palette->GetPixel(data[pixel+3], data[pixel+4], data[pixel+5]) << 6)) | (((x+2) > width) ? 0 : ((wxUint8)palette->GetPixel(data[pixel+6], data[pixel+7], data[pixel+8]) << 5)) | (((x+3) > width) ? 0 : ((wxUint8)palette->GetPixel(data[pixel+9], data[pixel+10], data[pixel+11]) << 4)) | (((x+4) > width) ? 0 : ((wxUint8)palette->GetPixel(data[pixel+12], data[pixel+13], data[pixel+14]) << 3)) | (((x+5) > width) ? 0 : ((wxUint8)palette->GetPixel(data[pixel+15], data[pixel+16], data[pixel+17]) << 2)) | (((x+6) > width) ? 0 : ((wxUint8)palette->GetPixel(data[pixel+18], data[pixel+19], data[pixel+20]) << 1)) | (((x+7) > width) ? 0 : ((wxUint8)palette->GetPixel(data[pixel+21], data[pixel+22], data[pixel+23]) )) ); #else // FIXME: what should this be? use some std palette maybe? buffer[x/8] = 0; #endif // wxUSE_PALETTE } } else if ( format == wxBMP_1BPP_BW ) // 1 bpp B&W colormap from red color ONLY { for (x = 0; x < width; x+=8) { pixel = 3*(y*width + x); buffer[x/8] = (wxUint8)( (((wxUint8)(data[pixel] /128.)) << 7) | (((x+1) > width) ? 0 : (((wxUint8)(data[pixel+3] /128.)) << 6)) | (((x+2) > width) ? 0 : (((wxUint8)(data[pixel+6] /128.)) << 5)) | (((x+3) > width) ? 0 : (((wxUint8)(data[pixel+9] /128.)) << 4)) | (((x+4) > width) ? 0 : (((wxUint8)(data[pixel+12]/128.)) << 3)) | (((x+5) > width) ? 0 : (((wxUint8)(data[pixel+15]/128.)) << 2)) | (((x+6) > width) ? 0 : (((wxUint8)(data[pixel+18]/128.)) << 1)) | (((x+7) > width) ? 0 : (((wxUint8)(data[pixel+21]/128.)) )) ); } } if ( !stream.Write(buffer, row_width) ) { if (verbose) { wxLogError(_("BMP: Couldn't write data.")); } delete[] buffer; #if wxUSE_PALETTE delete palette; #endif // wxUSE_PALETTE delete q_image; return false; } } delete[] buffer; #if wxUSE_PALETTE delete palette; #endif // wxUSE_PALETTE delete q_image; return true; }
/** @brief Write a long long to an outputstream * * @param out wxOutputStream& * @param val const longlong * @return bool * */ static bool WriteLongLong( wxOutputStream& out, const long long val ) { out.Write((const void*)&val, sizeof(val)); return true; }
/** @brief Write an int to an output stream * * @param out wxOutputStream& * @param val const int * @return bool * */ static bool WriteInt( wxOutputStream& out, const int val ) { out.Write((const void*)&val, sizeof(val)); return true; }
bool wxXPMHandler::SaveFile(wxImage * image, wxOutputStream& stream, bool WXUNUSED(verbose)) { // 1. count colours: #define MaxCixels 92 static const char Cixel[MaxCixels+1] = " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjk" "lzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|"; int i, j, k; wxImageHistogram histogram; int cols = int(image->ComputeHistogram(histogram)); int chars_per_pixel = 1; for ( k = MaxCixels; cols > k; k *= MaxCixels) chars_per_pixel++; // 2. write the header: wxString sName; if ( image->HasOption(wxIMAGE_OPTION_FILENAME) ) { wxFileName::SplitPath(image->GetOption(wxIMAGE_OPTION_FILENAME), NULL, &sName, NULL); sName << wxT("_xpm"); } if ( !sName.empty() ) sName = wxString(wxT("/* XPM */\nstatic const char *")) + sName; else sName = wxT("/* XPM */\nstatic const char *xpm_data"); stream.Write( (const char*) sName.ToAscii(), sName.Len() ); char tmpbuf[200]; // VS: 200b is safe upper bound for anything produced by sprintf below // (<101 bytes the string, neither %i can expand into more than 10 chars) sprintf(tmpbuf, "[] = {\n" "/* columns rows colors chars-per-pixel */\n" "\"%i %i %i %i\",\n", image->GetWidth(), image->GetHeight(), cols, chars_per_pixel); stream.Write(tmpbuf, strlen(tmpbuf)); // 3. create color symbols table: char *symbols_data = new char[cols * (chars_per_pixel+1)]; char **symbols = new char*[cols]; // 2a. find mask colour: unsigned long mask_key = 0x1000000 /*invalid RGB value*/; if (image->HasMask()) mask_key = (image->GetMaskRed() << 16) | (image->GetMaskGreen() << 8) | image->GetMaskBlue(); // 2b. generate colour table: for (wxImageHistogram::iterator entry = histogram.begin(); entry != histogram.end(); ++entry ) { unsigned long index = entry->second.index; symbols[index] = symbols_data + index * (chars_per_pixel+1); char *sym = symbols[index]; for (j = 0; j < chars_per_pixel; j++) { sym[j] = Cixel[index % MaxCixels]; index /= MaxCixels; } sym[j] = '\0'; unsigned long key = entry->first; if (key == 0) sprintf( tmpbuf, "\"%s c Black\",\n", sym); else if (key == mask_key) sprintf( tmpbuf, "\"%s c None\",\n", sym); else { wxByte r = wxByte(key >> 16); wxByte g = wxByte(key >> 8); wxByte b = wxByte(key); sprintf(tmpbuf, "\"%s c #%02X%02X%02X\",\n", sym, r, g, b); } stream.Write( tmpbuf, strlen(tmpbuf) ); } stream.Write("/* pixels */\n", 13); unsigned char *data = image->GetData(); for (j = 0; j < image->GetHeight(); j++) { char tmp_c; tmp_c = '\"'; stream.Write(&tmp_c, 1); for (i = 0; i < image->GetWidth(); i++, data += 3) { unsigned long key = (data[0] << 16) | (data[1] << 8) | (data[2]); stream.Write(symbols[histogram[key].index], chars_per_pixel); } tmp_c = '\"'; stream.Write(&tmp_c, 1); if ( j + 1 < image->GetHeight() ) { tmp_c = ','; stream.Write(&tmp_c, 1); } tmp_c = '\n'; stream.Write(&tmp_c, 1); } stream.Write("};\n", 3 ); // Clean up: delete[] symbols; delete[] symbols_data; return true; }
void WBinaryPage::ExportBuffer(wxOutputStream& outstream) { outstream.Write(bindata.GetData(), bindata.GetDataLen()); }
/*! The type wxJSONTYPE_MEMORYBUFF is a \b wxJSON extension that is not correctly read by other JSON implementations. By default, the function writes such a type as an array of INTs as follows: \code [ 0,32,45,255,6,...] \endcode If the writer object was constructed using the \c wxJSONWRITER_MEMORYBUFF flag, then the output is much more compact and recognized by the \b wxJSON reader as a memory buffer type: \code '00203FFF06..' \endcode */ int wxJSONWriter::WriteMemoryBuff( wxOutputStream& os, const wxMemoryBuffer& buff ) { #define MAX_BYTES_PER_ROW 20 char str[16]; // if STYLED and SPLIT_STRING flags are set, the function writes 20 bytes on every row // the following is the counter of bytes written. // the string is splitted only for the special meory buffer type, not for array of INTs int bytesWritten = 0; bool splitString = false; if ( (m_style & wxJSONWRITER_STYLED) && (m_style & wxJSONWRITER_SPLIT_STRING)) { splitString = true; } size_t buffLen = buff.GetDataLen(); unsigned char* ptr = (unsigned char*) buff.GetData(); wxASSERT( ptr ); char openChar = '\''; char closeChar = '\''; bool asArray = false; if ( (m_style & wxJSONWRITER_MEMORYBUFF ) == 0 ) { // if the special flag is not specified, write as an array of INTs openChar = '['; closeChar = ']'; asArray = true; } // write the open character os.PutC( openChar ); for ( size_t i = 0; i < buffLen; i++ ) { unsigned char c = *ptr; ++ptr; if ( asArray ) { snprintf( str, 14, "%d", c ); size_t len = strlen( str ); wxASSERT( len <= 3 ); wxASSERT( len >= 1 ); str[len] = ','; // do not write the comma char for the last element if ( i < buffLen - 1 ) { ++len; } os.Write( str, len ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { return -1; } } else { // now convert the byte in two hex digits char c1 = c / 16; char c2 = c % 16; c1 += '0'; c2 += '0'; if ( c1 > '9' ) { c1 += 7; } if ( c2 > '9' ) { c2 += 7; } os.PutC( c1 ); os.PutC( c2 ); if ( os.GetLastError() != wxSTREAM_NO_ERROR ) { return -1; } if ( splitString ) { ++bytesWritten; } if (( bytesWritten >= MAX_BYTES_PER_ROW ) && ((buffLen - i ) >= 5 )) { // split the string if we wrote 20 bytes, but only is we have to // write at least 5 bytes os.Write( "\'\n", 2 ); int lastChar = WriteIndent( os, m_level + 2 ); // write indentation os.PutC( '\'' ); // reopen quotes if ( lastChar < 0 ) { return lastChar; } bytesWritten = 0; } } } // write the close character os.PutC( closeChar ); return closeChar; }