void StateGraphViewerPanel:: OnMouseOverDisplayable(MouseOverDisplayableEvent const &Ev) { // Remove highlighting from the existing value (if any). if (auto const Prev = MouseOver.get()) { if (llvm::isa<DisplayableValue>(Prev)) { if (auto Access = CurrentAccess->getAccess()) Notifier->createNotify<ConEvHighlightValue>(nullptr, CurrentAccess); } else if (llvm::isa<DisplayableDereference>(Prev)) { if (auto Access = CurrentAccess->getAccess()) Notifier->createNotify<ConEvHighlightValue>(nullptr, CurrentAccess); } else if (llvm::isa<DisplayableFunctionState>(Prev)) { Notifier->createNotify<ConEvHighlightDecl>(nullptr); } else if (llvm::isa<DisplayableLocalState>(Prev)) { Notifier->createNotify<ConEvHighlightDecl>(nullptr); } else if (llvm::isa<DisplayableParamState>(Prev)) { Notifier->createNotify<ConEvHighlightDecl>(nullptr); } else if (llvm::isa<DisplayableGlobalVariable>(Prev)) { Notifier->createNotify<ConEvHighlightDecl>(nullptr); } else if (auto const DA = llvm::dyn_cast<DisplayableReferencedArea>(Prev)) { if (auto Access = CurrentAccess->getAccess()) { auto const Start = DA->getAreaStart(); auto const MMalloc = CurrentProcess->getDynamicMemoryAllocation(Start); if (MMalloc.assigned<seec::cm::MallocState>()) { auto const &Malloc = MMalloc.get<seec::cm::MallocState>(); if (Malloc.getAllocatorStmt()) Notifier->createNotify<ConEvHighlightStmt>(nullptr); } } } } MouseOver = Ev.getDisplayableShared(); auto const Node = MouseOver.get(); if (!Node) { if (Recording) Recording->recordEventL("StateGraphViewer.MouseOverNone"); } else if (auto const DV = llvm::dyn_cast<DisplayableValue>(Node)) { if (auto Access = CurrentAccess->getAccess()) { Notifier->createNotify<ConEvHighlightValue>(&(DV->getValue()), CurrentAccess); } if (Recording) { std::vector<std::unique_ptr<IAttributeReadOnly>> Attrs; addAttributesForValue(Attrs, DV->getValue()); Recording->recordEventV("StateGraphViewer.MouseOverValue", Attrs); } } else if (auto const DD = llvm::dyn_cast<DisplayableDereference>(Node)) { if (auto Access = CurrentAccess->getAccess()) { Notifier->createNotify<ConEvHighlightValue>(&(DD->getPointer()), CurrentAccess); } if (Recording) { std::vector<std::unique_ptr<IAttributeReadOnly>> Attrs; addAttributesForValue(Attrs, DD->getPointer()); Recording->recordEventV("StateGraphViewer.MouseOverDereference", Attrs); } } else if (auto const DF = llvm::dyn_cast<DisplayableFunctionState>(Node)) { auto const Decl = DF->getFunctionState().getFunctionDecl(); Notifier->createNotify<ConEvHighlightDecl>(Decl); if (Recording) { auto const &FS = DF->getFunctionState(); Recording->recordEventL("StateGraphViewer.MouseOverFunctionState", make_attribute("function", FS.getNameAsString())); } } else if (auto const DL = llvm::dyn_cast<DisplayableLocalState>(Node)) { auto const Decl = DL->getLocalState().getDecl(); Notifier->createNotify<ConEvHighlightDecl>(Decl); if (Recording) { // TODO } } else if (auto const DP = llvm::dyn_cast<DisplayableParamState>(Node)) { auto const Decl = DP->getParamState().getDecl(); Notifier->createNotify<ConEvHighlightDecl>(Decl); if (Recording) { // TODO } } else if (auto const DG = llvm::dyn_cast<DisplayableGlobalVariable>(Node)) { auto const Decl = DG->getGlobalVariable().getClangValueDecl(); Notifier->createNotify<ConEvHighlightDecl>(Decl); if (Recording) { // TODO } } else if (auto const DA = llvm::dyn_cast<DisplayableReferencedArea>(Node)) { if (auto Access = CurrentAccess->getAccess()) { auto const Start = DA->getAreaStart(); auto const MayMalloc = CurrentProcess->getDynamicMemoryAllocation(Start); if (MayMalloc.assigned<seec::cm::MallocState>()) { auto const &Malloc = MayMalloc.get<seec::cm::MallocState>(); if (auto const S = Malloc.getAllocatorStmt()) Notifier->createNotify<ConEvHighlightStmt>(S); } } if (Recording) { Recording->recordEventL("StateGraphViewer.MouseOverReferencedArea", make_attribute("start", DA->getAreaStart()), make_attribute("end", DA->getAreaEnd())); } } else { wxLogDebug("Mouse over unknown Displayable."); if (Recording) { Recording->recordEventL("StateGraphViewer.MouseOverUnknown"); } } }
raBid::raBid(const wxWindow* parent): wxPanel((wxWindow*)parent) { int i = 0; int j = 0; int best_width = 0; int temp_width = 0; int temp_height = 0; m_game = NULL; m_min_bid = 0; // Initializing the value of all the buttons to NULL for(i = 0; i < raBID_TOTAL_BTNS; ++i) m_buttons[i] = NULL; m_button_all = NULL; m_button_pass = NULL; // Calculate the best width for the buttons // The best width should be able to contain all bids from 14 // to 28 and the strings "All" and "Pass" best_width = 0; for(i = 0 ; i < raBID_TOTAL_BTNS; i++) { this->GetTextExtent(wxString::Format(wxT("%d"), i + 14), &temp_width, &temp_height); best_width = std::max(best_width, temp_width); } this->GetTextExtent(wxT("All"), &temp_width, &temp_height); best_width = std::max(best_width, temp_width); this->GetTextExtent(wxT("Pass"), &temp_width, &temp_height); best_width = std::max(best_width, temp_width); wxLogDebug(wxString::Format(wxT("Best width %d"), best_width)); #ifdef __WXMSW__ this->SetWindowStyle(wxRAISED_BORDER); #endif m_main_panel = new wxPanel(this); if(!m_main_panel) { wxLogError(wxString::Format(wxT("Failed to create main panel. %s:%d"), wxT(__FILE__), __LINE__)); return; } #ifdef __WXMSW__ m_main_panel->SetWindowStyle(wxSUNKEN_BORDER); #endif m_main_panel->SetBackgroundColour(*wxWHITE); m_main_sizer = new wxGridSizer(0, 0, 0, 0); // TODO : Add error checks m_main_panel_sizer = new wxBoxSizer(wxVERTICAL); m_head_panel = new wxPanel(m_main_panel); //m_head_panel->SetWindowStyle(wxRAISED_BORDER); m_head_panel->SetBackgroundColour(raCLR_HEAD_DARK); m_head_panel->SetForegroundColour(*wxWHITE); m_bold_font = m_head_panel->GetFont(); m_bold_font.SetWeight(wxFONTWEIGHT_BOLD); m_head_panel->SetFont(m_bold_font); m_head_panel_sizer = new wxGridSizer(0, 0, 0, 0); m_head_panel_text = new wxStaticText(m_head_panel, -1, wxT("Enter Bid")); m_head_panel_sizer->Add(m_head_panel_text, 0, wxALIGN_CENTER_HORIZONTAL| wxALIGN_CENTER_VERTICAL|wxALL, 2); m_head_panel->SetSizer(m_head_panel_sizer); m_bidbtn_panel = new wxPanel(m_main_panel); //m_bidbtn_panel->SetWindowStyle(wxSUNKEN_BORDER); m_bidbtn_panel_sizer = new wxGridSizer(5, 3, 0, 0); for(i = 0; i < raBID_BTN_ROWS; i++) { for(j = 0; j < raBID_BTN_COLS; j++) { m_buttons[(i * raBID_BTN_COLS) + j] = new wxButton(m_bidbtn_panel, raBID_BTN_ID_START + (i * raBID_BTN_COLS) + j, wxString::Format(wxT("%d"), (i * raBID_BTN_COLS) + j + 14), wxDefaultPosition, wxSize(best_width, -1)); m_bidbtn_panel_sizer->Add(m_buttons[(i * raBID_BTN_COLS) + j], 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL, 1); //m_buttons[(i * raBID_BTN_COLS) + j]->SetSize(10, 20); //m_buttons[(i * raBID_BTN_COLS) + j]->SetWindowStyle(wxNO_BORDER); m_buttons[(i * raBID_BTN_COLS) + j]->SetEventHandler(this->GetEventHandler()); } } m_bidbtn_panel->SetSizer(m_bidbtn_panel_sizer); m_bidbtn_panel_sizer->Fit(m_bidbtn_panel); // Create panel, assosiated sizer to hold the buttons // to bid "All" and "Pass" m_btns_panel = new wxPanel(m_main_panel); m_btns_panel_sizer = new wxGridSizer(1, 2, 0, 0); m_button_all = new wxButton(m_btns_panel, raBID_BTN_ID_ALL, wxT("All")); m_button_pass = new wxButton(m_btns_panel, raBID_BTN_ID_PASS, wxT("Pass")); //m_button_all->Disable(); //m_button_all->SetWindowStyle(wxNO_BORDER); //m_button_pass->SetWindowStyle(wxNO_BORDER); m_button_all->SetEventHandler(this->GetEventHandler()); m_button_pass->SetEventHandler(this->GetEventHandler()); m_btns_panel_sizer->Add(m_button_all, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL, 1); m_btns_panel_sizer->Add(m_button_pass, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL|wxEXPAND|wxALL, 1); m_btns_panel->SetSizer(m_btns_panel_sizer); m_btns_panel_sizer->Fit(m_btns_panel); m_main_panel_sizer->Add(m_head_panel, 0, wxEXPAND | wxALL, raBID_PNL_RELIEF); m_main_panel_sizer->Add(m_bidbtn_panel, 0, wxEXPAND, 0); #ifdef __WXMSW__ m_main_panel_sizer->Add(m_btns_panel, 0, wxEXPAND | wxBOTTOM, raBID_PNL_RELIEF * 3); #else m_main_panel_sizer->Add(m_btns_panel, 0, wxEXPAND, 0); #endif m_main_panel->SetSizer(m_main_panel_sizer); m_main_panel_sizer->Fit(m_main_panel); m_main_sizer->Add(m_main_panel, 0, wxEXPAND, 0); this->SetSizer(m_main_sizer); m_main_sizer->Fit(this); this->GetEventHandler()->Connect(raBID_BTN_ID_START, raBID_BTN_ID_START + raBID_TOTAL_BTNS - 1, wxEVT_COMMAND_BUTTON_CLICKED,wxCommandEventHandler(raBid::OnButtonClick)); }
bool wxAnimation::Load(wxInputStream &stream, wxAnimationType type) { UnRef(); char anim_type[12]; switch (type) { case wxANIMATION_TYPE_GIF: strcpy(anim_type, "gif"); break; case wxANIMATION_TYPE_ANI: strcpy(anim_type, "ani"); break; default: anim_type[0] = '\0'; break; } // create a GdkPixbufLoader GError *error = NULL; GdkPixbufLoader *loader; if (type != wxANIMATION_TYPE_INVALID && type != wxANIMATION_TYPE_ANY) loader = gdk_pixbuf_loader_new_with_type(anim_type, &error); else loader = gdk_pixbuf_loader_new(); if (!loader) { wxLogDebug(wxT("Could not create the loader for '%s' animation type"), anim_type); return false; } // connect to loader signals g_signal_connect(loader, "area-updated", G_CALLBACK(gdk_pixbuf_area_updated), this); guchar buf[2048]; while (stream.IsOk()) { // read a chunk of data stream.Read(buf, sizeof(buf)); // fetch all data into the loader if (!gdk_pixbuf_loader_write(loader, buf, stream.LastRead(), &error)) { gdk_pixbuf_loader_close(loader, &error); wxLogDebug(wxT("Could not write to the loader")); return false; } } // load complete if (!gdk_pixbuf_loader_close(loader, &error)) { wxLogDebug(wxT("Could not close the loader")); return false; } // wait until we get the last area_updated signal return true; }
CGKeyCode wxCharCodeWXToOSX(wxKeyCode code) { CGKeyCode keycode; switch (code) { // Clang warns about switch values not of the same type as (enumerated) // switch controlling expression. This is generally useful but here we // really want to be able to use letters and digits without making them // part of wxKeyCode enum. #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wswitch" #endif // __clang__ case 'a': case 'A': keycode = kVK_ANSI_A; break; case 'b': case 'B': keycode = kVK_ANSI_B; break; case 'c': case 'C': keycode = kVK_ANSI_C; break; case 'd': case 'D': keycode = kVK_ANSI_D; break; case 'e': case 'E': keycode = kVK_ANSI_E; break; case 'f': case 'F': keycode = kVK_ANSI_F; break; case 'g': case 'G': keycode = kVK_ANSI_G; break; case 'h': case 'H': keycode = kVK_ANSI_H; break; case 'i': case 'I': keycode = kVK_ANSI_I; break; case 'j': case 'J': keycode = kVK_ANSI_J; break; case 'k': case 'K': keycode = kVK_ANSI_K; break; case 'l': case 'L': keycode = kVK_ANSI_L; break; case 'm': case 'M': keycode = kVK_ANSI_M; break; case 'n': case 'N': keycode = kVK_ANSI_N; break; case 'o': case 'O': keycode = kVK_ANSI_O; break; case 'p': case 'P': keycode = kVK_ANSI_P; break; case 'q': case 'Q': keycode = kVK_ANSI_Q; break; case 'r': case 'R': keycode = kVK_ANSI_R; break; case 's': case 'S': keycode = kVK_ANSI_S; break; case 't': case 'T': keycode = kVK_ANSI_T; break; case 'u': case 'U': keycode = kVK_ANSI_U; break; case 'v': case 'V': keycode = kVK_ANSI_V; break; case 'w': case 'W': keycode = kVK_ANSI_W; break; case 'x': case 'X': keycode = kVK_ANSI_X; break; case 'y': case 'Y': keycode = kVK_ANSI_Y; break; case 'z': case 'Z': keycode = kVK_ANSI_Z; break; case '0': keycode = kVK_ANSI_0; break; case '1': keycode = kVK_ANSI_1; break; case '2': keycode = kVK_ANSI_2; break; case '3': keycode = kVK_ANSI_3; break; case '4': keycode = kVK_ANSI_4; break; case '5': keycode = kVK_ANSI_5; break; case '6': keycode = kVK_ANSI_6; break; case '7': keycode = kVK_ANSI_7; break; case '8': keycode = kVK_ANSI_8; break; case '9': keycode = kVK_ANSI_9; break; #ifdef __clang__ #pragma clang diagnostic pop #endif // __clang__ case WXK_BACK: keycode = kVK_Delete; break; case WXK_TAB: keycode = kVK_Tab; break; case WXK_RETURN: keycode = kVK_Return; break; case WXK_ESCAPE: keycode = kVK_Escape; break; case WXK_SPACE: keycode = kVK_Space; break; case WXK_DELETE: keycode = kVK_ForwardDelete; break; case WXK_SHIFT: keycode = kVK_Shift; break; case WXK_ALT: keycode = kVK_Option; break; case WXK_RAW_CONTROL: keycode = kVK_Control; break; case WXK_CONTROL: keycode = kVK_Command; break; case WXK_CAPITAL: keycode = kVK_CapsLock; break; case WXK_END: keycode = kVK_End; break; case WXK_HOME: keycode = kVK_Home; break; case WXK_LEFT: keycode = kVK_LeftArrow; break; case WXK_UP: keycode = kVK_UpArrow; break; case WXK_RIGHT: keycode = kVK_RightArrow; break; case WXK_DOWN: keycode = kVK_DownArrow; break; case WXK_HELP: keycode = kVK_Help; break; case WXK_NUMPAD0: keycode = kVK_ANSI_Keypad0; break; case WXK_NUMPAD1: keycode = kVK_ANSI_Keypad1; break; case WXK_NUMPAD2: keycode = kVK_ANSI_Keypad2; break; case WXK_NUMPAD3: keycode = kVK_ANSI_Keypad3; break; case WXK_NUMPAD4: keycode = kVK_ANSI_Keypad4; break; case WXK_NUMPAD5: keycode = kVK_ANSI_Keypad5; break; case WXK_NUMPAD6: keycode = kVK_ANSI_Keypad6; break; case WXK_NUMPAD7: keycode = kVK_ANSI_Keypad7; break; case WXK_NUMPAD8: keycode = kVK_ANSI_Keypad8; break; case WXK_NUMPAD9: keycode = kVK_ANSI_Keypad9; break; case WXK_F1: keycode = kVK_F1; break; case WXK_F2: keycode = kVK_F2; break; case WXK_F3: keycode = kVK_F3; break; case WXK_F4: keycode = kVK_F4; break; case WXK_F5: keycode = kVK_F5; break; case WXK_F6: keycode = kVK_F6; break; case WXK_F7: keycode = kVK_F7; break; case WXK_F8: keycode = kVK_F8; break; case WXK_F9: keycode = kVK_F9; break; case WXK_F10: keycode = kVK_F10; break; case WXK_F11: keycode = kVK_F11; break; case WXK_F12: keycode = kVK_F12; break; case WXK_F13: keycode = kVK_F13; break; case WXK_F14: keycode = kVK_F14; break; case WXK_F15: keycode = kVK_F15; break; case WXK_F16: keycode = kVK_F16; break; case WXK_F17: keycode = kVK_F17; break; case WXK_F18: keycode = kVK_F18; break; case WXK_F19: keycode = kVK_F19; break; case WXK_F20: keycode = kVK_F20; break; case WXK_PAGEUP: keycode = kVK_PageUp; break; case WXK_PAGEDOWN: keycode = kVK_PageDown; break; case WXK_NUMPAD_DELETE: keycode = kVK_ANSI_KeypadClear; break; case WXK_NUMPAD_EQUAL: keycode = kVK_ANSI_KeypadEquals; break; case WXK_NUMPAD_MULTIPLY: keycode = kVK_ANSI_KeypadMultiply; break; case WXK_NUMPAD_ADD: keycode = kVK_ANSI_KeypadPlus; break; case WXK_NUMPAD_SUBTRACT: keycode = kVK_ANSI_KeypadMinus; break; case WXK_NUMPAD_DECIMAL: keycode = kVK_ANSI_KeypadDecimal; break; case WXK_NUMPAD_DIVIDE: keycode = kVK_ANSI_KeypadDivide; break; default: wxLogDebug( "Unrecognised keycode %d", code ); keycode = static_cast<CGKeyCode>(-1); } return keycode; }
bool BundleManager::DownloadDir(const wxString& url, const wxFileName& path, wxProgressDialog& dlg) { // Get list of files and folders RemoteProfile rp; vector<cxFileInfo> fiList; CURLcode errorCode = m_remoteThread.GetRemoteListWait(url, rp, fiList); if (errorCode != CURLE_OK) goto error; // Download files and folders { unsigned int retryCount = 0; for (vector<cxFileInfo>::const_iterator p = fiList.begin(); p != fiList.end(); ++p) { if (p->m_isDir) { // Create subdir wxFileName dir = path; dir.AppendDir(p->m_name); wxMkdir(dir.GetPath()); const wxString dirName = p->m_name + wxT('/'); if (!dlg.Pulse(dirName)) return false; // Download contents const wxString dirUrl = url + dirName; if (!DownloadDir(dirUrl, dir, dlg)) return false; } else { wxString filename = p->m_name; #ifdef __WXMSW__ filename = UrlEncode::EncodeFilename(filename); // Make filename safe for win #endif wxFileName filePath = path; filePath.SetFullName(filename); const wxString pathStr = filePath.GetFullPath(); if (!dlg.Pulse(filename)) return false; // Download file const wxString fileUrl = url + p->m_name; errorCode = m_remoteThread.Download(fileUrl, pathStr, rp); // Check for errors if (errorCode != CURLE_OK) goto error; // There has been some cases where the download has ended // up with an empty file but no error. As a workaround // we give it one more try and then return an error. if (filePath.GetSize() == 0 && p->m_size != 0) { if (retryCount == 0) { wxLogDebug(wxT("Received empty file! Retrying download")); ++retryCount; --p; continue; } else { errorCode = CURLE_PARTIAL_FILE; goto error; } } // Set modDate filePath.SetTimes(NULL, &p->m_modDate, NULL); retryCount = 0; } } } return true; error: wxMessageBox(m_remoteThread.GetErrorText(errorCode), _("Download Error"), wxICON_ERROR|wxOK, this); return false; }
void GetLanguages(wxArrayString &langCodes, wxArrayString &langNames) { wxArrayString tempNames; wxArrayString tempCodes; LangHash localLanguageName; LangHash reverseHash; LangHash tempHash; // MM: Use only ASCII characters here to avoid problems with // charset conversion on Linux platforms localLanguageName[wxT("ar")] = wxT("Arabic"); localLanguageName[wxT("bg")] = wxT("Balgarski"); localLanguageName[wxT("bs")] = wxT("Bosnian"); localLanguageName[wxT("ca")] = wxT("Catalan"); localLanguageName[wxT("cs")] = wxT("Czech"); localLanguageName[wxT("da")] = wxT("Dansk"); localLanguageName[wxT("de")] = wxT("Deutsch"); localLanguageName[wxT("el")] = wxT("Ellinika"); localLanguageName[wxT("en")] = wxT("English"); localLanguageName[wxT("es")] = wxT("Espanol"); localLanguageName[wxT("eu")] = wxT("Euskara"); localLanguageName[wxT("fi")] = wxT("Suomi"); localLanguageName[wxT("fr")] = wxT("Francais"); localLanguageName[wxT("ga")] = wxT("Gaeilge"); localLanguageName[wxT("id")] = wxT("Bahasa Indonesia"); // aka Indonesian localLanguageName[wxT("it")] = wxT("Italiano"); localLanguageName[wxT("ja")] = wxT("Nihongo"); localLanguageName[wxT("ka")] = wxT("Georgian"); localLanguageName[wxT("km")] = wxT("Khmer"); localLanguageName[wxT("lo")] = wxT("Lao"); // aka Laothian localLanguageName[wxT("lt")] = wxT("Lietuviu"); localLanguageName[wxT("he")] = wxT("Hebrew"); localLanguageName[wxT("hu")] = wxT("Magyar"); localLanguageName[wxT("mk")] = wxT("Makedonski"); localLanguageName[wxT("nl")] = wxT("Nederlands"); localLanguageName[wxT("nb")] = wxT("Norsk"); localLanguageName[wxT("pl")] = wxT("Polski"); localLanguageName[wxT("pt")] = wxT("Portugues"); localLanguageName[wxT("pt_BR")] = wxT("Portugues (Brasil)"); localLanguageName[wxT("ru")] = wxT("Russky"); localLanguageName[wxT("sl")] = wxT("Slovenscina"); localLanguageName[wxT("sv")] = wxT("Svenska"); localLanguageName[wxT("tr")] = wxT("Turkce"); localLanguageName[wxT("uk")] = wxT("Ukrainska"); localLanguageName[wxT("[email protected]")] = wxT("Valencian (southern Catalan)"); localLanguageName[wxT("vi")] = wxT("Vietnamese"); localLanguageName[wxT("zh")] = wxT("Chinese (Simplified)"); localLanguageName[wxT("zh_TW")] = wxT("Chinese (Traditional)"); wxArrayString audacityPathList = wxGetApp().audacityPathList; wxGetApp().AddUniquePathToPathList(wxString::Format(wxT("%s/share/locale"), wxT(INSTALL_PREFIX)), audacityPathList); int i; for(i=wxLANGUAGE_UNKNOWN; i<wxLANGUAGE_USER_DEFINED; i++) { const wxLanguageInfo *info = wxLocale::GetLanguageInfo(i); if (!info) continue; wxString fullCode = info->CanonicalName; wxString code = fullCode.Left(2); wxString name = info->Description; // Logic: Languages codes are sometimes hierarchical, with a // general language code and then a subheading. For example, // zh_TW for Traditional Chinese and zh_CN for Simplified // Chinese - but just zh for Chinese in general. First we look // for the full code, like zh_TW. If that doesn't exist, we // look for a code corresponding to the first two letters. // Note that if the language for a fullCode exists but we only // have a name for the short code, we will use the short code's // name but associate it with the full code. This allows someone // to drop in a new language and still get reasonable behavior. if (fullCode.Length() < 2) continue; if (localLanguageName[code] != wxT("")) { name = localLanguageName[code]; } if (localLanguageName[fullCode] != wxT("")) { name = localLanguageName[fullCode]; } if (TranslationExists(audacityPathList, fullCode)) { code = fullCode; } if (tempHash[code] != wxT("")) continue; if (TranslationExists(audacityPathList, code) || code==wxT("en")) { tempCodes.Add(code); tempNames.Add(name); tempHash[code] = name; /* for debugging */ wxLogDebug(wxT("code=%s name=%s fullCode=%s name=%s -> %s\n"), code.c_str(), localLanguageName[code].c_str(), fullCode.c_str(), localLanguageName[fullCode].c_str(), name.c_str()); } } // JKC: Adding language for simplified audacity. { wxString code; wxString name; code = wxT("en-simple"); name = wxT("Simplified"); if (TranslationExists(audacityPathList, code) ) { tempCodes.Add(code); tempNames.Add(name); tempHash[code] = name; /* for debugging printf(wxT("code=%s name=%s fullCode=%s name=%s -> %s\n"), code.c_str(), localLanguageName[code].c_str(), fullCode.c_str(), localLanguageName[fullCode].c_str(), name.c_str()); */ } } // Sort unsigned int j; for(j=0; j<tempNames.GetCount(); j++) reverseHash[tempNames[j]] = tempCodes[j]; tempNames.Sort(); for(j=0; j<tempNames.GetCount(); j++) { langNames.Add(tempNames[j]); langCodes.Add(reverseHash[tempNames[j]]); } }
void wxHandheldInstallCtrl::InsertUserDestinations( handheld_dest_array_type& handheld_dest_array ) { wxLogDebug( wxT( "Entering wxHandheldInstallCtrl::InsertUserDestinations()" ) ); if ( handheld_dest_array.IsEmpty() ) { return; } // Insert by rows, starting at index zero. Achieve by getting number // of items in listctrl. int row_to_insert; wxString ram_or_card_string; wxString is_usb_pause_string; wxArrayString row_cells_contents; wxArrayInt matching_row_numbers; // Insert them for ( size_t n = 0; n < handheld_dest_array.GetCount(); n++ ) { row_to_insert = m_usersListCtrl->GetItemCount(); // Convert our handheld_target_storage_mode to the string in the column if( handheld_dest_array[ n ]->handheld_target_storage_mode == plkrHANDHELD_TARGET_STORAGE_MODE_SD_CARD ) { ram_or_card_string = _( "SD Card" ); } else if( handheld_dest_array[ n ]->handheld_target_storage_mode == plkrHANDHELD_TARGET_STORAGE_MODE_MEMORY_STICK ) { ram_or_card_string = _( "M.Stick" ); } else if( handheld_dest_array[ n ]->handheld_target_storage_mode == plkrHANDHELD_TARGET_STORAGE_MODE_COMPACT_FLASH ) { ram_or_card_string = _( "CF Card" ); } else { // All others are RAM. ram_or_card_string = _( "RAM" ); } // Convert our is_usb_pause to the string in the column if( handheld_dest_array[ n ]->is_usb_pause == 1 ) { is_usb_pause_string = _( "Yes" ); } else { is_usb_pause_string = _( "No" ); } // Only insert it if that user/RAM combo doesn't doesn't already exists in the // Empty matches from last iteration matching_row_numbers.Empty(); row_cells_contents.Empty(); // Make the row cell contents to look for: // NOTE: these must be added in the order of the columns! row_cells_contents.Add( handheld_dest_array[ n ]->user_name ); row_cells_contents.Add( ram_or_card_string ); // The card directory column goes in here row_cells_contents.Add( is_usb_pause_string ); // Look to see if there is matching rows... m_usersListCtrl->find_matching_rows( row_cells_contents, &matching_row_numbers ); // ...and if there isn't any matches... if ( matching_row_numbers.IsEmpty() ) { // ..then insert row: m_usersListCtrl->InsertItem( row_to_insert, handheld_dest_array[ n ]->user_name, m_usersListCtrlImageId ); m_usersListCtrl->SetItem( row_to_insert, RAM_OR_CARD_COLUMN, ram_or_card_string ); // The 3rd column, DIRECTORY_ON_CARD_COLUMN, would go here. m_usersListCtrl->SetItem( row_to_insert, IS_USB_PAUSE_COLUMN, is_usb_pause_string ); } } // Clear arrays to free memory matching_row_numbers.Clear(); row_cells_contents.Clear(); wxLogDebug( wxT( "Finished wxHandheldInstallCtrl::InsertUserDestinations()" ) ); }
long wxExecute( const wxString& command, int flags, wxProcess *process ) { wxCHECK_MSG( !command.empty(), 0, wxT("can't exec empty command") ); wxLogDebug(wxString(wxT("Launching: ")) + command); #if wxUSE_THREADS // fork() doesn't mix well with POSIX threads: on many systems the program // deadlocks or crashes for some reason. Probably our code is buggy and // doesn't do something which must be done to allow this to work, but I // don't know what yet, so for now just warn the user (this is the least we // can do) about it wxASSERT_MSG( wxThread::IsMain(), _T("wxExecute() can be called only from the main thread") ); #endif // wxUSE_THREADS int argc = 0; wxChar *argv[WXEXECUTE_NARGS]; wxString argument; const wxChar *cptr = command.c_str(); wxChar quotechar = wxT('\0'); // is arg quoted? bool escaped = false; // split the command line in arguments do { argument=wxT(""); quotechar = wxT('\0'); // eat leading whitespace: while ( wxIsspace(*cptr) ) cptr++; if ( *cptr == wxT('\'') || *cptr == wxT('"') ) quotechar = *cptr++; do { if ( *cptr == wxT('\\') && ! escaped ) { escaped = true; cptr++; continue; } // all other characters: argument += *cptr++; escaped = false; // have we reached the end of the argument? if ( (*cptr == quotechar && ! escaped) || (quotechar == wxT('\0') && wxIsspace(*cptr)) || *cptr == wxT('\0') ) { wxASSERT_MSG( argc < WXEXECUTE_NARGS, wxT("too many arguments in wxExecute") ); argv[argc] = new wxChar[argument.length() + 1]; wxStrcpy(argv[argc], argument.c_str()); argc++; // if not at end of buffer, swallow last character: if(*cptr) cptr++; break; // done with this one, start over } } while(*cptr); } while(*cptr); argv[argc] = NULL; long lRc; #if defined(__DARWIN__) // wxMacExecute only executes app bundles. // It returns an error code if the target is not an app bundle, thus falling // through to the regular wxExecute for non app bundles. lRc = wxMacExecute(argv, flags, process); if( lRc != ((flags & wxEXEC_SYNC) ? -1 : 0)) return lRc; #endif // do execute the command lRc = wxExecute(argv, flags, process); // clean up argc = 0; while( argv[argc] ) delete [] argv[argc++]; return lRc; }
// ---------------------------------------------------------------------------- // wxHIDDevice::Create // // nClass is the HID Page such as // kHIDPage_GenericDesktop // nType is the HID Usage such as // kHIDUsage_GD_Joystick,kHIDUsage_GD_Mouse,kHIDUsage_GD_Keyboard // nDev is the device number to use // // ---------------------------------------------------------------------------- bool wxHIDDevice::Create (int nClass, int nType, int nDev) { //Create the mach port if(IOMasterPort(bootstrap_port, &m_pPort) != kIOReturnSuccess) { wxLogSysError(wxT("Could not create mach port")); return false; } //Dictionary that will hold first //the matching dictionary for determining which kind of devices we want, //then later some registry properties from an iterator (see below) // //The call to IOServiceMatching filters down the //the services we want to hid services (and also eats the //dictionary up for us (consumes one reference)) CFMutableDictionaryRef pDictionary = IOServiceMatching(kIOHIDDeviceKey); if(pDictionary == NULL) { wxLogSysError( wxT("IOServiceMatching(kIOHIDDeviceKey) failed") ); return false; } //Here we'll filter down the services to what we want if (nType != -1) { CFNumberRef pType = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &nType); CFDictionarySetValue(pDictionary, CFSTR(kIOHIDPrimaryUsageKey), pType); CFRelease(pType); } if (nClass != -1) { CFNumberRef pClass = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &nClass); CFDictionarySetValue(pDictionary, CFSTR(kIOHIDPrimaryUsagePageKey), pClass); CFRelease(pClass); } //Now get the matching services io_iterator_t pIterator; if( IOServiceGetMatchingServices(m_pPort, pDictionary, &pIterator) != kIOReturnSuccess ) { wxLogSysError(wxT("No Matching HID Services")); return false; } //Were there any devices matched? if(pIterator == 0) return false; // No devices found //Now we iterate through them io_object_t pObject; while ( (pObject = IOIteratorNext(pIterator)) != 0) { if(--nDev != 0) { IOObjectRelease(pObject); continue; } if ( IORegistryEntryCreateCFProperties ( pObject, &pDictionary, kCFAllocatorDefault, kNilOptions ) != KERN_SUCCESS ) { wxLogDebug(wxT("IORegistryEntryCreateCFProperties failed")); } // // Now we get the attributes of each "product" in the iterator // //Get [product] name CFStringRef cfsProduct = (CFStringRef) CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDProductKey)); m_szProductName = wxCFStringRef( wxCFRetain(cfsProduct) ).AsString(); //Get the Product ID Key CFNumberRef cfnProductId = (CFNumberRef) CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDProductIDKey)); if (cfnProductId) { CFNumberGetValue(cfnProductId, kCFNumberIntType, &m_nProductId); } //Get the Vendor ID Key CFNumberRef cfnVendorId = (CFNumberRef) CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDVendorIDKey)); if (cfnVendorId) { CFNumberGetValue(cfnVendorId, kCFNumberIntType, &m_nManufacturerId); } // // End attribute getting // //Create the interface (good grief - long function names!) SInt32 nScore; IOCFPlugInInterface** ppPlugin; if(IOCreatePlugInInterfaceForService(pObject, kIOHIDDeviceUserClientTypeID, kIOCFPlugInInterfaceID, &ppPlugin, &nScore) != kIOReturnSuccess) { wxLogSysError(wxT("Could not create HID Interface for product")); return false; } //Now, the final thing we can check before we fall back to asserts //(because the dtor only checks if the device is ok, so if anything //fails from now on the dtor will delete the device anyway, so we can't break from this). //Get the HID interface from the plugin to the mach port if((*ppPlugin)->QueryInterface(ppPlugin, CFUUIDGetUUIDBytes(kIOHIDDeviceInterfaceID), (void**) &m_ppDevice) != S_OK) { wxLogSysError(wxT("Could not get device interface from HID interface")); return false; } //release the plugin (*ppPlugin)->Release(ppPlugin); //open the HID interface... if ( (*m_ppDevice)->open(m_ppDevice, 0) != S_OK ) { wxLogDebug(wxT("HID device: open failed")); } // //Now the hard part - in order to scan things we need "cookies" // CFArrayRef cfaCookies = (CFArrayRef)CFDictionaryGetValue(pDictionary, CFSTR(kIOHIDElementKey)); BuildCookies(cfaCookies); //cleanup CFRelease(pDictionary); IOObjectRelease(pObject); //iterator cleanup IOObjectRelease(pIterator); return true; } //iterator cleanup IOObjectRelease(pIterator); return false; //no device }//end Create()
bool MyPicsApp::OnInit() { wxImage::AddHandler( new wxJPEGHandler ); wxImage::AddHandler( new wxICOHandler ); // extract the applications resources to files, so we can use them. // we could have just put all // the resources in the .zip file, but then how would i have // demostrated the other ExtractXXX functions? :) // extract all resources of same type (in this case imagess // pecified as type "image" in the .rc file),in one call, // u can specify any type you want, but if you // use a number, make shure its an unsigned int OVER 255. // Also note that the exCount param passed here is optional. int exCount=0; bool resOk = m_Resources.ExtractResources(wxT("image"), &exCount); if(resOk) { wxLogDebug(wxT("%d files extracted to %s using ExtractResources()"), exCount, m_Resources.GetResourceDir()); } // extract a single resource file "wxmswres.h" of type "txtfile" // note that the resource name sould be the same in the .rc file // as the desired extracted file name INCLUDING EXTENSION, same // goes for ExtractResources() resOk = resOk && m_Resources.ExtractResource(wxT("wxmswres.h"), wxT("txtfile")); if(resOk) { wxLogDebug(wxT("resource file wxmswres.h extracted to %s using ExtractResource()"), m_Resources.GetResourceDir()); } // extract resources contained in a zip file, in this case, the .mo // catalog files, compressed to reduce .exe size exCount=0; resOk = resOk && m_Resources.ExtractZipResources(wxT("langcats"), wxT("zipfile"), &exCount); if(resOk) { wxLogDebug(wxT("%d files extracted to %s using ExtractZipResources()"), exCount, m_Resources.GetResourceDir()); } // if the ExtractXXX functions returned true, the resources were // extracted successfully, but still you can check if some // resource is actually there using this function if(m_Resources.RcExtracted(wxT("wx_es.mo"))) wxLogDebug(wxT("guess what??, wx_ex.mo was extracted successfully")); if(!resOk) { // oops! something went wrong, we better quit here wxMessageBox(_("Failed to extract the app´s resources.\nTerminating app..."), _("Fatal Error"), wxOK | wxCENTRE | wxICON_ERROR); return false; } // ask user for application language DlgLang dlg(NULL); wxString langName = dlg.GetSelLanguage(); // now set the locale & load the app & standar wxWidgets catalogs // (previously extracted), but only if selected language was spanish, // since wxWidgets & strings in source code are in english // set lookup path to our resource dir first!! , or wxLocale // will NOT find the catalogs & fail! m_Locale.AddCatalogLookupPathPrefix(m_Resources.GetResourceDir()); bool iInitOk = false; bool cInitOk = false; int langId = langName==_("Spanish") ? wxLANGUAGE_SPANISH_MODERN : wxLANGUAGE_ENGLISH_US; iInitOk= m_Locale.Init(langId, wxLOCALE_CONV_ENCODING); if(!iInitOk) wxLogDebug(wxT("Failed to initialize locale!")); if(iInitOk && langId == wxLANGUAGE_SPANISH_MODERN) { cInitOk = m_Locale.AddCatalog(wxT("wx_es")); cInitOk = cInitOk && m_Locale.AddCatalog(wxT("mypics_es")); } if(!cInitOk) wxLogDebug(wxT("Failed to load one or more catalogs!")); // create the app´s main window (go look at MyFrame´s creation code) MyFrame* pFrame = new MyFrame(NULL); pFrame->Maximize(); pFrame->Show(); SetTopWindow(pFrame); return true; }
void SjPlayer::DoReceiveSignal(int signal, uintptr_t extraLong) { if( !m_impl->InitXine() ) { return; // error } if( signal == THREAD_PREPARE_NEXT ) { // find out the next url to play wxString newUrl; //long newQueueId = 0; long newQueuePos = m_queue.GetCurrPos(); // try to get next url from queue newQueuePos = m_queue.GetNextPos(SJ_PREVNEXT_REGARD_REPEAT); if( newQueuePos == -1 ) { // try to enqueue auto-play url g_mainFrame->m_autoCtrl.DoAutoPlayIfEnabled(false /*ignoreTimeouts*/); newQueuePos = m_queue.GetNextPos(SJ_PREVNEXT_REGARD_REPEAT); if( newQueuePos == -1 ) { // no chance, there is nothing more to play ... if( signal == THREAD_OUT_OF_DATA ) { Stop(); SendSignalToMainThread(IDMODMSG_PLAYER_STOPPED_BY_EOQ); } return; } } newUrl = m_queue.GetUrlByPos(newQueuePos); //newQueueId = m_queue.GetIdByPos(newQueuePos); // has the URL just failed? try again in the next message look wxLogDebug(wxT(" ... SjPlayer::ReceiveSignal(): new URL is \"%s\""), newUrl.c_str()); if( m_failedUrls.Index( newUrl ) != wxNOT_FOUND ) { wxLogDebug(wxT(" ... SjPlayer::ReceiveSignal(): the URL has failed before, starting over.")); m_queue.SetCurrPos(newQueuePos); SendSignalToMainThread(signal); // start over return; } // try to create the next stream if( m_impl->m_currStream ) { delete m_impl->m_currStream; m_impl->m_currStream = NULL; } m_impl->m_currStream = new SjXineStream(m_impl, newUrl); if( !m_impl->m_currStream->XinePlay() ) { wxLogDebug(wxT(" ... SjPlayer::ReceiveSignal(): cannot create the new stream.")); delete m_impl->m_currStream; m_impl->m_currStream = NULL; } // realize the new position in the UI m_queue.SetCurrPos(newQueuePos); SendSignalToMainThread(IDMODMSG_TRACK_ON_AIR_CHANGED); } }
wxString PCB_BASE_FRAME::SelectFootprint( EDA_DRAW_FRAME* aWindow, const wxString& aLibraryName, const wxString& aMask, const wxString& aKeyWord, FP_LIB_TABLE* aTable ) { static wxString oldName; // Save the name of the last module loaded. wxString fpname; wxString msg; wxArrayString libraries; std::vector< wxArrayString > rows; wxASSERT( aTable != NULL ); MList.ReadFootprintFiles( aTable, !aLibraryName ? NULL : &aLibraryName ); if( MList.GetErrorCount() ) { MList.DisplayErrors( this ); return wxEmptyString; } if( MList.GetCount() == 0 ) { wxString tmp; for( unsigned i = 0; i < libraries.GetCount(); i++ ) { tmp += libraries[i] + wxT( "\n" ); } msg.Printf( _( "No footprints could be read from library file(s):\n\n%s\nin any of " "the library search paths. Verify your system is configured properly " "so the footprint libraries can be found." ), GetChars( tmp ) ); DisplayError( aWindow, msg ); return wxEmptyString; } if( !aKeyWord.IsEmpty() ) // Create a list of modules found by keyword. { for( unsigned ii = 0; ii < MList.GetCount(); ii++ ) { if( KeyWordOk( aKeyWord, MList.GetItem( ii ).GetKeywords() ) ) { wxArrayString cols; cols.Add( MList.GetItem( ii ).GetFootprintName() ); cols.Add( MList.GetItem( ii ).GetNickname() ); rows.push_back( cols ); } } } else if( !aMask.IsEmpty() ) // Create a list of modules found by pattern { for( unsigned ii = 0; ii < MList.GetCount(); ii++ ) { const wxString& candidate = MList.GetItem( ii ).GetFootprintName(); if( WildCompareString( aMask, candidate, false ) ) { wxArrayString cols; cols.Add( MList.GetItem( ii ).GetFootprintName() ); cols.Add( MList.GetItem( ii ).GetNickname() ); rows.push_back( cols ); } } } else // Create the full list of modules { for( unsigned ii = 0; ii < MList.GetCount(); ii++ ) { wxArrayString cols; cols.Add( MList.GetItem( ii ).GetFootprintName() ); cols.Add( MList.GetItem( ii ).GetNickname() ); rows.push_back( cols ); } } if( !rows.empty() ) { wxArrayString headers; headers.Add( _( "Footprint" ) ); headers.Add( _( "Library" ) ); msg.Printf( _( "Footprints [%d items]" ), (int) rows.size() ); EDA_LIST_DIALOG dlg( aWindow, msg, headers, rows, oldName, DisplayCmpDoc ); if( dlg.ShowModal() == wxID_OK ) { fpname = dlg.GetTextSelection(); fpname = dlg.GetTextSelection( 1 ) + wxT( ":" ) + fpname; SkipNextLeftButtonReleaseEvent(); } else fpname.Empty(); } else { DisplayError( aWindow, _( "No footprint found." ) ); fpname.Empty(); } if( fpname != wxEmptyString ) oldName = fpname; wxLogDebug( wxT( "Footprint '%s' was selected." ), GetChars( fpname ) ); return fpname; }
MODULE* PCB_BASE_FRAME::LoadModuleFromLibrary( const wxString& aLibrary, FP_LIB_TABLE* aTable, bool aUseFootprintViewer, wxDC* aDC ) { MODULE* module = NULL; wxPoint curspos = GetCrossHairPosition(); wxString moduleName, keys; wxString libName = aLibrary; bool allowWildSeach = true; static wxArrayString HistoryList; static wxString lastComponentName; // Ask for a component name or key words DIALOG_GET_COMPONENT dlg( this, HistoryList, _( "Load Footprint" ), aUseFootprintViewer ); dlg.SetComponentName( lastComponentName ); if( dlg.ShowModal() == wxID_CANCEL ) return NULL; if( dlg.m_GetExtraFunction ) { // SelectFootprintFromLibBrowser() returns the "full" footprint name, i.e. // <lib_name>/<footprint name> or FPID format "lib_name:fp_name:rev#" moduleName = SelectFootprintFromLibBrowser(); } else { moduleName = dlg.GetComponentName(); } if( moduleName.IsEmpty() ) // Cancel command { m_canvas->MoveCursorToCrossHair(); return NULL; } if( dlg.IsKeyword() ) // Selection by keywords { allowWildSeach = false; keys = moduleName; moduleName = SelectFootprint( this, libName, wxEmptyString, keys, aTable ); if( moduleName.IsEmpty() ) // Cancel command { m_canvas->MoveCursorToCrossHair(); return NULL; } } else if( moduleName.Contains( wxT( "?" ) ) || moduleName.Contains( wxT( "*" ) ) ) // Selection wild card { allowWildSeach = false; moduleName = SelectFootprint( this, libName, moduleName, wxEmptyString, aTable ); if( moduleName.IsEmpty() ) { m_canvas->MoveCursorToCrossHair(); return NULL; // Cancel command. } } FPID fpid; wxCHECK_MSG( fpid.Parse( moduleName ) < 0, NULL, wxString::Format( wxT( "Could not parse FPID string '%s'." ), GetChars( moduleName ) ) ); try { module = loadFootprint( fpid ); } catch( const IO_ERROR& ioe ) { wxLogDebug( wxT( "An error occurred attemping to load footprint '%s'.\n\nError: %s" ), fpid.Format().c_str(), GetChars( ioe.errorText ) ); } if( !module && allowWildSeach ) // Search with wild card { allowWildSeach = false; wxString wildname = wxChar( '*' ) + moduleName + wxChar( '*' ); moduleName = wildname; moduleName = SelectFootprint( this, libName, moduleName, wxEmptyString, aTable ); if( moduleName.IsEmpty() ) { m_canvas->MoveCursorToCrossHair(); return NULL; // Cancel command. } else { FPID fpid; wxCHECK_MSG( fpid.Parse( moduleName ) < 0, NULL, wxString::Format( wxT( "Could not parse FPID string '%s'." ), GetChars( moduleName ) ) ); try { module = loadFootprint( fpid ); } catch( const IO_ERROR& ioe ) { wxLogDebug( wxT( "An error occurred attemping to load footprint '%s'.\n\nError: %s" ), fpid.Format().c_str(), GetChars( ioe.errorText ) ); } } } SetCrossHairPosition( curspos ); m_canvas->MoveCursorToCrossHair(); if( module ) { GetBoard()->Add( module, ADD_APPEND ); lastComponentName = moduleName; AddHistoryComponentName( HistoryList, moduleName ); module->SetFlags( IS_NEW ); module->SetLink( 0 ); if( IsGalCanvasActive() ) module->SetPosition( wxPoint( 0, 0 ) ); // cursor in GAL may not be initialized at the moment else module->SetPosition( curspos ); module->SetTimeStamp( GetNewTimeStamp() ); GetBoard()->m_Status_Pcb = 0; // Put it on FRONT layer, // (Can be stored flipped if the lib is an archive built from a board) if( module->IsFlipped() ) module->Flip( module->GetPosition() ); // Place it in orientation 0, // even if it is not saved with orientation 0 in lib // (Can happen if the lib is an archive built from a board) Rotate_Module( NULL, module, 0, false ); RecalculateAllTracksNetcode(); if( aDC ) module->Draw( m_canvas, aDC, GR_OR ); } return module; }
void StateGraphViewerPanel::OnContextMenu(wxContextMenuEvent &Ev) { if (!MouseOver) return; UErrorCode Status = U_ZERO_ERROR; auto const TextTable = seec::getResource("TraceViewer", getLocale(), Status, "StateGraphViewer"); if (U_FAILURE(Status)) { wxLogDebug("Couldn't get StateGraphViewer resources."); return; } auto const TheNode = MouseOver.get(); if (auto const DV = llvm::dyn_cast<DisplayableValue>(TheNode)) { auto const ValuePtr = &(DV->getValue()); wxMenu CM{}; addValueNavigation(*this, CurrentAccess, CM, *ValuePtr, *CurrentProcess, Recording); // Allow the user to select the Value's layout engine. std::unique_lock<std::mutex> LockLayoutHandler(LayoutHandlerMutex); auto const Engines = LayoutHandler->listLayoutEnginesSupporting(*ValuePtr); LockLayoutHandler.unlock(); if (Engines.size() > 1) { auto SM = seec::makeUnique<wxMenu>(); for (auto const E : Engines) { auto const LazyName = E->getName(); if (!LazyName) continue; UErrorCode Status = U_ZERO_ERROR; auto const Name = LazyName->get(Status, getLocale()); if (U_FAILURE(Status)) continue; std::string UTF8Name; Name.toUTF8String(UTF8Name); auto const EngineID = reinterpret_cast<uintptr_t>(E); BindMenuItem( SM->Append(wxID_ANY, wxString{UTF8Name}), [=] (wxEvent &Ev) -> void { { std::lock_guard<std::mutex> LLH(this->LayoutHandlerMutex); this->LayoutHandler->setLayoutEngine(*ValuePtr, EngineID); } this->renderGraph(); }); } CM.AppendSubMenu(SM.release(), seec::getwxStringExOrEmpty(TextTable, "CMValueDisplayAs")); } PopupMenu(&CM); } else if (auto const DD = llvm::dyn_cast<DisplayableDereference>(TheNode)) { auto const ValOfPtr = &(DD->getPointer()); wxMenu CM{}; BindMenuItem( CM.Append(wxID_ANY, seec::getwxStringExOrEmpty(TextTable, "CMDereferenceUse")), [=] (wxEvent &Ev) -> void { { std::lock_guard<std::mutex> LLH(this->LayoutHandlerMutex); this->LayoutHandler->setAreaReference(*ValOfPtr); } this->renderGraph(); }); PopupMenu(&CM); } else if (auto const DF = llvm::dyn_cast<DisplayableFunctionState>(TheNode)) { wxMenu CM{}; auto const FnPtr = &(DF->getFunctionState()); BindMenuItem( CM.Append(wxID_ANY, seec::getwxStringExOrEmpty(TextTable, "CMFunctionRewindEntry")), [=] (wxEvent &Ev) -> void { raiseMovementEvent(*this, this->CurrentAccess, [=] (seec::cm::ProcessState &State) { return seec::cm::moveToFunctionEntry(*FnPtr); }); }); BindMenuItem( CM.Append(wxID_ANY, seec::getwxStringExOrEmpty(TextTable, "CMFunctionForwardExit")), [=] (wxEvent &Ev) -> void { raiseMovementEvent(*this, this->CurrentAccess, [=] (seec::cm::ProcessState &State) { return seec::cm::moveToFunctionFinished(*FnPtr); }); }); PopupMenu(&CM); } else if (auto const DA = llvm::dyn_cast<DisplayableReferencedArea>(TheNode)) { auto const Area = seec::MemoryArea(DA->getAreaStart(), DA->getAreaEnd()); auto const ValOfPtr = &(DA->getPointer()); wxMenu CM{}; // Allow the user to select the Area's layout engine. std::unique_lock<std::mutex> LLH(LayoutHandlerMutex); auto const Engines = LayoutHandler->listLayoutEnginesSupporting(Area, *ValOfPtr); LLH.unlock(); if (Engines.size() > 1) { auto SM = seec::makeUnique<wxMenu>(); for (auto const E : Engines) { auto const LazyName = E->getName(); if (!LazyName) continue; UErrorCode Status = U_ZERO_ERROR; auto const Name = LazyName->get(Status, getLocale()); if (U_FAILURE(Status)) continue; std::string UTF8Name; Name.toUTF8String(UTF8Name); auto const EngineID = reinterpret_cast<uintptr_t>(E); BindMenuItem( SM->Append(wxID_ANY, wxString{UTF8Name}), [=] (wxEvent &Ev) -> void { { std::lock_guard<std::mutex> LLH(this->LayoutHandlerMutex); this->LayoutHandler->setLayoutEngine(Area, *ValOfPtr, EngineID); } this->renderGraph(); }); } CM.AppendSubMenu(SM.release(), seec::getwxStringExOrEmpty(TextTable, "CMAreaDisplayAs")); } PopupMenu(&CM); } else { wxLogDebug("Unknown Displayable!"); } }
bool wxGISRasterDataset::Open(void) { if(m_bIsOpened) return true; wxCriticalSectionLocker locker(m_CritSect); m_poDataset = (GDALDataset *) GDALOpen( wgWX2MB(m_sPath.c_str()), GA_ReadOnly ); if( m_poDataset == NULL ) return false; int nXSize = m_poDataset->GetRasterXSize(); int nYSize = m_poDataset->GetRasterYSize(); bool bHasOverviews = false; char** papszFileList = m_poDataset->GetFileList(); if( CSLCount(papszFileList) == 0 ) { wxLogDebug(wxT( "Files: none associated" )); } else { wxLogDebug(wxT("Files: %s"), wgMB2WX(papszFileList[0]) ); for(int i = 1; papszFileList[i] != NULL; i++ ) { wxString sFileName = wgMB2WX(papszFileList[i]); if(sFileName.Find(wxT(".rrd")) != wxNOT_FOUND || sFileName.Find(wxT(".ovr")) != wxNOT_FOUND) bHasOverviews = true; wxLogDebug( wxT(" %s"), sFileName.c_str() ); } } CSLDestroy( papszFileList ); CPLSetConfigOption( "USE_RRD", "YES" ); CPLSetConfigOption( "HFA_USE_RRD", "YES" ); CPLSetConfigOption( "COMPRESS_OVERVIEW", "LZW" ); bool bAskCreateOvr = false; if(!bHasOverviews && bAskCreateOvr) { int anOverviewList[5] = { 4, 8, 16, 32, 64 }; CPLErr err = m_poDataset->BuildOverviews( "CUBIC", 5, anOverviewList, 0, NULL, GDALDummyProgress, NULL ); //"NEAREST", "GAUSS", "CUBIC", "AVERAGE", "MODE", "AVERAGE_MAGPHASE" or "NONE" } //GDALDriver* pDrv = m_poDataset->GetDriver(); //const char* desc = pDrv->GetDescription(); //wxLogDebug( wxT("Driver: %s/%s"), wgMB2WX(GDALGetDriverShortName( pDrv )), wgMB2WX(GDALGetDriverLongName( pDrv )) ); //char** papszMetadata = m_poDataset->GetMetadata(); // if( CSLCount(papszMetadata) > 0 ) // { // wxLogDebug( wxT( "Metadata:" )); // for(int i = 0; papszMetadata[i] != NULL; i++ ) // { // wxLogDebug( wxT( " %s"), wgMB2WX(papszMetadata[i]) ); // } // } ///* -------------------------------------------------------------------- */ ///* Report "IMAGE_STRUCTURE" metadata. */ ///* -------------------------------------------------------------------- */ // papszMetadata = m_poDataset->GetMetadata("IMAGE_STRUCTURE"); // if( CSLCount(papszMetadata) > 0 ) // { // wxLogDebug( wxT( "Image Structure Metadata:" )); // for(int i = 0; papszMetadata[i] != NULL; i++ ) // { // wxLogDebug( wxT( " %s"), wgMB2WX(papszMetadata[i]) ); // } // } ///* -------------------------------------------------------------------- */ ///* Report subdatasets. */ ///* -------------------------------------------------------------------- */ // papszMetadata = m_poDataset->GetMetadata("SUBDATASETS"); // if( CSLCount(papszMetadata) > 0 ) // { // wxLogDebug( wxT( "Subdatasets:" )); // for(int i = 0; papszMetadata[i] != NULL; i++ ) // { // wxLogDebug( wxT( " %s"), wgMB2WX(papszMetadata[i]) ); // } // } ///* -------------------------------------------------------------------- */ ///* Report geolocation. */ ///* -------------------------------------------------------------------- */ // papszMetadata = m_poDataset->GetMetadata("GEOLOCATION"); // if( CSLCount(papszMetadata) > 0 ) // { // wxLogDebug( wxT( "Geolocation:" )); // for(int i = 0; papszMetadata[i] != NULL; i++ ) // { // wxLogDebug( wxT( " %s"), wgMB2WX(papszMetadata[i]) ); // } // } ///* -------------------------------------------------------------------- */ ///* Report RPCs */ ///* -------------------------------------------------------------------- */ // papszMetadata = m_poDataset->GetMetadata("RPC"); // if( CSLCount(papszMetadata) > 0 ) // { // wxLogDebug( wxT( "RPC Metadata:" )); // for(int i = 0; papszMetadata[i] != NULL; i++ ) // { // wxLogDebug( wxT( " %s"), wgMB2WX(papszMetadata[i]) ); // } // } //for(int nBand = 0; nBand < m_poDataset->GetRasterCount(); nBand++ ) // { // double dfMin, dfMax, adfCMinMax[2], dfNoData; // int bGotMin, bGotMax, bGotNodata, bSuccess; // int nBlockXSize, nBlockYSize, nMaskFlags; // double dfMean, dfStdDev; // GDALColorTable* hTable; // CPLErr eErr; // GDALRasterBand* pBand = m_poDataset->GetRasterBand(nBand + 1); // //if( bSample ) // //{ // // float afSample[10000]; // // int nCount; // // nCount = GDALGetRandomRasterSample( hBand, 10000, afSample ); // // printf( "Got %d samples.\n", nCount ); // //} // // pBand->GetBlockSize(&nBlockXSize, &nBlockYSize); // wxLogDebug( wxT( "Band %d Block=%dx%d Type=%s, ColorInterp=%s"), nBand + 1, nBlockXSize, nBlockYSize, wgMB2WX(GDALGetDataTypeName(pBand->GetRasterDataType())), wgMB2WX(GDALGetColorInterpretationName(pBand->GetColorInterpretation()))); // wxString sDescription = wgMB2WX(pBand->GetDescription()); // wxLogDebug( wxT( " Description = %s"), sDescription.c_str()); // dfMin = pBand->GetMinimum(&bGotMin); // dfMax = pBand->GetMaximum(&bGotMax); // if( bGotMin || bGotMax ) // { // if( bGotMin ) // wxLogDebug( wxT( "Min=%.3f "), dfMin ); // if( bGotMax ) // wxLogDebug( wxT( "Max=%.3f "), dfMax ); // // pBand->ComputeRasterMinMax(FALSE, adfCMinMax ); // wxLogDebug( wxT(" Computed Min/Max=%.3f,%.3f"), adfCMinMax[0], adfCMinMax[1] ); // } // eErr = pBand->GetStatistics(TRUE, TRUE, &dfMin, &dfMax, &dfMean, &dfStdDev ); // if( eErr == CE_None ) // { // wxLogDebug( wxT(" Minimum=%.3f, Maximum=%.3f, Mean=%.3f, StdDev=%.3f"), dfMin, dfMax, dfMean, dfStdDev ); // } // //if( bReportHistograms ) // //{ // // int nBucketCount, *panHistogram = NULL; // // eErr = GDALGetDefaultHistogram( hBand, &dfMin, &dfMax, // // &nBucketCount, &panHistogram, // // TRUE, GDALTermProgress, NULL ); // // if( eErr == CE_None ) // // { // // int iBucket; // // printf( " %d buckets from %g to %g:\n ", // // nBucketCount, dfMin, dfMax ); // // for( iBucket = 0; iBucket < nBucketCount; iBucket++ ) // // printf( "%d ", panHistogram[iBucket] ); // // printf( "\n" ); // // CPLFree( panHistogram ); // // } // //} // //wxLogDebug( wxT(" Checksum=%d"), GDALChecksumImage(pBand, 0, 0, nXSize, nYSize)); // dfNoData = pBand->GetNoDataValue(&bGotNodata ); // if( bGotNodata ) // { // wxLogDebug( wxT(" NoData Value=%.18g"), dfNoData ); // } // if( pBand->GetOverviewCount() > 0 ) // { // wxString sOut(wxT(" Overviews: " )); // for(int iOverview = 0; iOverview < pBand->GetOverviewCount(); iOverview++ ) // { // const char *pszResampling = NULL; // if( iOverview != 0 ) // sOut += wxT( ", " ); // GDALRasterBand* pOverview = pBand->GetOverview( iOverview ); // sOut += wxString::Format(wxT("%dx%d"), pOverview->GetXSize(), pOverview->GetYSize()); // pszResampling = pOverview->GetMetadataItem("RESAMPLING", "" ); // if( pszResampling != NULL && EQUALN(pszResampling, "AVERAGE_BIT2", 12) ) // sOut += wxT( "*" ); // } // wxLogDebug(sOut); // // sOut = wxT( " Overviews checksum: " ); // // for(int iOverview = 0; iOverview < pBand->GetOverviewCount(); iOverview++ ) // //{ // // if( iOverview != 0 ) // // sOut += wxT( ", " ); // // GDALRasterBand* pOverview = pBand->GetOverview( iOverview ); // // sOut += GDALChecksumImage(pOverview, 0, 0, pOverview->GetXSize(), pOverview->GetYSize()); // // } // // wxLogDebug(sOut); // } // if( pBand->HasArbitraryOverviews() ) // { // wxLogDebug( wxT(" Overviews: arbitrary" )); // } // // nMaskFlags = pBand->GetMaskFlags(); // if( (nMaskFlags & (GMF_NODATA|GMF_ALL_VALID)) == 0 ) // { // GDALRasterBand* pMaskBand = pBand->GetMaskBand() ; // wxLogDebug( wxT(" Mask Flags: " )); // if( nMaskFlags & GMF_PER_DATASET ) // wxLogDebug( wxT("PER_DATASET " )); // if( nMaskFlags & GMF_ALPHA ) // wxLogDebug( wxT("ALPHA " )); // if( nMaskFlags & GMF_NODATA ) // wxLogDebug( wxT("NODATA " )); // if( nMaskFlags & GMF_ALL_VALID ) // wxLogDebug( wxT("ALL_VALID " )); // if( pMaskBand != NULL && pMaskBand->GetOverviewCount() > 0 ) // { // int iOverview; // wxLogDebug( wxT(" Overviews of mask band: " )); // for( int nOverview = 0; nOverview < pMaskBand->GetOverviewCount(); nOverview++ ) // { // GDALRasterBand* pOverview; // if( nOverview != 0 ) // wxLogDebug( wxT(", " )); // pOverview = pMaskBand->GetOverview( nOverview ); // wxLogDebug( wxT("%dx%d"), pOverview->GetXSize(), pOverview->GetYSize()); // } // } // } // if( strlen(pBand->GetUnitType()) > 0 ) // { // wxLogDebug( wxT(" Unit Type: %s"),wgMB2WX( pBand->GetUnitType()) ); // } // char **papszCategories = pBand->GetCategoryNames(); // if( papszCategories != NULL ) // { // int i; // wxLogDebug( wxT(" Categories:" )); // for( i = 0; papszCategories[i] != NULL; i++ ) // wxLogDebug( wxT(" %3d: %s"), i, wgMB2WX(papszCategories[i]) ); // } // if( pBand->GetScale( &bSuccess ) != 1.0 || pBand->GetOffset( &bSuccess ) != 0.0 ) // wxLogDebug( wxT(" Offset: %.15g, Scale:%.15g"), pBand->GetOffset( &bSuccess ), pBand->GetScale( &bSuccess ) ); // papszMetadata = pBand->GetMetadata(); // if( CSLCount(papszMetadata) > 0 ) // { // wxLogDebug( wxT(" Metadata:" )); // for( int i = 0; papszMetadata[i] != NULL; i++ ) // { // wxLogDebug( wxT(" %s"), wgMB2WX(papszMetadata[i]) ); // } // } // papszMetadata = pBand->GetMetadata( "IMAGE_STRUCTURE" ); // if( CSLCount(papszMetadata) > 0 ) // { // wxLogDebug( wxT(" Image Structure Metadata:" )); // for( int i = 0; papszMetadata[i] != NULL; i++ ) // { // wxLogDebug( wxT(" %s"), wgMB2WX(papszMetadata[i])); // } // } // if( pBand->GetColorInterpretation() == GCI_PaletteIndex && (hTable = pBand->GetColorTable()) != NULL ) // { // int i; // wxLogDebug( wxT(" Color Table (%s with %d entries)"), wgMB2WX(GDALGetPaletteInterpretationName(hTable->GetPaletteInterpretation())), hTable->GetColorEntryCount() ); // for( i = 0; i < hTable->GetColorEntryCount(); i++ ) // { // GDALColorEntry sEntry; // hTable->GetColorEntryAsRGB(i, &sEntry ); // wxLogDebug( wxT(" %3d: %d,%d,%d,%d"), i, sEntry.c1, sEntry.c2, sEntry.c3, sEntry.c4 ); // } // } // if( pBand->GetDefaultRAT() != NULL ) // { // const GDALRasterAttributeTable* pRAT = (const GDALRasterAttributeTable*)pBand->GetDefaultRAT(); // GDALRasterAttributeTable* pRATn = (GDALRasterAttributeTable*)pRAT; // pRATn->DumpReadable(); // } //} //CPLCleanupTLS(); m_psExtent = new OGREnvelope(); double adfGeoTransform[6]; if(m_poDataset->GetGeoTransform( adfGeoTransform ) != CE_Fatal ) { double inX[4]; double inY[4]; inX[0] = 0; inY[0] = 0; inX[1] = nXSize; inY[1] = 0; inX[2] = nXSize; inY[2] = nYSize; inX[3] = 0; inY[3] = nYSize; m_psExtent->MaxX = 0; m_psExtent->MaxY = 0; m_psExtent->MinX = 1000000000; m_psExtent->MinY = 1000000000; for(int i = 0; i < 4; i++) { double rX, rY; GDALApplyGeoTransform( adfGeoTransform, inX[i], inY[i], &rX, &rY ); if(m_psExtent->MaxX < rX) m_psExtent->MaxX = rX; if(m_psExtent->MinX > rX) m_psExtent->MinX = rX; if(m_psExtent->MaxY < rY) m_psExtent->MaxY = rY; if(m_psExtent->MinY > rY) m_psExtent->MinY = rY; } } else { wxDELETE(m_psExtent); m_psExtent = NULL; } // if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) // { // printf( "Origin = (%.6f,%.6f)\n", // adfGeoTransform[0], adfGeoTransform[3] ); // // printf( "Pixel Size = (%.6f,%.6f)\n", // adfGeoTransform[1], adfGeoTransform[5] ); // } m_bIsOpened = true; return true; }
void DevicePrefs::OnHost(wxCommandEvent & e) { // Bail if we have no hosts if (mHostNames.size() < 1) return; // Find the index for the host API selected int index = -1; wxString apiName = mHostNames[mHost->GetCurrentSelection()]; int nHosts = Pa_GetHostApiCount(); for (int i = 0; i < nHosts; ++i) { wxString name(Pa_GetHostApiInfo(i)->name, wxConvLocal); if (name == apiName) { index = i; break; } } // We should always find the host! if (index < 0) { wxLogDebug(wxT("DevicePrefs::OnHost(): API index not found")); return; } int nDevices = Pa_GetDeviceCount(); if (nDevices == 0) { mHost->Clear(); mHost->Append(_("No audio interfaces"), (void *) NULL); mHost->SetSelection(0); } const std::vector<DeviceSourceMap> &inMaps = DeviceManager::Instance()->GetInputDeviceMaps(); const std::vector<DeviceSourceMap> &outMaps = DeviceManager::Instance()->GetOutputDeviceMaps(); wxArrayString playnames; wxArrayString recordnames; size_t i; int devindex; /* temp variable to hold the numeric ID of each device in turn */ wxString device; wxString recDevice; recDevice = mRecordDevice; if (this->mRecordSource != wxT("")) recDevice += wxString(": ", wxConvLocal) + mRecordSource; mRecord->Clear(); for (i = 0; i < inMaps.size(); i++) { if (index == inMaps[i].hostIndex) { device = MakeDeviceSourceString(&inMaps[i]); devindex = mRecord->Append(device); // We need to const cast here because SetClientData is a wx function // It is okay beause the original variable is non-const. mRecord->SetClientData(devindex, const_cast<DeviceSourceMap *>(&inMaps[i])); if (device == recDevice) { /* if this is the default device, select it */ mRecord->SetSelection(devindex); } } } mPlay->Clear(); for (i = 0; i < outMaps.size(); i++) { if (index == outMaps[i].hostIndex) { device = MakeDeviceSourceString(&outMaps[i]); devindex = mPlay->Append(device); mPlay->SetClientData(devindex, const_cast<DeviceSourceMap *>(&outMaps[i])); if (device == mPlayDevice) { /* if this is the default device, select it */ mPlay->SetSelection(devindex); } } } /* deal with not having any devices at all */ if (mPlay->GetCount() == 0) { playnames.Add(_("No devices found")); mPlay->Append(playnames[0], (void *) NULL); mPlay->SetSelection(0); } if (mRecord->GetCount() == 0) { recordnames.Add(_("No devices found")); mRecord->Append(recordnames[0], (void *) NULL); mRecord->SetSelection(0); } /* what if we have no device selected? we should choose the default on * this API, as defined by PortAudio. We then fall back to using 0 only if * that fails */ if (mPlay->GetCount() && mPlay->GetSelection() == wxNOT_FOUND) { DeviceSourceMap *defaultMap = DeviceManager::Instance()->GetDefaultOutputDevice(index); if (defaultMap) mPlay->SetStringSelection(MakeDeviceSourceString(defaultMap)); if (mPlay->GetSelection() == wxNOT_FOUND) { mPlay->SetSelection(0); } } if (mRecord->GetCount() && mRecord->GetSelection() == wxNOT_FOUND) { DeviceSourceMap *defaultMap = DeviceManager::Instance()->GetDefaultInputDevice(index); if (defaultMap) mRecord->SetStringSelection(MakeDeviceSourceString(defaultMap)); if (mPlay->GetSelection() == wxNOT_FOUND) { mPlay->SetSelection(0); } } ShuttleGui S(this, eIsCreating); S.SetSizeHints(mPlay, mPlay->GetStrings()); S.SetSizeHints(mRecord, mRecord->GetStrings()); OnDevice(e); }
void wxMessageDialog::ReplaceStaticWithEdit() { // check if the message box fits the display int nDisplay = wxDisplay::GetFromWindow(this); if ( nDisplay == wxNOT_FOUND ) nDisplay = 0; const wxRect rectDisplay = wxDisplay(nDisplay).GetClientArea(); if ( rectDisplay.Contains(GetRect()) ) { // nothing to do return; } // find the static control to replace: normally there are two of them, the // icon and the text itself so search for all of them and ignore the icon // ones HWND hwndStatic = ::FindWindowEx(GetHwnd(), NULL, wxT("STATIC"), NULL); if ( ::GetWindowLong(hwndStatic, GWL_STYLE) & SS_ICON ) hwndStatic = ::FindWindowEx(GetHwnd(), hwndStatic, wxT("STATIC"), NULL); if ( !hwndStatic ) { wxLogDebug("Failed to find the static text control in message box."); return; } // set the right font for GetCharHeight() call below wxWindowBase::SetFont(GetMessageFont()); // put the new edit control at the same place RECT rc = wxGetWindowRect(hwndStatic); ScreenRectToClient(GetHwnd(), rc); // but make it less tall so that the message box fits on the screen: we try // to make the message box take no more than 7/8 of the screen to leave // some space above and below it const int hText = (7*rectDisplay.height)/8 - ( 2*::GetSystemMetrics(SM_CYFIXEDFRAME) + ::GetSystemMetrics(SM_CYCAPTION) + 5*GetCharHeight() // buttons + margins ); const int dh = (rc.bottom - rc.top) - hText; // vertical space we save rc.bottom -= dh; // and it also must be wider as it needs a vertical scrollbar (in order // to preserve the word wrap, otherwise the number of lines would change // and we want the control to look as similar as possible to the original) // // NB: you would have thought that 2*SM_CXEDGE would be enough but it // isn't, somehow, and the text control breaks lines differently from // the static one so fudge by adding some extra space const int dw = ::GetSystemMetrics(SM_CXVSCROLL) + 4*::GetSystemMetrics(SM_CXEDGE); rc.right += dw; // chop of the trailing new line(s) from the message box text, they are // ignored by the static control but result in extra lines and hence extra // scrollbar position in the edit one wxString text(wxGetWindowText(hwndStatic)); for ( wxString::reverse_iterator i = text.rbegin(); i != text.rend(); ++i ) { if ( *i != '\n' ) { // found last non-newline char, remove everything after it and stop text.erase(i.base() + 1, text.end()); break; } } // do create the new control HWND hwndEdit = ::CreateWindow ( wxT("EDIT"), wxTextBuffer::Translate(text).wx_str(), WS_CHILD | WS_VSCROLL | WS_VISIBLE | ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, GetHwnd(), NULL, wxGetInstance(), NULL ); if ( !hwndEdit ) { wxLogDebug("Creation of replacement edit control failed in message box"); return; } // copy the font from the original control LRESULT hfont = ::SendMessage(hwndStatic, WM_GETFONT, 0, 0); ::SendMessage(hwndEdit, WM_SETFONT, hfont, 0); // and get rid of it ::DestroyWindow(hwndStatic); // shrink and centre the message box vertically and widen it box to account // for the extra scrollbar RECT rcBox = wxGetWindowRect(GetHwnd()); const int hMsgBox = rcBox.bottom - rcBox.top - dh; rcBox.top = (rectDisplay.height - hMsgBox)/2; rcBox.bottom = rcBox.top + hMsgBox + (rectDisplay.height - hMsgBox)%2; rcBox.left -= dw/2; rcBox.right += dw - dw/2; SetWindowRect(GetHwnd(), rcBox); // and adjust all the buttons positions for ( unsigned n = 0; n < WXSIZEOF(ms_buttons); n++ ) { const HWND hwndBtn = ::GetDlgItem(GetHwnd(), ms_buttons[n].id); if ( !hwndBtn ) continue; // it's ok, not all buttons are always present RECT rc = wxGetWindowRect(hwndBtn); rc.top -= dh; rc.bottom -= dh; rc.left += dw/2; rc.right += dw/2; MoveWindowToScreenRect(hwndBtn, rc); } }
void ConvertViewCtrlToTrackData(const wxListCtrl &listctrl, const std::map< wxString, long > &mapping, std::vector<lfmt::TrackData> &tracklist, wxDateTime offset) { auto row_count = listctrl.GetItemCount(); if (row_count < 1) return; // grab column indices from string-long-map which we have just for purpose of dynamic indices (ie. changing column order is easy) auto idx_artist = mapping.find("Artist")->second; auto idx_tname = mapping.find("Trackname")->second; auto idx_album = mapping.find("Album")->second; auto idx_time = mapping.find("Time")->second; wxDateTime last_time = offset; // last track on the list is the most recentry track that was listened to; // moving up the list successive tracks will get earlier times for (int row = row_count-1; row >= 0; --row) { lfmt::TrackData td; // is there a better way of getting the info out of the listviewctrl? // it's questionable if I would have gotten it without the wxforum :( wxListItem item; item.SetId(row); item.SetMask(wxLIST_MASK_TEXT); // "unrolled loop" for all columns item.SetColumn(idx_artist); listctrl.GetItem(item); td.artist = item.GetText(); item.SetColumn(idx_tname); listctrl.GetItem(item); td.trackname = item.GetText(); item.SetColumn(idx_album); listctrl.GetItem(item); td.album = item.GetText(); td.timestamp = last_time.GetTicks(); // set time *before* calculating the descendant item.SetColumn(idx_time); listctrl.GetItem(item); { // now calculate 'last_time' offset according to playtime of the current track // defaults to 3 minutes if we don't know the track's length wxArrayString time_str = wxStringTokenize(item.GetText(), ":"); long minutes, seconds; bool success = true; success &= time_str[0].ToLong(&minutes); success &= time_str[1].ToLong(&seconds); if (success) last_time -= wxTimeSpan(0, minutes, seconds); else { wxLogWarning("Could not parse timespan " + item.GetText() + ". Assuming track length of 3 minutes."); last_time -= wxTimeSpan(0, 3, 0); } } tracklist.push_back(td); wxLogDebug("Converted track " + td.ToString() + " from row %d.", row); } }
void wxStackWalker::WalkFrom(const CONTEXT *pCtx, size_t skip) { if ( !wxDbgHelpDLL::Init() ) { // don't log a user-visible error message here because the stack trace // is only needed for debugging/diagnostics anyhow and we shouldn't // confuse the user by complaining that we couldn't generate it wxLogDebug(_T("Failed to get stack backtrace: %s"), wxDbgHelpDLL::GetErrorMessage().c_str()); return; } // according to MSDN, the first parameter should be just a unique value and // not process handle (although the parameter is prototyped as "HANDLE // hProcess") and actually it advises to use the process id and not handle // for Win9x, but then we need to use the same value in StackWalk() call // below which should be a real handle... so this is what we use const HANDLE hProcess = ::GetCurrentProcess(); if ( !wxDbgHelpDLL::SymInitialize ( hProcess, NULL, // use default symbol search path TRUE // load symbols for all loaded modules ) ) { wxDbgHelpDLL::LogError(_T("SymInitialize")); return; } CONTEXT ctx = *pCtx; // will be modified by StackWalk() DWORD dwMachineType; // initialize the initial frame: currently we can do it for x86 only STACKFRAME sf; wxZeroMemory(sf); #ifdef _M_IX86 sf.AddrPC.Offset = ctx.Eip; sf.AddrPC.Mode = AddrModeFlat; sf.AddrStack.Offset = ctx.Esp; sf.AddrStack.Mode = AddrModeFlat; sf.AddrFrame.Offset = ctx.Ebp; sf.AddrFrame.Mode = AddrModeFlat; dwMachineType = IMAGE_FILE_MACHINE_I386; #else #error "Need to initialize STACKFRAME on non x86" #endif // _M_IX86 // iterate over all stack frames (but stop after 200 to avoid entering // infinite loop if the stack is corrupted) for ( size_t nLevel = 0; nLevel < 200; nLevel++ ) { // get the next stack frame if ( !wxDbgHelpDLL::StackWalk ( dwMachineType, hProcess, ::GetCurrentThread(), &sf, &ctx, NULL, // read memory function (default) wxDbgHelpDLL::SymFunctionTableAccess, wxDbgHelpDLL::SymGetModuleBase, NULL // address translator for 16 bit ) ) { if ( ::GetLastError() ) wxDbgHelpDLL::LogError(_T("StackWalk")); break; } // don't show this frame itself in the output if ( nLevel >= skip ) { wxStackFrame frame(nLevel - skip, (void *)sf.AddrPC.Offset, sf.AddrFrame.Offset); OnStackFrame(frame); } } // this results in crashes inside ntdll.dll when called from // exception handler ... #if 0 if ( !wxDbgHelpDLL::SymCleanup(hProcess) ) { wxDbgHelpDLL::LogError(_T("SymCleanup")); } #endif }
// returns number of tracks imported int Importer::Import(wxString fName, TrackFactory *trackFactory, Track *** tracks, Tags *tags, wxString &errorMessage) { AudacityProject *pProj = GetActiveProject(); pProj->mbBusyImporting = true; ImportFileHandle *inFile = NULL; int numTracks = 0; wxString extension = fName.AfterLast(wxT('.')); // This list is used to call plugins in correct order ImportPluginList importPlugins; ImportPluginList::compatibility_iterator importPluginNode; // This list is used to remember plugins that should have been compatible with the file. ImportPluginList compatiblePlugins; // If user explicitly selected a filter, // then we should try importing via corresponding plugin first wxString type = gPrefs->Read(wxT("/LastOpenType"),wxT("")); // Not implemented (yet?) wxString mime_type = wxT("*"); // First, add user-selected filter bool usersSelectionOverrides; gPrefs->Read(wxT("/ExtendedImport/OverrideExtendedImportByOpenFileDialogChoice"), &usersSelectionOverrides, false); wxLogDebug(wxT("LastOpenType is %s"),type.c_str()); wxLogDebug(wxT("OverrideExtendedImportByOpenFileDialogChoice is %i"),usersSelectionOverrides); if (usersSelectionOverrides) { importPluginNode = mImportPluginList->GetFirst(); while (importPluginNode) { ImportPlugin *plugin = importPluginNode->GetData(); if (plugin->GetPluginFormatDescription().CompareTo(type) == 0) { // This plugin corresponds to user-selected filter, try it first. wxLogDebug(wxT("Inserting %s"),plugin->GetPluginStringID().c_str()); importPlugins.Insert(plugin); } importPluginNode = importPluginNode->GetNext(); } } wxLogMessage(wxT("File name is %s"),(const char *) fName.c_str()); wxLogMessage(wxT("Mime type is %s"),(const char *) mime_type.Lower().c_str()); for (size_t i = 0; i < mExtImportItems->Count(); i++) { ExtImportItem *item = &(*mExtImportItems)[i]; bool matches_ext = false, matches_mime = false; wxLogDebug(wxT("Testing extensions")); for (size_t j = 0; j < item->extensions.Count(); j++) { wxLogDebug(wxT("%s"), (const char *) item->extensions[j].Lower().c_str()); if (wxMatchWild (item->extensions[j].Lower(),fName.Lower(), false)) { wxLogDebug(wxT("Match!")); matches_ext = true; break; } } if (item->extensions.Count() == 0) { wxLogDebug(wxT("Match! (empty list)")); matches_ext = true; } if (matches_ext) wxLogDebug(wxT("Testing mime types")); else wxLogDebug(wxT("Not testing mime types")); for (size_t j = 0; matches_ext && j < item->mime_types.Count(); j++) { if (wxMatchWild (item->mime_types[j].Lower(),mime_type.Lower(), false)) { wxLogDebug(wxT("Match!")); matches_mime = true; break; } } if (item->mime_types.Count() == 0) { wxLogDebug(wxT("Match! (empty list)")); matches_mime = true; } if (matches_ext && matches_mime) { wxLogDebug(wxT("Complete match!")); for (size_t j = 0; j < item->filter_objects.Count() && (item->divider < 0 || (int) j < item->divider); j++) { // the filter_object can be NULL if a suitable importer was not found // this happens when we recompile with --without-ffmpeg and there // is still ffmpeg in prefs from previous --with-ffmpeg builds if (!(item->filter_objects[j])) continue; wxLogDebug(wxT("Inserting %s"),item->filter_objects[j]->GetPluginStringID().c_str()); importPlugins.Append(item->filter_objects[j]); } } } // Add all plugins that support the extension importPluginNode = mImportPluginList->GetFirst(); // Here we rely on the fact that the first plugin in mImportPluginList is libsndfile. // We want to save this for later insertion ahead of libmad, if libmad supports the extension. // The order of plugins in mImportPluginList is determined by the Importer constructor alone and // is not changed by user selection overrides or any other mechanism, but we include an assert // in case subsequent code revisions to the constructor should break this assumption that // libsndfile is first. ImportPlugin *libsndfilePlugin = importPluginNode->GetData(); wxASSERT(libsndfilePlugin->GetPluginStringID().IsSameAs(wxT("libsndfile"))); while (importPluginNode) { ImportPlugin *plugin = importPluginNode->GetData(); // Make sure its not already in the list if (importPlugins.Find(plugin) == NULL) { if (plugin->SupportsExtension(extension)) { // If libmad is accidentally fed a wav file which has been incorrectly // given an .mp3 extension then it can choke on the contents and crash. // To avoid this, put libsndfile ahead of libmad in the lists created for // mp3 files, or for any of the extensions supported by libmad. // A genuine .mp3 file will first fail an attempted import with libsndfile // but then get processed as desired by libmad. // But a wav file which bears an incorrect .mp3 extension will be successfully // processed by libsndfile and thus avoid being submitted to libmad. if (plugin->GetPluginStringID().IsSameAs(wxT("libmad"))) { // Make sure libsndfile is not already in the list if (importPlugins.Find(libsndfilePlugin) == NULL) { wxLogDebug(wxT("Appending %s"),libsndfilePlugin->GetPluginStringID().c_str()); importPlugins.Append(libsndfilePlugin); } } wxLogDebug(wxT("Appending %s"),plugin->GetPluginStringID().c_str()); importPlugins.Append(plugin); } } importPluginNode = importPluginNode->GetNext(); } // Add remaining plugins, except for libmad, which should not be used as a fallback for anything. // Otherwise, if FFmpeg (libav) has not been installed, libmad will still be there near the // end of the preference list importPlugins, where it will claim success importing FFmpeg file // formats unsuitable for it, and produce distorted results. importPluginNode = mImportPluginList->GetFirst(); while (importPluginNode) { ImportPlugin *plugin = importPluginNode->GetData(); if (!(plugin->GetPluginStringID().IsSameAs(wxT("libmad")))) { // Make sure its not already in the list if (importPlugins.Find(plugin) == NULL) { wxLogDebug(wxT("Appending %s"),plugin->GetPluginStringID().c_str()); importPlugins.Append(plugin); } } importPluginNode = importPluginNode->GetNext(); } importPluginNode = importPlugins.GetFirst(); while(importPluginNode) { ImportPlugin *plugin = importPluginNode->GetData(); // Try to open the file with this plugin (probe it) wxLogMessage(wxT("Opening with %s"),plugin->GetPluginStringID().c_str()); inFile = plugin->Open(fName); if ( (inFile != NULL) && (inFile->GetStreamCount() > 0) ) { wxLogMessage(wxT("Open(%s) succeeded"),(const char *) fName.c_str()); // File has more than one stream - display stream selector if (inFile->GetStreamCount() > 1) { ImportStreamDialog ImportDlg(inFile, NULL, -1, _("Select stream(s) to import")); if (ImportDlg.ShowModal() == wxID_CANCEL) { delete inFile; pProj->mbBusyImporting = false; return 0; } } // One stream - import it by default else inFile->SetStreamUsage(0,TRUE); int res; res = inFile->Import(trackFactory, tracks, &numTracks, tags); delete inFile; if (res == eProgressSuccess || res == eProgressStopped) { // LOF ("list-of-files") has different semantics if (extension.IsSameAs(wxT("lof"), false)) { pProj->mbBusyImporting = false; return 1; } if (numTracks > 0) { // success! pProj->mbBusyImporting = false; return numTracks; } } if (res == eProgressCancelled || res == eProgressFailed) { pProj->mbBusyImporting = false; return 0; } // We could exit here since we had a match on the file extension, // but there may be another plug-in that can import the file and // that may recognize the extension, so we allow the loop to // continue. } importPluginNode = importPluginNode->GetNext(); } wxLogError(wxT("Importer::Import: Opening failed.")); // None of our plugins can handle this file. It might be that // Audacity supports this format, but support was not compiled in. // If so, notify the user of this fact UnusableImportPluginList::compatibility_iterator unusableImporterNode = mUnusableImportPluginList->GetFirst(); while(unusableImporterNode) { UnusableImportPlugin *unusableImportPlugin = unusableImporterNode->GetData(); if( unusableImportPlugin->SupportsExtension(extension) ) { errorMessage.Printf(_("This version of Audacity was not compiled with %s support."), unusableImportPlugin-> GetPluginFormatDescription().c_str()); pProj->mbBusyImporting = false; return 0; } unusableImporterNode = unusableImporterNode->GetNext(); } /* warnings for unsupported data types */ #ifdef USE_MIDI // MIDI files must be imported, not opened if ((extension.IsSameAs(wxT("midi"), false))||(extension.IsSameAs(wxT("mid"), false))) { errorMessage.Printf(_("\"%s\" \nis a MIDI file, not an audio file. \nAudacity cannot open this type of file for playing, but you can\nedit it by clicking File > Import > MIDI."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } #endif if (compatiblePlugins.GetCount() <= 0) { // if someone has sent us a .cda file, send them away if (extension.IsSameAs(wxT("cda"), false)) { /* i18n-hint: %s will be the filename */ errorMessage.Printf(_("\"%s\" is an audio CD track. \nAudacity cannot open audio CDs directly. \nExtract (rip) the CD tracks to an audio format that \nAudacity can import, such as WAV or AIFF."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } // playlist type files if ((extension.IsSameAs(wxT("m3u"), false))||(extension.IsSameAs(wxT("ram"), false))||(extension.IsSameAs(wxT("pls"), false))) { errorMessage.Printf(_("\"%s\" is a playlist file. \nAudacity cannot open this file because it only contains links to other files. \nYou may be able to open it in a text editor and download the actual audio files."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } //WMA files of various forms if ((extension.IsSameAs(wxT("wma"), false))||(extension.IsSameAs(wxT("asf"), false))) { errorMessage.Printf(_("\"%s\" is a Windows Media Audio file. \nAudacity cannot open this type of file due to patent restrictions. \nYou need to convert it to a supported audio format, such as WAV or AIFF."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } //AAC files of various forms (probably not encrypted) if ((extension.IsSameAs(wxT("aac"), false))||(extension.IsSameAs(wxT("m4a"), false))||(extension.IsSameAs(wxT("m4r"), false))||(extension.IsSameAs(wxT("mp4"), false))) { errorMessage.Printf(_("\"%s\" is an Advanced Audio Coding file. \nAudacity cannot open this type of file. \nYou need to convert it to a supported audio format, such as WAV or AIFF."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } // encrypted itunes files if ((extension.IsSameAs(wxT("m4p"), false))) { errorMessage.Printf(_("\"%s\" is an encrypted audio file. \nThese typically are from an online music store. \nAudacity cannot open this type of file due to the encryption. \nTry recording the file into Audacity, or burn it to audio CD then \nextract the CD track to a supported audio format such as WAV or AIFF."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } // Real Inc. files of various sorts if ((extension.IsSameAs(wxT("ra"), false))||(extension.IsSameAs(wxT("rm"), false))||(extension.IsSameAs(wxT("rpm"), false))) { errorMessage.Printf(_("\"%s\" is a RealPlayer media file. \nAudacity cannot open this proprietary format. \nYou need to convert it to a supported audio format, such as WAV or AIFF."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } // Other notes-based formats if ((extension.IsSameAs(wxT("kar"), false))||(extension.IsSameAs(wxT("mod"), false))||(extension.IsSameAs(wxT("rmi"), false))) { errorMessage.Printf(_("\"%s\" is a notes-based file, not an audio file. \nAudacity cannot open this type of file. \nTry converting it to an audio file such as WAV or AIFF and \nthen import it, or record it into Audacity."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } // MusePack files if ((extension.IsSameAs(wxT("mp+"), false))||(extension.IsSameAs(wxT("mpc"), false))||(extension.IsSameAs(wxT("mpp"), false))) { errorMessage.Printf(_("\"%s\" is a Musepack audio file. \nAudacity cannot open this type of file. \nIf you think it might be an mp3 file, rename it to end with \".mp3\" \nand try importing it again. Otherwise you need to convert it to a supported audio \nformat, such as WAV or AIFF."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } // WavPack files if ((extension.IsSameAs(wxT("wv"), false))||(extension.IsSameAs(wxT("wvc"), false))) { errorMessage.Printf(_("\"%s\" is a Wavpack audio file. \nAudacity cannot open this type of file. \nYou need to convert it to a supported audio format, such as WAV or AIFF."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } // AC3 files if ((extension.IsSameAs(wxT("ac3"), false))) { errorMessage.Printf(_("\"%s\" is a Dolby Digital audio file. \nAudacity cannot currently open this type of file. \nYou need to convert it to a supported audio format, such as WAV or AIFF."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } // Speex files if ((extension.IsSameAs(wxT("spx"), false))) { errorMessage.Printf(_("\"%s\" is an Ogg Speex audio file. \nAudacity cannot currently open this type of file. \nYou need to convert it to a supported audio format, such as WAV or AIFF."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } // Video files of various forms if ((extension.IsSameAs(wxT("mpg"), false))||(extension.IsSameAs(wxT("mpeg"), false))||(extension.IsSameAs(wxT("avi"), false))||(extension.IsSameAs(wxT("wmv"), false))||(extension.IsSameAs(wxT("rv"), false))) { errorMessage.Printf(_("\"%s\" is a video file. \nAudacity cannot currently open this type of file. \nYou need to extract the audio to a supported format, such as WAV or AIFF."), fName.c_str()); pProj->mbBusyImporting = false; return 0; } // we were not able to recognize the file type errorMessage.Printf(_("Audacity did not recognize the type of the file '%s'.\nIf it is uncompressed, try importing it using \"Import Raw\"."),fName.c_str()); } else { // We DO have a plugin for this file, but import failed. wxString pluglist = wxEmptyString; importPluginNode = compatiblePlugins.GetFirst(); while(importPluginNode) { ImportPlugin *plugin = importPluginNode->GetData(); if (pluglist == wxEmptyString) pluglist = plugin->GetPluginFormatDescription(); else pluglist = pluglist + wxT(", ") + plugin->GetPluginFormatDescription(); importPluginNode = importPluginNode->GetNext(); } errorMessage.Printf(_("Audacity recognized the type of the file '%s'.\nImporters supposedly supporting such files are:\n%s,\nbut none of them understood this file format."),fName.c_str(), pluglist.c_str()); } pProj->mbBusyImporting = false; return 0; }
bool wxSpinCtrl::Create(wxWindow *parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, long style, int min, int max, int initial, const wxString& name) { m_blockEvent = false; // this should be in ctor/init function but I don't want to add one to 2.8 // to avoid problems with default ctor which can be inlined in the user // code and so might not get this fix without recompilation m_oldValue = INT_MIN; // before using DoGetBestSize(), have to set style to let the base class // know whether this is a horizontal or vertical control (we're always // vertical) style |= wxSP_VERTICAL; if ( (style & wxBORDER_MASK) == wxBORDER_DEFAULT ) #ifdef __WXWINCE__ style |= wxBORDER_SIMPLE; #else style |= wxBORDER_SUNKEN; #endif SetWindowStyle(style); WXDWORD exStyle = 0; WXDWORD msStyle = MSWGetStyle(GetWindowStyle(), & exStyle) ; // propagate text alignment style to text ctrl if ( style & wxALIGN_RIGHT ) msStyle |= ES_RIGHT; else if ( style & wxALIGN_CENTER ) msStyle |= ES_CENTER; // calculate the sizes: the size given is the total size for both controls // and we need to fit them both in the given width (height is the same) wxSize sizeText(size), sizeBtn(size); sizeBtn.x = wxSpinButton::DoGetBestSize().x; if ( sizeText.x <= 0 ) { // DEFAULT_ITEM_WIDTH is the default width for the text control sizeText.x = DEFAULT_ITEM_WIDTH + MARGIN_BETWEEN + sizeBtn.x; } sizeText.x -= sizeBtn.x + MARGIN_BETWEEN; if ( sizeText.x <= 0 ) { wxLogDebug(wxT("not enough space for wxSpinCtrl!")); } wxPoint posBtn(pos); posBtn.x += sizeText.x + MARGIN_BETWEEN; // we must create the text control before the spin button for the purpose // of the dialog navigation: if there is a static text just before the spin // control, activating it by Alt-letter should give focus to the text // control, not the spin and the dialog navigation code will give focus to // the next control (at Windows level), not the one after it // create the text window m_hwndBuddy = (WXHWND)::CreateWindowEx ( exStyle, // sunken border wxT("EDIT"), // window class NULL, // no window title msStyle, // style (will be shown later) pos.x, pos.y, // position 0, 0, // size (will be set later) GetHwndOf(parent), // parent (HMENU)-1, // control id wxGetInstance(), // app instance NULL // unused client data ); if ( !m_hwndBuddy ) { wxLogLastError(wxT("CreateWindow(buddy text window)")); return false; } // create the spin button if ( !wxSpinButton::Create(parent, id, posBtn, sizeBtn, style, name) ) { return false; } wxSpinButtonBase::SetRange(min, max); // subclass the text ctrl to be able to intercept some events wxSetWindowUserData(GetBuddyHwnd(), this); m_wndProcBuddy = (WXFARPROC)wxSetWindowProc(GetBuddyHwnd(), wxBuddyTextWndProc); // set up fonts and colours (This is nomally done in MSWCreateControl) InheritAttributes(); if (!m_hasFont) SetFont(GetDefaultAttributes().font); // set the size of the text window - can do it only now, because we // couldn't call DoGetBestSize() before as font wasn't set if ( sizeText.y <= 0 ) { int cx, cy; wxGetCharSize(GetHWND(), &cx, &cy, GetFont()); sizeText.y = EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy); } SetInitialSize(size); (void)::ShowWindow(GetBuddyHwnd(), SW_SHOW); // associate the text window with the spin button (void)::SendMessage(GetHwnd(), UDM_SETBUDDY, (WPARAM)m_hwndBuddy, 0); SetValue(initial); // Set the range in the native control SetRange(min, max); if ( !value.empty() ) { SetValue(value); m_oldValue = (int) wxAtol(value); } else { SetValue(wxString::Format(wxT("%d"), initial)); m_oldValue = initial; } // do it after finishing with m_hwndBuddy creation to avoid generating // initial wxEVT_COMMAND_TEXT_UPDATED message ms_allSpins.Add(this); return true; }
/* static */ bool wxAcceleratorEntry::ParseAccel(const wxString& text, int *flagsOut, int *keyOut) { // the parser won't like trailing spaces wxString label = text; label.Trim(true); // For compatibility with the old wx versions which accepted (and actually // even required) a TAB character in the string passed to this function we // ignore anything up to the first TAB. Notice however that the correct // input consists of just the accelerator itself and nothing else, this is // done for compatibility and compatibility only. int posTab = label.Find(wxT('\t')); if ( posTab == wxNOT_FOUND ) posTab = 0; else posTab++; // parse the accelerator string int accelFlags = wxACCEL_NORMAL; wxString current; for ( size_t n = (size_t)posTab; n < label.length(); n++ ) { if ( (label[n] == '+') || (label[n] == '-') ) { if ( CompareAccelString(current, wxTRANSLATE("ctrl")) ) accelFlags |= wxACCEL_CTRL; else if ( CompareAccelString(current, wxTRANSLATE("alt")) ) accelFlags |= wxACCEL_ALT; else if ( CompareAccelString(current, wxTRANSLATE("shift")) ) accelFlags |= wxACCEL_SHIFT; else if ( CompareAccelString(current, wxTRANSLATE("rawctrl")) ) accelFlags |= wxACCEL_RAW_CTRL; else // not a recognized modifier name { // we may have "Ctrl-+", for example, but we still want to // catch typos like "Crtl-A" so only give the warning if we // have something before the current '+' or '-', else take // it as a literal symbol if ( current.empty() ) { current += label[n]; // skip clearing it below continue; } else { wxLogDebug(wxT("Unknown accel modifier: '%s'"), current.c_str()); } } current.clear(); } else // not special character { current += (wxChar) wxTolower(label[n]); } } int keyCode; const size_t len = current.length(); switch ( len ) { case 0: wxLogDebug(wxT("No accel key found, accel string ignored.")); return false; case 1: // it's just a letter keyCode = current[0U]; // if the key is used with any modifiers, make it an uppercase one // because Ctrl-A and Ctrl-a are the same; but keep it as is if it's // used alone as 'a' and 'A' are different if ( accelFlags != wxACCEL_NORMAL ) keyCode = wxToupper(keyCode); break; default: keyCode = IsNumberedAccelKey(current, wxTRANSLATE("F"), WXK_F1, 1, 12); if ( !keyCode ) { for ( size_t n = 0; n < WXSIZEOF(wxKeyNames); n++ ) { const wxKeyName& kn = wxKeyNames[n]; if ( CompareAccelString(current, kn.name) ) { keyCode = kn.code; break; } } } if ( !keyCode ) keyCode = IsNumberedAccelKey(current, wxTRANSLATE("KP_"), WXK_NUMPAD0, 0, 9); if ( !keyCode ) keyCode = IsNumberedAccelKey(current, wxTRANSLATE("SPECIAL"), WXK_SPECIAL1, 1, 20); if ( !keyCode ) { wxLogDebug(wxT("Unrecognized accel key '%s', accel string ignored."), current.c_str()); return false; } } wxASSERT_MSG( keyCode, wxT("logic error: should have key code here") ); if ( flagsOut ) *flagsOut = accelFlags; if ( keyOut ) *keyOut = keyCode; return true; }
int wxFontMapperBase::NonInteractiveCharsetToEncoding(const wxString& charset) { wxFontEncoding encoding = wxFONTENCODING_SYSTEM; // we're going to modify it, make a copy wxString cs = charset; #if wxUSE_CONFIG && wxUSE_FILECONFIG // first try the user-defined settings wxFontMapperPathChanger path(this, FONTMAPPER_CHARSET_PATH); if ( path.IsOk() ) { wxConfigBase *config = GetConfig(); // do we have an encoding for this charset? long value = config->Read(charset, -1l); if ( value != -1 ) { if ( value == wxFONTENCODING_UNKNOWN ) { // don't try to find it, in particular don't ask the user return value; } if ( value >= 0 && value <= wxFONTENCODING_MAX ) { encoding = (wxFontEncoding)value; } else { wxLogDebug(wxT("corrupted config data: invalid encoding %ld for charset '%s' ignored"), value, charset.c_str()); } } if ( encoding == wxFONTENCODING_SYSTEM ) { // may be we have an alias? config->SetPath(FONTMAPPER_CHARSET_ALIAS_PATH); wxString alias = config->Read(charset); if ( !alias.empty() ) { // yes, we do - use it instead cs = alias; } } } #endif // wxUSE_CONFIG // if didn't find it there, try to recognize it ourselves if ( encoding == wxFONTENCODING_SYSTEM ) { // trim any spaces cs.Trim(true); cs.Trim(false); // discard the optional quotes if ( !cs.empty() ) { if ( cs[0u] == wxT('"') && cs.Last() == wxT('"') ) { cs = wxString(cs.c_str(), cs.length() - 1); } } for ( size_t i = 0; i < WXSIZEOF(gs_encodingNames); ++i ) { for ( const wxChar* const* encName = gs_encodingNames[i]; *encName; ++encName ) { if ( cs.CmpNoCase(*encName) == 0 ) return gs_encodings[i]; } } cs.MakeUpper(); if ( cs.Left(3) == wxT("ISO") ) { // the dash is optional (or, to be exact, it is not, but // several broken programs "forget" it) const wxChar *p = cs.c_str() + 3; if ( *p == wxT('-') ) p++; unsigned int value; if ( wxSscanf(p, wxT("8859-%u"), &value) == 1 ) { // make it 0 based and check that it is strictly positive in // the process (no such thing as iso8859-0 encoding) if ( (value-- > 0) && (value < wxFONTENCODING_ISO8859_MAX - wxFONTENCODING_ISO8859_1) ) { // it's a valid ISO8859 encoding value += wxFONTENCODING_ISO8859_1; encoding = (wxFontEncoding)value; } } } else if ( cs.Left(4) == wxT("8859") ) { const wxChar *p = cs.c_str(); unsigned int value; if ( wxSscanf(p, wxT("8859-%u"), &value) == 1 ) { // make it 0 based and check that it is strictly positive in // the process (no such thing as iso8859-0 encoding) if ( (value-- > 0) && (value < wxFONTENCODING_ISO8859_MAX - wxFONTENCODING_ISO8859_1) ) { // it's a valid ISO8859 encoding value += wxFONTENCODING_ISO8859_1; encoding = (wxFontEncoding)value; } } } else // check for Windows charsets { size_t len; if ( cs.Left(7) == wxT("WINDOWS") ) { len = 7; } else if ( cs.Left(2) == wxT("CP") ) { len = 2; } else // not a Windows encoding { len = 0; } if ( len ) { const wxChar *p = cs.c_str() + len; if ( *p == wxT('-') ) p++; unsigned int value; if ( wxSscanf(p, wxT("%u"), &value) == 1 ) { if ( value >= 1250 ) { value -= 1250; if ( value < wxFONTENCODING_CP12_MAX - wxFONTENCODING_CP1250 ) { // a valid Windows code page value += wxFONTENCODING_CP1250; encoding = (wxFontEncoding)value; } } switch ( value ) { case 866: encoding = wxFONTENCODING_CP866; break; case 874: encoding = wxFONTENCODING_CP874; break; case 932: encoding = wxFONTENCODING_CP932; break; case 936: encoding = wxFONTENCODING_CP936; break; case 949: encoding = wxFONTENCODING_CP949; break; case 950: encoding = wxFONTENCODING_CP950; break; } } } } //else: unknown } return encoding; }
bool wxAnimation::Load(wxInputStream &stream, wxAnimationType type) { UnRef(); char anim_type[12]; switch (type) { case wxANIMATION_TYPE_GIF: strcpy(anim_type, "gif"); break; case wxANIMATION_TYPE_ANI: strcpy(anim_type, "ani"); break; default: anim_type[0] = '\0'; break; } // create a GdkPixbufLoader GError *error = NULL; GdkPixbufLoader *loader; if (type != wxANIMATION_TYPE_INVALID && type != wxANIMATION_TYPE_ANY) loader = gdk_pixbuf_loader_new_with_type(anim_type, &error); else loader = gdk_pixbuf_loader_new(); if (!loader || error != NULL) // even if the loader was allocated, an error could have happened { wxLogDebug(wxT("Could not create the loader for '%s' animation type: %s"), anim_type, error->message); return false; } // connect to loader signals g_signal_connect(loader, "area-updated", G_CALLBACK(gdk_pixbuf_area_updated), this); guchar buf[2048]; bool data_written = false; while (stream.IsOk()) { // read a chunk of data if (!stream.Read(buf, sizeof(buf)) && stream.GetLastError() != wxSTREAM_EOF) // EOF is OK for now { // gdk_pixbuf_loader_close wants the GError == NULL gdk_pixbuf_loader_close(loader, NULL); return false; } // fetch all data into the loader if (!gdk_pixbuf_loader_write(loader, buf, stream.LastRead(), &error)) { wxLogDebug(wxT("Could not write to the loader: %s"), error->message); // gdk_pixbuf_loader_close wants the GError == NULL gdk_pixbuf_loader_close(loader, NULL); return false; } data_written = true; } if (!data_written) { wxLogDebug("Could not read data from the stream..."); return false; } // load complete: gdk_pixbuf_loader_close will now check if the data we // wrote inside the pixbuf loader does make sense and will give an error // if it doesn't (because of a truncated file, corrupted data or whatelse) if (!gdk_pixbuf_loader_close(loader, &error)) { wxLogDebug(wxT("Could not close the loader: %s"), error->message); return false; } // wait until we get the last area_updated signal return data_written; }
void mmStockDialog::OnHistoryDownloadButton(wxCommandEvent& /*event*/) { /* Example stock history download: https://code.google.com/p/yahoo-finance-managed/wiki/csvHistQuotesDownload */ if (m_stock->SYMBOL.IsEmpty()) return; const wxDateTime& StartDate = Model_Stock::PURCHASEDATE(m_stock); wxDateTime EndDate = wxDate::Today(); const wxTimeSpan time = EndDate - StartDate; long intervalMonths = EndDate.GetMonth() - StartDate.GetMonth() + 12 * (EndDate.GetYear() - StartDate.GetYear()) - (EndDate.GetDay() < StartDate.GetDay()); //Define frequency enum { DAILY, WEEKLY, MONTHLY }; wxArrayString FreqStrs; FreqStrs.Add(_("Days")); FreqStrs.Add(_("Weeks")); if (intervalMonths > 0) FreqStrs.Add(_("Months")); int freq = wxGetSingleChoiceIndex(_("Specify type frequency of stock history") , _("Stock History Update"), FreqStrs); long interval = 0; switch (freq) { case DAILY: interval = time.GetDays(); break; case WEEKLY: interval = time.GetWeeks(); break; case MONTHLY: interval = intervalMonths; break; default: return; } int nrPrices = (int) wxGetNumberFromUser(_("Specify how many stock history prices download from purchase date") , wxString::Format(_("Number of %s:"), FreqStrs.Item(freq).Lower()), _("Stock History Update") , interval, 1L, 9999L, this, wxDefaultPosition); if (nrPrices <= 0) { mmShowErrorMessageInvalid(this, FreqStrs[freq]); return; } else { switch (freq) { case DAILY: EndDate = wxDate(StartDate).Add(wxDateSpan::Days(nrPrices)); break; case WEEKLY: EndDate = wxDate(StartDate).Add(wxDateSpan::Weeks(nrPrices)); break; case MONTHLY: EndDate = wxDate(StartDate).Add(wxDateSpan::Months(nrPrices)); break; default: break; } } if (EndDate > wxDate::Today()) { mmShowWarningMessage(this, _("End date is in the future\nQuotes will be updated until today") , _("Stock History Error")); EndDate = wxDate::Today(); } wxString CSVQuotes; wxString URL = mmex::weblink::YahooQuotesHistory; URL += m_stock->SYMBOL; URL += wxString::Format("&a=%i", StartDate.GetMonth()); URL += wxString::Format("&b=%i", StartDate.GetDay()); URL += wxString::Format("&c=%i", StartDate.GetYear()); URL += wxString::Format("&d=%i", EndDate.GetMonth()); URL += wxString::Format("&e=%i", EndDate.GetDay()); URL += wxString::Format("&f=%i", EndDate.GetYear()); switch (freq) { case DAILY: URL += "&g=d"; break; case WEEKLY: URL += "&g=w"; break; case MONTHLY: URL += "&g=m"; break; default: break; } URL += "&ignore=.csv"; wxLogDebug("Start Date:%s End Date:%s URL:%s", StartDate.FormatISODate(), EndDate.FormatISODate(), URL); int err_code = site_content(URL, CSVQuotes); if (err_code != wxURL_NOERR) { if (err_code == -1) CSVQuotes = _("Stock history not found!"); mmShowErrorMessage(this, CSVQuotes, _("Stock History Error")); return; } double dPrice; wxString dateStr; Model_StockHistory::Data *data; wxStringTokenizer tkz(CSVQuotes, "\r\n"); Model_StockHistory::instance().Begin(); while (tkz.HasMoreTokens()) { wxStringTokenizer tkzSingleLine(tkz.GetNextToken(), ","); std::vector<wxString> tokens; while (tkzSingleLine.HasMoreTokens()) { const wxString& token = tkzSingleLine.GetNextToken(); tokens.push_back(token); } if (tokens[0].Contains("-")) { dateStr = tokens[0]; tokens[6].ToDouble(&dPrice); if (Model_StockHistory::instance().find( Model_StockHistory::SYMBOL(m_stock->SYMBOL), Model_StockHistory::DB_Table_STOCKHISTORY_V1::DATE(dateStr) ).size() == 0 && dPrice > 0) { data = Model_StockHistory::instance().create(); data->SYMBOL = m_stock->SYMBOL; data->DATE = dateStr; data->VALUE = dPrice; data->UPDTYPE = Model_StockHistory::ONLINE; Model_StockHistory::instance().save(data); } } } Model_StockHistory::instance().Commit(); showStockHistory(); }
void frmScanforDevices::OnButtonScanClick(wxCommandEvent& event) { bool bSlowAlgorithm = false; uint8_t val; uint8_t reg[256]; CMDF mdf; wxString url; wxTreeItemId newitem; wxBusyCursor wait; bSlowAlgorithm = m_slowAlgorithm->GetValue(); uint8_t scanFrom = vscp_readStringValue(m_ctrlEditFrom->GetValue()); uint8_t scanTo = vscp_readStringValue(m_ctrlEditTo->GetValue()); if ( scanFrom >= scanTo ) { wxMessageBox(_("Node to scan from must be less then to")); return; } m_DeviceTree->DeleteAllItems(); m_htmlWnd->SetPage( "<html><body></body></html>" ); m_htmlWnd->Update(); wxProgressDialog progressDlg(_("Scanning for VSCP devices"), _("Reading Registers"), 2*(scanTo-scanFrom+1), this, wxPD_ELAPSED_TIME | wxPD_AUTO_HIDE | wxPD_CAN_ABORT); wxTreeItemId rootItem = m_DeviceTree->AddRoot(_("Found device(s)")); m_DeviceTree->ExpandAll(); // Fetch GUID for the interface if ( USE_TCPIP_INTERFACE == m_csw.getDeviceType() ) { fetchIterfaceGUID(); } if ( bSlowAlgorithm ) { for ( int i = scanFrom; i <= scanTo; i++ ) { if (!progressDlg.Update(i, wxString::Format(_("Checking for device %d"), i))) { if (m_DeviceTree->GetCount()) { wxTreeItemIdValue cookie; wxTreeItemId item = m_DeviceTree->GetFirstChild(m_DeviceTree->GetRootItem(), cookie); if ( item.IsOk() ) m_DeviceTree->SelectItem( item ); } ::wxEndBusyCursor(); break; } if ( USE_DLL_INTERFACE == m_csw.getDeviceType() ) { // Empty input queue canalMsg canalmsg; while ( m_csw.getDllInterface()->doCmdDataAvailable() ) { if ( CANAL_ERROR_SUCCESS != m_csw.getDllInterface()->doCmdReceive( &canalmsg ) ) break; } if ( CANAL_ERROR_SUCCESS == m_csw.getDllInterface()->readLevel1Register( i, 0, 0xd0, &val ) ) { newitem = m_DeviceTree->AppendItem(rootItem, wxString::Format(_("Node with nickname=%d"), i)); m_DeviceTree->ExpandAll(); memset(reg, 0, sizeof(reg)); scanElement *pElement = new scanElement; if (NULL != pElement) { pElement->m_bLoaded = false; pElement->m_nodeid = i; //pElement->m_html = str; memset(pElement->m_reg, 0, 256); m_DeviceTree->SetItemData(newitem, pElement); } } } else if (USE_TCPIP_INTERFACE == m_csw.getDeviceType()) { cguid destguid; destguid = m_ifguid; destguid.setLSB(i); // Empty input queue m_csw.getTcpIpInterface()->doCmdClear(); if ( CANAL_ERROR_SUCCESS == m_csw.getTcpIpInterface()->readLevel2Register( 0xd0, 0, &val, m_ifguid, &destguid ) ) { newitem = m_DeviceTree->AppendItem(rootItem, wxString::Format(_("Node with nickname=%d"), i)); m_DeviceTree->ExpandAll(); scanElement *pElement = new scanElement; if (NULL != pElement) { pElement->m_bLoaded = false; pElement->m_nodeid = i; //pElement->m_html = str; memset(pElement->m_reg, 0, 256); m_DeviceTree->SetItemData(newitem, pElement); } } } ::wxSafeYield(); } // for } else { // Fast Algorithm vscpEventEx eventex; if (USE_DLL_INTERFACE == m_csw.getDeviceType()) { // Empty input queue canalMsg canalmsg; while ( m_csw.getDllInterface()->doCmdDataAvailable() ) { if ( CANAL_ERROR_SUCCESS != m_csw.getDllInterface()->doCmdReceive( &canalmsg ) ) break; } // Send read register to all nodes. for ( int i = scanFrom; i <= scanTo; i++ ) { #ifdef WIN32 progressDlg.Update(i, wxString::Format(_("Checking for device %d"), i)); #endif eventex.vscp_class = VSCP_CLASS1_PROTOCOL; eventex.vscp_type = VSCP_TYPE_PROTOCOL_READ_REGISTER; eventex.sizeData = 2; // nodeid + register to read eventex.data[ 0 ] = i; // nodeid eventex.data[ 1 ] = 0xd0; // Register to read m_csw.doCmdSend( &eventex ); wxMilliSleep( 20 ); } // Check for replies wxLongLong resendTime = ::wxGetLocalTimeMillis(); std::list<int> found_list; bool bLevel2 = false; uint8_t cnt = 0; while (true) { progressDlg.Pulse( wxString::Format(_("Found %d"), found_list.size())); while ( m_csw.doCmdDataAvailable() ) { // Message available if ( CANAL_ERROR_SUCCESS == m_csw.doCmdReceive( &eventex ) ) { // Valid event #if 0 { wxString str; str = wxString::Format(_("Received Event: class=%d type=%d size=%d data= "), eventex.vscp_class, eventex.vscp_type, eventex.sizeData ); for ( int ii = 0; ii < eventex.sizeData; ii++ ) { str += wxString::Format(_("%02X "), eventex.data[ii] ); } wxLogDebug(str); } #endif // Level I Read reply? if ( ( VSCP_CLASS1_PROTOCOL == eventex.vscp_class ) && ( VSCP_TYPE_PROTOCOL_RW_RESPONSE == eventex.vscp_type ) ) { if ( 0xd0 == eventex.data[ 0 ] ) { // Requested register? // Add nickname to list found_list.push_back( eventex.GUID[15] ); } } } // valid event } // Event is available if ((::wxGetLocalTimeMillis() - resendTime) > 3000 ) { // Take away duplicates found_list.unique(); wxTreeItemId newitem; for( std::list<int>::iterator list_iter = found_list.begin(); list_iter != found_list.end(); list_iter++) { newitem = m_DeviceTree->AppendItem(rootItem, wxString::Format(_("Node with nickname=%d"), *list_iter)); m_DeviceTree->ExpandAll(); scanElement *pElement = new scanElement; if (NULL != pElement) { pElement->m_bLoaded = false; pElement->m_nodeid = *list_iter; pElement->m_html = _("Right click on item to load info about node."); memset(pElement->m_reg, 0, 256); m_DeviceTree->SetItemData(newitem, pElement); } } break; } } // while } // TCP/IP else if (USE_TCPIP_INTERFACE == m_csw.getDeviceType()) { // Empty input queue m_csw.getTcpIpInterface()->doCmdClear(); // Read register at all nodes. for ( int i=scanFrom; i<=scanTo; i++ ) { cguid destguid; destguid.setLSB(i); eventex.head = VSCP_PRIORITY_NORMAL; eventex.timestamp = 0; eventex.obid = 0; // Check if a specific interface is used if ( !m_ifguid.isNULL() ) { progressDlg.Update(i, wxString::Format(_("Checking for device %d"), i)); eventex.vscp_class = VSCP_CLASS2_LEVEL1_PROTOCOL; eventex.vscp_type = VSCP_TYPE_PROTOCOL_READ_REGISTER; memset(eventex.GUID, 0, 16);// We use GUID for interface eventex.sizeData = 16 + 2; // Interface GUID + nodeid + register to read m_ifguid.writeGUID(eventex.data); eventex.data[ 16 ] = i; // nodeid eventex.data[ 17 ] = 0xd0; // Register to read m_csw.doCmdSend( &eventex ); wxMilliSleep( 10 ); } else { wxMessageBox( _("No interface specified. Please select one") ); goto error; } } // for // Check for replies wxLongLong resendTime = ::wxGetLocalTimeMillis(); std::list<int> found_list; bool bLevel2 = false; uint8_t cnt = 0; while (true) { progressDlg.Pulse( wxString::Format(_("Found %d"), found_list.size())); while ( m_csw.doCmdDataAvailable() ) { // Message available if ( CANAL_ERROR_SUCCESS == m_csw.doCmdReceive( &eventex ) ) { // Valid event #if 0 { wxString str; str = wxString::Format(_("Received Event: class=%d type=%d size=%d data=%d %d"), eventex.vscp_class, eventex.vscp_type, eventex.sizeData, eventex.data[15], eventex.data[16] ); wxLogDebug(str); } #endif // Level I Read reply? if ( ( VSCP_CLASS1_PROTOCOL == eventex.vscp_class ) && (VSCP_TYPE_PROTOCOL_RW_RESPONSE == eventex.vscp_type)) { if (eventex.data[ 0 ] == 0xd0) { // Requested register? // Add nickname to list found_list.push_back( eventex.GUID[ 15 ] ); } // Check for correct node } // Level II 512 Read reply? else if (/*!m_ifguid.isNULL() && !bLevel2 &&*/ (VSCP_CLASS2_LEVEL1_PROTOCOL == eventex.vscp_class) && (VSCP_TYPE_PROTOCOL_RW_RESPONSE == eventex.vscp_type)) { //if ( pdestGUID->isSameGUID( event.GUID ) ) { // Reg we requested? if (0xd0 == eventex.data[ 16 ] ) { // Add nickname to list found_list.push_back( eventex.GUID[ 15 ] ); } //} } // Level II Read reply? else if (m_ifguid.isNULL() && bLevel2 && (VSCP_CLASS2_PROTOCOL == eventex.vscp_class) && (VSCP2_TYPE_PROTOCOL_READ_WRITE_RESPONSE == eventex.vscp_type)) { // from us uint32_t retreg = (eventex.data[ 0 ] << 24) + (eventex.data[ 1 ] << 16) + (eventex.data[ 2 ] << 8) + eventex.data[ 3 ]; // Register we requested? if (retreg == 0xffffffd0) { // Add nickname to list found_list.push_back( eventex.data[ 15 ] ); } } } // valid event } //Event is available if ((::wxGetLocalTimeMillis() - resendTime) > 3000 ) { // Take away duplicates found_list.unique(); wxTreeItemId newitem; for ( std::list<int>::iterator list_iter = found_list.begin(); list_iter != found_list.end(); list_iter++) { newitem = m_DeviceTree->AppendItem(rootItem, wxString::Format(_("Node with nickname=%d"), *list_iter)); m_DeviceTree->ExpandAll(); scanElement *pElement = new scanElement; if (NULL != pElement) { pElement->m_bLoaded = false; pElement->m_nodeid = *list_iter; pElement->m_html = _("Right click on item to load info about node. Double click to open configuration window."); memset(pElement->m_reg, 0, 256); m_DeviceTree->SetItemData( newitem, pElement ); } } break; } // while } } // TCP/IP i/f } // fast if ( m_DeviceTree->GetCount() ) { m_DeviceTree->SelectItem( m_DeviceTree->GetRootItem() ); } error: Raise(); event.Skip(false); }
void guiPrefs::ViewContact(wxTreeItemId& id) { m_loadDone = false; bool localChange = m_aChange; AuthLoad* pMyLoader = wxGetApp().AccessLoader(); if (!pMyLoader) return; /* wxTextCtrl * pName = (wxTextCtrl *)FindWindow( ID_CON_EDIT_NAME ); wxComboBox * pInfoChoice = (wxComboBox *)FindWindow( ID_CON_EDIT_INFO_LIST ); wxTextCtrl * pInfoText = (wxTextCtrl *)FindWindow ( ID_CON_EDIT_INFO_TEXT ), * pNetScreenName = (wxTextCtrl *)FindWindow ( ID_CON_EDIT_NETS_SCREEN_NAME ); wxListBox * pUserNets = (wxListBox *)FindWindow ( ID_CON_EDIT_NETS_USER ), * pAllNets = (wxListBox *)FindWindow ( ID_CON_EDIT_NETS_ALL ); wxChoice * pPrefChoice = (wxChoice *)FindWindow ( ID_CON_EDIT_NET_PREF ); */ if (!id.IsOk()) { wxLogDebug("id is invalid in void guiPrefs::ViewContact()"); return; } wxString l_name = GetTree().GetItemText(id); m_sxName = l_name; if (!pMyLoader->UserExists(l_name.c_str()) ) { wxLogDebug("User does NOT exist in void guiPrefs::ViewContact()"); return; } vector<string> all_nets; if (!pMyLoader->GetAvailableNets(all_nets)) { wxLogDebug("GetAvailableNets() returns false in void guiPrefs::ViewContact()"); return; } if (!pMyLoader->GetInfo(l_name.c_str(), m_itemsStorage)) { wxLogDebug("GetInfo returned false in void guiPrefs::ViewContact()"); return; } if (!pMyLoader->GetNets(l_name.c_str(), m_netsStorage)) { wxLogDebug("GetNets returned false in void guiPrefs::ViewContact()"); return; } #ifdef __WXDEBUG__ if (!pName || !pInfoChoice || !pInfoText || !pUserNets || !pAllNets || !pNetScreenName || !pPrefChoice ) { wxLogDebug("A pointer from FindWindow is NULL!"); return; } #endif pName->SetValue(l_name); map<string, string>::const_iterator it; pInfoChoice->Clear(); for (it=m_itemsStorage.begin(); it!=m_itemsStorage.end();it++) { pInfoChoice->Append(it->first.c_str()); } if (pInfoChoice->GetCount() > 0) { pInfoText->SetValue(m_itemsStorage.begin()->second.c_str()); pInfoChoice->SetSelection(0); m_iLastItemSelection = 0; } else m_iLastItemSelection = -1; pUserNets->Clear(); for (it=m_netsStorage.begin(); it!=m_netsStorage.end();it++) { pUserNets->Append(it->first.c_str()); } if(pUserNets->GetCount() > 0) { pUserNets->SetSelection(0); pNetScreenName->SetValue(m_netsStorage.begin()->second.c_str()); m_iLastNetSelection = 0; } else m_iLastNetSelection = -1; pAllNets->Clear(); for (unsigned int i = 0; i < all_nets.size(); i++) { pAllNets->Append(all_nets[i].c_str()); } if (!localChange) { // ActivateSave(false); } m_loadDone = true; }
bool wxSpinCtrl::Create(wxWindow *parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, long style, int min, int max, int initial, const wxString& name) { // before using DoGetBestSize(), have to set style to let the base class // know whether this is a horizontal or vertical control (we're always // vertical) style |= wxSP_VERTICAL; if ( (style & wxBORDER_MASK) == wxBORDER_DEFAULT ) #ifdef __WXWINCE__ style |= wxBORDER_SIMPLE; #else style |= wxBORDER_SUNKEN; #endif SetWindowStyle(style); WXDWORD exStyle = 0; WXDWORD msStyle = MSWGetStyle(GetWindowStyle(), & exStyle) ; // Scroll text automatically if there is not enough space to show all of // it, this is better than not allowing to enter more digits at all. msStyle |= ES_AUTOHSCROLL; // propagate text alignment style to text ctrl if ( style & wxALIGN_RIGHT ) msStyle |= ES_RIGHT; else if ( style & wxALIGN_CENTER ) msStyle |= ES_CENTER; // calculate the sizes: the size given is the total size for both controls // and we need to fit them both in the given width (height is the same) wxSize sizeText(size), sizeBtn(size); sizeBtn.x = wxSpinButton::DoGetBestSize().x; if ( sizeText.x <= 0 ) { // DEFAULT_ITEM_WIDTH is the default width for the text control sizeText.x = DEFAULT_ITEM_WIDTH + MARGIN_BETWEEN + sizeBtn.x; } sizeText.x -= sizeBtn.x + MARGIN_BETWEEN; if ( sizeText.x <= 0 ) { wxLogDebug(wxS("wxSpinCtrl \"%s\": initial width %d is too small, ") wxS("at least %d pixels needed."), name, size.x, sizeBtn.x + MARGIN_BETWEEN + 1); } wxPoint posBtn(pos); posBtn.x += sizeText.x + MARGIN_BETWEEN; // we must create the text control before the spin button for the purpose // of the dialog navigation: if there is a static text just before the spin // control, activating it by Alt-letter should give focus to the text // control, not the spin and the dialog navigation code will give focus to // the next control (at Windows level), not the one after it // create the text window m_hwndBuddy = (WXHWND)::CreateWindowEx ( exStyle, // sunken border wxT("EDIT"), // window class NULL, // no window title msStyle, // style (will be shown later) pos.x, pos.y, // position 0, 0, // size (will be set later) GetHwndOf(parent), // parent (HMENU)-1, // control id wxGetInstance(), // app instance NULL // unused client data ); if ( !m_hwndBuddy ) { wxLogLastError(wxT("CreateWindow(buddy text window)")); return false; } // create the spin button if ( !wxSpinButton::Create(parent, id, posBtn, sizeBtn, style, name) ) { return false; } wxSpinButtonBase::SetRange(min, max); // subclass the text ctrl to be able to intercept some events gs_spinForTextCtrl[GetBuddyHwnd()] = this; m_wndProcBuddy = (WXFARPROC)wxSetWindowProc(GetBuddyHwnd(), wxBuddyTextWndProc); // set up fonts and colours (This is nomally done in MSWCreateControl) InheritAttributes(); if (!m_hasFont) SetFont(GetDefaultAttributes().font); // set the size of the text window - can do it only now, because we // couldn't call DoGetBestSize() before as font wasn't set if ( sizeText.y <= 0 ) { int cx, cy; wxGetCharSize(GetHWND(), &cx, &cy, GetFont()); sizeText.y = EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy); } SetInitialSize(size); (void)::ShowWindow(GetBuddyHwnd(), SW_SHOW); // associate the text window with the spin button (void)::SendMessage(GetHwnd(), UDM_SETBUDDY, (WPARAM)m_hwndBuddy, 0); // If the initial text value is actually a number, it overrides the // "initial" argument specified later. long initialFromText; if ( value.ToLong(&initialFromText) ) initial = initialFromText; // Set the range in the native control: notice that we must do it before // calling SetValue() to use the correct validity checks for the initial // value. SetRange(min, max); SetValue(initial); // Also set the text part of the control if it was specified independently // but don't generate an event for this, it would be unexpected. m_blockEvent = true; if ( !value.empty() ) SetValue(value); m_blockEvent = false; return true; }
/* static */ wxDynamicLibraryDetailsArray wxDynamicLibrary::ListLoaded() { wxDynamicLibraryDetailsArray dlls; #ifdef __LINUX__ // examine /proc/self/maps to find out what is loaded in our address space wxFFile file(_T("/proc/self/maps")); if ( file.IsOpened() ) { // details of the module currently being parsed wxString pathCur; void *startCur = NULL, *endCur = NULL; char path[1024]; char buf[1024]; while ( fgets(buf, WXSIZEOF(buf), file.fp()) ) { // format is: "start-end perm offset maj:min inode path", see proc(5) void *start, *end; switch ( sscanf(buf, "%p-%p %*4s %*p %*02x:%*02x %*d %1024s\n", &start, &end, path) ) { case 2: // there may be no path column path[0] = '\0'; break; case 3: // nothing to do, read everything we wanted break; default: // chop '\n' buf[strlen(buf) - 1] = '\0'; wxLogDebug(_T("Failed to parse line \"%s\" in /proc/self/maps."), buf); continue; } wxASSERT_MSG( start >= endCur, _T("overlapping regions in /proc/self/maps?") ); wxString pathNew = wxString::FromAscii(path); if ( pathCur.empty() ) { // new module start pathCur = pathNew; startCur = start; endCur = end; } else if ( pathCur == pathNew && endCur == end ) { // continuation of the same module in the address space endCur = end; } else // end of the current module { dlls.Add(wxDynamicLibraryDetailsCreator::New(startCur, endCur, pathCur)); pathCur.clear(); } } } #endif // __LINUX__ return dlls; }
bool StateGraphViewerPanel::Create(wxWindow *Parent, ContextNotifier &WithNotifier, ActionRecord &WithRecording, ActionReplayFrame &WithReplay, wxWindowID ID, wxPoint const &Position, wxSize const &Size) { if (!wxPanel::Create(Parent, ID, Position, Size)) return false; Notifier = &WithNotifier; Recording = &WithRecording; // Enable vfs access to request information about the state. auto const ThisAddr = reinterpret_cast<uintptr_t>(this); auto const CallbackProto = std::string{"seec"} + std::to_string(ThisAddr); CallbackFS = new seec::CallbackFSHandler(CallbackProto); CallbackFS->addCallback("notify_hover", std::function<void (std::string const &)>{ [this] (std::string const &NodeID) -> void { this->OnMouseOver(NodeID); } }); CallbackFS->addCallback("notify_contextmenu", std::function<void (std::string const &)>{ [this] (std::string const &Foo) -> void { this->RaiseContextMenu(); } }); CallbackFS->addCallback("log_debug", std::function<void (std::string const &)>{ [] (std::string const &Message) -> void { wxLogDebug("%s", wxString{Message}); } }); Bind(wxEVT_CONTEXT_MENU, &StateGraphViewerPanel::OnContextMenu, this); Bind(SEEC_EV_MOUSE_OVER_DISPLAYABLE, &StateGraphViewerPanel::OnMouseOverDisplayable, this); wxFileSystem::AddHandler(CallbackFS); // Get our resources from ICU. UErrorCode Status = U_ZERO_ERROR; auto Resources = seec::getResource("TraceViewer", getLocale(), Status, "StateGraphViewer"); if (!U_SUCCESS(Status)) return false; auto Sizer = new wxBoxSizer(wxVERTICAL); // Setup the webview. WebView = wxWebView::New(this, wxID_ANY); if (!WebView) { wxLogDebug("wxWebView::New failed."); return false; } WebView->RegisterHandler(wxSharedPtr<wxWebViewHandler> (new wxWebViewFSHandler("icurb"))); WebView->RegisterHandler(wxSharedPtr<wxWebViewHandler> (new wxWebViewFSHandler(CallbackProto))); Sizer->Add(WebView, wxSizerFlags(1).Expand()); SetSizerAndFit(Sizer); // Find the dot executable. PathToDot = getPathForDotExecutable(); if (!PathToDot.empty()) { // Determine the path to Graphviz's libraries, based on the location of dot. llvm::SmallString<256> PluginPath (PathToDot); llvm::sys::path::remove_filename(PluginPath); // */bin/dot -> */bin llvm::sys::path::remove_filename(PluginPath); // */bin -> * llvm::sys::path::append(PluginPath, "lib"); // * -> */lib PathToGraphvizLibraries = "DYLD_LIBRARY_PATH="; PathToGraphvizLibraries += PluginPath.str(); llvm::sys::path::append(PluginPath, "graphviz"); // */lib -> */lib/graphviz PathToGraphvizPlugins = "GVBINDIR="; PathToGraphvizPlugins += PluginPath.str(); // Setup the layout handler. { std::lock_guard<std::mutex> LockLayoutHandler (LayoutHandlerMutex); LayoutHandler.reset(new seec::cm::graph::LayoutHandler()); LayoutHandler->addBuiltinLayoutEngines(); } // After the webpage is loaded, setup the initial ColourScheme. WebView->Bind(wxEVT_WEBVIEW_LOADED, std::function<void (wxWebViewEvent &)>{ [this] (wxWebViewEvent &Event) -> void { setupColourScheme( *wxGetApp().getColourSchemeSettings().getColourScheme()); Event.Skip(); }}); // Load the webpage. auto const WebViewURL = std::string{"icurb://TraceViewer/StateGraphViewer/WebViewHTML#"} + CallbackProto; WebView->LoadURL(WebViewURL); // Wire up our event handlers. Bind(SEEC_EV_GRAPH_RENDERED, &StateGraphViewerPanel::OnGraphRendered, this); // Register for context notifications. Notifier->callbackAdd([this] (ContextEvent const &Ev) -> void { this->handleContextEvent(Ev); }); // Handle future changes to the ColourScheme. wxGetApp().getColourSchemeSettings().addListener( [this] (ColourSchemeSettings const &Settings) { setupColourScheme(*Settings.getColourScheme()); }); // Handle UAR replay. WithReplay.RegisterHandler("StateGraphViewer.MouseOverValue", {{"address", "type"}}, seec::make_function(this, &StateGraphViewerPanel::replayMouseOverValue)); } else { // If the user navigates to a link, open it in the default browser. WebView->Bind(wxEVT_WEBVIEW_NAVIGATING, std::function<void (wxWebViewEvent &)>{ [] (wxWebViewEvent &Event) -> void { if (Event.GetURL().StartsWith("http")) { wxLaunchDefaultBrowser(Event.GetURL()); Event.Veto(); } else Event.Skip(); }}); std::string const WebViewURL = "icurb://TraceViewer/StateGraphViewer/StateGraphViewerNoGraphviz.html"; // Load the webpage explaining that dot is required. WebView->LoadURL(WebViewURL); } // Create the worker thread that will perform our graph generation. WorkerThread = std::thread{ [this] () { this->workerTaskLoop(); }}; return true; }