/** * Creates a new figure in the model and returns it. * * @param type The type of figure that is requested. * @param layoutClass The specialization of the figure for a particular layout (can be NULL). * @result The new figure instance. */ CFigure* CGenericCanvas::createFigure(const char* type, const char* layoutClass) { if (layoutClass == NULL) return FModel->createFigure(utf8ToUtf16(type), L""); else return FModel->createFigure(utf8ToUtf16(type), utf8ToUtf16(layoutClass)); }
DLL_PUBLIC void * openFile(const char *filename, const char *mode, const char *proxy) { LPDVDFILEHANDLE pHandle = new DVDFILEHANDLE; if (pHandle == NULL) { return NULL; } pHandle->m_strFileName = filename; if (!isUrl(pHandle->m_strFileName)) { #ifdef _WIN32 wchar_t szUtf16Filename[MAX_PATH]; wchar_t szMode[20]; utf8ToUtf16(szMode, mode); if (utf8ToUtf16(szUtf16Filename, filename)) { pHandle->m_pFile = _wfopen(szUtf16Filename, szMode); } else { pHandle->m_pFile = NULL; } #else pHandle->m_pFile = fopen(filename, mode); #endif pHandle->m_pHttpServer = NULL; pHandle->m_bWebFile = false; if (pHandle->m_pFile == NULL) { closeFile(pHandle); pHandle = NULL; } } else { pHandle->m_pFile = NULL; pHandle->m_pHttpServer = new http; pHandle->m_bWebFile = true; if (proxy != NULL) { pHandle->m_pHttpServer->setProxy(proxy); } int res = pHandle->m_pHttpServer->request(http::GET, pHandle->m_strFileName); if (res != 200) { closeFile(pHandle); pHandle = NULL; } } return pHandle; }
/** * Interface function for the model's createConnection function. Read there for details. */ CConnection* CGenericCanvas::createConnection(const char* type, const char* layoutClass, CFigure* endPoint1, CFigure* endPoint2) { if (layoutClass == NULL) return FModel->createConnection(utf8ToUtf16(type), L"", endPoint1, endPoint2); else return FModel->createConnection(utf8ToUtf16(type), utf8ToUtf16(layoutClass), endPoint1, endPoint2); }
TGCError CGenericCanvas::addStylesFromFile(const char* filename, map<string, string>& variables) { map<wstring, wstring> wide_variables; for (map<string, string>::const_iterator iterator = variables.begin(); iterator != variables.end(); ++iterator) wide_variables[utf8ToUtf16(iterator->first)] = utf8ToUtf16(iterator->second); return addStylesFromFile(filename, wide_variables); }
// virtual bool SymbolsPropertyPage::onInitDialog() { wchar_t basename[] = L"\\symbols.dat"; std::wstring filename = userDir_ + basename; HANDLE file = CreateFile(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if(file == INVALID_HANDLE_VALUE) { // user specific symbols file does not exists, try the built-in one in Program files // try C:\program files (x86) first wchar_t path[MAX_PATH]; HRESULT result = ::SHGetFolderPathW(NULL, CSIDL_PROGRAM_FILESX86, NULL, 0, path); if(result != S_OK) // failed, fall back to C:\program files result = ::SHGetFolderPathW(NULL, CSIDL_PROGRAM_FILES, NULL, 0, path); if(result == S_OK) { // program files folder is found filename = path; filename += L"\\ChewingTextService\\Dictionary"; filename += basename; } file = CreateFile(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); } if(file != INVALID_HANDLE_VALUE) { DWORD size = GetFileSize(file, NULL); char* buf = new char[size+1]; DWORD rsize; ReadFile(file, buf, size, &rsize, NULL); CloseHandle(file); buf[size] = 0; std::wstring wstr = utf8ToUtf16(buf); delete []buf; ::SetDlgItemTextW(hwnd_, IDC_EDIT, wstr.c_str()); } return PropertyPage::onInitDialog(); }
static bool menuFromJson(ITfMenu* pMenu, const Json::Value& menuInfo) { if (pMenu != nullptr && menuInfo.isArray()) { for (Json::Value::const_iterator it = menuInfo.begin(); it != menuInfo.end(); ++it) { const Json::Value& item = *it; UINT id = item.get("id", 0).asUInt(); std::wstring text = utf8ToUtf16(item.get("text", "").asCString()); DWORD flags = 0; Json::Value submenuInfo; ITfMenu* submenu = nullptr; if (id == 0 && text.empty()) flags = TF_LBMENUF_SEPARATOR; else { if (item.get("checked", false).asBool()) flags |= TF_LBMENUF_CHECKED; if (!item.get("enabled", true).asBool()) flags |= TF_LBMENUF_GRAYED; submenuInfo = item["submenu"]; // FIXME: this is a deep copy. too bad! :-( if (submenuInfo.isArray()) { flags |= TF_LBMENUF_SUBMENU; } } pMenu->AddMenuItem(id, flags, NULL, NULL, text.c_str(), text.length(), flags & TF_LBMENUF_SUBMENU ? &submenu : nullptr); if (submenu != nullptr && submenuInfo.isArray()) { menuFromJson(submenu, submenuInfo); } } return true; } return false; }
static HMENU menuFromJson(const Json::Value& menuInfo) { if (menuInfo.isArray()) { HMENU menu = ::CreatePopupMenu(); for (auto it = menuInfo.begin(); it != menuInfo.end(); ++it) { const Json::Value& item = *it; UINT id = item.get("id", 0).asUInt(); std::wstring text = utf8ToUtf16(item.get("text", "").asCString()); UINT flags = MF_STRING; if (id == 0 && text.empty()) flags = MF_SEPARATOR; else { if (item.get("checked", false).asBool()) flags |= MF_CHECKED; if (!item.get("enabled", true).asBool()) flags |= MF_GRAYED; const Json::Value& subMenuValue = item.get("submenu", Json::nullValue); if (subMenuValue.isArray()) { HMENU submenu = menuFromJson(subMenuValue); flags |= MF_POPUP; id = UINT_PTR(submenu); } } AppendMenu(menu, flags, id, text.c_str()); } return menu; } return NULL; }
void MFPlayer::setSource(const std::string& url) { auto ws = utf8ToUtf16(url); BSTR bs = SysAllocStringLen(ws.data(), ws.size()); auto ret = m_pMediaEngine->SetSource(bs); assert(ret == S_OK); }
~BitmapDC() { prepareBitmap(0, 0); if (m_hDC) { DeleteDC(m_hDC); } HFONT hDefFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT); if (hDefFont != m_hFont) { DeleteObject(m_hFont); m_hFont = hDefFont; } // release temp font resource if (m_curFontPath.size() > 0) { wchar_t * pwszBuffer = utf8ToUtf16(m_curFontPath); if (pwszBuffer) { RemoveFontResourceW(pwszBuffer); SendMessage( m_hWnd, WM_FONTCHANGE, 0, 0); delete [] pwszBuffer; pwszBuffer = NULL; } } }
Bool isValidNCName(const char* name) { int len = utf8StrLength(name); if (len == 0) return FALSE; wchar_t *buff = new wchar_t[len + 1]; utf8ToUtf16(buff, name); Bool result = utf8IsLetter(buff[0]) || buff[0] == 0x005F; //underscore for (int i = 1; i < len && result; i++) { result = utf8IsLetter(buff[i]) || utf8IsDigit(buff[i]) || utf8IsCombiningChar(buff[i]) || utf8IsExtender(buff[i]) || buff[i] == 0x002E || //dot buff[i] == 0x002D || //hyphen buff[i] == 0x005F; //underscore } delete[] buff; return result; }
bool utf8ToMbs( const char* source, std::string& output ) { std::wstring utf16Name; bool ret = utf8ToUtf16( source, utf16Name ); if( ret ) { return utf16ToMbs( utf16Name.c_str(), output ); } return false; }
DLL_PUBLIC int statFile(const char *filename, LPDVDFILESTAT pFileStat, const char *proxy) { memset(pFileStat, 0, sizeof(DVDFILESTAT)); if (!isUrl(filename)) { // Local files #ifdef _WIN32 struct _stat buf; wchar_t szUtf16Filename[MAX_PATH]; if (utf8ToUtf16(szUtf16Filename, filename)) { if (_wstat(szUtf16Filename, &buf) == -1) { return -1; } } else { return -1; } #else struct stat buf; if (stat(filename, &buf) == -1) { return -1; } #endif pFileStat->m_FileTime = buf.st_mtime; pFileStat->m_qwFileSize = buf.st_size; pFileStat->m_bIsDirectory = S_ISDIR(buf.st_mode) ? true : false; } else { http httpserver; if (proxy != NULL) { httpserver.setProxy(proxy); } int res = httpserver.request(http::GET_HEADERSONLY, filename); if (res != 200) { return -1; } pFileStat->m_FileTime = httpserver.getTimeStamp(); pFileStat->m_qwFileSize = httpserver.getContentSize(); } return 0; }
FILE * openUtf8Filename( const char * utf8, char * mode ) { FILE * f; #ifdef WIN32 wchar_t * utf16 = utf8ToUtf16( utf8 ); wchar_t * mode16 = utf8ToUtf16( mode ); f = _wfopen(utf16, mode16); free( mode16 ); free( utf16 ); // For Windows 98/ME, let's try to open the file with fopen if( f==0 ) { f = fopen(utf8, mode); } #else f = fopen(utf8, mode); #endif return f; }
/** * Set the value of the given property, which must be a simple property. * * @param name The name of the property. * @param index If the property is a list then this is the index into that list. * @param value The new value of the property. Automatic conversion is performed where possible. */ void CGenericCanvas::propertySet(const char* name, unsigned int index, TGCVariant value) { switch (getPropertyID(name)) { case GC_PROPERTY_NAME: { FName = utf8ToUtf16(value); break; }; }; }
// virtual bool ImeModule::onConfigure(HWND hwndParent, LANGID langid, REFGUID rguidProfile) { // FIXME: this is inefficient. Should we cache known modules? LPOLESTR pGuidStr = NULL; if (FAILED(::StringFromCLSID(rguidProfile, &pGuidStr))) return false; std::string guidStr = utf16ToUtf8(pGuidStr); CoTaskMemFree(pGuidStr); // find the input method module std::wstring dirPath = programDir_ + L"\\server\\input_methods"; std::wstring configTool; // scan the dir for lang profile definition files WIN32_FIND_DATA findData = { 0 }; HANDLE hFind = ::FindFirstFile((dirPath + L"\\*").c_str(), &findData); if (hFind != INVALID_HANDLE_VALUE) { do { if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // this is a subdir if (findData.cFileName[0] != '.') { std::wstring imejson = dirPath; imejson += '\\'; imejson += findData.cFileName; imejson += L"\\ime.json"; FILE* fp = _wfopen(imejson.c_str(), L"r"); if (fp) { char buf[4096]; rapidjson::Document json; rapidjson::FileReadStream stream(fp, buf, sizeof(buf)); json.ParseStream(stream); fclose(fp); if (guidStr == json["guid"].GetString()) { // found the language profile std::wstring relPath = utf8ToUtf16(json["configTool"].GetString()); if (!relPath.empty()) { configTool = dirPath; configTool += '\\'; configTool += findData.cFileName; configTool += '\\'; configTool += relPath; } break; } } } } } while (::FindNextFile(hFind, &findData)); CloseHandle(hFind); } if(!configTool.empty()) ::ShellExecuteW(hwndParent, L"open", configTool.c_str(), NULL, NULL, SW_SHOWNORMAL); return true; }
/** * Returns the first view with the given name from the views collection. * * @param name The name of the view to return. * @return The first found view with the given name or NULL if no view could be found. */ CGCView* CGenericCanvas::viewByName(const char* name) { CGCView* result = NULL; wstring viewName = utf8ToUtf16(name); for (CViews::const_iterator iterator = FViews.begin(); iterator != FViews.end(); ++iterator) { CGCView* view = *iterator; if (view->FName == viewName) { result = view; break; }; }; return result; }
/** * Returns the first layer with the given name from the layers collection. * * @param name The name of the layer to return. * @return The first found layer with the given name or NULL if no layer could be found. */ CLayer* CGenericCanvas::layerByName(const char* name) { CLayer* result = NULL; wstring S = utf8ToUtf16(name); for (CLayers::const_iterator iterator = FLayers.begin(); iterator != FLayers.end(); ++iterator) { CLayer* layer = *iterator; if (layer->name() == S) { result = layer; break; }; }; return result; }
void Client::updateUI(const Json::Value& data) { for (auto it = data.begin(); it != data.end(); ++it) { const char* name = it.memberName(); const Json::Value& value = *it; if (value.isString() && strcmp(name, "candFontName") == 0) { wstring fontName = utf8ToUtf16(value.asCString()); textService_->setCandFontName(fontName); } else if (value.isInt() && strcmp(name, "candFontSize") == 0) { textService_->setCandFontSize(value.asInt()); } else if (value.isInt() && strcmp(name, "candPerRow") == 0) { textService_->setCandPerRow(value.asInt()); } else if (value.isBool() && strcmp(name, "candUseCursor") == 0) { textService_->setCandUseCursor(value.asBool()); } } }
/** * Generalized warning function. It can be called the same way that printf() can. * * @format format with the same meaning as in printf */ void DiagLog::warning(const char *format, ...) { char s[1024]; va_list argList; va_start(argList, format); vsnprintf( s, 1024-1, format, argList); va_end(argList); #ifdef WIN32 wchar_t * utf16 = utf8ToUtf16( s ); MessageBox( NULL, utf16, L"Warning", MB_OK ); free( utf16 ); #else printf("WARNING: "); printf( s ); printf( "\n" ); #endif }
bool setFont(const char * pFontName = nullptr, int nSize = 0) { bool bRet = false; do { std::string fontName = pFontName; std::string fontPath; HFONT hDefFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT); LOGFONTA tNewFont = {0}; LOGFONTA tOldFont = {0}; GetObjectA(hDefFont, sizeof(tNewFont), &tNewFont); if (fontName.c_str()) { // create font from ttf file int nFindttf = fontName.find(".ttf"); int nFindTTF = fontName.find(".TTF"); if (nFindttf >= 0 || nFindTTF >= 0) { fontPath = FileUtils::getInstance()->fullPathForFilename(fontName.c_str()); int nFindPos = fontName.rfind("/"); fontName = &fontName[nFindPos+1]; nFindPos = fontName.rfind("."); fontName = fontName.substr(0,nFindPos); } else { auto nFindPos = fontName.rfind("/"); if (nFindPos != fontName.npos) { if (fontName.length() == nFindPos + 1) { fontName = ""; } else { fontName = &fontName[nFindPos+1]; } } } tNewFont.lfCharSet = DEFAULT_CHARSET; strcpy_s(tNewFont.lfFaceName, LF_FACESIZE, fontName.c_str()); } if (nSize) { tNewFont.lfHeight = -nSize; } GetObjectA(_font, sizeof(tOldFont), &tOldFont); if (tOldFont.lfHeight == tNewFont.lfHeight && 0 == strcmp(tOldFont.lfFaceName, tNewFont.lfFaceName)) { // already has the font bRet = true; break; } // delete old font removeCustomFont(); if (fontPath.size() > 0) { _curFontPath = fontPath; wchar_t * pwszBuffer = utf8ToUtf16(_curFontPath); if (pwszBuffer) { if(AddFontResource(pwszBuffer)) { SendMessage( _wnd, WM_FONTCHANGE, 0, 0); } delete [] pwszBuffer; pwszBuffer = nullptr; } } _font = nullptr; // disable Cleartype tNewFont.lfQuality = ANTIALIASED_QUALITY; // create new font _font = CreateFontIndirectA(&tNewFont); if (! _font) { // create failed, use default font _font = hDefFont; break; } bRet = true; } while (0); return bRet; }
bool setFont(const char * pFontName = NULL, int nSize = 0) { bool bRet = false; do { std::string fontName = pFontName; std::string fontPath; HFONT hDefFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT); LOGFONTA tNewFont = {0}; LOGFONTA tOldFont = {0}; GetObjectA(hDefFont, sizeof(tNewFont), &tNewFont); if (fontName.c_str()) { // create font from ttf file int nFindttf = fontName.find(".ttf"); int nFindTTF = fontName.find(".TTF"); if (nFindttf >= 0 || nFindTTF >= 0) { fontPath = CCFileUtils::sharedFileUtils()->fullPathForFilename(fontName.c_str()); int nFindPos = fontName.rfind("/"); fontName = &fontName[nFindPos+1]; nFindPos = fontName.rfind("."); fontName = fontName.substr(0,nFindPos); } else { size_t nFindPos = fontName.rfind("/"); if (nFindPos != fontName.npos) { if (fontName.length() == nFindPos + 1) { fontName = ""; } else { fontName = &fontName[nFindPos+1]; } } } tNewFont.lfCharSet = DEFAULT_CHARSET; #if defined(__MINGW32__) strcpy(tNewFont.lfFaceName, fontName.c_str()); #elif defined(_MSC_VER) && _MSC_VER <= 1200 strcpy(tNewFont.lfFaceName, fontName.c_str()); #else strcpy_s(tNewFont.lfFaceName, LF_FACESIZE, fontName.c_str()); #endif } if (nSize) { tNewFont.lfHeight = -nSize; } GetObjectA(m_hFont, sizeof(tOldFont), &tOldFont); if (tOldFont.lfHeight == tNewFont.lfHeight && 0 == strcmp(tOldFont.lfFaceName, tNewFont.lfFaceName)) { // already has the font bRet = true; break; } // delete old font if (m_hFont != hDefFont) { DeleteObject(m_hFont); // release old font register if (m_curFontPath.size() > 0) { wchar_t * pwszBuffer = utf8ToUtf16(m_curFontPath); if (pwszBuffer) { if(RemoveFontResourceW(pwszBuffer)) { SendMessage( m_hWnd, WM_FONTCHANGE, 0, 0); } delete [] pwszBuffer; pwszBuffer = NULL; } } if (fontPath.size() > 0) m_curFontPath = fontPath; else #if defined(_MSC_VER) && _MSC_VER <= 1200 m_curFontPath.erase(); #else m_curFontPath.clear(); #endif // register temp font if (m_curFontPath.size() > 0) { wchar_t * pwszBuffer = utf8ToUtf16(m_curFontPath); if (pwszBuffer) { if(AddFontResourceW(pwszBuffer)) { SendMessage( m_hWnd, WM_FONTCHANGE, 0, 0); } delete [] pwszBuffer; pwszBuffer = NULL; } } } m_hFont = NULL; // disable Cleartype tNewFont.lfQuality = ANTIALIASED_QUALITY; // create new font m_hFont = CreateFontIndirectA(&tNewFont); if (! m_hFont) { // create failed, use default font m_hFont = hDefFont; break; } bRet = true; } while (0); return bRet; }
void Client::updateStatus(Json::Value& msg, Ime::EditSession* session) { // We need to handle ordering of some types of the requests. // For example, setCompositionCursor() should happen after setCompositionCursor(). // set sel keys before update candidates const auto& setSelKeysVal = msg["setSelKeys"]; if (setSelKeysVal.isString()) { // keys used to select candidates std::wstring selKeys = utf8ToUtf16(setSelKeysVal.asCString()); textService_->setSelKeys(selKeys); } // show message bool endComposition = false; const auto& showMessageVal = msg["showMessage"]; if (showMessageVal.isObject()) { const Json::Value& message = showMessageVal["message"]; const Json::Value& duration = showMessageVal["duration"]; if (message.isString() && duration.isInt()) { if (!textService_->isComposing()) { textService_->startComposition(session->context()); endComposition = true; } textService_->showMessage(session, utf8ToUtf16(message.asCString()), duration.asInt()); } } if (session != nullptr) { // if an edit session is available // handle candidate list const auto& showCandidatesVal = msg["showCandidates"]; if (showCandidatesVal.isBool()) { if (showCandidatesVal.asBool()) { // start composition if we are not composing. // this is required to get correctly position the candidate window if (!textService_->isComposing()) { textService_->startComposition(session->context()); } textService_->showCandidates(session); } else { textService_->hideCandidates(); } } const auto& candidateListVal = msg["candidateList"]; if (candidateListVal.isArray()) { // handle candidates // FIXME: directly access private member is dirty!!! vector<wstring>& candidates = textService_->candidates_; candidates.clear(); for (auto cand_it = candidateListVal.begin(); cand_it != candidateListVal.end(); ++cand_it) { wstring cand = utf8ToUtf16(cand_it->asCString()); candidates.push_back(cand); } textService_->updateCandidates(session); if (!showCandidatesVal.asBool()) { textService_->hideCandidates(); } } const auto& candidateCursorVal = msg["candidateCursor"]; if (candidateCursorVal.isInt()) { if (textService_->candidateWindow_ != nullptr) { textService_->candidateWindow_->setCurrentSel(candidateCursorVal.asInt()); textService_->refreshCandidates(); } } // handle comosition and commit strings const auto& commitStringVal = msg["commitString"]; if (commitStringVal.isString()) { std::wstring commitString = utf8ToUtf16(commitStringVal.asCString()); if (!commitString.empty()) { if (!textService_->isComposing()) { textService_->startComposition(session->context()); } textService_->setCompositionString(session, commitString.c_str(), commitString.length()); // FIXME: update the position of candidate and message window when the composition string is changed. if (textService_->candidateWindow_ != nullptr) { textService_->updateCandidatesWindow(session); } if (textService_->messageWindow_ != nullptr) { textService_->updateMessageWindow(session); } textService_->endComposition(session->context()); } } const auto& compositionStringVal = msg["compositionString"]; bool emptyComposition = false; bool hasCompositionString = false; std::wstring compositionString; if (compositionStringVal.isString()) { // composition buffer compositionString = utf8ToUtf16(compositionStringVal.asCString()); hasCompositionString = true; if (compositionString.empty()) { emptyComposition = true; if (textService_->isComposing() && !textService_->showingCandidates()) { // when the composition buffer is empty and we are not showing the candidate list, end composition. textService_->setCompositionString(session, L"", 0); endComposition = true; } } else { if (!textService_->isComposing()) { textService_->startComposition(session->context()); } textService_->setCompositionString(session, compositionString.c_str(), compositionString.length()); } // FIXME: update the position of candidate and message window when the composition string is changed. if (textService_->candidateWindow_ != nullptr) { textService_->updateCandidatesWindow(session); } if (textService_->messageWindow_ != nullptr) { textService_->updateMessageWindow(session); } } const auto& compositionCursorVal = msg["compositionCursor"]; if (compositionCursorVal.isInt()) { // composition cursor if (!emptyComposition) { int compositionCursor = compositionCursorVal.asInt(); if (!textService_->isComposing()) { textService_->startComposition(session->context()); } // NOTE: // This fixes PIME bug #166: incorrect handling of UTF-16 surrogate pairs. // The TSF API unfortunately treat a UTF-16 surrogate pair as two characters while // they actually represent one unicode character only. To workaround this TSF bug, // we get the composition string, and try to move the cursor twice when a UTF-16 // surrogate pair is found. if(!hasCompositionString) compositionString = textService_->compositionString(session); int fixedCursorPos = 0; for (int i = 0; i < compositionCursor; ++i) { ++fixedCursorPos; if (IS_HIGH_SURROGATE(compositionString[i])) // this is the first part of a UTF16 surrogate pair (Windows uses UTF16-LE) ++fixedCursorPos; } textService_->setCompositionCursor(session, fixedCursorPos); } } if (endComposition) { textService_->endComposition(session->context()); } } // language buttons const auto& addButtonVal = msg["addButton"]; if (addButtonVal.isArray()) { for (auto btn_it = addButtonVal.begin(); btn_it != addButtonVal.end(); ++btn_it) { const Json::Value& btn = *btn_it; // FIXME: when to clear the id <=> button map?? Ime::ComPtr<PIME::LangBarButton> langBtn{ PIME::LangBarButton::fromJson(textService_, btn), false }; if (langBtn != nullptr) { buttons_.emplace(langBtn->id(), langBtn); // insert into the map textService_->addButton(langBtn); } } } const auto& removeButtonVal = msg["removeButton"]; if (removeButtonVal.isArray()) { // FIXME: handle windows-mode-icon for (auto btn_it = removeButtonVal.begin(); btn_it != removeButtonVal.end(); ++btn_it) { if (btn_it->isString()) { string id = btn_it->asString(); auto map_it = buttons_.find(id); if (map_it != buttons_.end()) { textService_->removeButton(map_it->second); buttons_.erase(map_it); // remove from the map } } } } const auto& changeButtonVal = msg["changeButton"]; if (changeButtonVal.isArray()) { // FIXME: handle windows-mode-icon for (auto btn_it = changeButtonVal.begin(); btn_it != changeButtonVal.end(); ++btn_it) { const Json::Value& btn = *btn_it; if (btn.isObject()) { string id = btn["id"].asString(); auto map_it = buttons_.find(id); if (map_it != buttons_.end()) { map_it->second->updateFromJson(btn); } } } } // preserved keys const auto& addPreservedKeyVal = msg["addPreservedKey"]; if (addPreservedKeyVal.isArray()) { // preserved keys for (auto key_it = addPreservedKeyVal.begin(); key_it != addPreservedKeyVal.end(); ++key_it) { const Json::Value& key = *key_it; if (key.isObject()) { std::wstring guidStr = utf8ToUtf16(key["guid"].asCString()); CLSID guid = { 0 }; CLSIDFromString(guidStr.c_str(), &guid); UINT keyCode = key["keyCode"].asUInt(); UINT modifiers = key["modifiers"].asUInt(); textService_->addPreservedKey(keyCode, modifiers, guid); } } } const auto& removePreservedKeyVal = msg["removePreservedKey"]; if (removePreservedKeyVal.isArray()) { for (auto key_it = removePreservedKeyVal.begin(); key_it != removePreservedKeyVal.end(); ++key_it) { if (key_it->isString()) { std::wstring guidStr = utf8ToUtf16(key_it->asCString()); CLSID guid = { 0 }; CLSIDFromString(guidStr.c_str(), &guid); textService_->removePreservedKey(guid); } } } // keyboard status const auto& openKeyboardVal = msg["openKeyboard"]; if (openKeyboardVal.isBool()) { textService_->setKeyboardOpen(openKeyboardVal.asBool()); } // other configurations const auto& customizeUIVal = msg["customizeUI"]; if (customizeUIVal.isObject()) { // customize the UI updateUI(customizeUIVal); } // hide message const auto& hideMessageVal = msg["hideMessage"]; if (hideMessageVal.isBool()) { textService_->hideMessage(); } }
// Factory function for a canvas. GENERIC_CANVAS_API CGenericCanvas* CreateGenericCanvas(GCContext Context, char* name) { return new CGenericCanvas(Context, utf8ToUtf16(name)); }
/** * Renders the current scene to a file in the format given. * * @param filename The name of the target file. It must already contain the correct extension and must be encoded in UTF-8. * @param format The format of the file to render. Supported are PNG, PDF, PS (postscript) and EPS (encapsulated postscript). * @param title The titel for the document. Must be ANSI encoded for now. * @param software A string describing the producer of the document. Must be ANSI encoded for now. * @param content A set of flags indicating what additional info to render. * @param zoom The zoom at which render the file. * @param bounds Position and size of the area to store in the file (currently only for PNG). * @return True if successful otherwise false. */ bool CGenericCanvas::renderToFile(const char* filename, TGCFileFormat format, const char* title, const char* software, TGCRenderContent content, float zoom, TGCViewport& bounds) { bool result = false; if (!updating()) { beginUpdate(); try { if ((FStates & GC_STATE_PENDING_ACTIVATION) != 0) { // A pending activation state always means there is a valid current view. FStates &= ~GC_STATE_PENDING_ACTIVATION; FCurrentView->activate(); }; switch (format) { case GC_FILE_FORMAT_PDF: case GC_FILE_FORMAT_PS: case GC_FILE_FORMAT_EPS: { if (FCurrentView != NULL) { const int fileTypeMapper[4] = {GL2PS_PDF, GL2PS_PS, GL2PS_EPS, GL2PS_TEX}; FILE *file = openFile(filename, "wb"); GLint bufferSize = 0; GLint state = GL2PS_OVERFLOW; char *oldlocale = setlocale(LC_NUMERIC, "C"); while (state == GL2PS_OVERFLOW) { bufferSize += 1024 * 1024; gl2psBeginPage(title, software, NULL, fileTypeMapper[format], GL2PS_NO_SORT, GL2PS_DRAW_BACKGROUND | GL2PS_USE_CURRENT_VIEWPORT | GL2PS_COMPRESS, GL_RGBA, 0, NULL, 0, 0, 0, bufferSize, file, filename); gl2psEnable(GL2PS_BLEND); gl2psBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); clearBuffers(); FCurrentView->render(content); state = gl2psEndPage(); }; setlocale(LC_NUMERIC, oldlocale); fclose(file); result = true; }; break; }; case GC_FILE_FORMAT_PNG: { if (FCurrentView != NULL) { TImage image; float workspaceWidth; float workspaceHeight; FCurrentView->getWorkspace(&workspaceWidth, &workspaceHeight); image.width = bounds.width; if (image.width < 0) image.width = (int) workspaceWidth; image.height = bounds.height; if (image.height < 0) image.height = (int) workspaceHeight; // If the frame buffer extension is not supported then there is no sense // to allocate a buffer larger than the current viewport, // because we cannot render more than this area in this case. if (!supportsExtension(GC_OE_FRAME_BUFFER_OBJECTS)) { if (image.height > FCurrentView->viewportGet().height) image.height = FCurrentView->viewportGet().height; if (image.width > FCurrentView->viewportGet().width) image.width = FCurrentView->viewportGet().width; }; image.colorType = COLOR_TYPE_RGB_ALPHA; image.data = (unsigned char*) malloc(image.width * image.height * 4); if (image.data != NULL) { FCurrentView->renderToMemory(GC_COLOR_FORMAT_RGBA, content, zoom, bounds, image.data); image.width = bounds.width; image.height = bounds.height; result = savePNG(utf8ToUtf16(filename), &image, true, title, software); free(image.data); }; }; break; }; }; endUpdate(); } catch(...) { endUpdate(); throw; }; checkError(); }; return result; }
bool setFont(const char * pFontName = NULL, int nSize = 0) { bool bRet = false; do { std::string fontName = pFontName; std::string fontPath; HFONT hDefFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT); LOGFONTA tNewFont = {0}; LOGFONTA tOldFont = {0}; GetObjectA(hDefFont, sizeof(tNewFont), &tNewFont); if (fontName.c_str()) { // create font from ttf file int nFindttf = fontName.find(".ttf"); int nFindTTF = fontName.find(".TTF"); if (nFindttf >= 0 || nFindTTF >= 0) { fontPath = CCFileUtils::fullPathFromRelativePath(fontName.c_str()); int nFindPos = fontName.rfind("/"); fontName = &fontName[nFindPos+1]; nFindPos = fontName.rfind("."); fontName = fontName.substr(0,nFindPos); } tNewFont.lfCharSet = DEFAULT_CHARSET; strcpy_s(tNewFont.lfFaceName, LF_FACESIZE, fontName.c_str()); } if (nSize) { tNewFont.lfHeight = -nSize; } GetObjectA(m_hFont, sizeof(tOldFont), &tOldFont); if (tOldFont.lfHeight == tNewFont.lfHeight && ! strcpy(tOldFont.lfFaceName, tNewFont.lfFaceName)) { // already has the font bRet = true; break; } // delete old font if (m_hFont != hDefFont) { DeleteObject(m_hFont); // release old font register if (m_curFontPath.size() > 0) { wchar_t * pwszBuffer = utf8ToUtf16(m_curFontPath); if (pwszBuffer) { if(RemoveFontResource(pwszBuffer)) { SendMessage( m_hWnd, WM_FONTCHANGE, 0, 0); } delete [] pwszBuffer; pwszBuffer = NULL; } } fontPath.size()>0?(m_curFontPath = fontPath):(m_curFontPath.clear()); // register temp font if (m_curFontPath.size() > 0) { wchar_t * pwszBuffer = utf8ToUtf16(m_curFontPath); if (pwszBuffer) { if(AddFontResource(pwszBuffer)) { SendMessage( m_hWnd, WM_FONTCHANGE, 0, 0); } delete [] pwszBuffer; pwszBuffer = NULL; } } } m_hFont = NULL; // create new font m_hFont = CreateFontIndirectA(&tNewFont); if (! m_hFont) { // create failed, use default font m_hFont = hDefFont; break; } bRet = true; } while (0); return bRet; }
/** * Removes the style with the given name (UTF-8 encoded) from the canvas. Figure elements which used this style * will be left without visual appearence then. * * @param name The name of a style (encoded in UTF-8). */ void CGenericCanvas::removeStyle(const char* name) { wstring styleName = utf8ToUtf16(name); FModel->removeStyle(styleName); }
/** Does the message box thingy to show the error. * * @returns True if program should continue going forward. */ bool ErrorSystem::execLastError() { if (errorCount == 0) return true; string concatError = lastError.title + " -- " + lastError.heading; if (lastError.message != "") { concatError += " -- " + lastError.message; } // If this error is not fatal and it is set to be suppressed, return true here already if (!lastError.fatal && this->isSuppressed(concatError)) { return true; } #ifdef _WIN32 // Windows wants it's console output in codepage 1252 std::cerr << utf8toCP1252(concatError) << std::endl; #else std::cerr << concatError << std::endl; #endif if (lastError.fatal) { al_show_native_message_box( cb->gfxInterface->getWindow(), lastError.title.c_str(), lastError.heading.c_str(), lastError.message.c_str(), NULL, ALLEGRO_MESSAGEBOX_ERROR ); cb->stop(); return false; } #ifndef _WIN32 // Allegro doesn't support custom messagebox buttons with Windows int ret = al_show_native_message_box( cb->gfxInterface->getWindow(), lastError.title.c_str(), lastError.heading.c_str(), lastError.message.c_str(), "Abort|Continue|Suppress this error", ALLEGRO_MESSAGEBOX_OK_CANCEL ); switch (ret) { case 0: // No buttons clicked case 2: // User clicked continue return true; case 1: // User clicked abort cb->stop(); return false; case 3: // Suppress errors this->suppressError(concatError); return true; default: FIXME("Undefined messagebox return value %i in ErrorSystem::execLastError()", ret); cb->stop(); return false; } #else string message; if (lastError.message.empty()) { message = lastError.heading; } else { message = lastError.heading + "\n\n" + lastError.message; } // Convert message and title to utf-16 with the amazing UTF8-CPP library wstring wideMsg = utf8ToUtf16(message); wstring wideTitle = utf8ToUtf16(lastError.title); int ret = CBTMessageBox(al_get_win_window_handle(cb->gfxInterface->getWindow()), &wideMsg[0], &wideTitle[0], MB_ABORTRETRYIGNORE | MB_ICONERROR); switch (ret) { case 0: // No buttons clicked case IDRETRY: // User clicked continue return true; case IDABORT: // User clicked abort cb->stop(); return false; case IDIGNORE: // Suppress errors this->suppressError(concatError); return true; default: FIXME("Undefined messagebox return value %i in ErrorSystem::execLastError()", ret); cb->stop(); return false; } #endif // _WIN32 }