void wxGridCellNumberEditor::StartingKey(wxKeyEvent& event) { int keycode = event.GetKeyCode(); if ( !HasRange() ) { if ( wxIsdigit(keycode) || keycode == '+' || keycode == '-') { wxGridCellTextEditor::StartingKey(event); // skip Skip() below return; } } #if wxUSE_SPINCTRL else { if ( wxIsdigit(keycode) ) { wxSpinCtrl* spin = (wxSpinCtrl*)m_control; spin->SetValue(keycode - '0'); spin->SetSelection(1,1); return; } } #endif event.Skip(); }
double wxPdfUtility::String2Double(const wxString& str) { wxString value = str.Strip(wxString::both); double result = 0; double sign = 1; int scale = 0; int exponent = 0; int expsign = 1; int j = 0; int jMax = (int) value.Length(); if (jMax > 0) { if (value[j] == wxT('+')) { j++; } else if (value[j] == wxT('-')) { sign = -1; j++; } while (j < jMax && wxIsdigit(value[j])) { result = result*10 + (value[j] - wxT('0')); j++; } if (j < jMax && value[j] == wxT('.')) { j++; while (j < jMax && wxIsdigit(value[j])) { result = result*10 + (value[j] - wxT('0')); scale++; j++; } } if (j < jMax && (value[j] == wxT('E') || value[j] == wxT('e'))) { j++; if (value[j] == wxT('+')) { j++; } else if (value[j] == wxT('-')) { expsign = -1; j++; } while (j < jMax && wxIsdigit(value[j])) { exponent = exponent*10 + (value[j] - wxT('0')); j++; } exponent *= expsign; } result = sign * result * pow(10.0, exponent-scale); } return result; }
// [Russell] - These are 2 heavily modified routines of the javascript natural // compare by Kristof Coomans (it was easier to follow than the original C // version by Martin Pool), their versions were under the ZLIB license (which // is compatible with the GPL). // // Original Javascript version by Kristof Coomans // http://sourcefrog.net/projects/natsort/natcompare.js // // Do not contact the mentioned authors about my version. wxInt32 NaturalCompareWorker(const wxString &String1, const wxString &String2) { wxInt32 Direction = 0; wxChar String1Char, String2Char; for (wxUint32 String1Counter = 0, String2Counter = 0; String1.Len() > 0 && String2.Len() > 0; ++String1Counter, ++String2Counter) { String1Char = String1[String1Counter]; String2Char = String2[String2Counter]; if (!wxIsdigit(String1Char) && !wxIsdigit(String2Char)) { return Direction; } if (!wxIsdigit(String1Char)) { return -1; } if (!wxIsdigit(String2Char)) { return 1; } if (String1Char < String2Char) { if (Direction == 0) { Direction = -1; } } if (String1Char > String2Char) { if (Direction == 0) { Direction = 1; } } if (String1Char == 0 && String2Char == 0) { return Direction; } } return 0; }
ExpressionNode::ExpressionNodeType ExpressionNode::ParseNodeType(wxString token) { if (token.IsEmpty()) return ExpressionNode::Unknown; else if (token == ExpressionConsts::Plus) return ExpressionNode::Plus; else if (token == ExpressionConsts::Subtract) return ExpressionNode::Subtract; else if (token == ExpressionConsts::Multiply) return ExpressionNode::Multiply; else if (token == ExpressionConsts::Divide) return ExpressionNode::Divide; else if (token == ExpressionConsts::Mod) return ExpressionNode::Mod; else if (token == ExpressionConsts::Power) return ExpressionNode::Power; else if (token == ExpressionConsts::LParenthesis) return ExpressionNode::LParenthesis; else if (token == ExpressionConsts::RParenthesis) return ExpressionNode::RParenthesis; else if (token == ExpressionConsts::BitwiseAnd) return ExpressionNode::BitwiseAnd; else if (token == ExpressionConsts::BitwiseOr) return ExpressionNode::BitwiseOr; else if (token == ExpressionConsts::And) return ExpressionNode::And; else if (token == ExpressionConsts::Or) return ExpressionNode::Or; else if (token == ExpressionConsts::Not) return ExpressionNode::Not; else if (token == ExpressionConsts::Equal) return ExpressionNode::Equal; else if (token == ExpressionConsts::Unequal) return ExpressionNode::Unequal; else if (token == ExpressionConsts::GT) return ExpressionNode::GT; else if (token == ExpressionConsts::LT) return ExpressionNode::LT; else if (token == ExpressionConsts::GTOrEqual) return ExpressionNode::GTOrEqual; else if (token == ExpressionConsts::LTOrEqual) return ExpressionNode::LTOrEqual; else if (token == ExpressionConsts::LShift) return ExpressionNode::LShift; else if (token == ExpressionConsts::RShift) return ExpressionNode::RShift; else { if (wxIsdigit(token[0])) return ExpressionNode::Numeric; else return ExpressionNode::Unknown; } }
HighlightLanguage EditorColourSet::AddHighlightLanguage(int lexer, const wxString& name) { if ( lexer <= wxSCI_LEX_NULL || lexer > wxSCI_LEX_LAST // this is a C::B extension to wxscintilla.h || name.IsEmpty() ) { return HL_NONE; } // fix name to be XML compliant wxString newID; size_t pos = 0; while (pos < name.Length()) { wxChar ch = name[pos]; if (wxIsalnum(ch) || ch == _T('_')) newID.Append(ch); // valid character else if (wxIsspace(ch)) newID.Append(_T('_')); // convert spaces to underscores ++pos; } // make sure it's not starting with a number or underscore. // if it is, prepend an 'A' if (wxIsdigit(newID.GetChar(0)) || newID.GetChar(0) == _T('_')) newID.Prepend(_T('A')); if (GetHighlightLanguage(newID) != HL_NONE) return HL_NONE; m_Sets[newID].m_Langs = name; m_Sets[newID].m_Lexers = lexer; return newID; }
bool wxGridCellFloatEditor::IsAcceptedKey(wxKeyEvent& event) { if ( wxGridCellEditor::IsAcceptedKey(event) ) { const int keycode = event.GetKeyCode(); if ( wxIsascii(keycode) ) { #if wxUSE_INTL const wxString decimalPoint = wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT, wxLOCALE_CAT_NUMBER); #else const wxString decimalPoint(wxT('.')); #endif // accept digits, 'e' as in '1e+6', also '-', '+', and '.' if ( wxIsdigit(keycode) || tolower(keycode) == 'e' || keycode == decimalPoint || keycode == '+' || keycode == '-' ) { return true; } } } return false; }
void wxTextValidator::OnChar(wxKeyEvent& event) { /* if ( !M_VTEXTDATA ) return; */ if ( m_validatorWindow ) { int keyCode = event.GetKeyCode(); // we don't filter special keys and Delete if ( !(keyCode < WXK_SPACE || keyCode == WXK_DELETE || keyCode > WXK_START) && ( ((m_validatorStyle & wxFILTER_INCLUDE_CHAR_LIST) && !IsInCharIncludes(wxString((wxChar) keyCode, 1))) || ((m_validatorStyle & wxFILTER_EXCLUDE_CHAR_LIST) && !IsNotInCharExcludes(wxString((wxChar) keyCode, 1))) || ((m_validatorStyle & wxFILTER_ASCII) && !isascii(keyCode)) || ((m_validatorStyle & wxFILTER_ALPHA) && !wxIsalpha(keyCode)) || ((m_validatorStyle & wxFILTER_ALPHANUMERIC) && !wxIsalnum(keyCode)) || ((m_validatorStyle & wxFILTER_NUMERIC) && !wxIsdigit(keyCode) && keyCode != '.' && keyCode != ',' && keyCode != '-') ) ) { if ( !wxValidator::IsSilent() ) wxBell(); // eat message return; } } event.Skip(); }
void wxGridCellFloatEditor::StartingKey(wxKeyEvent& event) { int keycode = event.GetKeyCode(); char tmpbuf[2]; tmpbuf[0] = (char) keycode; tmpbuf[1] = '\0'; wxString strbuf(tmpbuf, *wxConvCurrent); #if wxUSE_INTL bool is_decimal_point = ( strbuf == wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT, wxLOCALE_CAT_NUMBER) ); #else bool is_decimal_point = ( strbuf == wxT(".") ); #endif if ( wxIsdigit(keycode) || keycode == '+' || keycode == '-' || is_decimal_point ) { wxGridCellTextEditor::StartingKey(event); // skip Skip() below return; } event.Skip(); }
bool wxFieldMaskData::IsValidInput(wxChar chNewChar) { bool bIsValidInput=FALSE; switch(m_eType) { // These are the input types. case MaskDataTypeDIGIT: bIsValidInput=wxIsdigit(chNewChar) != 0; break; case MaskDataTypeALPHANUMERIC: bIsValidInput=wxIsalnum(chNewChar) != 0; break; case MaskDataTypeALPHABETIC: case MaskDataTypeALPHAETICUPPER: case MaskDataTypeALPHAETICLOWER: bIsValidInput=wxIsalpha(chNewChar) != 0; break; case MaskDataTypeCHARACTER: if((chNewChar >= 32) && (chNewChar <= 126)) bIsValidInput=TRUE; if((chNewChar >= 128) && (chNewChar <= 255)) bIsValidInput = TRUE; break; } return bIsValidInput; }
bool wxExViMacros::StartsWith(const std::string& text) const { if (text.empty()) { return false; } if (wxIsdigit(text[0])) { return false; } for (const auto& it : m_Macros) { if (it.first.substr(0, text.size()) == text) { return true; } } for (const auto& it : m_Variables) { if (it.first.substr(0, text.size()) == text) { return true; } } return false; }
// DateCtrl void DateCtrl::OnChar(wxKeyEvent& event) { size_t keycode = event.GetKeyCode(); size_t point = GetInsertionPoint(); wxString value = GetValue(); long from, to; GetSelection(&from, &to); if ( from != to ) { value = DATE_PATTERN; } if ( WXK_BACK == keycode ) { size_t prevPoint = point - 1; if ( prevPoint >= 0 && prevPoint != 4 && prevPoint != 7 && value.Length() == 10 ) { value[prevPoint] = 32; SetValue(value); size_t prevPrev = prevPoint - 1; if ( prevPrev == 4 || prevPrev == 7 ) { SetInsertionPoint(prevPrev); } else { SetInsertionPoint(prevPoint); } } } else if ( WXK_DELETE == keycode ) { if ( point != 4 && point != 7 && value.Length() == 10 ) { value[point] = 32; SetValue(value); SetInsertionPoint(point); } } else if ( !wxIsprint((int)keycode) ) { event.Skip(); } else if ( point >= 10 ) { event.Skip(); } else { if ( point == 4 || point == 7 ) { point++; } // compatibility with pattern must be here if ( value.Length() != 10 ) { value = DATE_PATTERN; } if ( wxIsdigit((int)keycode) ) { value[point] = event.GetKeyCode(); SetValue(value); SetInsertionPoint(point+1); } } }
static inline bool wxIsNumeric(int keycode) { return keycode == wxT('.') || keycode == wxT(',') || keycode == wxT('e') || keycode == wxT('E') || keycode == wxT('+') || keycode == wxT('-') || wxIsdigit(keycode); }
bool wxPdfBarCodeCreator::I25(double xpos, double ypos, const wxString& code, double basewidth, double height) { // wide/narrow codes for the digits wxString locCode = code; double wide = basewidth; double narrow = basewidth / 3 ; double lineWidth; if ((locCode.Length() > 0 && !wxIsdigit(locCode[0])) || !locCode.IsNumber()) { return false; } // add leading zero if code-length is odd if (locCode.Length() % 2 != 0) { locCode = wxT("0") + locCode; } m_document->SetFont(wxT("Helvetica"), wxT(""), 10); m_document->Text(xpos, ypos + height + 4, locCode); m_document->SetFillColour(0); // add start and stop codes locCode = wxT("AA") + locCode + wxT("ZA"); size_t i; for (i = 0; i < locCode.Length(); i += 2) { // choose next pair of digits int digitBar = i25_chars.Find(locCode[i]); int digitSpace = i25_chars.Find(locCode[i+1]); // create a wide/narrow-sequence (first digit=bars, second digit=spaces) wxString seq = wxT(""); size_t j; for (j = 0; j < i25_barChar[digitBar].Length(); j++) { seq += wxString(i25_barChar[digitBar][j]) + wxString(i25_barChar[digitSpace][j]); } for (j = 0; j < seq.Length(); j++) { // set lineWidth depending on value lineWidth = (seq[j] == wxT('n')) ? narrow : wide; // draw every second value, because the second digit of the pair is represented by the spaces if (j % 2 == 0) { m_document->Rect(xpos, ypos, lineWidth, height, wxPDF_STYLE_FILL); } xpos += lineWidth; } } return true; }
static bool wxIsNumeric(const wxString& val) { int i; for ( i = 0; i < (int)val.Length(); i++) { // Allow for "," (French) as well as "." -- in future we should // use wxSystemSettings or other to do better localisation if ((!wxIsdigit(val[i])) && (val[i] != '.') && (val[i] != ',') && (val[i] != wxT('e')) && (val[i] != wxT('E')) && (val[i] != wxT('+')) && (val[i] != wxT('-'))) return false; } return true; }
static bool wxIsNumeric(const wxString& val) { for ( wxString::const_iterator i = val.begin(); i != val.end(); ++i ) { // Allow for "," (French) as well as "." -- in future we should // use wxSystemSettings or other to do better localisation if ((!wxIsdigit(*i)) && (*i != wxS('.')) && (*i != wxS(',')) && (*i != wxS('e')) && (*i != wxS('E')) && (*i != wxS('+')) && (*i != wxS('-'))) return false; } return true; }
void mmCalcValidator::OnChar(wxKeyEvent& event) { if (!m_validatorWindow) return event.Skip(); int keyCode = event.GetKeyCode(); // we don't filter special keys and delete if (keyCode < WXK_SPACE || keyCode == WXK_DELETE || keyCode >= WXK_START) return event.Skip(); wxString str((wxUniChar)keyCode, 1); if (!(wxIsdigit(str[0]) || wxString("+-.,*/ ()").Contains(str))) { if ( !wxValidator::IsSilent() ) wxBell(); return; // eat message } // only if it's a wxTextCtrl mmTextCtrl* text_field = wxDynamicCast(m_validatorWindow, mmTextCtrl); if (!m_validatorWindow || !text_field) return event.Skip(); wxChar decChar = text_field->currency_->DECIMAL_POINT[0]; bool numpad_dec_swap = (wxGetKeyState(wxKeyCode(WXK_NUMPAD_DECIMAL)) && decChar != str); if (numpad_dec_swap) str = wxString(decChar); // if decimal point, check if it's already in the string if (str == '.' || str == ',') { const wxString value = text_field->GetValue(); size_t ind = value.rfind(decChar); if (ind < value.Length()) { // check if after last decimal point there is an operation char (+-/*) if (value.find('+', ind + 1) >= value.Length() && value.find('-', ind + 1) >= value.Length() && value.find('*', ind + 1) >= value.Length() && value.find('/', ind + 1) >= value.Length()) return; } } if (numpad_dec_swap) return text_field->WriteText(str); else event.Skip(); }
bool wxGridCellNumberEditor::IsAcceptedKey(wxKeyEvent& event) { if ( wxGridCellEditor::IsAcceptedKey(event) ) { int keycode = event.GetKeyCode(); if ( (keycode < 128) && (wxIsdigit(keycode) || keycode == '+' || keycode == '-')) { return true; } } return false; }
// valid zip codes are of the form DDDDD or DDDDD-DDDD // where D is a digit from 0 to 9, returns the validated zip code bool wxPdfBarCodeCreator::ZipCodeValidate(const wxString& zipcode) { bool valid = true; if (zipcode.Length() == 5 || zipcode.Length() == 10) { // check that all characters are numeric size_t i; for (i = 0; valid && i < zipcode.Length(); i++ ) { if ((i != 5 && !wxIsdigit(zipcode[i])) || (i == 5 && zipcode[5] != wxT('-'))) { valid = false; } } } else { valid = false; } return valid; }
void MyValidator::OnChar(wxKeyEvent& event) { if (m_validatorWindow) { int keyCode = event.GetKeyCode(); // we don't filter special keys and Delete if (!(keyCode < WXK_SPACE || keyCode == WXK_DELETE || keyCode > WXK_START)) { bool chOk = true; switch (m_type) { case MYVAL_ANY: break; case MYVAL_NUMERIC: chOk = (wxIsdigit(keyCode) != 0); break; case MYVAL_HEX: chOk = (wxIsxdigit(keyCode) != 0); break; case MYVAL_HOST: chOk = (wxIsalnum(keyCode) || (keyCode == _T('.')) || (keyCode == _T('-'))); break; case MYVAL_FILENAME: chOk = (wxFileName::GetForbiddenChars().Find(keyCode) == -1); break; } if (!chOk) { if (!wxValidator::IsSilent()) wxBell(); // eat message return; } } } if (m_ktc) m_ktc->KeyTyped(); event.Skip(); }
void Compiler::MakeValidID() { // basically, make it XML-element compatible // only allow a-z, 0-9 and _ // (it is already lowercase) // any non-conformant character will be removed wxString newID; if (m_ID.IsEmpty()) m_ID = m_Name; size_t pos = 0; while (pos < m_ID.Length()) { wxChar ch = m_ID[pos]; if (wxIsalnum(ch) || ch == _T('_')) // valid character newID.Append(ch); else if (wxIsspace(ch)) // convert spaces to underscores newID.Append(_T('_')); ++pos; } // make sure it's not starting with a number. // if it is, prepend "cb" if (wxIsdigit(newID.GetChar(0))) newID.Prepend(_T("cb")); if (newID.IsEmpty()) // empty? wtf? cbThrow(_T("Can't create a valid compiler ID for ") + m_Name); m_ID = newID.Lower(); // check for unique ID if (!IsUniqueID(m_ID)) cbThrow(_T("Compiler ID already exists for ") + m_Name); m_CompilerIDs.Add(m_ID); }
inline bool ParseGDBWatchValue(cb::shared_ptr<GDBWatch> watch, wxString const &value, int &start, int length) { watch->SetDebugValue(value); watch->MarkChildsAsRemoved(); int position = start; Token token, token_name, token_value; wxString pythonToStringValue; bool skip_comma = false; bool last_was_closing_brace = false; int added_children = 0; int token_real_end = 0; while (GetNextToken(value, position, token)) { token_real_end = token.end; token.Trim(value); const wxString &str = token.ExtractString(value); if (str.StartsWith(wxT("members of "))) { wxString::size_type pos = str.find(wxT('\n')); if (pos == wxString::npos) { // If the token has no '\n' character, then we have to search the whole value // for the token and then we skip this token completely. wxString::size_type pos_val = value.find(wxT('\n'), token_real_end); if (pos_val == wxString::npos) return false; position = pos_val+1; if (length > 0 && position >= start + length) break; continue; } else { // If we have the '\n' in the token, then we have the next valid token, too, // so we correct the current token to be the correct one. if (str.find_last_of(wxT(':'), pos) == wxString::npos) return false; token.start += pos + 2; token.Trim(value); } } if (!token.hasRepeatedChar && regexRepeatedChar.Matches(str)) { Token expanded_token = token; while (1) { if (value[expanded_token.end] == wxT(',')) { position = token.end + 1; token_real_end = position; int comma_end = expanded_token.end; if (GetNextToken(value, position, expanded_token)) { const wxString &expanded_str = expanded_token.ExtractString(value); if (!expanded_str.empty() && (expanded_str[0] != wxT('"') && expanded_str[0] != wxT('\''))) { token.end = comma_end; position = comma_end; token_real_end = comma_end; break; } token.end = expanded_token.end; if (regexRepeatedChar.Matches(expanded_str)) continue; token_real_end = expanded_token.end; } } else if (expanded_token.end == static_cast<int>(value.length())) { token.end = expanded_token.end; token_real_end = expanded_token.end; } break; } } switch (token.type) { case Token::String: if (token_name.type == Token::Undefined) token_name = token; else if (token_value.type == Token::Undefined) { if ( wxIsdigit(str[0]) || str[0]==wxT('\'') || str[0]==wxT('"') || str[0]==wxT('<') || str[0]==wxT('-') || str.StartsWith(wxT("L\"")) || str.StartsWith(wxT("L'")) ) { token_value = token; } else { // Detect strings generated by python pretty printing to_string() method. Token expanded_token = token; int firstCloseBrace = -1; for (; expanded_token.end < static_cast<int>(value.length()); ++expanded_token.end) { if (value[expanded_token.end] == wxT('=')) { bool foundBrace = false; for (int ii = expanded_token.end + 1; ii < static_cast<int>(value.length()); ++ii) { if (value[ii] == wxT('{')) { foundBrace = true; break; } else if (value[ii] != wxT(' ') && value[ii] != wxT('\t') && value[ii] != wxT('\n') && value[ii] != wxT(' ')) { break; } } if (foundBrace) { token.end = token_real_end = expanded_token.end; token_value = token; token_value.end--; pythonToStringValue = token_value.ExtractString(value); } else { while (expanded_token.end >= 0) { if (value[expanded_token.end] == wxT(',')) { token.end = token_real_end = expanded_token.end; token_value = token; pythonToStringValue = token_value.ExtractString(value); break; } expanded_token.end--; } } break; } else if (firstCloseBrace == -1 && value[expanded_token.end] == wxT('}')) { firstCloseBrace=expanded_token.end; break; } } if (pythonToStringValue.empty()) { if (firstCloseBrace == -1) return false; token.end = token_real_end = firstCloseBrace; token_value = token; pythonToStringValue = token_value.ExtractString(value); if (pythonToStringValue.empty()) return false; } } } else return false; last_was_closing_brace = false; break; case Token::Equal: last_was_closing_brace = false; break; case Token::Comma: pythonToStringValue = wxEmptyString; last_was_closing_brace = false; if (skip_comma) skip_comma = false; else { if (token_name.type != Token::Undefined) { if (token_value.type != Token::Undefined) { cb::shared_ptr<GDBWatch> child = AddChild(watch, value, token_name); child->SetValue(token_value.ExtractString(value)); } else { int start_arr = watch->IsArray() ? watch->GetArrayStart() : 0; cb::shared_ptr<GDBWatch> child = AddChild(watch, wxString::Format(wxT("[%d]"), start_arr + added_children)); child->SetValue(token_name.ExtractString(value)); } token_name.type = token_value.type = Token::Undefined; added_children++; } else return false; } break; case Token::OpenBrace: { cb::shared_ptr<GDBWatch> child; if(token_name.type == Token::Undefined) { int start_arr = watch->IsArray() ? watch->GetArrayStart() : 0; child = AddChild(watch, wxString::Format(wxT("[%d]"), start_arr + added_children)); } else child = AddChild(watch, value, token_name); if (!pythonToStringValue.empty()) child->SetValue(pythonToStringValue); position = token_real_end; added_children++; if(!ParseGDBWatchValue(child, value, position, 0)) return false; token_real_end = position; token_name.type = token_value.type = Token::Undefined; skip_comma = true; last_was_closing_brace = true; } break; case Token::CloseBrace: if (!last_was_closing_brace) { if (token_name.type != Token::Undefined) { if (token_value.type != Token::Undefined) { cb::shared_ptr<GDBWatch> child = AddChild(watch, value, token_name); child->SetValue(token_value.ExtractString(value)); } else { int start_arr = watch->IsArray() ? watch->GetArrayStart() : 0; cb::shared_ptr<GDBWatch> child = AddChild(watch, wxString::Format(wxT("[%d]"), start_arr + added_children)); child->SetValue(token_name.ExtractString(value)); } token_name.type = token_value.type = Token::Undefined; added_children++; } else watch->SetValue(wxT("")); } start = token_real_end; return true; case Token::Undefined: default: return false; } position = token_real_end; if (length > 0 && position >= start + length) break; } start = position + 1; if (token_name.type != Token::Undefined) { if (token_value.type != Token::Undefined) { cb::shared_ptr<GDBWatch> child = AddChild(watch, value, token_name); child->SetValue(token_value.ExtractString(value)); } else { int start_arr = watch->IsArray() ? watch->GetArrayStart() : 0; cb::shared_ptr<GDBWatch> child = AddChild(watch, wxString::Format(wxT("[%d]"), start_arr + added_children)); child->SetValue(token_name.ExtractString(value)); } } return true; }
//vfc add bGetValue wxString Tokenizer::DoGetToken(bool bGetValue, bool bTemplate) { if (IsEOF()) return wxEmptyString; if (!SkipWhiteSpace()) return wxEmptyString; if (m_SkipUnwantedTokens && !SkipUnwanted(bGetValue)) return wxEmptyString; // if m_SkipUnwantedTokens is false, we need to handle comments here too if (!m_SkipUnwantedTokens) SkipComment(); int start = m_TokenIndex; wxString m_Str; wxChar c = CurrentChar(); if (c == '_' || wxIsalpha(c)) { // keywords, identifiers, etc. // operator== is cheaper than wxIsalnum, also MoveToNextChar already includes IsEOF while ( ( CurrentChar() == '_' || wxIsalnum(CurrentChar()) ) && MoveToNextChar() ) ; if (IsEOF()) return wxEmptyString; m_Str = m_Buffer.Mid(start, m_TokenIndex - start); m_IsOperator = m_Str.IsSameAs(TokenizerConsts::operator_str); } #ifdef __WXMSW__ // This is a Windows only bug! else if (c == 178 || c == 179 || c == 185) // fetch ?and ? { m_Str = c; MoveToNextChar(); } #endif else if (wxIsdigit(CurrentChar())) { // numbers while (NotEOF() && CharInString(CurrentChar(), _T("0123456789.abcdefABCDEFXxLl"))) MoveToNextChar(); if (IsEOF()) return wxEmptyString; m_Str = m_Buffer.Mid(start, m_TokenIndex - start); m_IsOperator = false; } else if (CurrentChar() == '"' || CurrentChar() == '\'') { // string, char, etc. wxChar match = CurrentChar(); MoveToNextChar(); // skip starting ' or " if (!SkipToChar(match)) return wxEmptyString; MoveToNextChar(); // skip ending ' or " m_Str = m_Buffer.Mid(start, m_TokenIndex - start); } else if (CurrentChar() == ':') { if (NextChar() == ':') { MoveToNextChar(); MoveToNextChar(); m_Str.assign(TokenizerConsts::colon_colon); // this only copies a pointer, but operator= allocates memory and does a memcpy! } else { MoveToNextChar(); m_Str.assign(TokenizerConsts::colon); } } else if (CurrentChar() == '<' && bTemplate) { wxChar match = _T('>'); MoveToNextChar(); if (!SkipToOneOfChars(_T(">\r\n")),false) return wxEmptyString; MoveToNextChar(); wxString tmp = m_Buffer.Mid(start+1,m_TokenIndex-start-2); tmp.Trim(); m_Str = _T("<"); m_Str += tmp; m_Str += _T(">");//m_Buffer.Mid(start, m_TokenIndex - start); } else if (CurrentChar() == '(') { m_IsOperator = false; // skip blocks () [] if (!SkipBlock(CurrentChar())) return wxEmptyString; wxString tmp = m_Buffer.Mid(start, m_TokenIndex - start); // tmp.Replace(_T("\t"), _T(" ")); // replace tabs with spaces // tmp.Replace(_T("\n"), _T(" ")); // replace LF with spaces // tmp.Replace(_T("\r"), _T(" ")); // replace CR with spaces { // this is much faster: size_t i; while((i = tmp.find_first_of(TokenizerConsts::tabcrlf)) != wxString::npos) //tmp[i] = _T(' '); tmp.SetAt(i,_T(' ')); } // fix-up arguments (remove excessive spaces/tabs/newlines) for (unsigned int i = 0; i < tmp.Length() - 1; ++i) { //skip spaces before '=' and ',' if (tmp.GetChar(i) == ' ' && (tmp.GetChar(i + 1) == ',' || tmp.GetChar(i + 1) == '=')) continue; if (tmp.GetChar(i) == '/' && tmp.GetChar(i + 1) == '*') { // skip C comments i += 2; while (i < tmp.Length() - 1) { if (tmp.GetChar(i) == '*' && tmp.GetChar(i + 1) == '/') break; ++i; } if (i >= tmp.Length() - 1 || tmp.GetChar(i + 1) != '/') continue; // we failed... i += 2; } else if (tmp.GetChar(i) == '=') { // skip default assignments ++i; int level = 0; // nesting parenthesis while (i < tmp.Length()) { if (tmp.GetChar(i) == '(') ++level; else if (tmp.GetChar(i) == ')') --level; if ((tmp.GetChar(i) == ',' && level == 0) || (tmp.GetChar(i) == ')' && level < 0)) break; ++i; } if (i < tmp.Length() && tmp.GetChar(i) == ',') --i; continue; // we are done here } if (i < tmp.Length() - 1) { if ((tmp.GetChar(i) == ' ') && (tmp.GetChar(i + 1) == ' ')) continue; // skip excessive spaces // in case of c-style comments "i" might already be tmp.Length() // thus do only add the current char otherwise. // otherwise the following statement: // m_Str << _T(')'); // below would add another closing bracket. m_Str << tmp.GetChar(i); } } m_Str << _T(')'); // add closing parenthesis (see "i < tmp.Length() - 1" in previous "for") // m_Str.Replace(_T(" "), _T(" ")); // replace two-spaces with single-space (introduced if it skipped comments or assignments) // m_Str.Replace(_T("( "), _T("(")); // m_Str.Replace(_T(" )"), _T(")")); //Str.Replace is massive overkill here since it has to allocate one new block per replacement CompactSpaces(m_Str); } else { if (CurrentChar() == '{') ++m_NestLevel; else if (CurrentChar() == '}') --m_NestLevel; m_Str = CurrentChar(); MoveToNextChar(); } if (m_LastWasPreprocessor && !m_Str.IsSameAs(_T("#")) && !m_LastPreprocessor.IsSameAs(_T("#"))) { if (!m_LastPreprocessor.IsSameAs(TokenizerConsts::include_str)) { // except for #include and #if[[n]def], all other preprocessor directives need only // one word exactly after the directive, e.g. #define THIS_WORD SkipToEOL(); } m_LastPreprocessor.Clear(); } if (m_LastWasPreprocessor) m_LastPreprocessor << m_Str; m_LastWasPreprocessor = false; return m_Str; }
void MainFrame::update_state_ts(bool force) { bool any_states = false; for (int i = 0; i < 10; i++) { if (force) state_ts[i] = wxInvalidDateTime; if (panel->game_type() != IMAGE_UNKNOWN) { wxString fn; fn.Printf(SAVESLOT_FMT, panel->game_name().c_str(), i + 1); wxFileName fp(panel->state_dir(), fn); wxDateTime ts; // = wxInvalidDateTime if (fp.IsFileReadable()) { ts = fp.GetModificationTime(); any_states = true; } // if(ts != state_ts[i] || (force && !ts.IsValid())) { // to prevent assertions (stupid wx): if (ts.IsValid() != state_ts[i].IsValid() || (ts.IsValid() && ts != state_ts[i]) || (force && !ts.IsValid())) { // wx has no easy way of doing the -- bit independent // of locale // so use a real date and substitute all digits wxDateTime fts = ts.IsValid() ? ts : wxDateTime::Now(); wxString df = fts.Format(wxT("0&0 %x %X")); if (!ts.IsValid()) for (int j = 0; j < df.size(); j++) if (wxIsdigit(df[j])) df[j] = wxT('-'); df[0] = i == 9 ? wxT('1') : wxT(' '); df[2] = wxT('0') + (i + 1) % 10; if (loadst_mi[i]) { wxString lab = loadst_mi[i]->GetItemLabel(); size_t tab = lab.find(wxT('\t')), dflen = df.size(); if (tab != wxString::npos) df.append(lab.substr(tab)); loadst_mi[i]->SetItemLabel(df); loadst_mi[i]->Enable(ts.IsValid()); if (tab != wxString::npos) df.resize(dflen); } if (savest_mi[i]) { wxString lab = savest_mi[i]->GetItemLabel(); size_t tab = lab.find(wxT('\t')); if (tab != wxString::npos) df.append(lab.substr(tab)); savest_mi[i]->SetItemLabel(df); } } state_ts[i] = ts; } } int cmd_flg = any_states ? CMDEN_SAVST : 0; if ((cmd_enable & CMDEN_SAVST) != cmd_flg) { cmd_enable = (cmd_enable & ~CMDEN_SAVST) | cmd_flg; enable_menus(); } }
bool wxSimpleHtmlParser::IsNumeric(int ch) { return (wxIsdigit((wxChar) ch) != 0 || ch == wxT('-') || ch == wxT('.')) ; }
wxInt32 NaturalCompare(wxString String1, wxString String2, bool CaseSensitive = false) { wxInt32 StringCounter1 = 0, StringCounter2 = 0; wxInt32 String1Zeroes = 0, String2Zeroes = 0; wxChar String1Char, String2Char; wxInt32 Result; if (!CaseSensitive) { String1.MakeLower(); String2.MakeLower(); } while (true) { String1Zeroes = 0; String2Zeroes = 0; String1Char = String1[StringCounter1]; String2Char = String2[StringCounter2]; // skip past whitespace or zeroes in first string while (wxIsspace(String1Char) || String1Char == '0' ) { if (String1Char == '0') { String1Zeroes++; } else { String1Zeroes = 0; } String1Char = String1[++StringCounter1]; } // skip past whitespace or zeroes in second string while (wxIsspace(String2Char) || String2Char == '0') { if (String2Char == '0') { String2Zeroes++; } else { String2Zeroes = 0; } String2Char = String2[++StringCounter2]; } // We encountered some digits, compare these. if (wxIsdigit(String1Char) && wxIsdigit(String2Char)) { if ((Result = NaturalCompareWorker( String1.Mid(StringCounter1), String2.Mid(StringCounter2))) != 0) { return Result; } } if ((String1Char == 0) && (String2Char == 0)) { return (String1Zeroes - String2Zeroes); } if (String1Char < String2Char) { return -1; } else if (String1Char > String2Char) { return 1; } ++StringCounter1; ++StringCounter2; } }
wxString Tokenizer::DoGetToken() { int start = m_TokenIndex; bool needReplace = false; wxString str; wxChar c = CurrentChar(); if (c == '_' || wxIsalpha(c)) { // keywords, identifiers, etc. // operator== is cheaper than wxIsalnum, also MoveToNextChar already includes IsEOF while ( ( (c == '_') || (wxIsalnum(c)) ) && MoveToNextChar() ) c = CurrentChar(); // repeat if (IsEOF()) return wxEmptyString; needReplace = true; str = m_Buffer.Mid(start, m_TokenIndex - start); } #ifdef __WXMSW__ // This is a Windows only bug! // fetch non-English characters, see more details in: http://forums.codeblocks.org/index.php/topic,11387.0.html else if (c == 178 || c == 179 || c == 185) { str = c; MoveToNextChar(); } #endif else if (wxIsdigit(c)) { // numbers while (NotEOF() && CharInString(CurrentChar(), _T("0123456789.abcdefABCDEFXxLl"))) MoveToNextChar(); if (IsEOF()) return wxEmptyString; str = m_Buffer.Mid(start, m_TokenIndex - start); } else if ( (c == '"') || (c == '\'') ) { SkipString(); //Now, we are after the end of the C-string, so return the whole string as a token. str = m_Buffer.Mid(start, m_TokenIndex - start); } else if (c == ':') { if (NextChar() == ':') { MoveToNextChar(); MoveToNextChar(); // this only copies a pointer, but operator= allocates memory and does a memcpy! str.assign(TokenizerConsts::colon_colon); } else { MoveToNextChar(); str.assign(TokenizerConsts::colon); } } else if (c == '<') { if (m_State&tsSingleAngleBrace) { if ( !SkipToOneOfChars( _T(">"), true, true) ) return wxEmptyString; MoveToNextChar(); str= m_Buffer.Mid(start, m_TokenIndex - start); } else { str = c; MoveToNextChar(); } } else if (c == '(') { if (m_State & tsReadRawExpression) { str = c; MoveToNextChar(); } else { ReadParentheses(str); } } else { if (c == '{') ++m_NestLevel; else if (c == '}') --m_NestLevel; str = c; MoveToNextChar(); } if (m_FirstRemainingLength != 0 && m_BufferLen - m_FirstRemainingLength < m_TokenIndex) { m_FirstRemainingLength = 0; m_IsReplaceParsing = false; m_RepeatReplaceCount = 0; } if (needReplace && m_State ^ tsReadRawExpression) MacroReplace(str); return str; }
int wxRegExImpl::Replace(wxString *text, const wxString& replacement, size_t maxMatches) const { wxCHECK_MSG( text, wxNOT_FOUND, wxT("NULL text in wxRegEx::Replace") ); wxCHECK_MSG( IsValid(), wxNOT_FOUND, wxT("must successfully Compile() first") ); // the input string #ifndef WXREGEX_CONVERT_TO_MB const wxChar *textstr = text->c_str(); size_t textlen = text->length(); #else const wxWX2MBbuf textstr = WXREGEX_CHAR(*text); if (!textstr) { wxLogError(_("Failed to find match for regular expression: %s"), GetErrorMsg(0, true).c_str()); return 0; } size_t textlen = strlen(textstr); text->clear(); #endif // the replacement text wxString textNew; // the result, allow 25% extra wxString result; result.reserve(5 * textlen / 4); // attempt at optimization: don't iterate over the string if it doesn't // contain back references at all bool mayHaveBackrefs = replacement.find_first_of(wxT("\\&")) != wxString::npos; if ( !mayHaveBackrefs ) { textNew = replacement; } // the position where we start looking for the match size_t matchStart = 0; // number of replacement made: we won't make more than maxMatches of them // (unless maxMatches is 0 which doesn't limit the number of replacements) size_t countRepl = 0; // note that "^" shouldn't match after the first call to Matches() so we // use wxRE_NOTBOL to prevent it from happening while ( (!maxMatches || countRepl < maxMatches) && Matches( #ifndef WXREGEX_CONVERT_TO_MB textstr + matchStart, #else textstr.data() + matchStart, #endif countRepl ? wxRE_NOTBOL : 0 WXREGEX_IF_NEED_LEN(textlen - matchStart)) ) { // the string possibly contains back references: we need to calculate // the replacement text anew after each match if ( mayHaveBackrefs ) { mayHaveBackrefs = false; textNew.clear(); textNew.reserve(replacement.length()); for ( const wxChar *p = replacement.c_str(); *p; p++ ) { size_t index = (size_t)-1; if ( *p == wxT('\\') ) { if ( wxIsdigit(*++p) ) { // back reference wxChar *end; index = (size_t)wxStrtoul(p, &end, 10); p = end - 1; // -1 to compensate for p++ in the loop } //else: backslash used as escape character } else if ( *p == wxT('&') ) { // treat this as "\0" for compatbility with ed and such index = 0; } // do we have a back reference? if ( index != (size_t)-1 ) { // yes, get its text size_t start, len; if ( !GetMatch(&start, &len, index) ) { wxFAIL_MSG( wxT("invalid back reference") ); // just eat it... } else { textNew += wxString( #ifndef WXREGEX_CONVERT_TO_MB textstr #else textstr.data() #endif + matchStart + start, *wxConvCurrent, len); mayHaveBackrefs = true; } } else // ordinary character { textNew += *p; } } } size_t start, len; if ( !GetMatch(&start, &len) ) { // we did have match as Matches() returned true above! wxFAIL_MSG( wxT("internal logic error in wxRegEx::Replace") ); return wxNOT_FOUND; } // an insurance against implementations that don't grow exponentially // to ensure building the result takes linear time if (result.capacity() < result.length() + start + textNew.length()) result.reserve(2 * result.length()); #ifndef WXREGEX_CONVERT_TO_MB result.append(*text, matchStart, start); #else result.append(wxString(textstr.data() + matchStart, *wxConvCurrent, start)); #endif matchStart += start; result.append(textNew); countRepl++; matchStart += len; } #ifndef WXREGEX_CONVERT_TO_MB result.append(*text, matchStart, wxString::npos); #else result.append(wxString(textstr.data() + matchStart, *wxConvCurrent)); #endif *text = result; return countRepl; }
bool Tokenizer::CalcConditionExpression() { // need to force the tokenizer skip raw expression const TokenizerState oldState = m_State; m_State = tsReadRawExpression; const unsigned int undoIndex = m_TokenIndex; const unsigned int undoLine = m_LineNumber; SkipToEOL(false); const unsigned int lastBufferLen = m_BufferLen - m_TokenIndex; m_TokenIndex = undoIndex; m_LineNumber = undoLine; Expression exp; while (m_BufferLen - m_TokenIndex > lastBufferLen) { while (SkipComment()) ; wxString token = DoGetToken(); if (token[0] <= _T(' ') || token == _T("defined") || token == _T("\\")) continue; if (token.Len() > 1 && !wxIsdigit(token[0])) // handle macro { const int id = m_TokensTree->TokenExists(token, -1, tkPreprocessor); if (id != -1) { Token* tk = m_TokensTree->at(id); if (tk) { if (tk->m_Type.IsEmpty() || tk->m_Type == token) { if (tk->m_Args.IsEmpty()) { exp.AddToInfixExpression(_T("1")); continue; } else { if (ReplaceBufferForReparse(tk->m_Args, false)) continue; } } else if (!tk->m_Args.IsEmpty()) { if (ReplaceMacroActualContext(tk, false)) continue; } else if (wxIsdigit(tk->m_Type[0])) token = tk->m_Type; else if (tk->m_Type != tk->m_Name) { if (ReplaceBufferForReparse(tk->m_Type, false)) continue; } } } else { exp.AddToInfixExpression(_T("0")); continue; } } // only remaining number now if (!token.StartsWith(_T("0x"))) exp.AddToInfixExpression(token); else { long value; if (token.ToLong(&value, 16)) exp.AddToInfixExpression(wxString::Format(_T("%ld"), value)); else exp.AddToInfixExpression(_T("0")); } } // reset tokenizer's functionality m_State = oldState; exp.ConvertInfixToPostfix(); if (exp.CalcPostfix()) { TRACE(_T("CalcConditionExpression() : exp.GetStatus() : %d, exp.GetResult() : %d"), exp.GetStatus(), exp.GetResult()); return exp.GetStatus() && exp.GetResult(); } return true; }