virtual wxDirTraverseResult OnFile(const wxString& filename) { if (path+"\\"+item == pathNew.Left(path.Len())) return wxDIR_CONTINUE; wxString newFile = filename; newFile.Replace(path, pathNew); if (newFile == filename.Left(newFile.Len())) return wxDIR_CONTINUE; bool blnCopy = false; int intCopy = COPY_FILE_OK; //wxString itemNew (path == pathNew ) "Copy of " + item : item); if (m_onBeginCopyFile) intCopy = m_onBeginCopyFile(m_parent, filename, newFile); if (intCopy == COPY_FILE_OK) blnCopy = wxCopyFile(filename, newFile, true); if (m_onBeginCopyFile) m_onEndCopyFile(m_parent, blnCopy, filename, newFile); return (intCopy != ABORT_COPY_PROCESS ? wxDIR_CONTINUE : wxDIR_STOP); }
bool CServerPath::ExtractFile(wxString& dir, wxString& file) { int pos = dir.find_last_of(traits[m_type].separators); if (pos == (int)dir.Length() - 1) return false; if (pos == -1) { file = dir; dir.clear(); return true; } file = dir.Mid(pos + 1); dir = dir.Left(pos + 1); return true; }
void inifile_trim( wxString& buffer ) { buffer.Trim(false); // trims left side. if( buffer.Length() <= 1 ) // this I'm not sure about... - air { buffer.Empty(); return; } if( buffer.Left( 2 ) == L"//" ) { buffer.Empty(); return; } buffer.Trim(true); // trims right side. }
bool CState::LocalDirHasParent(const wxString& dir) { #ifdef __WXMSW__ if (dir.Left(2) == _T("\\\\")) { int pos = dir.Mid(2).Find('\\'); if (pos == -1 || pos + 3 == (int)dir.Len()) return false; } if (dir == _T("\\") || dir == _T("//")) return false; #endif if (dir == _T("/")) return false; return true; }
bool CChatSelector::ProcessMessage(uint64 sender_id, const wxString& message) { CChatSession* session = GetPageByClientID(sender_id); // Try to get the name (core sent it?) int separator = message.Find(wxT("|")); wxString client_name; wxString client_message; if (separator != -1) { client_name = message.Left(separator); client_message = message.Mid(separator+1); } else { // No need to define client_name. If needed, will be build on tab creation. client_message = message; } bool newtab = !session; if ( !session ) { // This must be a mesage from a client that is not already chatting if (client_name.IsEmpty()) { // Core did not send us the name. // This must NOT happen. // Build a client name based on the ID uint32 ip = IP_FROM_GUI_ID(sender_id); client_name = CFormat(wxT("IP: %s Port: %u")) % Uint32toStringIP(ip) % PORT_FROM_GUI_ID(sender_id); } session = StartSession( sender_id, client_name, true ); } // Other client connected after disconnection or a new session if ( !session->m_active ) { session->m_active = true; session->AddText( _("*** Connected to Client ***"), COLOR_RED ); } // Page text is client name session->AddText( GetPageText(GetTabByClientID(sender_id)), COLOR_BLUE, false ); session->AddText( wxT(": ") + client_message, COLOR_BLACK ); return newtab; }
void CCCSHandler::writeAMBE(CAMBEData& data, const wxString& dtmf) { if (m_state != CS_CONNECTED && m_state != CS_ACTIVE) return; if (m_state == CS_CONNECTED) { if (!dtmf.Left(1U).IsSameAs(wxT("*"))) return; wxString callsign = findInCache(dtmf.Mid(1U)); if (!callsign.IsEmpty()) { wxLogMessage(wxT("CCS: New outgoing link to %s/%s from %s"), dtmf.Mid(1U).c_str(), callsign.c_str(), m_myCall1.c_str()); m_handler->ccsLinkMade(callsign); m_yourCall = callsign; } else { wxLogMessage(wxT("CCS: New outgoing link to %s from %s"), dtmf.Mid(1U).c_str(), m_myCall1.c_str()); m_yourCall = dtmf; } m_local = m_myCall1; m_seqNo = 0U; m_time = ::time(NULL); m_stateChange = true; m_state = CS_ACTIVE; m_direction = DIR_OUTGOING; m_inactivityTimer.start(); } CAMBEData temp(data); CHeaderData& header = temp.getHeader(); header.setMyCall1(m_myCall1); header.setMyCall2(m_myCall2); header.setYourCall(m_yourCall); header.setRptCall1(m_callsign); header.setRptCall2(m_reflector); temp.setRptSeq(m_seqNo++); temp.setDestination(m_ccsAddress, CCS_PORT); m_protocol.writeData(temp); }
void COptions::SetServer(wxString path, const CServer& server) { if (!m_pXmlFile) return; if (path.empty()) return; TiXmlElement *element = m_pXmlFile->GetElement(); while (!path.empty()) { wxString sub; int pos = path.Find('/'); if (pos != -1) { sub = path.Left(pos); path = path.Mid(pos + 1); } else { sub = path; path = _T(""); } wxScopedCharBuffer utf8 = sub.utf8_str(); if (!utf8) return; TiXmlElement *newElement = element->FirstChildElement(utf8); if (newElement) element = newElement; else { TiXmlNode *node = element->LinkEndChild(new TiXmlElement(utf8)); if (!node || !node->ToElement()) return; element = node->ToElement(); } } ::SetServer(element, server); if (GetOptionVal(OPTION_DEFAULT_KIOSKMODE) == 2) return; CInterProcessMutex mutex(MUTEX_OPTIONS); m_pXmlFile->Save(true); }
/** * Process text sent by the server, not users * Check for vote events, promote events and something else */ void ChatPanel::DidAction(const wxString& who, const wxString& action) { //Handle vote events in chat by VotePanel if (m_votePanel != NULL) { m_votePanel->OnChatAction(who, action); } //Look for "promote" notifications from server CheckForPromotion(who, action); // change the image of the tab to show new events SetIconHighlight(highlight_say); OutputLine(_T( "* " ) + who + _T( " " ) + action, sett().GetChatColorAction()); if (m_type == CPT_User && (ui().GetActiveChatPanel() != this || !wxTheApp->IsActive())) { const wxString msg = wxString::Format(_T("%s \n%s"), who.c_str(), action.Left(50).c_str()); UiEvents::GetNotificationEventSender().SendEvent( UiEvents::NotficationData(UiEvents::PrivateMessage, msg)); } }
wxString StandardPaths::DoDecodePath(wxString path) { if (!path || path[0] != '?') return path; // Split ?part from rest path.Replace("\\","/"); int pos = path.Find("/"); wxString path1,path2; if (pos == wxNOT_FOUND) path1 = path; else { path1 = path.Left(pos); path2 = path.Mid(pos+1); } // Replace ?part if valid std::map<wxString,wxString>::iterator iter = paths.find(path1); if (iter == paths.end()) return path; wxString final = iter->second + "/" + path2; final.Replace("//","/");
void CommandBuilder::BuildCommand(wxString cmdString) { // Find the command name terminator... If there is more than one word and // no terminator, the command is badly formed cmdString.Trim(true); cmdString.Trim(false); int splitAt = cmdString.Find(wxT(':')); if (splitAt < 0 && cmdString.Find(wxT(' ')) >= 0) { mError = wxT("Command is missing ':'"); ScriptCommandRelay::SendResponse(wxT("\n")); mValid = false; return; } wxString cmdName = cmdString.Left(splitAt); wxString cmdParams = cmdString.Mid(splitAt+1); cmdName.Trim(true); cmdParams.Trim(false); BuildCommand(cmdName, cmdParams); }
wxString CDTMF::processDPlus(const wxString& command) const { unsigned int len = command.Len(); if (len < 2U || len > 4U) return wxEmptyString; unsigned long n; command.Left(len - 1U).ToULong(&n); if (n == 0UL) return wxEmptyString; wxChar c = command.GetChar(len - 1U); if (c != wxT('A') && c != wxT('B') && c != wxT('C') && c != wxT('D')) return wxEmptyString; wxString out; out.Printf(wxT("REF%03lu%cL"), n, c); return out; }
void COptions::SetServer(wxString path, const CServer& server) { if (!m_pXmlFile) return; if (path.empty()) return; auto element = m_pXmlFile->GetElement(); while (!path.empty()) { wxString sub; int pos = path.Find('/'); if (pos != -1) { sub = path.Left(pos); path = path.Mid(pos + 1); } else { sub = path; path = _T(""); } wxScopedCharBuffer utf8 = sub.utf8_str(); if (!utf8) return; auto newElement = element.child(utf8); if (newElement) element = newElement; else { element = element.append_child(utf8); } } ::SetServer(element, server); if (GetOptionVal(OPTION_DEFAULT_KIOSKMODE) == 2) return; CInterProcessMutex mutex(MUTEX_OPTIONS); m_pXmlFile->Save(true); }
void nmeaSendObj::SetNMEASentence(wxString &sentence) { unsigned int i = 0; while ( i < NeededSentences.GetCount() ) { wxString s = sentence.Left( NeededSentences[i].Length() ); if ( s.Matches(NeededSentences[i]) ) //we have a wildcard match { ReceivedSentencesMap[NeededSentences[i]] = sentence; //save sentence int j = NeededSentencesMinusReceived.Index(NeededSentences[i]); if ( j != wxNOT_FOUND ){//!= wxNOT_FOUND ) NeededSentencesMinusReceived.RemoveAt(j); } } i++; } if ( NeededSentencesMinusReceived.IsEmpty() & ( SendMode == ALLVAL) ) { ComputeOutputSentence(); NeededSentencesMinusReceived = NeededSentences; } }
// old function which only chops '\n' and not '\r\n' wxProtocolError GetLine(wxSocketBase *sock, wxString& result) { #define PROTO_BSIZE 2048 size_t avail, size; char tmp_buf[PROTO_BSIZE], tmp_str[PROTO_BSIZE]; char *ret; bool found; avail = sock->Read(tmp_buf, PROTO_BSIZE).LastCount(); if (sock->Error() || avail == 0) return wxPROTO_NETERR; memcpy(tmp_str, tmp_buf, avail); // Not implemented on all systems // ret = (char *)memccpy(tmp_str, tmp_buf, '\n', avail); found = false; for (ret=tmp_str;ret < (tmp_str+avail); ret++) if (*ret == '\n') { found = true; break; } if (!found) return wxPROTO_PROTERR; *ret = 0; result = wxString::FromAscii( tmp_str ); result = result.Left(result.length()-1); size = ret-tmp_str+1; sock->Unread(&tmp_buf[size], avail-size); return wxPROTO_NOERR; #undef PROTO_BSIZE }
bool OpenInFileManager(const wxString& dir) { bool ret = false; #ifdef __WXMSW__ // Unfortunately under Windows, UTF-8 encoded file:// URLs don't work, so use native paths. // Unfortunatelier, we cannot use this for UNC paths, have to use file:// here // Unfortunateliest, we again have a problem with UTF-8 characters which we cannot fix... if (dir.Left(2) != _T("\\\\") && dir != _T("/")) ret = wxLaunchDefaultBrowser(dir); else #endif { wxString url = GetAsURL(dir); if (!url.IsEmpty()) ret = wxLaunchDefaultBrowser(url); } if (!ret) wxBell(); return ret; }
void Shader::EnableMenu(const wxString& label, bool enable) { int slash = label.Find('/'); if (slash != wxNOT_FOUND) { wxString first = label.Left(slash); wxString second = label.Mid(slash + 1); int id = m_MenuBar->FindMenuItem(first, second); if (id != wxNOT_FOUND) { m_MenuBar->Enable(id, enable); } } else { int pos = m_MenuBar->FindMenu(label); if (pos != wxNOT_FOUND) { m_MenuBar->EnableTop(pos, enable); } } }
bool COptions::GetServer(wxString path, CServer& server) { if (path == _T("")) return false; if (!m_pXmlFile) return false; TiXmlElement *element = m_pXmlFile->GetElement(); while (path != _T("")) { wxString sub; int pos = path.Find('/'); if (pos != -1) { sub = path.Left(pos); path = path.Mid(pos + 1); } else { sub = path; path = _T(""); } char *utf8 = ConvUTF8(sub); if (!utf8) return false; element = element->FirstChildElement(utf8); delete [] utf8; if (!element) return false; } bool res = ::GetServer(element, server); return res; }
// return prefixCode+number if the string is of the form "<prefix><number>" and // 0 if it isn't // // first and last parameter specify the valid domain for "number" part static int IsNumberedAccelKey(const wxString& str, const char *prefix, wxKeyCode prefixCode, unsigned first, unsigned last) { const size_t lenPrefix = wxStrlen(prefix); if ( !CompareAccelString(str.Left(lenPrefix), prefix) ) return 0; unsigned long num; if ( !str.Mid(lenPrefix).ToULong(&num) ) return 0; if ( num < first || num > last ) { // this must be a mistake, chances that this is a valid name of another // key are vanishingly small wxLogDebug(wxT("Invalid key string \"%s\""), str.c_str()); return 0; } return prefixCode + num - first; }
bool CServer::ParseUrl(wxString host, unsigned int port, wxString user, wxString pass, wxString &error, CServerPath &path) { m_type = DEFAULT; if (host == _T("")) { error = _("No host given, please enter a host."); return false; } int pos = host.Find(_T("://")); if (pos != -1) { wxString protocol = host.Left(pos).Lower(); host = host.Mid(pos + 3); if (protocol.Left(3) == _T("fz_")) protocol = protocol.Mid(3); m_protocol = GetProtocolFromPrefix(protocol.Lower()); if (m_protocol == UNKNOWN) { // TODO: http:// once WebDAV is officially supported error = _("Invalid protocol specified. Valid protocols are:\nftp:// for normal FTP,\nsftp:// for SSH file transfer protocol,\nftps:// for FTP over SSL (implicit) and\nftpes:// for FTP over SSL (explicit)."); return false; } } pos = host.Find('@'); if (pos != -1) { // Check if it's something like // user@name:password@host:port/path // => If there are multiple at signs, username/port ends at last at before // the first slash. (Since host and port never contain any at sign) int slash = host.Mid(pos + 1).Find('/'); if (slash != -1) slash += pos + 1; int next_at = host.Mid(pos + 1).Find('@'); while (next_at != -1) { next_at += pos + 1; if (slash != -1 && next_at > slash) break; pos = next_at; next_at = host.Mid(pos + 1).Find('@'); } user = host.Left(pos); host = host.Mid(pos + 1); // Extract password (if any) from username pos = user.Find(':'); if (pos != -1) { pass = user.Mid(pos + 1); user = user.Left(pos); } // Remove leading and trailing whitespace user.Trim(true); user.Trim(false); if (user == _T("")) { error = _("Invalid username given."); return false; } } else { // Remove leading and trailing whitespace user.Trim(true); user.Trim(false); if (user == _T("")) { user = _T("anonymous"); pass = _T("*****@*****.**"); } } pos = host.Find('/'); if (pos != -1) { path = CServerPath(host.Mid(pos)); host = host.Left(pos); } pos = host.Find(':'); if (pos != -1) { if (!pos) { error = _("No host given, please enter a host."); return false; } long tmp; if (!host.Mid(pos + 1).ToLong(&tmp) || tmp < 1 || tmp > 65535) { error = _("Invalid port given. The port has to be a value from 1 to 65535."); return false; } port = tmp; host = host.Left(pos); } else { if (!port) port = GetDefaultPort(m_protocol); else if (port > 65535) { error = _("Invalid port given. The port has to be a value from 1 to 65535."); return false; } } host.Trim(true); host.Trim(false); if (host == _T("")) { error = _("No host given, please enter a host."); return false; } m_host = host; m_port = port; m_user = user; m_pass = pass; m_account = _T(""); if (m_user == _T("") || m_user == _T("anonymous")) m_logonType = ANONYMOUS; else m_logonType = NORMAL; if (m_protocol == UNKNOWN) m_protocol = GetProtocolFromPort(port); return true; }
bool vtElevLayer::ImportFromFile(const wxString &strFileName, bool progress_callback(int), vtElevError *err) { // Avoid trouble with '.' and ',' in Europe - all the file readers assume // the default "C" locale. ScopedLocale normal_numbers(LC_NUMERIC, "C"); wxString strExt = strFileName.AfterLast('.'); vtString fname = (const char *) strFileName.mb_str(wxConvUTF8); VTLOG("ImportFromFile '%s'\n", (const char *) fname); if (!strExt.CmpNoCase(_T("gz"))) { // ignore .gz, look at extension under it wxString dropped = strFileName.Left(strFileName.Len()-3); strExt = dropped.AfterLast('.'); } if (!strExt.CmpNoCase(_T("bz2"))) { // ignore .bz2, look at extension under it wxString dropped = strFileName.Left(strFileName.Len()-4); strExt = dropped.AfterLast('.'); } // The first character in the file is useful for telling which format // the file really is. FILE *fp = vtFileOpen(fname, "rb"); char first = fgetc(fp); fclose(fp); bool success = false; if (!strExt.CmpNoCase(_T("dxf"))) { m_pTin = new vtTin2d; success = m_pTin->ReadDXF(fname, progress_callback); } else if (!strFileName.Right(6).CmpNoCase(_T("xy.adf"))) { m_pTin = new vtTin2d; success = m_pTin->ReadADF(fname, progress_callback); } else if (!strFileName.Right(4).CmpNoCase(_T(".tin"))) { m_pTin = new vtTin2d; success = m_pTin->ReadGMS(fname, progress_callback); } else if (!strFileName.Right(4).CmpNoCase(_T(".ply"))) { m_pTin = new vtTin2d; success = m_pTin->ReadPLY(fname, progress_callback); } else { if (m_pGrid == NULL) m_pGrid = new vtElevationGrid; } if (!strExt.CmpNoCase(_T("3tx"))) { success = m_pGrid->LoadFrom3TX(fname, progress_callback); } else if (!strExt.CmpNoCase(_T("dem"))) { // If there is a .hdr file in the same place, it is most likely // a GTOPO30/SRTM30 file vtString hdr_fname = ChangeFileExtension(fname, ".hdr"); if (vtFileExists(hdr_fname)) success = m_pGrid->LoadFromGTOPO30(hdr_fname, progress_callback); else { if (first == '*') success = m_pGrid->LoadFromMicroDEM(fname, progress_callback); else success = m_pGrid->LoadFromDEM(fname, progress_callback, err); } } else if (!strExt.CmpNoCase(_T("asc"))) { success = m_pGrid->LoadFromASC(fname, progress_callback); // vtElevationGrid does have its own ASC reader, but use GDAL instead // success = m_pGrid->LoadWithGDAL(strFileName.mb_str(wxConvUTF8), progress_callback, err); } else if (!strExt.CmpNoCase(_T("bil"))) { success = m_pGrid->LoadWithGDAL(fname, progress_callback, err); } else if (!strExt.CmpNoCase(_T("mem"))) { success = m_pGrid->LoadWithGDAL(fname, progress_callback, err); } else if (!strExt.CmpNoCase(_T("ter"))) { success = m_pGrid->LoadFromTerragen(fname, progress_callback); } else if (!strExt.CmpNoCase(_T("cdf"))) { success = m_pGrid->LoadWithGDAL(fname, progress_callback, err); } else if (!strExt.CmpNoCase(_T("hdr"))) { success = m_pGrid->LoadFromGTOPO30(fname, progress_callback); if (!success) success = m_pGrid->LoadFromGLOBE(fname, progress_callback); } else if (!strExt.CmpNoCase(_T("dte")) || !strExt.CmpNoCase(_T("dt0")) || !strExt.CmpNoCase(_T("dt1")) || !strExt.CmpNoCase(_T("dt2"))) { success = m_pGrid->LoadFromDTED(fname, progress_callback); } else if (!strExt.Left(3).CmpNoCase(_T("pgm"))) { success = m_pGrid->LoadFromPGM(fname, progress_callback); } else if (!strExt.CmpNoCase(_T("grd"))) { // might by CDF, might be Surfer GRD if (first == 'D') { VTLOG("First character is 'D', attempting load as a Surfer Grid file.\n"); success = m_pGrid->LoadFromGRD(fname, progress_callback); } else { VTLOG("First character is not 'D', attempting load as a netCDF file.\n"); success = m_pGrid->LoadWithGDAL(fname, progress_callback, err); } if (!success) { VTLOG("Didn't load successfully, attempting load with GDAL.\n"); // Might be 'Arc Binary Grid', try GDAL success = m_pGrid->LoadWithGDAL(fname, progress_callback, err); } } else if (!strFileName.Right(8).CmpNoCase(_T("catd.ddf")) || !strExt.Left(3).CmpNoCase(_T("tif")) || !strExt.Left(3).CmpNoCase(_T("png")) || !strExt.Left(3).CmpNoCase(_T("img")) || !strExt.CmpNoCase(_T("adf"))) { if (m_pGrid) success = m_pGrid->LoadWithGDAL(fname, progress_callback, err); } else if (!strExt.CmpNoCase(_T("raw"))) { RawDlg dlg(NULL, -1, _("Raw Elevation File")); dlg.m_iBytes = 2; dlg.m_iWidth = 100; dlg.m_iHeight = 100; dlg.m_fVUnits = 1.0f; dlg.m_fSpacing = 30.0f; dlg.m_bBigEndian = false; dlg.m_extents.SetToZero(); g_bld->GetProjection(dlg.m_original); if (dlg.ShowModal() == wxID_OK) { success = m_pGrid->LoadFromRAW(fname, dlg.m_iWidth, dlg.m_iHeight, dlg.m_iBytes, dlg.m_fVUnits, dlg.m_bBigEndian, progress_callback); } if (success) { m_pGrid->SetEarthExtents(dlg.m_extents); m_pGrid->SetProjection(dlg.m_proj); } } else if (!strExt.CmpNoCase(_T("ntf"))) { success = m_pGrid->LoadFromNTF5(fname, progress_callback); } else if (!strExt.CmpNoCase(_T("txt")) || !strExt.CmpNoCase(_T("xyz"))) { success = m_pGrid->LoadFromXYZ(fname, progress_callback); } else if (!strExt.CmpNoCase(_T("hgt"))) { success = m_pGrid->LoadFromHGT(fname, progress_callback); } else if (!strExt.Left(2).CmpNoCase(_T("db"))) { success = ImportFromDB(fname, progress_callback); } if (!success) return false; vtProjection *pProj; if (m_pGrid) pProj = &m_pGrid->GetProjection(); else pProj = &m_pTin->m_proj; // We should ask for a CRS before asking for extents if (!g_bld->ConfirmValidCRS(pProj)) { if (err) { err->type = vtElevError::CANCELLED; err->message = "Cancelled"; } return false; } if (m_pGrid != NULL) { if (m_pGrid->GetEarthExtents().IsEmpty()) { // No extents. wxString msg = _("File lacks geographic location (extents). Would you like to specify extents?\n Yes - specify extents\n No - use some default values\n"); int res = wxMessageBox(msg, _("Elevation Import"), wxYES_NO | wxCANCEL); if (res == wxYES) { DRECT ext; ext.SetToZero(); ExtentDlg dlg(NULL, -1, _("Elevation Grid Extents")); dlg.SetArea(ext, (pProj->IsGeographic() != 0)); if (dlg.ShowModal() == wxID_OK) m_pGrid->SetEarthExtents(dlg.m_area); else return false; } if (res == wxNO) { // Just make up some fake extents, assuming a regular even grid int xsize, ysize; m_pGrid->GetDimensions(xsize, ysize); DRECT ext; ext.left = ext.bottom = 0; if (pProj->IsGeographic()) { ext.right = xsize * (1.0/3600); // arc second ext.top = ysize * (1.0/3600); } else { ext.right = xsize * 10; // 10 linear units (meters, feet..) ext.top = ysize * 10; } m_pGrid->SetEarthExtents(ext); } if (res == wxCANCEL) { if (err) { err->type = vtElevError::CANCELLED; err->message = "Cancelled"; } return false; } } m_pGrid->SetupLocalCS(1.0f); } return true; }
bool CLocalListView::DisplayDir(wxString dirname) { wxString focused; std::list<wxString> selectedNames; if (m_dir != dirname) { // Clear selection int item = -1; while (true) { item = GetNextItem(item, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED); if (item == -1) break; SetItemState(item, 0, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED); } focused = _T(".."); if (GetItemCount()) EnsureVisible(0); m_dir = dirname; } else { // Remember which items were selected selectedNames = RememberSelectedItems(focused); } const int oldItemCount = m_indexMapping.size(); m_fileData.clear(); m_indexMapping.clear(); m_hasParent = CState::LocalDirHasParent(dirname); if (m_hasParent) { t_fileData data; data.dir = true; data.icon = -2; data.name = _T(".."); data.size = -1; data.hasTime = 0; m_fileData.push_back(data); m_indexMapping.push_back(0); } #ifdef __WXMSW__ if (dirname == _T("\\")) { DisplayDrives(); } else if (dirname.Left(2) == _T("\\\\")) { int pos = dirname.Mid(2).Find('\\'); if (pos != -1 && pos + 3 != (int)dirname.Len()) goto regular_dir; // UNC path without shares DisplayShares(dirname); } else #endif { #ifdef __WXMSW__ regular_dir: #endif CFilterDialog filter; wxDir dir(dirname); if (!dir.IsOpened()) { SetItemCount(1); return false; } wxString file; bool found = dir.GetFirst(&file); int num = m_fileData.size(); while (found) { if (file == _T("")) { wxGetApp().DisplayEncodingWarning(); found = dir.GetNext(&file); continue; } t_fileData data; data.dir = wxFileName::DirExists(dirname + file); data.icon = -2; data.name = file; wxStructStat buf; int result; result = wxStat(dirname + file, &buf); if (!result) { data.hasTime = true; data.lastModified = wxDateTime(buf.st_mtime); } else data.hasTime = false; if (data.dir) data.size = -1; else data.size = result ? -1 : buf.st_size; m_fileData.push_back(data); if (!filter.FilenameFiltered(data.name, data.dir, data.size, true)) m_indexMapping.push_back(num); num++; found = dir.GetNext(&file); } } if (m_dropTarget != -1) { t_fileData* data = GetData(m_dropTarget); if (!data || !data->dir) { SetItemState(m_dropTarget, 0, wxLIST_STATE_DROPHILITED); m_dropTarget = -1; } } const int count = m_indexMapping.size(); if (oldItemCount != count) SetItemCount(count); SortList(); ReselectItems(selectedNames, focused); Refresh(); return true; }
bool wxDirData::Read(wxString *filename) { if ( !m_isDir ) return false ; wxString result; short err = noErr ; while ( err == noErr ) { m_index++ ; m_CPB.dirInfo.ioFDirIndex = m_index; m_CPB.dirInfo.ioDrDirID = m_dirId; /* we need to do this every time */ err = PBGetCatInfoSync((CInfoPBPtr)&m_CPB); if ( err != noErr ) break ; // its hidden but we don't want it if ( ( m_CPB.hFileInfo.ioFlFndrInfo.fdFlags & kIsInvisible ) && !(m_flags & wxDIR_HIDDEN) ) continue ; #ifdef __DARWIN__ // under X, names that start with '.' are hidden if ( ( m_name[1] == '.' ) && !(m_flags & wxDIR_HIDDEN) ) continue; #endif #if TARGET_CARBON // under X thats the way the mounting points look like if ( ( m_CPB.dirInfo.ioDrDirID == 0 ) && ( m_flags & wxDIR_DIRS) ) break ; #endif // we have a directory if ( ( m_CPB.dirInfo.ioFlAttrib & ioDirMask) != 0 && (m_flags & wxDIR_DIRS) ) break ; // its a file but we don't want it if ( ( m_CPB.dirInfo.ioFlAttrib & ioDirMask) == 0 && !(m_flags & wxDIR_FILES ) ) continue ; wxString file = wxMacMakeStringFromPascal( m_name ) ; if ( m_filespec.empty() || m_filespec == wxT("*.*") || m_filespec == wxT("*") ) { } else if ( m_filespec.Length() > 1 && m_filespec.Left(1) == wxT("*") ) { if ( file.Right( m_filespec.Length() - 1 ).Upper() != m_filespec.Mid(1).Upper() ) { continue ; } } else if ( m_filespec.Length() > 1 && m_filespec.Right(1) == wxT("*") ) { if ( file.Left( m_filespec.Length() - 1 ).Upper() != m_filespec.Left( m_filespec.Length() - 1 ).Upper() ) { continue ; } } else if ( file.Upper() != m_filespec.Upper() ) { continue ; } break ; } if ( err != noErr ) { return false ; } *filename = wxMacMakeStringFromPascal( m_name ) ; return true; }
bool IsRoutableAddress(const wxString& address, CSocket::address_family family) { if (family == CSocket::ipv6) { wxString long_address = GetIPV6LongForm(address); if (long_address.size() != 39) return false; if (long_address[0] == '0') { // ::/128 if (long_address == _T("0000:0000:0000:0000:0000:0000:0000:0000")) return false; // ::1/128 if (long_address == _T("0000:0000:0000:0000:0000:0000:0000:0001")) return false; if (long_address.Left(30) == _T("0000:0000:0000:0000:0000:ffff:")) { // IPv4 mapped wxString ipv4 = wxString::Format(_T("%d.%d.%d.%d"), DigitHexToDecNum(long_address[30]) * 16 + DigitHexToDecNum(long_address[31]), DigitHexToDecNum(long_address[32]) * 16 + DigitHexToDecNum(long_address[33]), DigitHexToDecNum(long_address[35]) * 16 + DigitHexToDecNum(long_address[36]), DigitHexToDecNum(long_address[37]) * 16 + DigitHexToDecNum(long_address[38])); return IsRoutableAddress(ipv4, CSocket::ipv4); } return true; } if (long_address[0] == 'f') { if (long_address[1] == 'e') { // fe80::/10 (link local) const wxChar& c = long_address[2]; int v; if (c >= 'a') v = c - 'a' + 10; else v = c - '0'; if ((v & 0xc) == 0x8) return false; return true; } else if (long_address[1] == 'c' || long_address[1] == 'd') { // fc00::/7 (site local) return false; } } return true; } else { // Assumes address is already a valid IP address if (address.Left(3) == _T("127") || address.Left(3) == _T("10.") || address.Left(7) == _T("192.168") || address.Left(7) == _T("169.254")) return false; if (address.Left(3) == _T("172")) { wxString middle = address.Mid(4); int pos = address.Find(_T(".")); wxASSERT(pos != -1); long part; middle.Left(pos).ToLong(&part); if (part >= 16 && part <= 31) return false; } return true; } }
wxString Model_Billsdeposits::toShortStatus(const wxString& fullStatus) { wxString s = fullStatus.Left(1); s.Replace("N", ""); return s; }
long wxExecute(const wxString& cmd, int flags, wxProcess *handler, const wxExecuteEnv *env) { wxCHECK_MSG( !cmd.empty(), 0, wxT("empty command in wxExecute") ); #if wxUSE_THREADS // for many reasons, the code below breaks down if it's called from another // thread -- this could be fixed, but as Unix versions don't support this // neither I don't want to waste time on this now wxASSERT_MSG( wxThread::IsMain(), wxT("wxExecute() can be called only from the main thread") ); #endif // wxUSE_THREADS wxString command; #if wxUSE_IPC // DDE hack: this is really not pretty, but we need to allow this for // transparent handling of DDE servers in wxMimeTypesManager. Usually it // returns the command which should be run to view/open/... a file of the // given type. Sometimes, however, this command just launches the server // and an additional DDE request must be made to really open the file. To // keep all this well hidden from the application, we allow a special form // of command: WX_DDE#<command>#DDE_SERVER#DDE_TOPIC#DDE_COMMAND in which // case we execute just <command> and process the rest below wxString ddeServer, ddeTopic, ddeCommand; static const size_t lenDdePrefix = 7; // strlen("WX_DDE:") if ( cmd.Left(lenDdePrefix) == wxT("WX_DDE#") ) { // speed up the concatenations below ddeServer.reserve(256); ddeTopic.reserve(256); ddeCommand.reserve(256); const wxChar *p = cmd.c_str() + 7; #if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */ # pragma ivdep # pragma swp # pragma unroll # pragma prefetch # if 0 # pragma simd noassert # endif #endif /* VDM auto patch */ while ( *p && *p != wxT('#') ) { command += *p++; } if ( *p ) { // skip '#' p++; } else { wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute")); } #if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */ # pragma ivdep # pragma swp # pragma unroll # pragma prefetch # if 0 # pragma simd noassert # endif #endif /* VDM auto patch */ while ( *p && *p != wxT('#') ) { ddeServer += *p++; } if ( *p ) { // skip '#' p++; } else { wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute")); } #if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */ # pragma ivdep # pragma swp # pragma unroll # pragma prefetch # if 0 # pragma simd noassert # endif #endif /* VDM auto patch */ while ( *p && *p != wxT('#') ) { ddeTopic += *p++; } if ( *p ) { // skip '#' p++; } else { wxFAIL_MSG(wxT("invalid WX_DDE command in wxExecute")); } #if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */ # pragma ivdep # pragma swp # pragma unroll # pragma prefetch # if 0 # pragma simd noassert # endif #endif /* VDM auto patch */ while ( *p ) { ddeCommand += *p++; } // if we want to just launch the program and not wait for its // termination, try to execute DDE command right now, it can succeed if // the process is already running - but as it fails if it's not // running, suppress any errors it might generate if ( !(flags & wxEXEC_SYNC) ) { wxLogNull noErrors; if ( wxExecuteDDE(ddeServer, ddeTopic, ddeCommand) ) { // a dummy PID - this is a hack, of course, but it's well worth // it as we don't open a new server each time we're called // which would be quite bad return -1; } } } else #endif // wxUSE_IPC { // no DDE command = cmd; } // the IO redirection is only supported with wxUSE_STREAMS BOOL redirect = FALSE; #if wxUSE_STREAMS wxPipe pipeIn, pipeOut, pipeErr; // open the pipes to which child process IO will be redirected if needed if ( handler && handler->IsRedirected() ) { // create pipes for redirecting stdin, stdout and stderr if ( !pipeIn.Create() || !pipeOut.Create() || !pipeErr.Create() ) { wxLogSysError(_("Failed to redirect the child process IO")); // indicate failure: we need to return different error code // depending on the sync flag return flags & wxEXEC_SYNC ? -1 : 0; } redirect = TRUE; } #endif // wxUSE_STREAMS // create the process STARTUPINFO si; wxZeroMemory(si); si.cb = sizeof(si); #if wxUSE_STREAMS if ( redirect ) { si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = pipeIn[wxPipe::Read]; si.hStdOutput = pipeOut[wxPipe::Write]; si.hStdError = pipeErr[wxPipe::Write]; // We must set the handles to those sides of std* pipes that we won't // in the child to be non-inheritable. We must do this before launching // the child process as otherwise these handles will be inherited by // the child which will never close them and so the pipe will not // return ERROR_BROKEN_PIPE if the parent or child exits unexpectedly // causing the remaining process to potentially become deadlocked in // ReadFile() or WriteFile(). if ( !::SetHandleInformation(pipeIn[wxPipe::Write], HANDLE_FLAG_INHERIT, 0) ) wxLogLastError(wxT("SetHandleInformation(pipeIn)")); if ( !::SetHandleInformation(pipeOut[wxPipe::Read], HANDLE_FLAG_INHERIT, 0) ) wxLogLastError(wxT("SetHandleInformation(pipeOut)")); if ( !::SetHandleInformation(pipeErr[wxPipe::Read], HANDLE_FLAG_INHERIT, 0) ) wxLogLastError(wxT("SetHandleInformation(pipeErr)")); } #endif // wxUSE_STREAMS // The default logic for showing the console is to show it only if the IO // is not redirected however wxEXEC_{SHOW,HIDE}_CONSOLE flags can be // explicitly specified to change it. if ( (flags & wxEXEC_HIDE_CONSOLE) || (redirect && !(flags & wxEXEC_SHOW_CONSOLE)) ) { si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; } PROCESS_INFORMATION pi; DWORD dwFlags = CREATE_SUSPENDED; if ( (flags & wxEXEC_MAKE_GROUP_LEADER) ) dwFlags |= CREATE_NEW_PROCESS_GROUP; dwFlags |= CREATE_DEFAULT_ERROR_MODE ; wxWxCharBuffer envBuffer; bool useCwd = false; if ( env ) { useCwd = !env->cwd.empty(); // Translate environment variable map into NUL-terminated list of // NUL-terminated strings. if ( !env->env.empty() ) { #if wxUSE_UNICODE // Environment variables can contain non-ASCII characters. We could // check for it and not use this flag if everything is really ASCII // only but there doesn't seem to be any reason to do it so just // assume Unicode by default. dwFlags |= CREATE_UNICODE_ENVIRONMENT; #endif // wxUSE_UNICODE wxEnvVariableHashMap::const_iterator it; size_t envSz = 1; // ending '\0' #if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */ # pragma ivdep # pragma swp # pragma unroll # pragma prefetch # if 0 # pragma simd noassert # endif #endif /* VDM auto patch */ for ( it = env->env.begin(); it != env->env.end(); ++it ) { // Add size of env variable name and value, and '=' char and // ending '\0' envSz += it->first.length() + it->second.length() + 2; } envBuffer.extend(envSz); wxChar *p = envBuffer.data(); #if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */ # pragma ivdep # pragma swp # pragma unroll # pragma prefetch # if 0 # pragma simd noassert # endif #endif /* VDM auto patch */ for ( it = env->env.begin(); it != env->env.end(); ++it ) { const wxString line = it->first + wxS("=") + it->second; // Include the trailing NUL which will always terminate the // buffer returned by t_str(). const size_t len = line.length() + 1; wxTmemcpy(p, line.t_str(), len); p += len; } // And another NUL to terminate the list of NUL-terminated strings. *p = 0; } } // Translate wxWidgets priority to Windows conventions. if ( handler ) { unsigned prio = handler->GetPriority(); if ( prio <= 20 ) dwFlags |= IDLE_PRIORITY_CLASS; else if ( prio <= 40 ) dwFlags |= BELOW_NORMAL_PRIORITY_CLASS; else if ( prio <= 60 ) dwFlags |= NORMAL_PRIORITY_CLASS; else if ( prio <= 80 ) dwFlags |= ABOVE_NORMAL_PRIORITY_CLASS; else if ( prio <= 99 ) dwFlags |= HIGH_PRIORITY_CLASS; else if ( prio <= 100 ) dwFlags |= REALTIME_PRIORITY_CLASS; else { wxFAIL_MSG(wxT("invalid value of thread priority parameter")); dwFlags |= NORMAL_PRIORITY_CLASS; } } bool ok = ::CreateProcess ( NULL, // application name (use only cmd line) wxMSW_CONV_LPTSTR(command), // full command line NULL, // security attributes: defaults for both NULL, // the process and its main thread redirect, // inherit handles if we use pipes dwFlags, // process creation flags envBuffer.data(), // environment (may be NULL which is fine) useCwd // initial working directory ? wxMSW_CONV_LPTSTR(env->cwd) : NULL, // (or use the same) &si, // startup info (unused here) &pi // process info ) != 0; #if wxUSE_STREAMS // we can close the pipe ends used by child anyhow if ( redirect ) { ::CloseHandle(pipeIn.Detach(wxPipe::Read)); ::CloseHandle(pipeOut.Detach(wxPipe::Write)); ::CloseHandle(pipeErr.Detach(wxPipe::Write)); } #endif // wxUSE_STREAMS if ( !ok ) { #if wxUSE_STREAMS // close the other handles too if ( redirect ) { ::CloseHandle(pipeIn.Detach(wxPipe::Write)); ::CloseHandle(pipeOut.Detach(wxPipe::Read)); ::CloseHandle(pipeErr.Detach(wxPipe::Read)); } #endif // wxUSE_STREAMS wxLogSysError(_("Execution of command '%s' failed"), command.c_str()); return flags & wxEXEC_SYNC ? -1 : 0; } #if wxUSE_STREAMS // the input buffer bufOut is connected to stdout, this is why it is // called bufOut and not bufIn wxStreamTempInputBuffer bufOut, bufErr; if ( redirect ) { // We can now initialize the wxStreams wxPipeInputStream * outStream = new wxPipeInputStream(pipeOut.Detach(wxPipe::Read)); wxPipeInputStream * errStream = new wxPipeInputStream(pipeErr.Detach(wxPipe::Read)); wxPipeOutputStream * inStream = new wxPipeOutputStream(pipeIn.Detach(wxPipe::Write)); handler->SetPipeStreams(outStream, inStream, errStream); bufOut.Init(outStream); bufErr.Init(errStream); } #endif // wxUSE_STREAMS // create a hidden window to receive notification about process // termination HWND hwnd = wxCreateHiddenWindow ( &gs_classForHiddenWindow, wxMSWEXEC_WNDCLASSNAME, (WNDPROC)wxExecuteWindowCbk ); wxASSERT_MSG( hwnd, wxT("can't create a hidden window for wxExecute") ); // Alloc data wxExecuteData *data = new wxExecuteData; data->hProcess = pi.hProcess; data->dwProcessId = pi.dwProcessId; data->hWnd = hwnd; data->state = (flags & wxEXEC_SYNC) != 0; if ( flags & wxEXEC_SYNC ) { // handler may be !NULL for capturing program output, but we don't use // it wxExecuteData struct in this case data->handler = NULL; } else { // may be NULL or not data->handler = handler; if (handler) handler->SetPid(pi.dwProcessId); } DWORD tid; HANDLE hThread = ::CreateThread(NULL, 0, wxExecuteThread, (void *)data, 0, &tid); // resume process we created now - whether the thread creation succeeded or // not if ( ::ResumeThread(pi.hThread) == (DWORD)-1 ) { // ignore it - what can we do? wxLogLastError(wxT("ResumeThread in wxExecute")); } // close unneeded handle if ( !::CloseHandle(pi.hThread) ) { wxLogLastError(wxT("CloseHandle(hThread)")); } if ( !hThread ) { wxLogLastError(wxT("CreateThread in wxExecute")); DestroyWindow(hwnd); delete data; // the process still started up successfully... return pi.dwProcessId; } gs_asyncThreads.push_back(hThread); data->hThread = hThread; #if wxUSE_IPC // second part of DDE hack: now establish the DDE conversation with the // just launched process if ( !ddeServer.empty() ) { bool ddeOK; // give the process the time to init itself // // we use a very big timeout hoping that WaitForInputIdle() will return // much sooner, but not INFINITE just in case the process hangs // completely - like this we will regain control sooner or later switch ( ::WaitForInputIdle(pi.hProcess, 10000 /* 10 seconds */) ) { default: wxFAIL_MSG( wxT("unexpected WaitForInputIdle() return code") ); // fall through case WAIT_FAILED: wxLogLastError(wxT("WaitForInputIdle() in wxExecute")); case WAIT_TIMEOUT: wxLogDebug(wxT("Timeout too small in WaitForInputIdle")); ddeOK = false; break; case 0: // ok, process ready to accept DDE requests ddeOK = wxExecuteDDE(ddeServer, ddeTopic, ddeCommand); } if ( !ddeOK ) { wxLogDebug(wxT("Failed to send DDE request to the process \"%s\"."), cmd.c_str()); } } #endif // wxUSE_IPC if ( !(flags & wxEXEC_SYNC) ) { // clean up will be done when the process terminates // return the pid return pi.dwProcessId; } wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL; wxCHECK_MSG( traits, -1, wxT("no wxAppTraits in wxExecute()?") ); void *cookie = NULL; if ( !(flags & wxEXEC_NODISABLE) ) { // disable all app windows while waiting for the child process to finish cookie = traits->BeforeChildWaitLoop(); } // wait until the child process terminates #if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */ # pragma ivdep # pragma swp # pragma unroll # pragma prefetch # if 0 # pragma simd noassert # endif #endif /* VDM auto patch */ while ( data->state ) { #if wxUSE_STREAMS if ( !bufOut.Update() && !bufErr.Update() ) #endif // wxUSE_STREAMS { // don't eat 100% of the CPU -- ugly but anything else requires // real async IO which we don't have for the moment ::Sleep(50); } // we must always process messages for our hidden window or we'd never // get wxWM_PROC_TERMINATED and so this loop would never terminate MSG msg; ::PeekMessage(&msg, data->hWnd, 0, 0, PM_REMOVE); // we may also need to process messages for all the other application // windows if ( !(flags & wxEXEC_NOEVENTS) ) { wxEventLoopBase * const loop = wxEventLoopBase::GetActive(); if ( loop ) loop->Yield(); } } if ( !(flags & wxEXEC_NODISABLE) ) { // reenable disabled windows back traits->AfterChildWaitLoop(cookie); } DWORD dwExitCode = data->dwExitCode; delete data; // return the exit code return dwExitCode; }
wxString Model_Checking::toShortStatus(const wxString& fullStatus) { wxString s = fullStatus.Left(1); s.Replace("N", ""); return s; }
/* * This first function contains the code common to both * Export() and ExportLossy() * * For safety, if the file already exists it stores the filename * the user wants in actualName, and returns a temporary file name. * The calling function should rename the file when it's successfully * exported. */ wxString ExportCommon( AudacityProject *project, wxString format, wxString defaultExtension, bool selectionOnly, double *t0, double *t1, int *numChannels, wxString &actualName, int maxNumChannels, MixerSpec **mixerSpec ) { TrackList *tracks = project->GetTracks(); /* First analyze the selected audio, perform sanity checks, and provide * information as appropriate. */ /* Tally how many are right, left, mono, and make sure at least one track is selected (if selectionOnly==true) */ int numSelected = 0, numLeft = 0, numRight = 0, numMono = 0; float earliestBegin = *t1; float latestEnd = *t0; TrackListIterator iter1(tracks); Track *tr = iter1.First(); while (tr) { if (tr->GetKind() == Track::Wave) { if (tr->GetSelected() || !selectionOnly) { numSelected++; if (tr->GetChannel() == Track::LeftChannel) numLeft++; else if (tr->GetChannel() == Track::RightChannel) numRight++; else if (tr->GetChannel() == Track::MonoChannel) { // It's a mono channel, but it may be panned float pan = ((WaveTrack*)tr)->GetPan(); if (pan == -1.0) numLeft++; else if (pan == 1.0) numRight++; else if (pan == 0) numMono++; else { // Panned partially off-center. Mix as stereo. numLeft++; numRight++; } } if(tr->GetOffset() < earliestBegin) earliestBegin = tr->GetOffset(); if(tr->GetEndTime() > latestEnd) latestEnd = tr->GetEndTime(); } } tr = iter1.Next(); } if(*t0 < earliestBegin) *t0 = earliestBegin; if(*t1 > latestEnd) *t1 = latestEnd; if (numSelected == 0 && selectionOnly) { wxMessageBox(_("No tracks are selected! Use Ctrl-A (Select All)\nChoose Export... to export all tracks."), _("Unable to export"), wxOK | wxICON_INFORMATION); return wxT(""); } /* Detemine if exported file will be stereo or mono or multichannel, and if mixing will occur */ bool downMix = (gPrefs->Read( wxT("/FileFormats/ExportDownMix" ), true ) !=0) ? true:false ; int channels; if( downMix || !mixerSpec ) { if (numRight > 0 || numLeft > 0) channels = 2; else channels = 1; numRight += numMono; numLeft += numMono; if (numLeft > 1 || numRight > 1) if (channels == 2) { ShowWarningDialog(project, wxT("MixStereo"), _("Your tracks will be mixed down to two stereo channels in the exported file.")); } else { ShowWarningDialog(project, wxT("MixMono"), _("Your tracks will be mixed down to a single mono channel in the exported file.")); } } else { ExportMixerDialog md( tracks, selectionOnly, maxNumChannels, NULL, 1, _( "Advanced Mixing Options" ) ); if( md.ShowModal() != wxID_OK ) return wxT( "" ); *mixerSpec = new MixerSpec( *( md.GetMixerSpec() ) ); channels = ( *mixerSpec )->GetNumChannels(); } /* Prepare and display the filename selection dialog */ wxString path = gPrefs->Read(wxT("/DefaultExportPath"), ::wxGetCwd()); wxString nameOnly; wxString extension; wxString defaultName = project->GetName(); wxString fName; wxString maskString; wxString endOfPathSep; #if 0 // this code shouldn't be here --dmazzoni //MERGE exercise exception if (defaultName == wxT("ThrowExceptionOnExport")) { //lda throw("Exercise exception"); } #endif if (defaultExtension.Left(1) == wxT(".")) defaultExtension = defaultExtension.Right(defaultExtension.Length()-1); maskString.Printf(wxT("%s files (*.%s)|*.%s|All files (*.*)|*.*"), format.c_str(), defaultExtension.c_str(), defaultExtension.c_str()); bool fileOkay; do { fileOkay = true; fName = defaultName + wxT(".") + defaultExtension; fName = wxFileSelector(wxString::Format(_("Save %s File As:"), format.c_str()), path, fName, // default file name defaultExtension, maskString, wxSAVE | wxOVERWRITE_PROMPT); if (fName.Length() >= 256) { wxMessageBox (_("Sorry, pathnames longer than 256 characters not supported.")); return wxT(""); } if (fName == wxT("")) return wxT(""); ::wxSplitPath(fName, &path, &nameOnly, &extension); // // Make sure the user doesn't accidentally save the file // as an extension with no name, like just plain ".wav". // if ((nameOnly.Left(1)==wxT(".") && extension==wxT("")) || (nameOnly==wxT("") && extension!=wxT(""))) { wxString prompt = _("Are you sure you want to save the file as \"")+ ::wxFileNameFromPath(fName)+wxT("\"?\n"); int action = wxMessageBox(prompt, wxT("Warning"), wxYES_NO | wxICON_EXCLAMATION, project); fileOkay = (action == wxYES); continue; } // // Check the extension - add the default if it's not there, // and warn user if it's abnormal. // wxString defaultExtension3 = defaultExtension; if (defaultExtension.Length() > 3) defaultExtension = defaultExtension.Left(3); if (extension == wxT("")) { #ifdef __WXMSW__ // Windows prefers 3-char uppercase extensions extension = defaultExtension; #else // Linux and Mac prefer lowercase extensions extension = defaultExtension.Lower(); #endif } else if (extension.Upper() != defaultExtension.Upper() && extension.Upper() != defaultExtension3.Upper()) { #ifdef __WXMSW__ // Windows prefers 3-char extensions defaultExtension3 = defaultExtension3; #endif wxString prompt; prompt.Printf(_("You are about to save a %s file with the name %s.\nNormally these files end in %s, and some programs will not open files with nonstandard extensions.\nAre you sure you want to save the file under this name?"), format.c_str(), (wxT("\"")+nameOnly+wxT(".")+extension+wxT("\"")).c_str(), (wxT("\".")+defaultExtension+wxT("\"")).c_str()); int action = wxMessageBox(prompt, wxT("Warning"), wxYES_NO | wxICON_EXCLAMATION, project); if (action == wxYES) fileOkay = true; else { fileOkay = false; defaultName = nameOnly + wxT(".") + extension; } } if (path.Length() > 0 && path.Last() == wxFILE_SEP_PATH) endOfPathSep = wxT(""); else endOfPathSep = wxFILE_SEP_PATH; fName = path + endOfPathSep + nameOnly + wxT(".") + extension; } while(!fileOkay); /* * Ensure that exporting a file by this name doesn't overwrite * one of the existing files in the project. (If it would * overwrite an existing file, DirManager tries to rename the * existing file.) */ if (!project->GetDirManager()->EnsureSafeFilename(wxFileName(fName))) return wxT(""); gPrefs->Write(wxT("/DefaultExportPath"), path); *numChannels = channels; /* * To be even MORE safe, return a temporary file name based * on this one... */ actualName = fName; int suffix = 0; while(::wxFileExists(fName)) { fName = path + endOfPathSep + nameOnly + wxString::Format(wxT("%d"), suffix) + wxT(".") + extension; suffix++; } return fName; }
bool CFilterManager::FilenameFilteredByFilter(const wxString& name, bool dir, wxLongLong size, unsigned int filterIndex, int attributes) const { wxRegEx regex; const CFilter& filter = m_filters[filterIndex]; if (dir && !filter.filterDirs) return false; else if (!dir && !filter.filterFiles) return false; for (std::vector<CFilterCondition>::const_iterator iter = filter.filters.begin(); iter != filter.filters.end(); iter++) { bool match = false; const CFilterCondition& condition = *iter; switch (condition.type) { case (enum t_filterType)::name: switch (condition.condition) { case 0: if (filter.matchCase) { if (name.Contains(condition.strValue)) match = true; } else { if (name.Lower().Contains(condition.strValue.Lower())) match = true; } break; case 1: if (filter.matchCase) { if (name == condition.strValue) match = true; } else { if (!name.CmpNoCase(condition.strValue)) match = true; } break; case 2: { const wxString& left = name.Left(condition.strValue.Len()); if (filter.matchCase) { if (left == condition.strValue) match = true; } else { if (!left.CmpNoCase(condition.strValue)) match = true; } } break; case 3: { const wxString& right = name.Right(condition.strValue.Len()); if (filter.matchCase) { if (right == condition.strValue) match = true; } else { if (!right.CmpNoCase(condition.strValue)) match = true; } } break; case 4: wxASSERT(condition.pRegEx); if (condition.pRegEx && condition.pRegEx->Matches(name)) match = true; } break; case (enum t_filterType)::size: if (size == -1) continue; switch (condition.condition) { case 0: if (size > condition.value) match = true; break; case 1: if (size == condition.value) match = true; break; case 2: if (size < condition.value) match = true; break; } break; case (enum t_filterType)::attributes: #ifndef __WXMSW__ continue; #else if (!attributes) continue; { int flag = 0; switch (condition.condition) { case 0: flag = FILE_ATTRIBUTE_ARCHIVE; break; case 1: flag = FILE_ATTRIBUTE_COMPRESSED; break; case 2: flag = FILE_ATTRIBUTE_ENCRYPTED; break; case 3: flag = FILE_ATTRIBUTE_HIDDEN; break; case 4: flag = FILE_ATTRIBUTE_READONLY; break; case 5: flag = FILE_ATTRIBUTE_SYSTEM; break; } int set = (flag & attributes) ? 1 : 0; if (set == condition.value) match = true; } #endif //__WXMSW__ break; case permissions: #ifdef __WXMSW__ continue; #else if (attributes == -1) continue; { int flag = 0; switch (condition.condition) { case 0: flag = S_IRUSR; break; case 1: flag = S_IWUSR; break; case 2: flag = S_IXUSR; break; case 3: flag = S_IRGRP; break; case 4: flag = S_IWGRP; break; case 5: flag = S_IXGRP; break; case 6: flag = S_IROTH; break; case 7: flag = S_IWOTH; break; case 8: flag = S_IXOTH; break; } int set = (flag & attributes) ? 1 : 0; if (set == condition.value) match = true; } #endif //__WXMSW__ break; default: wxFAIL_MSG(_T("Unhandled filter type")); break; } if (match) { if (filter.matchType == CFilter::any) return true; else if (filter.matchType == CFilter::none) return false; } else { if (filter.matchType == CFilter::all) return false; } } if (filter.matchType != CFilter::any) return true; return false; }
void DebuggerTree::ParseEntry(WatchTreeEntry& entry, Watch* watch, wxString& text, long array_index) { if (text.IsEmpty()) return; // Manager::Get()->GetLogManager()->DebugLog(F(_T("DebuggerTree::ParseEntry(): %s"), text.c_str())); while (1) { // trim the string from left and right text.Trim(true); text.Trim(false); // find position of '{', '}' and ',' ***outside*** of any quotes. // decide which is nearer to the start int braceOpenPos = FindCharOutsideQuotes(text, _T('{')); if (braceOpenPos == -1) braceOpenPos = 0xFFFFFE; int braceClosePos = FindCharOutsideQuotes(text, _T('}')); if (braceClosePos == -1) braceClosePos = 0xFFFFFE; int commaPos = FindCommaPos(text); if (commaPos == -1) commaPos = 0xFFFFFE; int pos = std::min(commaPos, std::min(braceOpenPos, braceClosePos)); if (pos == 0xFFFFFE) { // no comma, opening or closing brace if (text.Right(3).Matches(_T(" = "))) text.Truncate(text.Length() - 3); if (!text.IsEmpty()) { entry.AddChild(text, watch); text.Clear(); } break; } else { // display array on a single line? // normal (multiple lines) display is taken care below, with array indexing if (watch && watch->is_array && braceOpenPos != 0xFFFFFE && braceClosePos != 0xFFFFFE) { wxString tmp = text.Left(braceClosePos + 1); // if more than one opening/closing brace, then it's a complex array so // ignore single-line if (text.Freq(_T('{')) == 1 && text.Freq(_T('}')) == 1) { // array on single line for up to 8 (by default) elements // if more elements, fall through to the multi-line display int commas = Manager::Get()->GetConfigManager(_T("debugger"))->ReadInt(_T("/single_line_array_elem_count"), 8); if (tmp.Freq(_T(',')) < commas) { // array watch type tmp[braceOpenPos] = _T('['); tmp.Last() = _T(']'); entry.AddChild(tmp, watch); text.Remove(0, braceClosePos + 1); continue; } } } wxString tmp = text.Left(pos); WatchTreeEntry* newchild = 0; if (tmp.Right(3).Matches(_T(" = "))) tmp.Truncate(tmp.Length() - 3); // remove " = " if last in string if (!tmp.IsEmpty()) { // take array indexing into account (if applicable) if (array_index != -1) { tmp.Prepend(wxString::Format(_T("[%ld]: "), array_index)); // if array element would occur multiple times, gdb adds as default "<repeated xx times> to the output // so we have to look for it and increase the array_index correctly // as default we increase by 1 long incIndex = 1; if (reRepeatedElements.Matches(tmp)) { reRepeatedElements.GetMatch(tmp, 1).ToLong(&incIndex); } array_index += incIndex; } newchild = &entry.AddChild(tmp, watch); } text.Remove(0, pos + 1); if (pos == braceOpenPos) { if (!newchild) newchild = &entry; // enable array indexing (if applicable) bool no_indexing = array_index == -1; if (watch && watch->is_array && no_indexing && text.Freq(_T('{')) == 0 && text.Freq(_T('}')) == 1) // don't index complex arrays { array_index = 0; } ParseEntry(*newchild, watch, text, array_index); // proceed one level deeper // reset array indexing if (no_indexing) array_index = -1; } else if (pos == braceClosePos) break; // return one level up } } }
wxString CRCppEmitter::BreakString (const wxString &str, const wxArrayString &breakStrs, unsigned int &idx, size_t minIdx, bool isCode) const { if (str.Length () > m_maxChars) { size_t foundIdx = 0; size_t maxFoundIdx = 0; unsigned int breakStrsIdx = 0; for (size_t i = 0; i < breakStrs.Count (); i++) { // Blanks at the line ends can be omitted (unless it is code): int breakStrLen; if (isCode) { breakStrLen = breakStrs.Item (i).Length (); } else { breakStrLen = breakStrs.Item (i).Strip ().Length (); } foundIdx = str.rfind (breakStrs.Item (i), m_maxChars - breakStrLen); if (foundIdx != wxString::npos) { // Prevent line break in non-integer number code emitting: if (breakStrs.Item (i) == _T(".")) { // 1. Check that "." is not in a string wxString line = str.Left (foundIdx); if (!HasBrokenInString(line)) { // 2. Check that all characters before "." are digits, // prepended by "," and whitespace int charIdx = foundIdx - 1; bool foundComma = false; bool foundWhitespace = false; bool finished = false; while (charIdx > 0 && !finished) { if (isdigit (line.GetChar (charIdx))) { if (foundWhitespace || foundComma) { finished = true; } charIdx--; } else if (line.GetChar (charIdx) == ' ') { if (foundComma) { finished = true; } foundWhitespace = true; charIdx--; } else if (line.GetChar (charIdx) == ',') { finished = true; foundComma = true; foundIdx = 0; } else { finished = true; } } } } if (foundIdx > maxFoundIdx) { maxFoundIdx = foundIdx; breakStrsIdx = i; } } } // No breaking string found, break by brute force: if ((maxFoundIdx == 0) || ((minIdx != wxString::npos) && (maxFoundIdx < minIdx))) { idx = m_maxChars; return str.Left (m_maxChars); } else { idx = maxFoundIdx + breakStrs.Item (breakStrsIdx).Length (); // Blanks at the line ends can be omitted (unless it is code): wxString firstLine; if (isCode) { firstLine = str.Left (idx); } else { firstLine = str.Left (idx).Strip (); } return firstLine; } } else { idx = 0; return str; } }