TempStream::TempStream(const std::string &prefix, bool deleteOnClose, IOManager *ioManager, Scheduler *scheduler) { std::string tempdir; bool absolutePath = #ifdef WINDOWS (prefix.size() >= 2 && (prefix[1] == ':' || prefix[1] == '\\')) || (!prefix.empty() && prefix[0] == '\\'); #else !prefix.empty() && prefix[0] == '/'; #endif if (!absolutePath) tempdir = g_tempDir->val(); #ifdef WINDOWS std::wstring wtempdir = toUtf16(tempdir); if (!absolutePath && wtempdir.empty()) { wtempdir.resize(MAX_PATH); DWORD len = GetTempPathW(MAX_PATH, &wtempdir[0]); if (len == 0) wtempdir = L"."; else wtempdir.resize(len); } std::wstring prefixW = toUtf16(prefix); size_t backslash = prefixW.rfind(L'\\'); if (backslash != std::wstring::npos) { wtempdir += prefixW.substr(0, backslash); prefixW = prefixW.substr(backslash + 1); } std::wstring tempfile; tempfile.resize(MAX_PATH); UINT len = GetTempFileNameW(wtempdir.c_str(), prefixW.c_str(), 0, &tempfile[0]); if (len == 0) MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("GetTempFileNameW"); init(tempfile, FileStream::READWRITE, (FileStream::CreateFlags)(FileStream::OPEN | (deleteOnClose ? FileStream::DELETE_ON_CLOSE : 0)), ioManager, scheduler); #else if (!absolutePath && tempdir.empty()) tempdir = "/tmp/" + prefix + "XXXXXX"; else if (!absolutePath) tempdir += prefix + "XXXXXX"; else tempdir = prefix + "XXXXXX"; int fd = mkstemp(&tempdir[0]); if (fd < 0) MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("mkstemp"); init(fd, ioManager, scheduler); if (deleteOnClose) { int rc = unlink(tempdir.c_str()); if (rc != 0) MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("unlink"); } m_path = tempdir; #endif }
NegotiateAuth::NegotiateAuth(const std::string &username, const std::string &password) : m_username(toUtf16(username)), m_password(toUtf16(password)) { SecInvalidateHandle(&m_creds); SecInvalidateHandle(&m_secCtx); size_t pos = m_username.find(L'\\'); if (pos != std::wstring::npos) { m_domain = m_username.substr(0, pos); m_username = m_username.substr(pos + 1); } }
Run( const std::string &aText, const Font &aFont, const ColorA &aColor ) : mText( aText ), mFont( aFont ), mColor( aColor ) { #if defined( CINDER_MSW ) mWideText = toUtf16( mText ); #endif }
void Font::renderString( const std::string & str, glm::vec2 & cursor, float fontSize, float maxWidth) { renderString(toUtf16(str), cursor, fontSize, maxWidth); }
fs::path AppImplMsw::getFolderPath( const fs::path &initialPath ) { wstring initialPathWide( toUtf16( initialPath.string() ) ); string result; ::BROWSEINFO bi = { 0 }; bi.lParam = reinterpret_cast<LPARAM>( initialPathWide.c_str() ); bi.lpfn = getFolderPathBrowseCallbackProc; bi.lpszTitle = L"Pick a Directory"; ::LPITEMIDLIST pidl = ::SHBrowseForFolder( &bi ); if( pidl ) { // get the name of the folder TCHAR path[MAX_PATH]; if( ::SHGetPathFromIDList ( pidl, path ) ) { result = toUtf8( path ); } // free memory used ::IMalloc * imalloc = 0; if( SUCCEEDED( ::SHGetMalloc( &imalloc ) ) ) { imalloc->Free( pidl ); imalloc->Release(); } } return result; }
void Document::saveAs( const string_t& fullPath ) { if (doc_) { VARIANT fname; VariantInit(&fname); fname.vt = VT_BSTR; fname.bstrVal = ::SysAllocString(toUtf16(fullPath).c_str()); OLEMethod(DISPATCH_METHOD, NULL, doc_, L"SaveAs", 1, fname); SysFreeString(fname.bstrVal); } }
TextFile::TextFile(const std::string &fileName): fileName_(getFullFileName(fileName)) { if (!fileName.empty()) setName(toUtf16(baseName(fileName))); else setName(L"Untitled"); std::ifstream f(fileName_); if (f.is_open()) while (!f.eof()) { std::string line; std::getline(f, line); buffer_.push_back(toUtf16(line)); } else buffer_.push_back(L""); if (isCpp(fileName)) highlighter_ = new CppHighlighter(this); }
void SaveDialog::scanDirectory() { buffer_.clear(); char *tmp = getcwd(nullptr, MAXPATHLEN); auto currentDir = toUtf16(tmp); free(tmp); setName(std::wstring{begin(currentDir) + currentDir.rfind(L'/'), end(currentDir)}); buffer_.push_back(currentDir + L":"); auto d = opendir("."); buffer_.push_back(L""); while (auto de = readdir(d)) { auto fileName = toUtf16(de->d_name); if (fileName == L".." || (fileName.size() > 0 && fileName[0] != L'.' && fileName[fileName.size() - 1] != L'~')) buffer_.push_back(fileName); } closedir(d); std::sort(begin(buffer_) + 2, end(buffer_)); }
std::string Url::encode( const std::string &unescaped ) { #if defined( CINDER_COCOA ) cocoa::SafeCfString unescapedStr = cocoa::createSafeCfString( unescaped ); CFStringRef escaped = ::CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, unescapedStr.get(), NULL, NULL, kCFStringEncodingUTF8 ); std::string result = cocoa::convertCfString( escaped ); ::CFRelease( escaped ); return result; #elif defined( CINDER_MSW ) wchar_t buffer[4096]; DWORD bufferSize = 4096; std::wstring wideUnescaped = toUtf16( unescaped ); UrlEscape( wideUnescaped.c_str(), buffer, &bufferSize, 0 ); return toUtf8( std::wstring( buffer ) ); #endif }
void TextFile::saveAs(const std::string &fileName) { fileName_ = fileName; setName(toUtf16(baseName(fileName))); std::ofstream f(fileName_); bool first = true; for (const auto &l: buffer_) { if (first) first = false; else f << std::endl; f << toUtf8(l); } clearModified(); }
std::vector<std::wstring> inline Tokenize(const std::wstring &source) { static std::wstring tokens = toUtf16(" "); std::vector<std::wstring> results; size_t prev = 0; size_t next = 0; while ((next = source.find_first_of(tokens, prev)) != std::wstring::npos) { if (next - prev != 0) { results.push_back(source.substr(prev, next - prev)); } prev = next + 1; } if (prev < source.size()) { results.push_back(source.substr(prev)); } return results; }
std::string Url::encode( const std::string &unescaped ) { #if defined( CINDER_COCOA ) cocoa::SafeCfString unescapedStr = cocoa::createSafeCfString( unescaped ); CFStringRef escaped = ::CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, unescapedStr.get(), NULL, NULL, kCFStringEncodingUTF8 ); std::string result = cocoa::convertCfString( escaped ); ::CFRelease( escaped ); return result; #elif defined( CINDER_MSW ) char16_t buffer[4096]; DWORD bufferSize = 4096; std::u16string wideUnescaped = toUtf16( unescaped ); UrlEscape( (wchar_t*)wideUnescaped.c_str(), (wchar_t*)buffer, &bufferSize, 0 ); return toUtf8( buffer ); #elif defined( CINDER_WINRT ) std::wstring urlStr = msw::toWideString( unescaped ); auto uri = ref new Windows::Foundation::Uri(ref new Platform::String(urlStr.c_str())); return msw::toUtf8String( std::wstring( uri->AbsoluteCanonicalUri->Data())); #endif }
void CharMapping::loadMappingFile( const string_t& mapFile ) { if (mapFile.find("cm-arafi.txt") != string_t::npos) { /// clear default mapping for (wchar_t i = 0x0021; i <= 0x007E; ++i) quickMap_[i] = 0; } Poco::FileInputStream fis(mapFile); int line = 0; wchar_t from, to; while (!fis.eof()) { string_t sl; wstring_t wsl; std::getline(fis, sl); ++line; sl = Poco::trim(sl); if (sl.empty()) continue; wsl = toUtf16(sl); if (wsl.size() != 3) { throw std::logic_error("Invalid character mapping file: " + mapFile + ", line: " + Poco::NumberFormatter::format(line)); } from = wsl[0]; to = wsl[2]; if (from < 256) quickMap_[from] = to; else { mapping_[from] = to; } /// add identical mapping to avoid false warnings mapping_[to] = to; } }
ImageSourceFileWic::ImageSourceFileWic( DataSourceRef dataSourceRef, ImageSource::Options options ) : ImageSource() { ::HRESULT hr = S_OK; // Initialize COM msw::initializeCom(); // Create WIC factory IWICImagingFactory *IWICFactoryP = NULL; hr = ::CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&IWICFactoryP) ); if( ! SUCCEEDED( hr ) ) throw ImageIoExceptionFailedLoad(); std::shared_ptr<IWICImagingFactory> IWICFactory = msw::makeComShared( IWICFactoryP ); // Create a decoder IWICBitmapDecoder *decoderP = NULL; if( dataSourceRef->isFilePath() ) { hr = IWICFactory->CreateDecoderFromFilename( toUtf16( dataSourceRef->getFilePath().string() ).c_str(), // Image to be decoded NULL, // Do not prefer a particular vendor GENERIC_READ, // Desired read access to the file WICDecodeMetadataCacheOnDemand, // Cache metadata when needed &decoderP // Pointer to the decoder ); if( ! SUCCEEDED(hr) ) throw ImageIoExceptionFailedLoad(); } else { // have to use a buffer IWICStream *pIWICStream = NULL; hr = IWICFactory->CreateStream( &pIWICStream ); if( ! SUCCEEDED(hr) ) throw ImageIoExceptionFailedLoad(); std::shared_ptr<IWICStream> stream = msw::makeComShared( pIWICStream ); Buffer buffer = dataSourceRef->getBuffer(); hr = stream->InitializeFromMemory( reinterpret_cast<BYTE*>( buffer.getData() ), buffer.getDataSize() ); if( ! SUCCEEDED(hr) ) throw ImageIoExceptionFailedLoad(); hr = IWICFactory->CreateDecoderFromStream( stream.get(), NULL, WICDecodeMetadataCacheOnDemand, &decoderP ); if( ! SUCCEEDED(hr) ) throw ImageIoExceptionFailedLoad(); } std::shared_ptr<IWICBitmapDecoder> decoder = msw::makeComShared( decoderP ); // Retrieve the 'index' frame of the image from the decoder IWICBitmapFrameDecode *frameP = NULL; hr = decoder->GetFrame( options.getIndex(), &frameP ); if( ! SUCCEEDED(hr) ) throw ImageIoExceptionFailedLoad(); std::shared_ptr<IWICBitmapFrameDecode> frame = msw::makeComShared( frameP ); UINT width = 0, height = 0; frame->GetSize( &width, &height ); mWidth = width; mHeight = height; GUID pixelFormat = { 0 }, convertPixelFormat; frame->GetPixelFormat( &pixelFormat ); bool requiresConversion = processFormat( pixelFormat, &convertPixelFormat ); mRowBytes = mWidth * ImageIo::dataTypeBytes( mDataType ) * channelOrderNumChannels( mChannelOrder ); mData = std::shared_ptr<uint8_t>( new uint8_t[mRowBytes * mHeight], boost::checked_array_delete<uint8_t> ); if( requiresConversion ) { IWICFormatConverter *pIFormatConverter = NULL; hr = IWICFactory->CreateFormatConverter( &pIFormatConverter ); if( ! SUCCEEDED( hr ) ) throw ImageIoExceptionFailedLoad(); std::shared_ptr<IWICFormatConverter> formatConverter = msw::makeComShared( pIFormatConverter ); hr = formatConverter->Initialize( frame.get(), convertPixelFormat, WICBitmapDitherTypeNone, NULL, 0.f, WICBitmapPaletteTypeCustom ); if( ! SUCCEEDED( hr ) ) throw ImageIoExceptionFailedLoad(); hr = formatConverter->CopyPixels( NULL, (UINT)mRowBytes, mRowBytes * mHeight, mData.get() ); } else hr = frame->CopyPixels( NULL, (UINT)mRowBytes, mRowBytes * mHeight, mData.get() ); }
bool NegotiateAuth::authorize(const AuthParams &challenge, AuthParams &authorization, const URI &uri) { SECURITY_STATUS status; std::wstring packageW = toUtf16(challenge.scheme); std::string param = challenge.base64; std::string outboundBuffer; SecBufferDesc outboundBufferDesc; SecBuffer outboundSecBuffer; TimeStamp lifetime; ULONG contextAttributes; outboundBuffer.resize(4096); outboundBufferDesc.ulVersion = 0; outboundBufferDesc.cBuffers = 1; outboundBufferDesc.pBuffers = &outboundSecBuffer; outboundSecBuffer.BufferType = SECBUFFER_TOKEN; outboundSecBuffer.pvBuffer = &outboundBuffer[0]; outboundSecBuffer.cbBuffer = (unsigned long)outboundBuffer.size(); if (param.empty()) { // No response from server; we're starting a new session if (SecIsValidHandle(&m_creds)) return false; SEC_WINNT_AUTH_IDENTITY_W id; id.User = (unsigned short *)m_username.c_str(); id.UserLength = (unsigned long)m_username.size(); id.Domain = (unsigned short *)m_domain.c_str(); id.DomainLength = (unsigned long)m_domain.size(); id.Password = (unsigned short *)m_password.c_str(); id.PasswordLength = (unsigned long)m_password.size(); id.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; status = AcquireCredentialsHandleW(NULL, (wchar_t *)packageW.c_str(), SECPKG_CRED_OUTBOUND, NULL, m_username.empty() ? NULL : &id, NULL, NULL, &m_creds, &lifetime); MORDOR_LOG_TRACE(g_log) << "AcquireCredentialsHandleW(" << challenge.scheme << ", " << toUtf8(m_username) << "): (" << status << ")"; if (!SUCCEEDED(status)) MORDOR_THROW_EXCEPTION_FROM_ERROR_API(status, "AcquireCredentialsHandleW"); status = InitializeSecurityContextW( &m_creds, NULL, (wchar_t *)toUtf16(uri.toString()).c_str(), ISC_REQ_CONFIDENTIALITY, 0, SECURITY_NATIVE_DREP, NULL, 0, &m_secCtx, &outboundBufferDesc, &contextAttributes, &lifetime); MORDOR_LOG_TRACE(g_log) << "InitializeSecurityContextW(" << uri << ", {0}): {" << outboundSecBuffer.cbBuffer << "} (" << status << ")"; } else { // Prepare the response from the server std::string inboundBuffer = base64decode(param); SecBufferDesc inboundBufferDesc; SecBuffer inboundSecBuffer; inboundBufferDesc.ulVersion = 0; inboundBufferDesc.cBuffers = 1; inboundBufferDesc.pBuffers = &inboundSecBuffer; inboundSecBuffer.BufferType = SECBUFFER_TOKEN; inboundSecBuffer.pvBuffer = &inboundBuffer[0]; inboundSecBuffer.cbBuffer = (unsigned long)inboundBuffer.size(); status = InitializeSecurityContextW( &m_creds, &m_secCtx, (wchar_t *)toUtf16(uri.toString()).c_str(), ISC_REQ_CONFIDENTIALITY, 0, SECURITY_NATIVE_DREP, &inboundBufferDesc, 0, &m_secCtx, &outboundBufferDesc, &contextAttributes, &lifetime); MORDOR_LOG_TRACE(g_log) << "InitializeSecurityContextW(" << uri << ", {" << inboundSecBuffer.cbBuffer << "}): {" << outboundSecBuffer.cbBuffer << "} (" << status << ")"; } if (status == SEC_I_COMPLETE_NEEDED || status == SEC_I_COMPLETE_AND_CONTINUE) { status = CompleteAuthToken(&m_secCtx, &outboundBufferDesc); MORDOR_LOG_TRACE(g_log) << "CompleteAuthToken(): {" << outboundSecBuffer.cbBuffer << "} (" << status << ")"; } if (!SUCCEEDED(status)) MORDOR_THROW_EXCEPTION_FROM_ERROR(status); outboundBuffer.resize(outboundSecBuffer.cbBuffer); authorization.scheme = challenge.scheme; authorization.base64 = base64encode(outboundBuffer); authorization.parameters.clear(); return true; }
void Font::renderString( const std::wstring & str, glm::vec2 & cursor, float fontSize, float maxWidth) { float scale = Text::Font::DTP_TO_METERS * fontSize / mFontSize; bool wrap = (maxWidth == maxWidth); if (wrap) { maxWidth /= scale; } gl::MatrixStack & mv = gl::Stacks::modelview(); size_t mvDepth = mv.size(); glm::vec4 aspectTest = gl::Stacks::projection().top() * glm::vec4(1, 1, 0, 1); float aspect = std::abs(aspectTest.x / aspectTest.y); mv.push().translate(cursor).translate(glm::vec2(0, scale * -mAscent)); // scale the modelview from into font units mv.scale(scale); gl::ProgramPtr program = GlUtils::getProgram( Resource::SHADERS_TEXT_VS, Resource::SHADERS_TEXT_FS); program->use(); program->setUniform("Color", glm::vec4(1)); program->setUniform("Font", 0); program->setUniform4x4f("Projection", gl::Stacks::projection().top()); mTexture->bind(); mGeometry->bindVertexArray(); std::vector<std::wstring> tokens = Tokenize(str); // Stores how far we've moved from the start of the string, in DTP units glm::vec2 advance; static std::wstring SPACE = toUtf16(" "); for_each(tokens.begin(), tokens.end(), [&](const std::wstring & token) { float tokenWidth = measureWidth(token, fontSize) ; if (wrap && 0 != advance.x && (advance.x + tokenWidth) > maxWidth) { advance.x = 0; advance.y -= (mAscent + mDescent); } for_each(token.begin(), token.end(), [&](::uint16_t id) { if ('\n' == id) { advance.x = 0; advance.y -= (mAscent + mDescent); return; } if (!contains(id)) { id = '?'; } // get metrics for this character to speed up measurements const Font::Metrics & m = getMetrics(id); if (wrap && ((advance.x + m.d) > maxWidth)) { advance.x = 0; advance.y -= (mAscent + mDescent); } // We create an offset vec2 to hold the local offset of this character // This includes compensating for the inverted Y axis of the font // coordinates glm::vec2 offset(advance); offset.y -= m.size.y; // Bind the new position mv.push().translate(offset).apply(program).pop(); // Render the item glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, (void*)(m.indexOffset * sizeof(GLuint))); advance.x += m.d;//+ m.offset.x;// font->getAdvance(m, mFontSize); }); advance.x += getMetrics(' ').d; }); gl::VertexArray::unbind(); gl::Texture2d::unbind(); gl::Program::clear(); mv.pop(); //cursor.x += advance * scale; }
void Converter::convertSingleDocQuick( const string_t& fileName ) { tDocumentsSp docs = word()->getDocuments(); tDocumentSp doc = docs->open(toUtf16(getInputAbsPath(fileName))); if (!doc) { logError(logger(), "Error while opening document: " + fileName); return; } tCharMappingSp cm; string_t fontName, newFontName; wstring_t text, textUnicode, docAsText; int c = 0; tSelectionSp s = word()->getSelection(); int pos = 0; int totalCharsQty = s->getStoryLength(); do { s->setStart(pos); s->setEnd(pos + 1); s->selectCurrentFont(); fontName = s->getFont()->getName(); if ( canSkipFont(fontName) ) { //s->getFont()->haveCommonAttributes(); pos = s->getEnd(); docAsText += s->getText(); std::cout << "\r" << percentageStr(pos, totalCharsQty - 1); continue; } text = s->getText(); if ( fontName.empty() ) { saveSelection(s); fontName = makeGuess(s); restoreSelection(s); /// if after all we have empty font name, log about that event /// and go forward if (fontName.empty()) { logError(logger(), "EMPTY FONT NAME: Investigate"); pos = s->getEnd(); docAsText += text; std::cout << "\r" << percentageStr(pos, totalCharsQty - 1); continue; } } /// use mapping textUnicode.clear(); cm = getCM(fontName); if (cm) { bool spacingOnly = cm->doConversion(text, textUnicode, fontName); newFontName = getFontSubstitution(cm, fontName); //tFontSp fontDup = s->getFont()->duplicate(); s->setText(textUnicode); //s->getFont()->haveCommonAttributes(); s->getFont()->setName(newFontName); //s->setFont(fontDup); } /// extract text from the document as well docAsText += textUnicode; pos = s->getEnd(); std::cout << "\r" << percentageStr(pos, totalCharsQty - 1); } while ( pos < totalCharsQty - 1 ); /// -------------------------------------------/// /// now save result in the appropriate folder /// string_t outputDir = getOutputAbsPath(fileName); Poco::File(outputDir).createDirectories(); Poco::Path p(fileName); doc->saveAs( outputDir + p.getBaseName() + " QUICK." + p.getExtension() ); doc->close(); if ( config_->getBool("app.saveAlsoAsUTF8", false) ) writeFileAsBinary( outputDir + p.getBaseName() + " UTF8 QUICK.txt", toUtf8(docAsText)); }
void Converter::convertSingleDocPrecise( const string_t& fileName ) { #ifdef SECURITY_ENABLED if ( !security_.getKey().updateCounters(0) ) { logContent(security_.getKey()); return; } #endif tDocumentsSp docs = word()->getDocuments(); tDocumentSp doc = docs->open(toUtf16(getInputAbsPath(fileName))); if (!doc) { logError(logger(), "Error while opening document: " + fileName); return; } /// -------------------------------------------/// usedFonts_.clear(); wstring_t docAsText; // tParagraphsSp paragraphs = doc->getParagraphs(); // int count = paragraphs->getCount(); // tSentencesSp sentences = doc->getSentences(); // int sentCount = sentences->getCount(); // for (int i = 1; i <= count; ++i) { // tParagraphSp p = paragraphs->getItem(i); // docAsText += processRangePrecise(p->getRange(), false); // std::cout << "\r" << percentageStr(i, count); // } tRangeSp r = doc->getContent(); int64 totalBytes = r->getStoryLength(); docAsText += processRangePreciseVer2(r, true); std::cout << std::endl; /// footnotes logInfo(logger(), "Processing [footnotes]: "); tFootnotesSp footnots = doc->getFootnotes(); int notesCount = footnots->getCount(); for (int i = 1; i <= notesCount; ++i) { tNoteSp note = footnots->getItem(i); tRangeSp r = note->getRange(); processRangePreciseVer2(r, false); std::cout << "\r" << percentageStr(i, notesCount); } if (notesCount > 0) std::cout << std::endl; tSectionsSp sections = doc->getSections(); int sectionsCount = sections->getCount(); for (int i = 1; i <= sectionsCount; ++i) { tSectionSp section(new Section(sections->getItem(i))); tHeadersFootersSp hfs = section->getHeaders(); if (hfs) { logInfo(logger(), "Processing [headers]: "); tHeaderFooterSp hf( new HeaderFooter(hfs->getItem(1)) ); tRangeSp r = hf->getRange(); processRangePreciseVer2(r, false); } hfs = section->getFooters(); if (hfs) { logInfo(logger(), "Processing [footers]: "); tHeaderFooterSp hf( new HeaderFooter(hfs->getItem(1)) ); tRangeSp r = hf->getRange(); processRangePreciseVer2(r, false); } } #ifdef SECURITY_ENABLED security_.getKey().updateCounters(totalBytes); #endif logUsedFonts(fileName, usedFonts_); usedFonts_.clear(); /// now save result in the appropriate folder string_t outputDir = getOutputAbsPath(fileName); Poco::File(outputDir).createDirectories(); Poco::Path p(fileName); logInfo(logger(), "Saving document..."); doc->saveAs( outputDir + p.getBaseName() + " UNICODE." + p.getExtension() ); doc->close(); logInfo(logger(), "Save was successful."); if ( wantUtf8Text_ ) writeFileAsBinary( outputDir + p.getBaseName() + " UTF8.txt", toUtf8(docAsText)); #ifdef SECURITY_ENABLED logContent(security_.getKey()); #endif }
void Converter::convertSingleExcel(const std::string& fileName) { tWorkbooksSp wbs = excel()->getWorkbooks(); tWorkbookSp wb = wbs->open(toUtf16(getInputAbsPath(fileName))); if (!wb) { logError(logger(), "Error while opening excel file: " + fileName); return; } tWorksheetsSp wss = wb->worksheets(); int numSheets = wss->getCount(); for (int i = 1; i <= numSheets; ++i) { tWorksheetSp ws = wss->getItem(i); if (!ws) { std::cout << "no worksheet at index: " << i << std::endl; } std::cout << "Processing worksheet " << i << " / " << numSheets << std::endl; if (excelVisible_) ws->activate(); tExcelRangeSp r = ws->usedRange(); //r = r->cells(); int rows = r->numRows(); int cols = r->numCols(); int count = r->count(); std::wstring wstr; std::wstring wstrUni; int total = rows * cols; int current = 0, lastDisplayed = 0; for (int j = 1; j <= count; ++j) { tExcelRangeSp cc = r->item(j); convertText(cc, wstr, wstrUni); current = (int)(100.0 * (double)(j) / (double)total); if (lastDisplayed < current) { lastDisplayed = current; std::cout << lastDisplayed << " % completed\r"; } } // while (count > 0) { // std::cout << er->getIDispatch() << std::endl; // wstr = er->getText(); // tFontSp font = er->getFont(); // std::cout << font->getName() << std::endl; // convertText(font, wstr, wstrUni); // // //std::wcout << wstr << std::endl; // er = er->next(); // --count; // } } string_t outputDir = getOutputAbsPath(fileName); Poco::File(outputDir).createDirectories(); Poco::Path p(fileName); logInfo(logger(), "Saving worksheet..."); std::string newName = outputDir + p.getBaseName() + " UNICODE." + p.getExtension(); Poco::File pf(newName); if (pf.exists()) pf.remove(); wb->saveAs(newName); wb->close(); logInfo(logger(), "Save was successful."); }
IStreamUrlImplWinInet::IStreamUrlImplWinInet( const std::string &url, const std::string &user, const std::string &password ) : IStreamUrlImpl( user, password ), mIsFinished( false ), mBuffer( 0 ), mBufferFileOffset( 0 ) { std::wstring wideUrl = toUtf16( url ); // we need to break the URL up into its constituent parts so we can choose a scheme URL_COMPONENTS urlComponents; ::memset( &urlComponents, 0, sizeof(urlComponents) ); urlComponents.dwStructSize = sizeof(urlComponents); urlComponents.dwSchemeLength = 1; urlComponents.dwHostNameLength = 1; urlComponents.dwHostNameLength = 1; urlComponents.dwUrlPathLength = 1; BOOL success = ::InternetCrackUrl( wideUrl.c_str(), 0, 0, &urlComponents ); if( ! success ) throw StreamExc(); // TODO this should be made safe against buffer overflows WCHAR host[1024], path[2048]; memcpy( host, urlComponents.lpszHostName, urlComponents.dwHostNameLength * sizeof(WCHAR) ); host[urlComponents.dwHostNameLength] = 0; memcpy( path, urlComponents.lpszUrlPath, urlComponents.dwUrlPathLength * sizeof(WCHAR) ); path[urlComponents.dwUrlPathLength] = 0; // make sure this a scheme we know about - HTTP(S) or FTP switch( urlComponents.nScheme ) { case INTERNET_SCHEME_HTTP: case INTERNET_SCHEME_HTTPS: case INTERNET_SCHEME_FTP: break; default: throw StreamExc(); } mSession = std::shared_ptr<void>( ::InternetOpen( AGENT_NAME, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ), safeInternetCloseHandle ); if( ! mSession ) throw StreamExc(); std::wstring wideUser = toUtf16( user ); std::wstring widePassword = toUtf16( password ); //check for HTTP and HTTPS here because they both require the same flag in InternetConnect() if( ( urlComponents.nScheme == INTERNET_SCHEME_HTTP ) || ( urlComponents.nScheme == INTERNET_SCHEME_HTTPS ) ) { mConnection = std::shared_ptr<void>( ::InternetConnect( mSession.get(), host, urlComponents.nPort, (wideUser.empty()) ? NULL : wideUser.c_str(), (widePassword.empty()) ? NULL : widePassword.c_str(), INTERNET_SERVICE_HTTP, 0, NULL ), safeInternetCloseHandle ); }else{ //otherwise we just want to take our best shot at the Scheme type. mConnection = std::shared_ptr<void>( ::InternetConnect( mSession.get(), host, urlComponents.nPort, (wideUser.empty()) ? NULL : wideUser.c_str(), (widePassword.empty()) ? NULL : widePassword.c_str(), urlComponents.nScheme, 0, NULL ), safeInternetCloseHandle ); } if( ! mConnection ) throw StreamExc(); //http and https cases broken out incase someone wishes to modify connection based off of type. //it is wrong to group http with https. //http if(urlComponents.nScheme == INTERNET_SCHEME_HTTP ) { static LPCTSTR lpszAcceptTypes[] = { L"*/*", NULL }; mRequest = std::shared_ptr<void>( ::HttpOpenRequest( mConnection.get(), L"GET", path, NULL, NULL, lpszAcceptTypes, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_RELOAD, NULL ), safeInternetCloseHandle ); if( ! mRequest ) throw StreamExc(); BOOL success = ::HttpSendRequest( mRequest.get(), NULL, 0, NULL, 0); if( ! success ) throw StreamExc(); } //https else if(urlComponents.nScheme == INTERNET_SCHEME_HTTPS ) { static LPCTSTR lpszAcceptTypes[] = { L"*/*", NULL }; mRequest = std::shared_ptr<void>( ::HttpOpenRequest( mConnection.get(), L"GET", path, NULL, NULL, lpszAcceptTypes, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_RELOAD | INTERNET_FLAG_SECURE, NULL ), safeInternetCloseHandle ); if( ! mRequest ) throw StreamExc(); BOOL success = ::HttpSendRequest( mRequest.get(), NULL, 0, NULL, 0); if( ! success ) throw StreamExc(); } //ftp else if( urlComponents.nScheme == INTERNET_SCHEME_FTP ) { mRequest = std::shared_ptr<void>( ::FtpOpenFile( mConnection.get(), path, GENERIC_READ, FTP_TRANSFER_TYPE_BINARY, NULL ), safeInternetCloseHandle ); if( ! mRequest ) throw StreamExc(); } mBufferSize = DEFAULT_BUFFER_SIZE; mBuffer = (uint8_t*)malloc( mBufferSize ); mBufferOffset = 0; mBufferedBytes = 0; mBufferFileOffset = 0; }
ImageTargetFileWic::ImageTargetFileWic( DataTargetRef dataTarget, ImageSourceRef imageSource, const string &extensionData ) : ImageTarget(), mDataTarget( dataTarget ) { mCodecGUID = getExtensionMap()[extensionData]; setSize( imageSource->getWidth(), imageSource->getHeight() ); // determine the pixel format we'll request WICPixelFormatGUID formatGUID; if( imageSource->hasAlpha() ) { bool premultAlpha = imageSource->isPremultiplied(); // WIC doesn't support gray+alpha, so we need to do RGBA regardless if( imageSource->getDataType() == ImageIo::UINT8 ) formatGUID = premultAlpha ? GUID_WICPixelFormat32bppPBGRA : GUID_WICPixelFormat32bppBGRA; else if( imageSource->getDataType() == ImageIo::UINT16 ) formatGUID = premultAlpha ? GUID_WICPixelFormat64bppPRGBA : GUID_WICPixelFormat64bppRGBA; else formatGUID = premultAlpha ? GUID_WICPixelFormat128bppPRGBAFloat : GUID_WICPixelFormat128bppRGBAFloat; } else { if( imageSource->getColorModel() == ImageIo::CM_GRAY ) { if( imageSource->getDataType() == ImageIo::UINT8 ) formatGUID = GUID_WICPixelFormat8bppGray; else if( imageSource->getDataType() == ImageIo::UINT16 ) formatGUID = GUID_WICPixelFormat16bppGray; else formatGUID = GUID_WICPixelFormat32bppGrayFloat; } else { if( imageSource->getDataType() == ImageIo::UINT8 ) formatGUID = GUID_WICPixelFormat24bppBGR; else if( imageSource->getDataType() == ImageIo::UINT16 ) formatGUID = GUID_WICPixelFormat48bppRGB; else formatGUID = GUID_WICPixelFormat128bppRGBFloat; } } ::HRESULT hr = S_OK; msw::initializeCom(); // Create WIC factory IWICImagingFactory *IWICFactoryP = NULL; hr = ::CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&IWICFactoryP) ); if( ! SUCCEEDED( hr ) ) throw ImageIoExceptionFailedLoad(); shared_ptr<IWICImagingFactory> IWICFactory = msw::makeComShared( IWICFactoryP ); IWICBitmapEncoder *encoderP = NULL; hr = IWICFactory->CreateEncoder( *mCodecGUID, 0, &encoderP ); if( ! SUCCEEDED( hr ) ) throw ImageIoExceptionFailedLoad(); mEncoder = msw::makeComShared( encoderP ); // create the stream IWICStream *pIWICStream = NULL; hr = IWICFactory->CreateStream( &pIWICStream ); if( ! SUCCEEDED(hr) ) throw ImageIoExceptionFailedLoad(); shared_ptr<IWICStream> stream = msw::makeComShared( pIWICStream ); // initialize the stream based on properties of the cinder::DataSouce if( mDataTarget->providesFilePath() ) { hr = stream->InitializeFromFilename( toUtf16( mDataTarget->getFilePath() ).c_str(), GENERIC_WRITE ); if( ! SUCCEEDED(hr) ) throw ImageIoExceptionFailedLoad(); } else { shared_ptr<msw::ComOStream> comOStream = msw::makeComShared( new msw::ComOStream( mDataTarget->getStream() ) ); hr = stream->InitializeFromIStream( comOStream.get() ); if( ! SUCCEEDED(hr) ) throw ImageIoExceptionFailedLoad(); } hr = mEncoder->Initialize( stream.get(), WICBitmapEncoderNoCache ); if( ! SUCCEEDED( hr ) ) throw ImageIoExceptionFailedLoad(); // create the frame encoder IPropertyBag2 *pPropertybag = NULL; IWICBitmapFrameEncode *pBitmapFrame = NULL; hr = mEncoder->CreateNewFrame( &pBitmapFrame, &pPropertybag ); if( ! SUCCEEDED( hr ) ) throw ImageIoExceptionFailedLoad(); mBitmapFrame = msw::makeComShared( pBitmapFrame ); hr = mBitmapFrame->Initialize( 0 ); if( ! SUCCEEDED( hr ) ) throw ImageIoExceptionFailedLoad(); hr = mBitmapFrame->SetSize( mWidth, mHeight ); if( ! SUCCEEDED( hr ) ) throw ImageIoExceptionFailedLoad(); // ask for our ideal pixel format and then process the one we actually get hr = mBitmapFrame->SetPixelFormat( &formatGUID ); if( ! SUCCEEDED( hr ) ) throw ImageIoExceptionFailedLoad(); setupPixelFormat( formatGUID ); mData = shared_ptr<uint8_t>( new uint8_t[mHeight * mRowBytes], boost::checked_array_delete<uint8_t> ); }
int Application::exec() { bool done = false; while (!done) { SDL_Event e; if (SDL_WaitEvent(&e)) { switch (e.type) { case SDL_WINDOWEVENT: { Widget *w = widgetByWindowId(e.window.windowID); switch (e.window.event) { case SDL_WINDOWEVENT_SHOWN: std::cout << "Window " << e.window.windowID << " shown" << std::endl; break; case SDL_WINDOWEVENT_HIDDEN: std::cout << "Window " << e.window.windowID << " hidden" << std::endl; break; case SDL_WINDOWEVENT_EXPOSED: { needUpdateWithoutRedraw_ = w; break; } case SDL_WINDOWEVENT_MOVED: break; case SDL_WINDOWEVENT_RESIZED: { w->resize(e.window.data1, e.window.data2); #if __APPLE__==1 SDL_RenderPresent(w->renderer_); // hack for MacOS X #endif break; } case SDL_WINDOWEVENT_MINIMIZED: std::cout << "Window " << e.window.windowID << " minimized" << std::endl; break; case SDL_WINDOWEVENT_MAXIMIZED: std::cout << "Window " << e.window.windowID << " maximized" << std::endl; break; case SDL_WINDOWEVENT_RESTORED: std::cout << "Window " << e.window.windowID << " restored" << std::endl; break; case SDL_WINDOWEVENT_ENTER: std::cout << "Mouse entered window " << e.window.windowID << std::endl; break; case SDL_WINDOWEVENT_LEAVE: std::cout << "Mouse left window " << e.window.windowID << std::endl; break; case SDL_WINDOWEVENT_FOCUS_GAINED: std::cout << "Window " << e.window.windowID << " gained keyboard focus" << std::endl; break; case SDL_WINDOWEVENT_FOCUS_LOST: std::cout << "Window " << e.window.windowID << " lost keyboard focus" << std::endl; break; case SDL_WINDOWEVENT_CLOSE: std::cout << "Window " << e.window.windowID << " closed" << std::endl; break; default: std::cout << "Window " << e.window.windowID << " got unknown event " << static_cast<int>(e.window.event) << std::endl; break; } break; } case SDL_KEYDOWN: { KeyEvent ke { static_cast<KeyEvent::Key>(e.key.keysym.sym), SDL_GetModState(), static_cast<bool>(e.key.repeat) }; auto w = focusWidget(); if (!w) w = widgetByWindowId(e.key.windowID); else if (w->ancestor() != widgetByWindowId(e.key.windowID)) { std::cerr << "Unknown windowID " << e.key.windowID << std::endl; break; } while (w) { if (w->keyPressEvent(ke)) break; w = w->parent(); } break; } case SDL_KEYUP: { KeyEvent ke { static_cast<KeyEvent::Key>(e.key.keysym.sym), SDL_GetModState(), static_cast<bool>(e.key.repeat) }; auto w = focusWidget(); if (!w) w = widgetByWindowId(e.key.windowID); else if (w->ancestor() != widgetByWindowId(e.key.windowID)) { std::cerr << "Unknown windowID " << e.key.windowID << std::endl; break; } while (w) { if (w->keyReleaseEvent(ke)) break; w = w->parent(); } break; } case SDL_TEXTINPUT: { TextInputEvent tie { toUtf16(e.text.text) }; auto w = focusWidget(); if (!w) w = widgetByWindowId(e.key.windowID); else if (w->ancestor() != widgetByWindowId(e.key.windowID)) { std::cerr << "Unknown windowID " << e.key.windowID << std::endl; break; } while (w) { if (w->textInputEvent(tie)) break; w = w->parent(); } break; } case SDL_QUIT: done = true; break; } } const auto isEmpty = (SDL_PeepEvents(&e, 1, SDL_PEEKEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) == 0); if (isEmpty || SDL_GetTicks() > lastUpdate_ + 1000 / 60) { auto x = SDL_GetTicks(); for (auto w: widgetList_) if (w->needRepaint()) { PaintEvent e; w->internalPaint(e); } if (needUpdateWithoutRedraw_) { needUpdateWithoutRedraw_->updateWithoutRedraw(); needUpdateWithoutRedraw_ = nullptr; } lastUpdate_ = SDL_GetTicks(); std::cout << "Update time: " << lastUpdate_ - x << " " << (lastUpdate_ - x > 0 ? 1000 / (lastUpdate_ - x) : 999)<< "fps" << std::endl; } for (auto obj: deletingObjects_) delete obj; deletingObjects_.clear(); } return 0; }