Remove braces for single lines of conditions

#!/usr/bin/env ruby

Dir.glob('**/*.cpp') { |file|
  # skip ast (excluding paste, astpath, and canv'ast'imer)
  next if file =~ /ast[^eip]|keywords\.|qualifiers|preprocessor|names.cpp/i
  s = File.read(file)
  next if s.include?('qlalr')
  orig = s.dup
  s.gsub!(/\n *if [^\n]*{\n[^\n]*\n\s+}(\s+else if [^\n]* {\n[^\n]*\n\s+})*(\s+else {\n[^\n]*\n\s+})?\n/m) { |m|
    res = $&
    if res =~ /^\s*(\/\/|[A-Z_]{3,})/ # C++ comment or macro (Q_UNUSED, SDEBUG), do not touch braces
      res
    else
      res.gsub!('} else', 'else')
      res.gsub!(/\n +} *\n/m, "\n")
      res.gsub(/ *{$/, '')
    end
  }
  s.gsub!(/ *$/, '')
  File.open(file, 'wb').write(s) if s != orig
}

Change-Id: I3b30ee60df0986f66c02132c65fc38a3fbb6bbdc
Reviewed-by: hjk <qthjk@ovi.com>
This commit is contained in:
Orgad Shaneh
2013-01-08 03:32:53 +02:00
committed by hjk
parent 73a2717bed
commit 29a93998df
396 changed files with 1856 additions and 3135 deletions
+3 -6
View File
@@ -129,9 +129,8 @@ void Bind::setDeclSpecifiers(Symbol *symbol, const FullySpecifiedType &declSpeci
symbol->setStorage(storage); symbol->setStorage(storage);
if (Function *funTy = symbol->asFunction()) { if (Function *funTy = symbol->asFunction()) {
if (declSpecifiers.isVirtual()) { if (declSpecifiers.isVirtual())
funTy->setVirtual(true); funTy->setVirtual(true);
}
} }
if (declSpecifiers.isDeprecated()) if (declSpecifiers.isDeprecated())
@@ -466,9 +465,8 @@ void Bind::enumerator(EnumeratorAST *ast, Enum *symbol)
EnumeratorDeclaration *e = control()->newEnumeratorDeclaration(ast->identifier_token, name); EnumeratorDeclaration *e = control()->newEnumeratorDeclaration(ast->identifier_token, name);
e->setType(control()->integerType(IntegerType::Int)); // ### introduce IntegerType::Enumerator e->setType(control()->integerType(IntegerType::Int)); // ### introduce IntegerType::Enumerator
if (ExpressionAST *expr = ast->expression) { if (ExpressionAST *expr = ast->expression)
e->setConstantValue(asStringLiteral(expr->firstToken(), expr->lastToken())); e->setConstantValue(asStringLiteral(expr->firstToken(), expr->lastToken()));
}
symbol->addMember(e); symbol->addMember(e);
} }
@@ -1845,9 +1843,8 @@ bool Bind::visit(SimpleDeclarationAST *ast)
const Name *declName = 0; const Name *declName = 0;
unsigned sourceLocation = location(it->value, ast->firstToken()); unsigned sourceLocation = location(it->value, ast->firstToken());
if (declaratorId && declaratorId->name) { if (declaratorId && declaratorId->name)
declName = declaratorId->name->name; declName = declaratorId->name->name;
}
Declaration *decl = control()->newDeclaration(sourceLocation, declName); Declaration *decl = control()->newDeclaration(sourceLocation, declName);
decl->setType(declTy); decl->setType(declTy);
+1 -2
View File
@@ -206,9 +206,8 @@ bool Identifier::isEqualTo(const Name *other) const
return true; return true;
else if (other) { else if (other) {
if (const Identifier *nameId = other->asNameId()) { if (const Identifier *nameId = other->asNameId())
return equalTo(nameId); return equalTo(nameId);
}
} }
return false; return false;
} }
+11 -19
View File
@@ -898,9 +898,8 @@ bool Parser::parseConversionFunctionId(NameAST *&node)
return false; return false;
unsigned operator_token = consumeToken(); unsigned operator_token = consumeToken();
SpecifierListAST *type_specifier = 0; SpecifierListAST *type_specifier = 0;
if (! parseTypeSpecifier(type_specifier)) { if (! parseTypeSpecifier(type_specifier))
return false; return false;
}
PtrOperatorListAST *ptr_operators = 0, **ptr_operators_tail = &ptr_operators; PtrOperatorListAST *ptr_operators = 0, **ptr_operators_tail = &ptr_operators;
while (parsePtrOperator(*ptr_operators_tail)) while (parsePtrOperator(*ptr_operators_tail))
ptr_operators_tail = &(*ptr_operators_tail)->next; ptr_operators_tail = &(*ptr_operators_tail)->next;
@@ -1550,9 +1549,8 @@ bool Parser::parseDeclarator(DeclaratorAST *&node, SpecifierListAST *decl_specif
for (SpecifierListAST *iter = decl_specifier_list; !hasAuto && iter; iter = iter->next) { for (SpecifierListAST *iter = decl_specifier_list; !hasAuto && iter; iter = iter->next) {
SpecifierAST *spec = iter->value; SpecifierAST *spec = iter->value;
if (SimpleSpecifierAST *simpleSpec = spec->asSimpleSpecifier()) { if (SimpleSpecifierAST *simpleSpec = spec->asSimpleSpecifier()) {
if (_translationUnit->tokenKind(simpleSpec->specifier_token) == T_AUTO) { if (_translationUnit->tokenKind(simpleSpec->specifier_token) == T_AUTO)
hasAuto = true; hasAuto = true;
}
} }
} }
@@ -1567,9 +1565,8 @@ bool Parser::parseDeclarator(DeclaratorAST *&node, SpecifierListAST *decl_specif
} else if (LA() == T_LBRACKET) { } else if (LA() == T_LBRACKET) {
ArrayDeclaratorAST *ast = new (_pool) ArrayDeclaratorAST; ArrayDeclaratorAST *ast = new (_pool) ArrayDeclaratorAST;
ast->lbracket_token = consumeToken(); ast->lbracket_token = consumeToken();
if (LA() == T_RBRACKET || parseConstantExpression(ast->expression)) { if (LA() == T_RBRACKET || parseConstantExpression(ast->expression))
match(T_RBRACKET, &ast->rbracket_token); match(T_RBRACKET, &ast->rbracket_token);
}
*postfix_ptr = new (_pool) PostfixDeclaratorListAST(ast); *postfix_ptr = new (_pool) PostfixDeclaratorListAST(ast);
postfix_ptr = &(*postfix_ptr)->next; postfix_ptr = &(*postfix_ptr)->next;
} else } else
@@ -1715,9 +1712,8 @@ bool Parser::parseEnumSpecifier(SpecifierListAST *&node)
skipUntil(T_IDENTIFIER); skipUntil(T_IDENTIFIER);
} }
if (parseEnumerator(*enumerator_ptr)) { if (parseEnumerator(*enumerator_ptr))
enumerator_ptr = &(*enumerator_ptr)->next; enumerator_ptr = &(*enumerator_ptr)->next;
}
if (LA() == T_COMMA && LA(2) == T_RBRACE) if (LA() == T_COMMA && LA(2) == T_RBRACE)
ast->stray_comma_token = consumeToken(); ast->stray_comma_token = consumeToken();
@@ -2182,11 +2178,10 @@ bool Parser::parseQtPropertyDeclaration(DeclarationAST *&node)
SimpleNameAST *property_name = new (_pool) SimpleNameAST; SimpleNameAST *property_name = new (_pool) SimpleNameAST;
// special case: keywords are allowed for property names! // special case: keywords are allowed for property names!
if (tok().isKeyword()) { if (tok().isKeyword())
property_name->identifier_token = consumeToken(); property_name->identifier_token = consumeToken();
} else { else
match(T_IDENTIFIER, &property_name->identifier_token); match(T_IDENTIFIER, &property_name->identifier_token);
}
ast->property_name = property_name; ast->property_name = property_name;
QtPropertyDeclarationItemListAST **iter = &ast->property_declaration_item_list; QtPropertyDeclarationItemListAST **iter = &ast->property_declaration_item_list;
@@ -3484,11 +3479,10 @@ bool Parser::parseForStatement(StatementAST *&node)
ast->colon_token = consumeToken(); ast->colon_token = consumeToken();
blockErrors(blocked); blockErrors(blocked);
if (LA() == T_LBRACE) { if (LA() == T_LBRACE)
parseBracedInitList0x(ast->expression); parseBracedInitList0x(ast->expression);
} else { else
parseExpression(ast->expression); parseExpression(ast->expression);
}
match(T_RPAREN, &ast->rparen_token); match(T_RPAREN, &ast->rparen_token);
parseStatement(ast->statement); parseStatement(ast->statement);
@@ -5093,11 +5087,10 @@ bool Parser::parseNewArrayDeclarator(NewArrayDeclaratorListAST *&node)
bool Parser::parseNewInitializer(ExpressionAST *&node) bool Parser::parseNewInitializer(ExpressionAST *&node)
{ {
DEBUG_THIS_RULE(); DEBUG_THIS_RULE();
if (LA() == T_LPAREN) { if (LA() == T_LPAREN)
return parseExpressionListParen(node); return parseExpressionListParen(node);
} else if (_cxx0xEnabled && LA() == T_LBRACE) { else if (_cxx0xEnabled && LA() == T_LBRACE)
return parseBracedInitList0x(node); return parseBracedInitList0x(node);
}
return false; return false;
} }
@@ -5787,9 +5780,8 @@ bool Parser::parseObjCMethodDefinition(DeclarationAST *&node)
// - (void) foo; { body; } // - (void) foo; { body; }
// so a method is a forward declaration when it doesn't have a _body_. // so a method is a forward declaration when it doesn't have a _body_.
// However, we still need to read the semicolon. // However, we still need to read the semicolon.
if (LA() == T_SEMICOLON) { if (LA() == T_SEMICOLON)
ast->semicolon_token = consumeToken(); ast->semicolon_token = consumeToken();
}
parseFunctionBody(ast->function_body); parseFunctionBody(ast->function_body);
+1 -2
View File
@@ -499,9 +499,8 @@ Symbol *Clone::instantiate(Template *templ, const FullySpecifiedType *const args
if (argc < templ->templateParameterCount()) { if (argc < templ->templateParameterCount()) {
for (unsigned i = argc; i < templ->templateParameterCount(); ++i) { for (unsigned i = argc; i < templ->templateParameterCount(); ++i) {
Symbol *formal = templ->templateParameterAt(i); Symbol *formal = templ->templateParameterAt(i);
if (TypenameArgument *tn = formal->asTypenameArgument()) { if (TypenameArgument *tn = formal->asTypenameArgument())
subst.bind(name(formal->name(), &subst), type(tn->type(), &subst)); subst.bind(name(formal->name(), &subst), type(tn->type(), &subst));
}
} }
} }
if (Symbol *inst = symbol(templ->declaration(), &subst)) { if (Symbol *inst = symbol(templ->declaration(), &subst)) {
+4 -6
View File
@@ -89,9 +89,8 @@ protected:
bool preVisit(Symbol *s) bool preVisit(Symbol *s)
{ {
if (s->asBlock()) { if (s->asBlock()) {
if (s->line() < line || (s->line() == line && s->column() <= column)) { if (s->line() < line || (s->line() == line && s->column() <= column))
return true; return true;
}
// skip blocks // skip blocks
} if (s->line() < line || (s->line() == line && s->column() <= column)) { } if (s->line() < line || (s->line() == line && s->column() <= column)) {
symbol = s; symbol = s;
@@ -594,13 +593,12 @@ void Document::check(CheckMode mode)
if (! _translationUnit->ast()) if (! _translationUnit->ast())
return; // nothing to do. return; // nothing to do.
if (TranslationUnitAST *ast = _translationUnit->ast()->asTranslationUnit()) { if (TranslationUnitAST *ast = _translationUnit->ast()->asTranslationUnit())
semantic(ast, _globalNamespace); semantic(ast, _globalNamespace);
} else if (ExpressionAST *ast = _translationUnit->ast()->asExpression()) { else if (ExpressionAST *ast = _translationUnit->ast()->asExpression())
semantic(ast, _globalNamespace); semantic(ast, _globalNamespace);
} else if (DeclarationAST *ast = translationUnit()->ast()->asDeclaration()) { else if (DeclarationAST *ast = translationUnit()->ast()->asDeclaration())
semantic(ast, _globalNamespace); semantic(ast, _globalNamespace);
}
} }
void Document::keepSourceAndAST() void Document::keepSourceAndAST()
+2 -4
View File
@@ -406,9 +406,8 @@ FullySpecifiedType UseMinimalNames::apply(const Name *name, Rewrite *rewrite) co
const QList<LookupItem> results = context.lookup(name, scope); const QList<LookupItem> results = context.lookup(name, scope);
foreach (const LookupItem &r, results) { foreach (const LookupItem &r, results) {
if (Symbol *d = r.declaration()) { if (Symbol *d = r.declaration())
return control->namedType(LookupContext::minimalName(d, _target, control)); return control->namedType(LookupContext::minimalName(d, _target, control));
}
return r.type(); return r.type();
} }
@@ -605,9 +604,8 @@ CPLUSPLUS_EXPORT QString simplifySTLType(const QString &typeIn)
QRegExp mapRE2(QString::fromLatin1("map<const %1, ?%2, ?std::less<const %3>, ?%4\\s*>") QRegExp mapRE2(QString::fromLatin1("map<const %1, ?%2, ?std::less<const %3>, ?%4\\s*>")
.arg(keyEsc, valueEsc, keyEsc, allocEsc)); .arg(keyEsc, valueEsc, keyEsc, allocEsc));
mapRE2.setMinimal(true); mapRE2.setMinimal(true);
if (mapRE2.indexIn(type) != -1) { if (mapRE2.indexIn(type) != -1)
type.replace(mapRE2.cap(0), QString::fromLatin1("map<const %1, %2>").arg(key, value)); type.replace(mapRE2.cap(0), QString::fromLatin1("map<const %1, %2>").arg(key, value));
}
} }
} }
} }
+5 -10
View File
@@ -83,18 +83,14 @@ QString CPlusPlus::toString(const Symbol *s, QString id)
QString CPlusPlus::toString(LookupItem it, QString id) QString CPlusPlus::toString(LookupItem it, QString id)
{ {
QString result = QString::fromLatin1("%1:").arg(id); QString result = QString::fromLatin1("%1:").arg(id);
if (it.declaration()) { if (it.declaration())
result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.declaration(), QLatin1String("Decl"))))); result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.declaration(), QLatin1String("Decl")))));
} if (it.type().isValid())
if (it.type().isValid()) {
result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.type())))); result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.type()))));
} if (it.scope())
if (it.scope()) {
result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.scope(), QLatin1String("Scope"))))); result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.scope(), QLatin1String("Scope")))));
} if (it.binding())
if (it.binding()) {
result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.binding(), QLatin1String("Binding"))))); result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.binding(), QLatin1String("Binding")))));
}
return result; return result;
} }
@@ -106,9 +102,8 @@ QString CPlusPlus::toString(const ClassOrNamespace *binding, QString id)
QString result = QString::fromLatin1("%0: %1 symbols").arg( QString result = QString::fromLatin1("%0: %1 symbols").arg(
id, id,
QString::number(binding->symbols().length())); QString::number(binding->symbols().length()));
if (binding->templateId()) { if (binding->templateId())
result.append(QString::fromLatin1("\n%1").arg(indent(toString(binding->templateId(), QLatin1String("Template"))))); result.append(QString::fromLatin1("\n%1").arg(indent(toString(binding->templateId(), QLatin1String("Template")))));
}
return result; return result;
} }
+2 -3
View File
@@ -98,11 +98,10 @@ int ExpressionUnderCursor::startOfExpression_helper(BackwardsScanner &tk, int in
return index - 1; return index - 1;
} else if (tk[index - 1].is(T_IDENTIFIER)) { } else if (tk[index - 1].is(T_IDENTIFIER)) {
if (tk[index - 2].is(T_TILDE)) { if (tk[index - 2].is(T_TILDE)) {
if (tk[index - 3].is(T_COLON_COLON)) { if (tk[index - 3].is(T_COLON_COLON))
return startOfExpression(tk, index - 3); return startOfExpression(tk, index - 3);
} else if (tk[index - 3].is(T_DOT) || tk[index - 3].is(T_ARROW)) { else if (tk[index - 3].is(T_DOT) || tk[index - 3].is(T_ARROW))
return startOfExpression(tk, index - 3); return startOfExpression(tk, index - 3);
}
return index - 2; return index - 2;
} else if (tk[index - 2].is(T_COLON_COLON)) { } else if (tk[index - 2].is(T_COLON_COLON)) {
return startOfExpression(tk, index - 1); return startOfExpression(tk, index - 1);
+6 -8
View File
@@ -88,13 +88,12 @@ Icons::IconType Icons::iconTypeForSymbol(const Symbol *symbol)
function = symbol->type()->asFunctionType(); function = symbol->type()->asFunctionType();
if (function->isSlot()) { if (function->isSlot()) {
if (function->isPublic()) { if (function->isPublic())
return SlotPublicIconType; return SlotPublicIconType;
} else if (function->isProtected()) { else if (function->isProtected())
return SlotProtectedIconType; return SlotProtectedIconType;
} else if (function->isPrivate()) { else if (function->isPrivate())
return SlotPrivateIconType; return SlotPrivateIconType;
}
} else if (function->isSignal()) { } else if (function->isSignal()) {
return SignalIconType; return SignalIconType;
} else if (symbol->isPublic()) { } else if (symbol->isPublic()) {
@@ -107,13 +106,12 @@ Icons::IconType Icons::iconTypeForSymbol(const Symbol *symbol)
} else if (symbol->enclosingScope() && symbol->enclosingScope()->isEnum()) { } else if (symbol->enclosingScope() && symbol->enclosingScope()->isEnum()) {
return EnumeratorIconType; return EnumeratorIconType;
} else if (symbol->isDeclaration() || symbol->isArgument()) { } else if (symbol->isDeclaration() || symbol->isArgument()) {
if (symbol->isPublic()) { if (symbol->isPublic())
return VarPublicIconType; return VarPublicIconType;
} else if (symbol->isProtected()) { else if (symbol->isProtected())
return VarProtectedIconType; return VarProtectedIconType;
} else if (symbol->isPrivate()) { else if (symbol->isPrivate())
return VarPrivateIconType; return VarPrivateIconType;
}
} else if (symbol->isEnum()) { } else if (symbol->isEnum()) {
return EnumIconType; return EnumIconType;
} else if (symbol->isClass() || symbol->isForwardClassDeclaration()) { } else if (symbol->isClass() || symbol->isForwardClassDeclaration()) {
+6 -12
View File
@@ -643,13 +643,11 @@ ClassOrNamespace *ClassOrNamespace::lookupType_helper(const Name *name,
if (const QualifiedNameId *q = name->asQualifiedNameId()) { if (const QualifiedNameId *q = name->asQualifiedNameId()) {
QSet<ClassOrNamespace *> innerProcessed; QSet<ClassOrNamespace *> innerProcessed;
if (! q->base()) { if (! q->base())
return globalNamespace()->lookupType_helper(q->name(), &innerProcessed, true, origin); return globalNamespace()->lookupType_helper(q->name(), &innerProcessed, true, origin);
}
if (ClassOrNamespace *binding = lookupType_helper(q->base(), processed, true, origin)) { if (ClassOrNamespace *binding = lookupType_helper(q->base(), processed, true, origin))
return binding->lookupType_helper(q->name(), &innerProcessed, false, origin); return binding->lookupType_helper(q->name(), &innerProcessed, false, origin);
}
return 0; return 0;
@@ -966,9 +964,8 @@ bool ClassOrNamespace::NestedClassInstantiator::containsTemplateType(Declaration
NamedType *memberNamedType = findMemberNamedType(memberType); NamedType *memberNamedType = findMemberNamedType(memberType);
if (memberNamedType) { if (memberNamedType) {
const Name *name = memberNamedType->name(); const Name *name = memberNamedType->name();
if (_subst.contains(name)) { if (_subst.contains(name))
return true; return true;
}
} }
return false; return false;
} }
@@ -981,15 +978,12 @@ bool ClassOrNamespace::NestedClassInstantiator::containsTemplateType(Function *
NamedType *ClassOrNamespace::NestedClassInstantiator::findMemberNamedType(Type *memberType) const NamedType *ClassOrNamespace::NestedClassInstantiator::findMemberNamedType(Type *memberType) const
{ {
if (NamedType *namedType = memberType->asNamedType()) { if (NamedType *namedType = memberType->asNamedType())
return namedType; return namedType;
} else if (PointerType *pointerType = memberType->asPointerType())
else if (PointerType *pointerType = memberType->asPointerType()) {
return findMemberNamedType(pointerType->elementType().type()); return findMemberNamedType(pointerType->elementType().type());
} else if (ReferenceType *referenceType = memberType->asReferenceType())
else if (ReferenceType *referenceType = memberType->asReferenceType()) {
return findMemberNamedType(referenceType->elementType().type()); return findMemberNamedType(referenceType->elementType().type());
}
return 0; return 0;
} }
+1 -2
View File
@@ -123,9 +123,8 @@ int OverviewModel::rowCount(const QModelIndex &parent) const
parentSymbol = templateParentSymbol; parentSymbol = templateParentSymbol;
if (Scope *parentScope = parentSymbol->asScope()) { if (Scope *parentScope = parentSymbol->asScope()) {
if (!parentScope->isFunction() && !parentScope->isObjCMethod()) { if (!parentScope->isFunction() && !parentScope->isObjCMethod())
return parentScope->memberCount(); return parentScope->memberCount();
}
} }
return 0; return 0;
} }
+1 -2
View File
@@ -357,9 +357,8 @@ void ResolveExpression::thisObject()
bool ResolveExpression::visit(CompoundExpressionAST *ast) bool ResolveExpression::visit(CompoundExpressionAST *ast)
{ {
CompoundStatementAST *cStmt = ast->statement; CompoundStatementAST *cStmt = ast->statement;
if (cStmt && cStmt->statement_list) { if (cStmt && cStmt->statement_list)
accept(cStmt->statement_list->lastValue()); accept(cStmt->statement_list->lastValue());
}
return false; return false;
} }
+2 -4
View File
@@ -368,9 +368,8 @@ protected:
env, client) env, client)
!= 0); != 0);
++(*_lex); ++(*_lex);
if ((*_lex)->is(T_RPAREN)) { if ((*_lex)->is(T_RPAREN))
++(*_lex); ++(*_lex);
}
} }
} }
} else if ((*_lex)->is(T_IDENTIFIER)) { } else if ((*_lex)->is(T_IDENTIFIER)) {
@@ -1539,9 +1538,8 @@ void Preprocessor::handleDefineDirective(PPToken *tk)
} }
} }
} else if (macroReference) { } else if (macroReference) {
if (tk->is(T_LPAREN)) { if (tk->is(T_LPAREN))
m_client->notifyMacroReference(previousOffset, previousLine, *macroReference); m_client->notifyMacroReference(previousOffset, previousLine, *macroReference);
}
macroReference = 0; macroReference = 0;
} }
+1 -2
View File
@@ -174,9 +174,8 @@ bool OptionsParser::checkForPluginOption()
if (!spec) if (!spec)
return false; return false;
spec->addArgument(m_currentArg); spec->addArgument(m_currentArg);
if (requiresParameter && nextToken(RequiredToken)) { if (requiresParameter && nextToken(RequiredToken))
spec->addArgument(m_currentArg); spec->addArgument(m_currentArg);
}
return true; return true;
} }
+7 -12
View File
@@ -335,9 +335,8 @@ bool PluginManager::hasError()
{ {
foreach (PluginSpec *spec, plugins()) { foreach (PluginSpec *spec, plugins()) {
// only show errors on startup if plugin is enabled. // only show errors on startup if plugin is enabled.
if (spec->hasError() && spec->isEnabled() && !spec->isDisabledIndirectly()) { if (spec->hasError() && spec->isEnabled() && !spec->isDisabledIndirectly())
return true; return true;
}
} }
return false; return false;
} }
@@ -505,11 +504,10 @@ QString PluginManager::serializedArguments()
foreach (const QString &argument, m_instance->d->arguments) { foreach (const QString &argument, m_instance->d->arguments) {
rc += separator; rc += separator;
const QFileInfo fi(argument); const QFileInfo fi(argument);
if (fi.exists() && fi.isRelative()) { if (fi.exists() && fi.isRelative())
rc += fi.absoluteFilePath(); rc += fi.absoluteFilePath();
} else { else
rc += argument; rc += argument;
}
} }
} }
return rc; return rc;
@@ -857,9 +855,8 @@ void PluginManagerPrivate::writeSettings()
*/ */
void PluginManagerPrivate::readSettings() void PluginManagerPrivate::readSettings()
{ {
if (globalSettings) { if (globalSettings)
defaultDisabledPlugins = globalSettings->value(QLatin1String(C_IGNORED_PLUGINS)).toStringList(); defaultDisabledPlugins = globalSettings->value(QLatin1String(C_IGNORED_PLUGINS)).toStringList();
}
if (settings) { if (settings) {
disabledPlugins = settings->value(QLatin1String(C_IGNORED_PLUGINS)).toStringList(); disabledPlugins = settings->value(QLatin1String(C_IGNORED_PLUGINS)).toStringList();
forceEnabledPlugins = settings->value(QLatin1String(C_FORCEENABLED_PLUGINS)).toStringList(); forceEnabledPlugins = settings->value(QLatin1String(C_FORCEENABLED_PLUGINS)).toStringList();
@@ -996,9 +993,8 @@ void PluginManagerPrivate::shutdown()
shutdownEventLoop->exec(); shutdownEventLoop->exec();
} }
deleteAll(); deleteAll();
if (!allObjects.isEmpty()) { if (!allObjects.isEmpty())
qDebug() << "There are" << allObjects.size() << "objects left in the plugin manager pool: " << allObjects; qDebug() << "There are" << allObjects.size() << "objects left in the plugin manager pool: " << allObjects;
}
} }
/*! /*!
@@ -1270,11 +1266,10 @@ void PluginManagerPrivate::profilingReport(const char *what, const PluginSpec *s
const int absoluteElapsedMS = m_profileTimer->elapsed(); const int absoluteElapsedMS = m_profileTimer->elapsed();
const int elapsedMS = absoluteElapsedMS - m_profileElapsedMS; const int elapsedMS = absoluteElapsedMS - m_profileElapsedMS;
m_profileElapsedMS = absoluteElapsedMS; m_profileElapsedMS = absoluteElapsedMS;
if (spec) { if (spec)
qDebug("%-22s %-22s %8dms (%8dms)", what, qPrintable(spec->name()), absoluteElapsedMS, elapsedMS); qDebug("%-22s %-22s %8dms (%8dms)", what, qPrintable(spec->name()), absoluteElapsedMS, elapsedMS);
} else { else
qDebug("%-45s %8dms (%8dms)", what, absoluteElapsedMS, elapsedMS); qDebug("%-45s %8dms (%8dms)", what, absoluteElapsedMS, elapsedMS);
}
} }
} }
+5 -8
View File
@@ -667,11 +667,10 @@ void PluginSpecPrivate::readArgumentDescriptions(QXmlStreamReader &reader)
switch (reader.tokenType()) { switch (reader.tokenType()) {
case QXmlStreamReader::StartElement: case QXmlStreamReader::StartElement:
element = reader.name().toString(); element = reader.name().toString();
if (element == QLatin1String(ARGUMENT)) { if (element == QLatin1String(ARGUMENT))
readArgumentDescription(reader); readArgumentDescription(reader);
} else { else
reader.raiseError(msgInvalidElement(name)); reader.raiseError(msgInvalidElement(name));
}
break; break;
case QXmlStreamReader::Comment: case QXmlStreamReader::Comment:
case QXmlStreamReader::Characters: case QXmlStreamReader::Characters:
@@ -720,11 +719,10 @@ void PluginSpecPrivate::readDependencies(QXmlStreamReader &reader)
switch (reader.tokenType()) { switch (reader.tokenType()) {
case QXmlStreamReader::StartElement: case QXmlStreamReader::StartElement:
element = reader.name().toString(); element = reader.name().toString();
if (element == QLatin1String(DEPENDENCY)) { if (element == QLatin1String(DEPENDENCY))
readDependencyEntry(reader); readDependencyEntry(reader);
} else { else
reader.raiseError(msgInvalidElement(name)); reader.raiseError(msgInvalidElement(name));
}
break; break;
case QXmlStreamReader::Comment: case QXmlStreamReader::Comment:
case QXmlStreamReader::Characters: case QXmlStreamReader::Characters:
@@ -1019,9 +1017,8 @@ bool PluginSpecPrivate::delayedInitialize()
{ {
if (hasError) if (hasError)
return false; return false;
if (state != PluginSpec::Running) { if (state != PluginSpec::Running)
return false; return false;
}
if (!plugin) { if (!plugin) {
errorString = QCoreApplication::translate("PluginSpec", "Internal error: have no plugin instance to perform delayedInitialize"); errorString = QCoreApplication::translate("PluginSpec", "Internal error: have no plugin instance to perform delayedInitialize");
hasError = true; hasError = true;
+6 -9
View File
@@ -184,11 +184,10 @@ bool Semantic::visit(StructTypeAST::Field *ast)
bool Semantic::visit(IdentifierExpressionAST *ast) bool Semantic::visit(IdentifierExpressionAST *ast)
{ {
if (ast->name) { if (ast->name) {
if (Symbol *s = _scope->lookup(*ast->name)) { if (Symbol *s = _scope->lookup(*ast->name))
_expr.type = s->type(); _expr.type = s->type();
} else { else
_engine->error(ast->lineno, QString::fromLatin1("`%1' was not declared in this scope").arg(*ast->name)); _engine->error(ast->lineno, QString::fromLatin1("`%1' was not declared in this scope").arg(*ast->name));
}
} }
return false; return false;
} }
@@ -291,17 +290,15 @@ bool Semantic::visit(MemberAccessExpressionAST *ast)
ExprResult expr = expression(ast->expr); ExprResult expr = expression(ast->expr);
if (expr.type && ast->field) { if (expr.type && ast->field) {
if (const VectorType *vecTy = expr.type->asVectorType()) { if (const VectorType *vecTy = expr.type->asVectorType()) {
if (Symbol *s = vecTy->find(*ast->field)) { if (Symbol *s = vecTy->find(*ast->field))
_expr.type = s->type(); _expr.type = s->type();
} else { else
_engine->error(ast->lineno, QString::fromLatin1("`%1' has no member named `%2'").arg(vecTy->name()).arg(*ast->field)); _engine->error(ast->lineno, QString::fromLatin1("`%1' has no member named `%2'").arg(vecTy->name()).arg(*ast->field));
}
} else if (const Struct *structTy = expr.type->asStructType()) { } else if (const Struct *structTy = expr.type->asStructType()) {
if (Symbol *s = structTy->find(*ast->field)) { if (Symbol *s = structTy->find(*ast->field))
_expr.type = s->type(); _expr.type = s->type();
} else { else
_engine->error(ast->lineno, QString::fromLatin1("`%1' has no member named `%2'").arg(structTy->name()).arg(*ast->field)); _engine->error(ast->lineno, QString::fromLatin1("`%1' has no member named `%2'").arg(structTy->name()).arg(*ast->field));
}
} else { } else {
_engine->error(ast->lineno, QString::fromLatin1("Requested for member `%1', in a non class or vec instance").arg(*ast->field)); _engine->error(ast->lineno, QString::fromLatin1("Requested for member `%1', in a non class or vec instance").arg(*ast->field));
} }
+3 -4
View File
@@ -173,13 +173,12 @@ void DeclarativeToolsClient::messageReceived(const QByteArray &message)
log(LogReceive, type, QString::number(toolId)); log(LogReceive, type, QString::number(toolId));
if (toolId == Constants::ZoomMode) { if (toolId == Constants::ZoomMode)
emit zoomToolActivated(); emit zoomToolActivated();
} else if (toolId == Constants::SelectionToolMode) { else if (toolId == Constants::SelectionToolMode)
emit selectToolActivated(); emit selectToolActivated();
} else if (toolId == Constants::MarqueeSelectionToolMode) { else if (toolId == Constants::MarqueeSelectionToolMode)
emit selectMarqueeToolActivated(); emit selectMarqueeToolActivated();
}
break; break;
} }
case InspectorProtocol::AnimationSpeedChanged: { case InspectorProtocol::AnimationSpeedChanged: {
+2 -3
View File
@@ -203,11 +203,10 @@ void QmlDebugConnectionPrivate::readyRead()
QHash<QString, QmlDebugClient *>::Iterator iter = QHash<QString, QmlDebugClient *>::Iterator iter =
plugins.find(name); plugins.find(name);
if (iter == plugins.end()) { if (iter == plugins.end())
qWarning() << "QML Debug Client: Message received for missing plugin" << name; qWarning() << "QML Debug Client: Message received for missing plugin" << name;
} else { else
(*iter)->messageReceived(message); (*iter)->messageReceived(message);
}
} }
} }
} }
+2 -4
View File
@@ -118,9 +118,8 @@ void QmlProfilerTraceClient::setRecording(bool v)
d->recording = v; d->recording = v;
if (status() == Enabled) { if (status() == Enabled)
sendRecordingStatus(); sendRecordingStatus();
}
emit recordingChanged(v); emit recordingChanged(v);
} }
@@ -225,9 +224,8 @@ void QmlProfilerTraceClient::messageReceived(const QByteArray &data)
if (!stream.atEnd()) if (!stream.atEnd())
stream >> column; stream >> column;
if (d->rangeCount[range] > 0) { if (d->rangeCount[range] > 0)
d->rangeLocations[range].push(QmlEventLocation(fileName, line, column)); d->rangeLocations[range].push(QmlEventLocation(fileName, line, column));
}
} else { } else {
if (d->rangeCount[range] > 0) { if (d->rangeCount[range] > 0) {
--d->rangeCount[range]; --d->rangeCount[range];
+3 -5
View File
@@ -57,11 +57,10 @@ void QV8ProfilerClientPrivate::sendRecordingStatus()
QByteArray option(""); QByteArray option("");
QByteArray title(""); QByteArray title("");
if (recording) { if (recording)
option = "start"; option = "start";
} else { else
option = "stop"; option = "stop";
}
stream << cmd << option << title; stream << cmd << option << title;
q->sendMessage(ba); q->sendMessage(ba);
} }
@@ -108,9 +107,8 @@ void QV8ProfilerClient::setRecording(bool v)
d->recording = v; d->recording = v;
if (status() == Enabled) { if (status() == Enabled)
sendRecordingStatus(); sendRecordingStatus();
}
emit recordingChanged(v); emit recordingChanged(v);
} }
@@ -169,17 +169,15 @@ void ContextPaneTextWidget::setProperties(QmlJS::PropertyReader *propertyReader)
ui->strikeoutButton->setChecked(false); ui->strikeoutButton->setChecked(false);
} }
if (propertyReader->hasProperty(QLatin1String("color"))) { if (propertyReader->hasProperty(QLatin1String("color")))
ui->colorButton->setColor(propertyReader->readProperty(QLatin1String("color")).toString()); ui->colorButton->setColor(propertyReader->readProperty(QLatin1String("color")).toString());
} else { else
ui->colorButton->setColor(QLatin1String("black")); ui->colorButton->setColor(QLatin1String("black"));
}
if (propertyReader->hasProperty(QLatin1String("styleColor"))) { if (propertyReader->hasProperty(QLatin1String("styleColor")))
ui->textColorButton->setColor(propertyReader->readProperty(QLatin1String("styleColor")).toString()); ui->textColorButton->setColor(propertyReader->readProperty(QLatin1String("styleColor")).toString());
} else { else
ui->textColorButton->setColor(QLatin1String("black")); ui->textColorButton->setColor(QLatin1String("black"));
}
if (propertyReader->hasProperty(QLatin1String("font.family"))) { if (propertyReader->hasProperty(QLatin1String("font.family"))) {
QString familyName = propertyReader->readProperty(QLatin1String("font.family")).toString(); QString familyName = propertyReader->readProperty(QLatin1String("font.family")).toString();
@@ -310,11 +308,10 @@ void ContextPaneTextWidget::onFontSizeChanged(int)
void ContextPaneTextWidget::onFontFormatChanged() void ContextPaneTextWidget::onFontFormatChanged()
{ {
int size = ui->fontSizeSpinBox->value(); int size = ui->fontSizeSpinBox->value();
if (ui->fontSizeSpinBox->isPointSize()) { if (ui->fontSizeSpinBox->isPointSize())
emit removeAndChangeProperty(QLatin1String("font.pixelSize"), QLatin1String("font.pointSize"), size, true); emit removeAndChangeProperty(QLatin1String("font.pixelSize"), QLatin1String("font.pointSize"), size, true);
} else { else
emit removeAndChangeProperty(QLatin1String("font.pointSize"), QLatin1String("font.pixelSize"), size, true); emit removeAndChangeProperty(QLatin1String("font.pointSize"), QLatin1String("font.pixelSize"), size, true);
}
} }
@@ -231,9 +231,8 @@ void ContextPaneWidgetRectangle::onBorderNoneClicked()
void ContextPaneWidgetRectangle::onBorderSolidClicked() void ContextPaneWidgetRectangle::onBorderSolidClicked()
{ {
if (ui->borderSolid->isChecked()) { if (ui->borderSolid->isChecked())
emit propertyChanged(QLatin1String("border.color"), QLatin1String("\"black\"")); emit propertyChanged(QLatin1String("border.color"), QLatin1String("\"black\""));
}
} }
void ContextPaneWidgetRectangle::onGradientLineDoubleClicked(const QPoint &p) void ContextPaneWidgetRectangle::onGradientLineDoubleClicked(const QPoint &p)
+15 -26
View File
@@ -82,9 +82,8 @@ public:
if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) { if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) {
const QString valueName = stringLiteral->value.toString(); const QString valueName = stringLiteral->value.toString();
if (!enumValue->keys().contains(valueName)) { if (!enumValue->keys().contains(valueName))
setMessage(ErrInvalidEnumValue); setMessage(ErrInvalidEnumValue);
}
} else if (! _rhsValue->asStringValue() && ! _rhsValue->asNumberValue() } else if (! _rhsValue->asStringValue() && ! _rhsValue->asNumberValue()
&& ! _rhsValue->asUnknownValue()) { && ! _rhsValue->asUnknownValue()) {
setMessage(ErrEnumValueMustBeStringOrNumber); setMessage(ErrEnumValueMustBeStringOrNumber);
@@ -131,9 +130,8 @@ public:
fileName.prepend(QDir::separator()); fileName.prepend(QDir::separator());
fileName.prepend(_doc->path()); fileName.prepend(_doc->path());
} }
if (!QFileInfo(fileName).exists()) { if (!QFileInfo(fileName).exists())
setMessage(WarnFileOrDirectoryDoesNotExist); setMessage(WarnFileOrDirectoryDoesNotExist);
}
} }
} }
} }
@@ -421,9 +419,8 @@ protected:
bool visit(VariableStatement *ast) bool visit(VariableStatement *ast)
{ {
if (_seenNonDeclarationStatement) { if (_seenNonDeclarationStatement)
addMessage(HintDeclarationsShouldBeAtStartOfFunction, ast->declarationKindToken); addMessage(HintDeclarationsShouldBeAtStartOfFunction, ast->declarationKindToken);
}
return true; return true;
} }
@@ -433,13 +430,12 @@ protected:
return true; return true;
const QString &name = ast->name.toString(); const QString &name = ast->name.toString();
if (_formalParameterNames.contains(name)) { if (_formalParameterNames.contains(name))
addMessage(WarnAlreadyFormalParameter, ast->identifierToken, name); addMessage(WarnAlreadyFormalParameter, ast->identifierToken, name);
} else if (_declaredFunctions.contains(name)) { else if (_declaredFunctions.contains(name))
addMessage(WarnAlreadyFunction, ast->identifierToken, name); addMessage(WarnAlreadyFunction, ast->identifierToken, name);
} else if (_declaredVariables.contains(name)) { else if (_declaredVariables.contains(name))
addMessage(WarnDuplicateDeclaration, ast->identifierToken, name); addMessage(WarnDuplicateDeclaration, ast->identifierToken, name);
}
if (_possiblyUndeclaredUses.contains(name)) { if (_possiblyUndeclaredUses.contains(name)) {
foreach (const SourceLocation &loc, _possiblyUndeclaredUses.value(name)) { foreach (const SourceLocation &loc, _possiblyUndeclaredUses.value(name)) {
@@ -454,9 +450,8 @@ protected:
bool visit(FunctionDeclaration *ast) bool visit(FunctionDeclaration *ast)
{ {
if (_seenNonDeclarationStatement) { if (_seenNonDeclarationStatement)
addMessage(HintDeclarationsShouldBeAtStartOfFunction, ast->functionToken); addMessage(HintDeclarationsShouldBeAtStartOfFunction, ast->functionToken);
}
return visit(static_cast<FunctionExpression *>(ast)); return visit(static_cast<FunctionExpression *>(ast));
} }
@@ -467,13 +462,12 @@ protected:
return false; return false;
const QString &name = ast->name.toString(); const QString &name = ast->name.toString();
if (_formalParameterNames.contains(name)) { if (_formalParameterNames.contains(name))
addMessage(WarnAlreadyFormalParameter, ast->identifierToken, name); addMessage(WarnAlreadyFormalParameter, ast->identifierToken, name);
} else if (_declaredVariables.contains(name)) { else if (_declaredVariables.contains(name))
addMessage(WarnAlreadyVar, ast->identifierToken, name); addMessage(WarnAlreadyVar, ast->identifierToken, name);
} else if (_declaredFunctions.contains(name)) { else if (_declaredFunctions.contains(name))
addMessage(WarnDuplicateDeclaration, ast->identifierToken, name); addMessage(WarnDuplicateDeclaration, ast->identifierToken, name);
}
if (FunctionDeclaration *decl = cast<FunctionDeclaration *>(ast)) { if (FunctionDeclaration *decl = cast<FunctionDeclaration *>(ast)) {
if (_possiblyUndeclaredUses.contains(name)) { if (_possiblyUndeclaredUses.contains(name)) {
@@ -642,9 +636,8 @@ void Check::checkProperty(UiQualifiedId *qualifiedId)
{ {
const QString id = toString(qualifiedId); const QString id = toString(qualifiedId);
if (id.at(0).isLower()) { if (id.at(0).isLower()) {
if (m_propertyStack.top().contains(id)) { if (m_propertyStack.top().contains(id))
addMessage(ErrPropertiesCanOnlyHaveOneBinding, fullLocationForQualifiedId(qualifiedId)); addMessage(ErrPropertiesCanOnlyHaveOneBinding, fullLocationForQualifiedId(qualifiedId));
}
m_propertyStack.top().insert(id); m_propertyStack.top().insert(id);
} }
} }
@@ -1155,9 +1148,8 @@ bool Check::visit(ExpressionStatement *ast)
default: break; default: break;
} }
} }
if (!ok) { if (!ok)
ok = _inStatementBinding; ok = _inStatementBinding;
}
if (!ok) { if (!ok) {
addMessage(WarnConfusingExpressionStatement, addMessage(WarnConfusingExpressionStatement,
@@ -1242,9 +1234,8 @@ void Check::checkNewExpression(ExpressionNode *ast)
const QString name = functionName(ast, &location); const QString name = functionName(ast, &location);
if (name.isEmpty()) if (name.isEmpty())
return; return;
if (!name.at(0).isUpper()) { if (!name.at(0).isUpper())
addMessage(WarnNewWithLowercaseFunction, location); addMessage(WarnNewWithLowercaseFunction, location);
}
} }
void Check::checkBindingRhs(Statement *statement) void Check::checkBindingRhs(Statement *statement)
@@ -1261,9 +1252,8 @@ void Check::checkBindingRhs(Statement *statement)
void Check::checkExtraParentheses(ExpressionNode *expression) void Check::checkExtraParentheses(ExpressionNode *expression)
{ {
if (NestedExpression *nested = cast<NestedExpression *>(expression)) { if (NestedExpression *nested = cast<NestedExpression *>(expression))
addMessage(HintExtraParentheses, nested->lparenToken); addMessage(HintExtraParentheses, nested->lparenToken);
}
} }
void Check::addMessages(const QList<Message> &messages) void Check::addMessages(const QList<Message> &messages)
@@ -1311,9 +1301,8 @@ void Check::scanCommentsForAnnotations()
const QString &comment = _doc->source().mid(commentLoc.begin(), commentLoc.length); const QString &comment = _doc->source().mid(commentLoc.begin(), commentLoc.length);
// enable all checks annotation // enable all checks annotation
if (comment.contains(QLatin1String("@enable-all-checks"))) { if (comment.contains(QLatin1String("@enable-all-checks")))
_enabledMessages = Message::allMessageTypes().toSet(); _enabledMessages = Message::allMessageTypes().toSet();
}
// find all disable annotations // find all disable annotations
int lastOffset = -1; int lastOffset = -1;
+3 -5
View File
@@ -833,11 +833,10 @@ int CodeFormatter::column(int index) const
const QChar tab = QLatin1Char('\t'); const QChar tab = QLatin1Char('\t');
for (int i = 0; i < index; i++) { for (int i = 0; i < index; i++) {
if (m_currentLine[i] == tab) { if (m_currentLine[i] == tab)
col = ((col / m_tabSize) + 1) * m_tabSize; col = ((col / m_tabSize) + 1) * m_tabSize;
} else { else
col++; col++;
}
} }
return col; return col;
} }
@@ -1318,9 +1317,8 @@ void QtStyleCodeFormatter::adjustIndent(const QList<Token> &tokens, int startLex
break; break;
case Colon: case Colon:
if (topState.type == ternary_op) { if (topState.type == ternary_op)
*indentDepth -= 2; *indentDepth -= 2;
}
break; break;
case Question: case Question:
@@ -238,9 +238,8 @@ void CompletionContextFinder::checkImport()
break; break;
} }
} else if (tokenString == QLatin1String("import")) { } else if (tokenString == QLatin1String("import")) {
if (state == Unknown || (state & ExpectImport)) { if (state == Unknown || (state & ExpectImport))
m_inImport = true; m_inImport = true;
}
} else { } else {
if (state == Unknown || (state & ExpectAnyTarget) if (state == Unknown || (state & ExpectAnyTarget)
|| (state & ExpectTargetIdentifier)) { || (state & ExpectTargetIdentifier)) {
+5 -10
View File
@@ -61,9 +61,8 @@ private:
bool BuildParentHash::preVisit(Node* ast) bool BuildParentHash::preVisit(Node* ast)
{ {
if (ast->uiObjectMemberCast()) { if (ast->uiObjectMemberCast())
stack.append(ast->uiObjectMemberCast()); stack.append(ast->uiObjectMemberCast());
}
return true; return true;
} }
@@ -71,9 +70,8 @@ void BuildParentHash::postVisit(Node* ast)
{ {
if (ast->uiObjectMemberCast()) { if (ast->uiObjectMemberCast()) {
stack.removeLast(); stack.removeLast();
if (!stack.isEmpty()) { if (!stack.isEmpty())
parent.insert(ast->uiObjectMemberCast(), stack.last()); parent.insert(ast->uiObjectMemberCast(), stack.last());
}
} }
} }
@@ -291,9 +289,8 @@ static QString _propertyName(UiQualifiedId *id)
static QString _methodName(UiSourceElement *source) static QString _methodName(UiSourceElement *source)
{ {
if (source) { if (source) {
if (FunctionDeclaration *declaration = cast<FunctionDeclaration*>(source->sourceElement)) { if (FunctionDeclaration *declaration = cast<FunctionDeclaration*>(source->sourceElement))
return declaration->name.toString(); return declaration->name.toString();
}
} }
return QString(); return QString();
} }
@@ -415,9 +412,8 @@ void Delta::update(UiObjectMember* oldObject, const QmlJS::Document::Ptr& oldDoc
const QString scriptCode = _scriptCode(script, newDoc); const QString scriptCode = _scriptCode(script, newDoc);
UiScriptBinding *previousScript = cast<UiScriptBinding *>(oldMember); UiScriptBinding *previousScript = cast<UiScriptBinding *>(oldMember);
if (!previousScript || _scriptCode(previousScript, oldDoc) != scriptCode) { if (!previousScript || _scriptCode(previousScript, oldDoc) != scriptCode) {
if (debugReferences.count()==0) { if (debugReferences.count()==0)
notifyUnsyncronizableElementChange(newObject); notifyUnsyncronizableElementChange(newObject);
}
foreach (DebugId ref, debugReferences) { foreach (DebugId ref, debugReferences) {
if (ref != -1) if (ref != -1)
updateScriptBinding(ref, newObject, script, property, scriptCode); updateScriptBinding(ref, newObject, script, property, scriptCode);
@@ -429,9 +425,8 @@ void Delta::update(UiObjectMember* oldObject, const QmlJS::Document::Ptr& oldDoc
UiSourceElement *previousSource = cast<UiSourceElement*>(oldMember); UiSourceElement *previousSource = cast<UiSourceElement*>(oldMember);
if (!previousSource || _methodCode(previousSource, oldDoc) != methodCode) { if (!previousSource || _methodCode(previousSource, oldDoc) != methodCode) {
if (debugReferences.count()==0) { if (debugReferences.count()==0)
notifyUnsyncronizableElementChange(newObject); notifyUnsyncronizableElementChange(newObject);
}
foreach (DebugId ref, debugReferences) { foreach (DebugId ref, debugReferences) {
if (ref != -1) if (ref != -1)
updateMethodBody(ref, newObject, script, methodName, methodCode); updateMethodBody(ref, newObject, script, methodName, methodCode);
+1 -2
View File
@@ -378,9 +378,8 @@ Document::MutablePtr Snapshot::documentFromSource(
{ {
Document::MutablePtr newDoc = Document::create(fileName, language); Document::MutablePtr newDoc = Document::create(fileName, language);
if (Document::Ptr thisDocument = document(fileName)) { if (Document::Ptr thisDocument = document(fileName))
newDoc->_editorRevision = thisDocument->_editorRevision; newDoc->_editorRevision = thisDocument->_editorRevision;
}
newDoc->setSource(code); newDoc->setSource(code);
return newDoc; return newDoc;
+4 -8
View File
@@ -318,9 +318,8 @@ bool Evaluate::visit(AST::FieldMemberExpression *ast)
return false; return false;
if (const Value *base = _valueOwner->convertToObject(value(ast->base))) { if (const Value *base = _valueOwner->convertToObject(value(ast->base))) {
if (const ObjectValue *obj = base->asObjectValue()) { if (const ObjectValue *obj = base->asObjectValue())
_result = obj->lookupMember(ast->name.toString(), _context); _result = obj->lookupMember(ast->name.toString(), _context);
}
} }
return false; return false;
@@ -328,26 +327,23 @@ bool Evaluate::visit(AST::FieldMemberExpression *ast)
bool Evaluate::visit(AST::NewMemberExpression *ast) bool Evaluate::visit(AST::NewMemberExpression *ast)
{ {
if (const FunctionValue *ctor = value_cast<FunctionValue>(value(ast->base))) { if (const FunctionValue *ctor = value_cast<FunctionValue>(value(ast->base)))
_result = ctor->returnValue(); _result = ctor->returnValue();
}
return false; return false;
} }
bool Evaluate::visit(AST::NewExpression *ast) bool Evaluate::visit(AST::NewExpression *ast)
{ {
if (const FunctionValue *ctor = value_cast<FunctionValue>(value(ast->expression))) { if (const FunctionValue *ctor = value_cast<FunctionValue>(value(ast->expression)))
_result = ctor->returnValue(); _result = ctor->returnValue();
}
return false; return false;
} }
bool Evaluate::visit(AST::CallExpression *ast) bool Evaluate::visit(AST::CallExpression *ast)
{ {
if (const Value *base = value(ast->base)) { if (const Value *base = value(ast->base)) {
if (const FunctionValue *obj = base->asFunctionValue()) { if (const FunctionValue *obj = base->asFunctionValue())
_result = obj->returnValue(); _result = obj->returnValue();
}
} }
return false; return false;
} }
+2 -4
View File
@@ -119,12 +119,10 @@ QIcon Icons::icon(const QString &packageName, const QString typeName) const
QIcon Icons::icon(Node *node) const QIcon Icons::icon(Node *node) const
{ {
if (dynamic_cast<AST::UiObjectDefinition*>(node)) { if (dynamic_cast<AST::UiObjectDefinition*>(node))
return objectDefinitionIcon(); return objectDefinitionIcon();
} if (dynamic_cast<AST::UiScriptBinding*>(node))
if (dynamic_cast<AST::UiScriptBinding*>(node)) {
return scriptBindingIcon(); return scriptBindingIcon();
}
return QIcon(); return QIcon();
} }
+8 -12
View File
@@ -147,11 +147,10 @@ int QmlJSIndenter::columnForIndex(const QString &t, int index) const
index = t.length(); index = t.length();
for (int i = 0; i < index; i++) { for (int i = 0; i < index; i++) {
if (t.at(i) == QLatin1Char('\t')) { if (t.at(i) == QLatin1Char('\t'))
col = ((col / ppHardwareTabSize) + 1) * ppHardwareTabSize; col = ((col / ppHardwareTabSize) + 1) * ppHardwareTabSize;
} else { else
col++; col++;
}
} }
return col; return col;
} }
@@ -288,11 +287,10 @@ int QmlJSIndenter::indentForContinuationLine()
delimiters. delimiters.
*/ */
if (braceDepth == -1) { if (braceDepth == -1) {
if (j < yyLine->length() - 1) { if (j < yyLine->length() - 1)
hook = j; hook = j;
} else { else
return 0; // shouldn't happen return 0; // shouldn't happen
}
} }
break; break;
case '=': case '=':
@@ -587,17 +585,15 @@ int QmlJSIndenter::indentForBottomLine(QTextBlock begin, QTextBlock end, QChar t
smartly, unless the user has already played around with it, smartly, unless the user has already played around with it,
in which case it's better to leave her stuff alone. in which case it's better to leave her stuff alone.
*/ */
if (isOnlyWhiteSpace(bottomLine)) { if (isOnlyWhiteSpace(bottomLine))
indent = indentWhenBottomLineStartsInMultiLineComment(); indent = indentWhenBottomLineStartsInMultiLineComment();
} else { else
indent = indentOfLine(bottomLine); indent = indentOfLine(bottomLine);
}
} else { } else {
if (isUnfinishedLine()) { if (isUnfinishedLine())
indent = indentForContinuationLine(); indent = indentForContinuationLine();
} else { else
indent = indentForStandaloneLine(); indent = indentForStandaloneLine();
}
if ((okay(typedIn, QLatin1Char('}')) && firstCh == QLatin1Char('}')) if ((okay(typedIn, QLatin1Char('}')) && firstCh == QLatin1Char('}'))
|| (okay(typedIn, QLatin1Char(']')) && firstCh == QLatin1Char(']'))) { || (okay(typedIn, QLatin1Char(']')) && firstCh == QLatin1Char(']'))) {
+16 -28
View File
@@ -357,9 +357,8 @@ const Value *CppComponentValue::valueForCppName(const QString &typeName) const
// might be an enum // might be an enum
const CppComponentValue *base = this; const CppComponentValue *base = this;
const QStringList components = typeName.split(QLatin1String("::")); const QStringList components = typeName.split(QLatin1String("::"));
if (components.size() == 2) { if (components.size() == 2)
base = valueOwner()->cppQmlTypes().objectByCppName(components.first()); base = valueOwner()->cppQmlTypes().objectByCppName(components.first());
}
if (base) { if (base) {
if (const QmlEnumValue *value = base->getEnumValue(components.last())) if (const QmlEnumValue *value = base->getEnumValue(components.last()))
return value; return value;
@@ -413,9 +412,8 @@ QString CppComponentValue::propertyType(const QString &propertyName) const
foreach (const CppComponentValue *it, prototypes()) { foreach (const CppComponentValue *it, prototypes()) {
FakeMetaObject::ConstPtr iter = it->_metaObject; FakeMetaObject::ConstPtr iter = it->_metaObject;
int propIdx = iter->propertyIndex(propertyName); int propIdx = iter->propertyIndex(propertyName);
if (propIdx != -1) { if (propIdx != -1)
return iter->property(propIdx).typeName(); return iter->property(propIdx).typeName();
}
} }
return QString(); return QString();
} }
@@ -425,9 +423,8 @@ bool CppComponentValue::isListProperty(const QString &propertyName) const
foreach (const CppComponentValue *it, prototypes()) { foreach (const CppComponentValue *it, prototypes()) {
FakeMetaObject::ConstPtr iter = it->_metaObject; FakeMetaObject::ConstPtr iter = it->_metaObject;
int propIdx = iter->propertyIndex(propertyName); int propIdx = iter->propertyIndex(propertyName);
if (propIdx != -1) { if (propIdx != -1)
return iter->property(propIdx).isList(); return iter->property(propIdx).isList();
}
} }
return false; return false;
} }
@@ -510,9 +507,8 @@ bool CppComponentValue::isWritable(const QString &propertyName) const
foreach (const CppComponentValue *it, prototypes()) { foreach (const CppComponentValue *it, prototypes()) {
FakeMetaObject::ConstPtr iter = it->_metaObject; FakeMetaObject::ConstPtr iter = it->_metaObject;
int propIdx = iter->propertyIndex(propertyName); int propIdx = iter->propertyIndex(propertyName);
if (propIdx != -1) { if (propIdx != -1)
return iter->property(propIdx).isWritable(); return iter->property(propIdx).isWritable();
}
} }
return false; return false;
} }
@@ -522,9 +518,8 @@ bool CppComponentValue::isPointer(const QString &propertyName) const
foreach (const CppComponentValue *it, prototypes()) { foreach (const CppComponentValue *it, prototypes()) {
FakeMetaObject::ConstPtr iter = it->_metaObject; FakeMetaObject::ConstPtr iter = it->_metaObject;
int propIdx = iter->propertyIndex(propertyName); int propIdx = iter->propertyIndex(propertyName);
if (propIdx != -1) { if (propIdx != -1)
return iter->property(propIdx).isPointer(); return iter->property(propIdx).isPointer();
}
} }
return false; return false;
} }
@@ -542,9 +537,8 @@ bool CppComponentValue::hasProperty(const QString &propertyName) const
foreach (const CppComponentValue *it, prototypes()) { foreach (const CppComponentValue *it, prototypes()) {
FakeMetaObject::ConstPtr iter = it->_metaObject; FakeMetaObject::ConstPtr iter = it->_metaObject;
int propIdx = iter->propertyIndex(propertyName); int propIdx = iter->propertyIndex(propertyName);
if (propIdx != -1) { if (propIdx != -1)
return true; return true;
}
} }
return false; return false;
} }
@@ -956,9 +950,8 @@ const ObjectValue *ObjectValue::prototype(const Context *context) const
{ {
const ObjectValue *prototypeObject = value_cast<ObjectValue>(_prototype); const ObjectValue *prototypeObject = value_cast<ObjectValue>(_prototype);
if (! prototypeObject) { if (! prototypeObject) {
if (const Reference *prototypeReference = value_cast<Reference>(_prototype)) { if (const Reference *prototypeReference = value_cast<Reference>(_prototype))
prototypeObject = value_cast<ObjectValue>(context->lookupReference(prototypeReference)); prototypeObject = value_cast<ObjectValue>(context->lookupReference(prototypeReference));
}
} }
return prototypeObject; return prototypeObject;
} }
@@ -1110,9 +1103,8 @@ const ObjectValue *PrototypeIterator::next()
const ObjectValue *PrototypeIterator::peekNext() const ObjectValue *PrototypeIterator::peekNext()
{ {
if (hasNext()) { if (hasNext())
return m_next; return m_next;
}
return 0; return 0;
} }
@@ -1299,11 +1291,10 @@ void CppQmlTypesLoader::parseQmlTypeDescriptions(const QByteArray &xml,
warningMessage->clear(); warningMessage->clear();
TypeDescriptionReader reader(QString::fromUtf8(xml)); TypeDescriptionReader reader(QString::fromUtf8(xml));
if (!reader(newObjects, newModuleApis)) { if (!reader(newObjects, newModuleApis)) {
if (reader.errorMessage().isEmpty()) { if (reader.errorMessage().isEmpty())
*errorMessage = QLatin1String("unknown error"); *errorMessage = QLatin1String("unknown error");
} else { else
*errorMessage = reader.errorMessage(); *errorMessage = reader.errorMessage();
}
} }
*warningMessage = reader.warningMessage(); *warningMessage = reader.warningMessage();
} }
@@ -2106,18 +2097,16 @@ ImportInfo ImportInfo::pathImport(const QString &docPath, const QString &path,
info._name = path; info._name = path;
QFileInfo importFileInfo(path); QFileInfo importFileInfo(path);
if (!importFileInfo.isAbsolute()) { if (!importFileInfo.isAbsolute())
importFileInfo = QFileInfo(docPath + QDir::separator() + path); importFileInfo = QFileInfo(docPath + QDir::separator() + path);
}
info._path = importFileInfo.absoluteFilePath(); info._path = importFileInfo.absoluteFilePath();
if (importFileInfo.isFile()) { if (importFileInfo.isFile())
info._type = FileImport; info._type = FileImport;
} else if (importFileInfo.isDir()) { else if (importFileInfo.isDir())
info._type = DirectoryImport; info._type = DirectoryImport;
} else { else
info._type = UnknownFileImport; info._type = UnknownFileImport;
}
info._version = version; info._version = version;
info._as = as; info._as = as;
@@ -2230,11 +2219,10 @@ void TypeScope::processMembers(MemberProcessor *processor) const
if (info.type() == ImportInfo::FileImport) if (info.type() == ImportInfo::FileImport)
continue; continue;
if (!info.as().isEmpty()) { if (!info.as().isEmpty())
processor->processProperty(info.as(), import); processor->processProperty(info.as(), import);
} else { else
import->processMembers(processor); import->processMembers(processor);
}
} }
} }
+2 -3
View File
@@ -205,11 +205,10 @@ QString LineInfo::trimmedCodeLine(const QString &t)
while (i >= 2) { while (i >= 2) {
const Token &prev = yyLinizerState.tokens.at(i-1); const Token &prev = yyLinizerState.tokens.at(i-1);
const Token &prevPrev = yyLinizerState.tokens.at(i-2); const Token &prevPrev = yyLinizerState.tokens.at(i-2);
if (prev.kind == Token::Dot && prevPrev.kind == Token::Identifier) { if (prev.kind == Token::Dot && prevPrev.kind == Token::Identifier)
i -= 2; i -= 2;
} else { else
break; break;
}
} }
// it could also be 'a = \n Foo \n {', but that sounds unlikely // it could also be 'a = \n Foo \n {', but that sounds unlikely
+4 -7
View File
@@ -460,11 +460,10 @@ bool LinkPrivate::importLibrary(Document::Ptr doc,
// all but no-uri module apis become available for import // all but no-uri module apis become available for import
QList<ModuleApiInfo> noUriModuleApis; QList<ModuleApiInfo> noUriModuleApis;
foreach (const ModuleApiInfo &moduleApi, libraryInfo.moduleApis()) { foreach (const ModuleApiInfo &moduleApi, libraryInfo.moduleApis()) {
if (moduleApi.uri.isEmpty()) { if (moduleApi.uri.isEmpty())
noUriModuleApis += moduleApi; noUriModuleApis += moduleApi;
} else { else
importableModuleApis[moduleApi.uri] += moduleApi; importableModuleApis[moduleApi.uri] += moduleApi;
}
} }
// if a module api has no uri, it shares the same name // if a module api has no uri, it shares the same name
@@ -501,9 +500,8 @@ void LinkPrivate::loadQmldirComponents(ObjectValue *import, ComponentVersion ver
const LibraryInfo &libraryInfo, const QString &libraryPath) const LibraryInfo &libraryInfo, const QString &libraryPath)
{ {
// if the version isn't valid, import the latest // if the version isn't valid, import the latest
if (!version.isValid()) { if (!version.isValid())
version = ComponentVersion(ComponentVersion::MaxVersion, ComponentVersion::MaxVersion); version = ComponentVersion(ComponentVersion::MaxVersion, ComponentVersion::MaxVersion);
}
QSet<QString> importedTypes; QSet<QString> importedTypes;
@@ -535,9 +533,8 @@ void LinkPrivate::loadImplicitDirectoryImports(Imports *imports, Document::Ptr d
if (directoryImport.object) if (directoryImport.object)
importCache.insert(ImportCacheKey(implcitDirectoryImportInfo), directoryImport); importCache.insert(ImportCacheKey(implcitDirectoryImportInfo), directoryImport);
} }
if (directoryImport.object) { if (directoryImport.object)
imports->append(directoryImport); imports->append(directoryImport);
}
} }
void LinkPrivate::loadImplicitDefaultImports(Imports *imports) void LinkPrivate::loadImplicitDefaultImports(Imports *imports)
+1 -2
View File
@@ -143,9 +143,8 @@ static bool isEnum(AST::Statement *ast)
if (!ast) if (!ast)
return false; return false;
if (ExpressionStatement *exprStmt = cast<ExpressionStatement*>(ast)) { if (ExpressionStatement *exprStmt = cast<ExpressionStatement*>(ast))
return isEnum(exprStmt->expression); return isEnum(exprStmt->expression);
}
return false; return false;
} }
+14 -20
View File
@@ -166,11 +166,10 @@ protected:
if (precededByEmptyLine(fixedLoc)) if (precededByEmptyLine(fixedLoc))
newLine(); newLine();
out(toString(fixedLoc)); // don't use the sourceloc overload here out(toString(fixedLoc)); // don't use the sourceloc overload here
if (followedByNewLine(fixedLoc)) { if (followedByNewLine(fixedLoc))
newLine(); newLine();
} else { else
out(" "); out(" ");
}
} }
void out(const QString &str, const SourceLocation &lastLoc = SourceLocation()) void out(const QString &str, const SourceLocation &lastLoc = SourceLocation())
@@ -260,9 +259,8 @@ protected:
qreal result = badnessFromSplits; qreal result = badnessFromSplits;
foreach (const QString &line, lines) { foreach (const QString &line, lines) {
// really long lines should be avoided at all cost // really long lines should be avoided at all cost
if (line.size() > strongMaxLineLength) { if (line.size() > strongMaxLineLength)
result += 50 + (line.size() - strongMaxLineLength); result += 50 + (line.size() - strongMaxLineLength);
}
// having long lines is bad // having long lines is bad
else if (line.size() > maxLineLength) { else if (line.size() > maxLineLength) {
result += 3 + (line.size() - maxLineLength); result += 3 + (line.size() - maxLineLength);
@@ -446,22 +444,20 @@ protected:
virtual bool preVisit(Node *ast) virtual bool preVisit(Node *ast)
{ {
SourceLocation firstLoc; SourceLocation firstLoc;
if (ExpressionNode *expr = ast->expressionCast()) { if (ExpressionNode *expr = ast->expressionCast())
firstLoc = expr->firstSourceLocation(); firstLoc = expr->firstSourceLocation();
} else if (Statement *stmt = ast->statementCast()) { else if (Statement *stmt = ast->statementCast())
firstLoc = stmt->firstSourceLocation(); firstLoc = stmt->firstSourceLocation();
} else if (UiObjectMember *mem = ast->uiObjectMemberCast()) { else if (UiObjectMember *mem = ast->uiObjectMemberCast())
firstLoc = mem->firstSourceLocation(); firstLoc = mem->firstSourceLocation();
} else if (UiImport *import = cast<UiImport *>(ast)) { else if (UiImport *import = cast<UiImport *>(ast))
firstLoc = import->firstSourceLocation(); firstLoc = import->firstSourceLocation();
}
if (firstLoc.isValid() && int(firstLoc.offset) != _lastNewlineOffset) { if (firstLoc.isValid() && int(firstLoc.offset) != _lastNewlineOffset) {
_lastNewlineOffset = firstLoc.offset; _lastNewlineOffset = firstLoc.offset;
if (precededByEmptyLine(firstLoc) && !_result.endsWith(QLatin1String("\n\n"))) { if (precededByEmptyLine(firstLoc) && !_result.endsWith(QLatin1String("\n\n")))
newLine(); newLine();
}
} }
return true; return true;
@@ -470,15 +466,14 @@ protected:
virtual void postVisit(Node *ast) virtual void postVisit(Node *ast)
{ {
SourceLocation lastLoc; SourceLocation lastLoc;
if (ExpressionNode *expr = ast->expressionCast()) { if (ExpressionNode *expr = ast->expressionCast())
lastLoc = expr->lastSourceLocation(); lastLoc = expr->lastSourceLocation();
} else if (Statement *stmt = ast->statementCast()) { else if (Statement *stmt = ast->statementCast())
lastLoc = stmt->lastSourceLocation(); lastLoc = stmt->lastSourceLocation();
} else if (UiObjectMember *mem = ast->uiObjectMemberCast()) { else if (UiObjectMember *mem = ast->uiObjectMemberCast())
lastLoc = mem->lastSourceLocation(); lastLoc = mem->lastSourceLocation();
} else if (UiImport *import = cast<UiImport *>(ast)) { else if (UiImport *import = cast<UiImport *>(ast))
lastLoc = import->lastSourceLocation(); lastLoc = import->lastSourceLocation();
}
if (lastLoc.isValid()) { if (lastLoc.isValid()) {
const QList<SourceLocation> &comments = _doc->engine()->comments(); const QList<SourceLocation> &comments = _doc->engine()->comments();
@@ -510,11 +505,10 @@ protected:
virtual bool visit(UiImport *ast) virtual bool visit(UiImport *ast)
{ {
out("import ", ast->importToken); out("import ", ast->importToken);
if (!ast->fileName.isNull()) { if (!ast->fileName.isNull())
out(QString::fromLatin1("\"%1\"").arg(ast->fileName.toString())); out(QString::fromLatin1("\"%1\"").arg(ast->fileName.toString()));
} else { else
accept(ast->importUri); accept(ast->importUri);
}
if (ast->versionToken.isValid()) { if (ast->versionToken.isValid()) {
out(" "); out(" ");
out(ast->versionToken); out(ast->versionToken);
+8 -15
View File
@@ -288,9 +288,8 @@ void Rewriter::changeBinding(UiObjectInitializer *ast,
// for grouped properties: // for grouped properties:
else if (!prefix.isEmpty()) { else if (!prefix.isEmpty()) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) { if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
if (toString(def->qualifiedTypeNameId) == prefix) { if (toString(def->qualifiedTypeNameId) == prefix)
changeBinding(def->initializer, suffix, newValue, binding); changeBinding(def->initializer, suffix, newValue, binding);
}
} }
} }
} }
@@ -353,11 +352,10 @@ bool Rewriter::isMatchingPropertyMember(const QString &propertyName,
bool Rewriter::nextMemberOnSameLine(UiObjectMemberList *members) bool Rewriter::nextMemberOnSameLine(UiObjectMemberList *members)
{ {
if (members && members->next && members->next->member) { if (members && members->next && members->next->member)
return members->next->member->firstSourceLocation().startLine == members->member->lastSourceLocation().startLine; return members->next->member->firstSourceLocation().startLine == members->member->lastSourceLocation().startLine;
} else { else
return false; return false;
}
} }
void Rewriter::insertIntoArray(UiArrayBinding *ast, const QString &newValue) void Rewriter::insertIntoArray(UiArrayBinding *ast, const QString &newValue)
@@ -388,15 +386,13 @@ void Rewriter::removeBindingByName(UiObjectInitializer *ast, const QString &prop
UiObjectMember *member = it->member; UiObjectMember *member = it->member;
// run full name match (for ungrouped properties): // run full name match (for ungrouped properties):
if (isMatchingPropertyMember(propertyName, member)) { if (isMatchingPropertyMember(propertyName, member))
removeMember(member); removeMember(member);
}
// check for grouped properties: // check for grouped properties:
else if (!prefix.isEmpty()) { else if (!prefix.isEmpty()) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) { if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
if (toString(def->qualifiedTypeNameId) == prefix) { if (toString(def->qualifiedTypeNameId) == prefix)
removeGroupedProperty(def, propertyName); removeGroupedProperty(def, propertyName);
}
} }
} }
} }
@@ -417,9 +413,8 @@ void Rewriter::removeGroupedProperty(UiObjectDefinition *ast,
++memberCount; ++memberCount;
UiObjectMember *member = it->member; UiObjectMember *member = it->member;
if (!wanted && isMatchingPropertyMember(propName, member)) { if (!wanted && isMatchingPropertyMember(propName, member))
wanted = member; wanted = member;
}
} }
if (!wanted) if (!wanted)
@@ -517,9 +512,8 @@ void Rewriter::includeEmptyGroupedProperty(UiObjectDefinition *groupedProperty,
// grouped property // grouped property
UiObjectMemberList *memberIter = groupedProperty->initializer->members; UiObjectMemberList *memberIter = groupedProperty->initializer->members;
while (memberIter) { while (memberIter) {
if (memberIter->member != memberToBeRemoved) { if (memberIter->member != memberToBeRemoved)
return; return;
}
memberIter = memberIter->next; memberIter = memberIter->next;
} }
start = groupedProperty->firstSourceLocation().begin(); start = groupedProperty->firstSourceLocation().begin();
@@ -670,9 +664,8 @@ void Rewriter::removeObjectMember(UiObjectMember *member, UiObjectMember *parent
if (UiArrayBinding *parentArray = cast<UiArrayBinding *>(parent)) { if (UiArrayBinding *parentArray = cast<UiArrayBinding *>(parent)) {
extendToLeadingOrTrailingComma(parentArray, member, start, end); extendToLeadingOrTrailingComma(parentArray, member, start, end);
} else { } else {
if (UiObjectDefinition *parentObjectDefinition = cast<UiObjectDefinition *>(parent)) { if (UiObjectDefinition *parentObjectDefinition = cast<UiObjectDefinition *>(parent))
includeEmptyGroupedProperty(parentObjectDefinition, member, start, end); includeEmptyGroupedProperty(parentObjectDefinition, member, start, end);
}
includeSurroundingWhitespace(m_originalText, start, end); includeSurroundingWhitespace(m_originalText, start, end);
} }
+3 -4
View File
@@ -55,13 +55,12 @@ void ScopeAstPath::accept(Node *node)
bool ScopeAstPath::preVisit(Node *node) bool ScopeAstPath::preVisit(Node *node)
{ {
if (Statement *stmt = node->statementCast()) { if (Statement *stmt = node->statementCast())
return containsOffset(stmt->firstSourceLocation(), stmt->lastSourceLocation()); return containsOffset(stmt->firstSourceLocation(), stmt->lastSourceLocation());
} else if (ExpressionNode *exp = node->expressionCast()) { else if (ExpressionNode *exp = node->expressionCast())
return containsOffset(exp->firstSourceLocation(), exp->lastSourceLocation()); return containsOffset(exp->firstSourceLocation(), exp->lastSourceLocation());
} else if (UiObjectMember *ui = node->uiObjectMemberCast()) { else if (UiObjectMember *ui = node->uiObjectMemberCast())
return containsOffset(ui->firstSourceLocation(), ui->lastSourceLocation()); return containsOffset(ui->firstSourceLocation(), ui->lastSourceLocation());
}
return true; return true;
} }
+6 -10
View File
@@ -81,14 +81,12 @@ void ScopeBuilder::push(AST::Node *node)
break; break;
} }
// signals defined in QML // signals defined in QML
if (const ASTSignal *astsig = value_cast<ASTSignal>(value)) { if (const ASTSignal *astsig = value_cast<ASTSignal>(value))
_scopeChain->appendJsScope(astsig->bodyScope()); _scopeChain->appendJsScope(astsig->bodyScope());
}
// signals defined in C++ // signals defined in C++
else if (const CppComponentValue *qmlObject = value_cast<CppComponentValue>(owner)) { else if (const CppComponentValue *qmlObject = value_cast<CppComponentValue>(owner)) {
if (const ObjectValue *scope = qmlObject->signalScope(name)) { if (const ObjectValue *scope = qmlObject->signalScope(name))
_scopeChain->appendJsScope(scope); _scopeChain->appendJsScope(scope);
}
} }
} }
} }
@@ -170,11 +168,10 @@ void ScopeBuilder::setQmlScopeObject(Node *node)
} }
const ObjectValue *scopeObject = _scopeChain->document()->bind()->findQmlObject(node); const ObjectValue *scopeObject = _scopeChain->document()->bind()->findQmlObject(node);
if (scopeObject) { if (scopeObject)
qmlScopeObjects += scopeObject; qmlScopeObjects += scopeObject;
} else { else
return; // Probably syntax errors, where we're working with a "recovered" AST. return; // Probably syntax errors, where we're working with a "recovered" AST.
}
// check if the object has a Qt.ListElement or Qt.Connections ancestor // check if the object has a Qt.ListElement or Qt.Connections ancestor
// ### allow only signal bindings for Connections // ### allow only signal bindings for Connections
@@ -208,11 +205,10 @@ void ScopeBuilder::setQmlScopeObject(Node *node)
Evaluate evaluator(_scopeChain); Evaluate evaluator(_scopeChain);
const Value *targetValue = evaluator(scriptBinding->statement); const Value *targetValue = evaluator(scriptBinding->statement);
if (const ObjectValue *target = value_cast<ObjectValue>(targetValue)) { if (const ObjectValue *target = value_cast<ObjectValue>(targetValue))
qmlScopeObjects.prepend(target); qmlScopeObjects.prepend(target);
} else { else
qmlScopeObjects.clear(); qmlScopeObjects.clear();
}
} }
} }
} }
+22 -28
View File
@@ -157,11 +157,10 @@ void TypeDescriptionReader::readModule(UiObjectDefinition *ast)
continue; continue;
} }
if (typeName == QLatin1String("Component")) { if (typeName == QLatin1String("Component"))
readComponent(component); readComponent(component);
} else if (typeName == QLatin1String("ModuleApi")) { else if (typeName == QLatin1String("ModuleApi"))
readModuleApi(component); readModuleApi(component);
}
} }
} }
@@ -191,15 +190,14 @@ void TypeDescriptionReader::readComponent(UiObjectDefinition *ast)
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (component) { if (component) {
QString name = toString(component->qualifiedTypeNameId); QString name = toString(component->qualifiedTypeNameId);
if (name == QLatin1String("Property")) { if (name == QLatin1String("Property"))
readProperty(component, fmo); readProperty(component, fmo);
} else if (name == QLatin1String("Method") || name == QLatin1String("Signal")) { else if (name == QLatin1String("Method") || name == QLatin1String("Signal"))
readSignalOrMethod(component, name == QLatin1String("Method"), fmo); readSignalOrMethod(component, name == QLatin1String("Method"), fmo);
} else if (name == QLatin1String("Enum")) { else if (name == QLatin1String("Enum"))
readEnum(component, fmo); readEnum(component, fmo);
} else { else
addWarning(component->firstSourceLocation(), tr("Expected only Property, Method, Signal and Enum object definitions")); addWarning(component->firstSourceLocation(), tr("Expected only Property, Method, Signal and Enum object definitions"));
}
} else if (script) { } else if (script) {
QString name = toString(script->qualifiedId); QString name = toString(script->qualifiedId);
if (name == QLatin1String("name")) { if (name == QLatin1String("name")) {
@@ -283,22 +281,20 @@ void TypeDescriptionReader::readSignalOrMethod(UiObjectDefinition *ast, bool isM
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (component) { if (component) {
QString name = toString(component->qualifiedTypeNameId); QString name = toString(component->qualifiedTypeNameId);
if (name == QLatin1String("Parameter")) { if (name == QLatin1String("Parameter"))
readParameter(component, &fmm); readParameter(component, &fmm);
} else { else
addWarning(component->firstSourceLocation(), tr("Expected only Parameter object definitions")); addWarning(component->firstSourceLocation(), tr("Expected only Parameter object definitions"));
}
} else if (script) { } else if (script) {
QString name = toString(script->qualifiedId); QString name = toString(script->qualifiedId);
if (name == QLatin1String("name")) { if (name == QLatin1String("name"))
fmm.setMethodName(readStringBinding(script)); fmm.setMethodName(readStringBinding(script));
} else if (name == QLatin1String("type")) { else if (name == QLatin1String("type"))
fmm.setReturnType(readStringBinding(script)); fmm.setReturnType(readStringBinding(script));
} else if (name == QLatin1String("revision")) { else if (name == QLatin1String("revision"))
fmm.setRevision(readIntBinding(script)); fmm.setRevision(readIntBinding(script));
} else { else
addWarning(script->firstSourceLocation(), tr("Expected only name and type script bindings")); addWarning(script->firstSourceLocation(), tr("Expected only name and type script bindings"));
}
} else { } else {
addWarning(member->firstSourceLocation(), tr("Expected only script bindings and object definitions")); addWarning(member->firstSourceLocation(), tr("Expected only script bindings and object definitions"));
@@ -331,21 +327,20 @@ void TypeDescriptionReader::readProperty(UiObjectDefinition *ast, FakeMetaObject
} }
QString id = toString(script->qualifiedId); QString id = toString(script->qualifiedId);
if (id == QLatin1String("name")) { if (id == QLatin1String("name"))
name = readStringBinding(script); name = readStringBinding(script);
} else if (id == QLatin1String("type")) { else if (id == QLatin1String("type"))
type = readStringBinding(script); type = readStringBinding(script);
} else if (id == QLatin1String("isPointer")) { else if (id == QLatin1String("isPointer"))
isPointer = readBoolBinding(script); isPointer = readBoolBinding(script);
} else if (id == QLatin1String("isReadonly")) { else if (id == QLatin1String("isReadonly"))
isReadonly = readBoolBinding(script); isReadonly = readBoolBinding(script);
} else if (id == QLatin1String("isList")) { else if (id == QLatin1String("isList"))
isList = readBoolBinding(script); isList = readBoolBinding(script);
} else if (id == QLatin1String("revision")) { else if (id == QLatin1String("revision"))
revision = readIntBinding(script); revision = readIntBinding(script);
} else { else
addWarning(script->firstSourceLocation(), tr("Expected only type, name, revision, isPointer, isReadonly and isList script bindings")); addWarning(script->firstSourceLocation(), tr("Expected only type, name, revision, isPointer, isReadonly and isList script bindings"));
}
} }
if (name.isEmpty() || type.isEmpty()) { if (name.isEmpty() || type.isEmpty()) {
@@ -369,13 +364,12 @@ void TypeDescriptionReader::readEnum(UiObjectDefinition *ast, FakeMetaObject::Pt
} }
QString name = toString(script->qualifiedId); QString name = toString(script->qualifiedId);
if (name == QLatin1String("name")) { if (name == QLatin1String("name"))
fme.setName(readStringBinding(script)); fme.setName(readStringBinding(script));
} else if (name == QLatin1String("values")) { else if (name == QLatin1String("values"))
readEnumValues(script, &fme); readEnumValues(script, &fme);
} else { else
addWarning(script->firstSourceLocation(), tr("Expected only name and values script bindings")); addWarning(script->firstSourceLocation(), tr("Expected only name and values script bindings"));
}
} }
fmo->addEnum(fme); fmo->addEnum(fme);
@@ -132,16 +132,14 @@ void QStyleItem::initStyleOption()
break; break;
case Splitter: { case Splitter: {
if (!m_styleoption) { if (!m_styleoption)
m_styleoption = new QStyleOption; m_styleoption = new QStyleOption;
}
} }
break; break;
case Item: { case Item: {
if (!m_styleoption) { if (!m_styleoption)
m_styleoption = new QStyleOptionViewItemV4(); m_styleoption = new QStyleOptionViewItemV4();
}
QStyleOptionViewItemV4 *opt = qstyleoption_cast<QStyleOptionViewItemV4*>(m_styleoption); QStyleOptionViewItemV4 *opt = qstyleoption_cast<QStyleOptionViewItemV4*>(m_styleoption);
opt->features = QStyleOptionViewItemV4::HasDisplay; opt->features = QStyleOptionViewItemV4::HasDisplay;
opt->text = text(); opt->text = text();
@@ -446,11 +444,10 @@ void QStyleItem::initStyleOption()
m_styleoption->fontMetrics = widget()->fontMetrics(); m_styleoption->fontMetrics = widget()->fontMetrics();
if (!m_styleoption->palette.resolve()) if (!m_styleoption->palette.resolve())
m_styleoption->palette = widget()->palette(); m_styleoption->palette = widget()->palette();
if (m_hint.contains("mac.mini")) { if (m_hint.contains("mac.mini"))
widget()->setAttribute(Qt::WA_MacMiniSize); widget()->setAttribute(Qt::WA_MacMiniSize);
} else if (m_hint.contains("mac.small")) { else if (m_hint.contains("mac.small"))
widget()->setAttribute(Qt::WA_MacSmallSize); widget()->setAttribute(Qt::WA_MacSmallSize);
}
} }
} }
@@ -1018,9 +1015,8 @@ void QStyleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWid
qApp->style()->drawComplexControl(QStyle::CC_ScrollBar, qstyleoption_cast<QStyleOptionComplex*>(m_styleoption), painter, widget()); qApp->style()->drawComplexControl(QStyle::CC_ScrollBar, qstyleoption_cast<QStyleOptionComplex*>(m_styleoption), painter, widget());
break; break;
case Menu: { case Menu: {
if (QMenu *menu = qobject_cast<QMenu*>(widget())) { if (QMenu *menu = qobject_cast<QMenu*>(widget()))
m_styleoption->palette = menu->palette(); m_styleoption->palette = menu->palette();
}
QStyleHintReturnMask val; QStyleHintReturnMask val;
qApp->style()->styleHint(QStyle::SH_Menu_Mask, m_styleoption, widget(), &val); qApp->style()->styleHint(QStyle::SH_Menu_Mask, m_styleoption, widget(), &val);
painter->save(); painter->save();
+6 -9
View File
@@ -360,11 +360,10 @@ AbstractSymbolGroupNodePtrVector
block -= blockArraySize; block -= blockArraySize;
const ULONG64 blockOffset = offset % dequeSize; const ULONG64 blockOffset = offset % dequeSize;
const ULONG64 address = blockArray[block] + innerTypeSize * blockOffset; const ULONG64 address = blockArray[block] + innerTypeSize * blockOffset;
if (SymbolGroupNode *n = sg->addSymbol(module, SymbolGroupValue::pointedToSymbolName(address, innerType), std::string(), &errorMessage)) { if (SymbolGroupNode *n = sg->addSymbol(module, SymbolGroupValue::pointedToSymbolName(address, innerType), std::string(), &errorMessage))
rc.push_back(ReferenceSymbolGroupNode::createArrayNode(i, n)); rc.push_back(ReferenceSymbolGroupNode::createArrayNode(i, n));
} else { else
return AbstractSymbolGroupNodePtrVector(); return AbstractSymbolGroupNodePtrVector();
}
} }
return rc; return rc;
} }
@@ -842,11 +841,10 @@ SymbolGroupValueVector qHashNodes(const SymbolGroupValue &v,
nodeList.reserve(count); nodeList.reserve(count);
const SymbolGroupValueVector::const_iterator dcend = dummyNodeList.end(); const SymbolGroupValueVector::const_iterator dcend = dummyNodeList.end();
for (SymbolGroupValueVector::const_iterator it = dummyNodeList.begin(); it != dcend; ++it) { for (SymbolGroupValueVector::const_iterator it = dummyNodeList.begin(); it != dcend; ++it) {
if (const SymbolGroupValue n = (*it).typeCast(nodeType.c_str())) { if (const SymbolGroupValue n = (*it).typeCast(nodeType.c_str()))
nodeList.push_back(n); nodeList.push_back(n);
} else { } else
return SymbolGroupValueVector(); return SymbolGroupValueVector();
}
} }
return nodeList; return nodeList;
} }
@@ -865,11 +863,10 @@ static inline AbstractSymbolGroupNodePtrVector
return rc; return rc;
rc.reserve(count); rc.reserve(count);
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
if (const SymbolGroupValue key = nodes.at(i)["key"]) { if (const SymbolGroupValue key = nodes.at(i)["key"])
rc.push_back(ReferenceSymbolGroupNode::createArrayNode(i, key.node())); rc.push_back(ReferenceSymbolGroupNode::createArrayNode(i, key.node()));
} else { else
return AbstractSymbolGroupNodePtrVector(); return AbstractSymbolGroupNodePtrVector();
}
} }
return rc; return rc;
} }
@@ -88,11 +88,10 @@ void ExtensionContext::hookCallbacks(CIDebugClient *client)
void ExtensionContext::startRecordingOutput() void ExtensionContext::startRecordingOutput()
{ {
if (m_creatorOutputCallback) { if (m_creatorOutputCallback)
m_creatorOutputCallback->startRecording(); m_creatorOutputCallback->startRecording();
} else { else
report('X', 0, 0, "Error", "ExtensionContext::startRecordingOutput() called with no output hooked.\n"); report('X', 0, 0, "Error", "ExtensionContext::startRecordingOutput() called with no output hooked.\n");
}
} }
std::wstring ExtensionContext::stopRecordingOutput() std::wstring ExtensionContext::stopRecordingOutput()
@@ -189,18 +188,16 @@ void ExtensionContext::notifyIdleCommand(CIDebugClient *client)
formatGdbmiHash(str, stopReasons, false); formatGdbmiHash(str, stopReasons, false);
const std::string threadInfo = gdbmiThreadList(exc.systemObjects(), exc.symbols(), const std::string threadInfo = gdbmiThreadList(exc.systemObjects(), exc.symbols(),
exc.control(), exc.advanced(), &errorMessage); exc.control(), exc.advanced(), &errorMessage);
if (threadInfo.empty()) { if (threadInfo.empty())
str << ",threaderror=" << gdbmiStringFormat(errorMessage); str << ",threaderror=" << gdbmiStringFormat(errorMessage);
} else { else
str << ",threads=" << threadInfo; str << ",threads=" << threadInfo;
}
const std::string stackInfo = gdbmiStack(exc.control(), exc.symbols(), const std::string stackInfo = gdbmiStack(exc.control(), exc.symbols(),
maxStackFrames, false, &errorMessage); maxStackFrames, false, &errorMessage);
if (stackInfo.empty()) { if (stackInfo.empty())
str << ",stackerror=" << gdbmiStringFormat(errorMessage); str << ",stackerror=" << gdbmiStringFormat(errorMessage);
} else { else
str << ",stack=" << stackInfo; str << ",stack=" << stackInfo;
}
str << '}'; str << '}';
reportLong('E', 0, "session_idle", str.str()); reportLong('E', 0, "session_idle", str.str());
} }
+2 -3
View File
@@ -107,11 +107,10 @@ void getFrame(CIDebugSymbols *debugSymbols,
WCHAR wBuf[MAX_PATH]; WCHAR wBuf[MAX_PATH];
f->address = s.InstructionOffset; f->address = s.InstructionOffset;
HRESULT hr = debugSymbols->GetNameByOffsetWide(f->address, wBuf, MAX_PATH, 0, 0); HRESULT hr = debugSymbols->GetNameByOffsetWide(f->address, wBuf, MAX_PATH, 0, 0);
if (SUCCEEDED(hr)) { if (SUCCEEDED(hr))
f->function = wBuf; f->function = wBuf;
} else { else
f->function.clear(); f->function.clear();
}
ULONG64 ul64Displacement = 0; ULONG64 ul64Displacement = 0;
hr = debugSymbols->GetLineByOffsetWide(f->address, &(f->line), wBuf, MAX_PATH, 0, &ul64Displacement); hr = debugSymbols->GetLineByOffsetWide(f->address, &(f->line), wBuf, MAX_PATH, 0, &ul64Displacement);
if (SUCCEEDED(hr)) { if (SUCCEEDED(hr)) {
@@ -277,11 +277,10 @@ extern "C" HRESULT CALLBACK pid(CIDebugClient *client, PCSTR args)
commandTokens<StringList>(args, &token); commandTokens<StringList>(args, &token);
dprintf("Qt Creator CDB extension version 2.7 (Qt 5 support) %d bit built %s.\n", dprintf("Qt Creator CDB extension version 2.7 (Qt 5 support) %d bit built %s.\n",
sizeof(void *) * 8, __DATE__); sizeof(void *) * 8, __DATE__);
if (const ULONG pid = currentProcessId(client)) { if (const ULONG pid = currentProcessId(client))
ExtensionContext::instance().report('R', token, 0, "pid", "%u", pid); ExtensionContext::instance().report('R', token, 0, "pid", "%u", pid);
} else { else
ExtensionContext::instance().report('N', token, 0, "pid", "0"); ExtensionContext::instance().report('N', token, 0, "pid", "0");
}
return S_OK; return S_OK;
} }
@@ -564,11 +563,10 @@ extern "C" HRESULT CALLBACK locals(CIDebugClient *client, PCSTR args)
int token; int token;
const std::string output = commmandLocals(exc, args, &token, &errorMessage); const std::string output = commmandLocals(exc, args, &token, &errorMessage);
SymbolGroupValue::verbose = 0; SymbolGroupValue::verbose = 0;
if (output.empty()) { if (output.empty())
ExtensionContext::instance().report('N', token, 0, "locals", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "locals", errorMessage.c_str());
} else { else
ExtensionContext::instance().reportLong('R', token, "locals", output); ExtensionContext::instance().reportLong('R', token, "locals", output);
}
return S_OK; return S_OK;
} }
@@ -619,11 +617,10 @@ extern "C" HRESULT CALLBACK watches(CIDebugClient *client, PCSTR args)
int token = 0; int token = 0;
const std::string output = commmandWatches(exc, args, &token, &errorMessage); const std::string output = commmandWatches(exc, args, &token, &errorMessage);
SymbolGroupValue::verbose = 0; SymbolGroupValue::verbose = 0;
if (output.empty()) { if (output.empty())
ExtensionContext::instance().report('N', token, 0, "locals", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "locals", errorMessage.c_str());
} else { else
ExtensionContext::instance().reportLong('R', token, "locals", output); ExtensionContext::instance().reportLong('R', token, "locals", output);
}
return S_OK; return S_OK;
} }
@@ -670,11 +667,10 @@ extern "C" HRESULT CALLBACK dumplocal(CIDebugClient *client, PCSTR argsIn)
std::string errorMessage; std::string errorMessage;
int token = 0; int token = 0;
const std::string value = dumplocalHelper(exc,argsIn, &token, &errorMessage); const std::string value = dumplocalHelper(exc,argsIn, &token, &errorMessage);
if (value.empty()) { if (value.empty())
ExtensionContext::instance().report('N', token, 0, "dumplocal", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "dumplocal", errorMessage.c_str());
} else { else
ExtensionContext::instance().reportLong('R', token, "dumplocal", value); ExtensionContext::instance().reportLong('R', token, "dumplocal", value);
}
return S_OK; return S_OK;
} }
@@ -699,11 +695,10 @@ extern "C" HRESULT CALLBACK typecast(CIDebugClient *client, PCSTR args)
} else { } else {
errorMessage = singleLineUsage(commandDescriptions[CmdTypecast]); errorMessage = singleLineUsage(commandDescriptions[CmdTypecast]);
} }
if (symGroup != 0 && symGroup->typeCast(iname, desiredType, &errorMessage)) { if (symGroup != 0 && symGroup->typeCast(iname, desiredType, &errorMessage))
ExtensionContext::instance().report('R', token, 0, "typecast", "OK"); ExtensionContext::instance().report('R', token, 0, "typecast", "OK");
} else { else
ExtensionContext::instance().report('N', token, 0, "typecast", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "typecast", errorMessage.c_str());
}
return S_OK; return S_OK;
} }
@@ -729,11 +724,10 @@ extern "C" HRESULT CALLBACK addsymbol(CIDebugClient *client, PCSTR args)
} else { } else {
errorMessage = singleLineUsage(commandDescriptions[CmdAddsymbol]); errorMessage = singleLineUsage(commandDescriptions[CmdAddsymbol]);
} }
if (symGroup != 0 && symGroup->addSymbol(std::string(), name, iname, &errorMessage)) { if (symGroup != 0 && symGroup->addSymbol(std::string(), name, iname, &errorMessage))
ExtensionContext::instance().report('R', token, 0, "addsymbol", "OK"); ExtensionContext::instance().report('R', token, 0, "addsymbol", "OK");
} else { else
ExtensionContext::instance().report('N', token, 0, "addsymbol", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "addsymbol", errorMessage.c_str());
}
return S_OK; return S_OK;
} }
@@ -763,11 +757,10 @@ extern "C" HRESULT CALLBACK addwatch(CIDebugClient *client, PCSTR argsIn)
success = watchesSymGroup->addWatch(exc.symbols(), iname, watchExpression, &errorMessage); success = watchesSymGroup->addWatch(exc.symbols(), iname, watchExpression, &errorMessage);
} while (false); } while (false);
if (success) { if (success)
ExtensionContext::instance().report('R', token, 0, "addwatch", "Ok"); ExtensionContext::instance().report('R', token, 0, "addwatch", "Ok");
} else { else
ExtensionContext::instance().report('N', token, 0, "addwatch", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "addwatch", errorMessage.c_str());
}
return S_OK; return S_OK;
} }
@@ -824,11 +817,10 @@ extern "C" HRESULT CALLBACK assign(CIDebugClient *client, PCSTR argsIn)
&errorMessage); &errorMessage);
} while (false); } while (false);
if (success) { if (success)
ExtensionContext::instance().report('R', token, 0, "assign", "Ok"); ExtensionContext::instance().report('R', token, 0, "assign", "Ok");
} else { else
ExtensionContext::instance().report('N', token, 0, "assign", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "assign", errorMessage.c_str());
}
return S_OK; return S_OK;
} }
@@ -848,11 +840,10 @@ extern "C" HRESULT CALLBACK threads(CIDebugClient *client, PCSTR argsIn)
exc.control(), exc.control(),
exc.advanced(), exc.advanced(),
&errorMessage); &errorMessage);
if (gdbmi.empty()) { if (gdbmi.empty())
ExtensionContext::instance().report('N', token, 0, "threads", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "threads", errorMessage.c_str());
} else { else
ExtensionContext::instance().reportLong('R', token, "threads", gdbmi); ExtensionContext::instance().reportLong('R', token, "threads", gdbmi);
}
return S_OK; return S_OK;
} }
@@ -868,11 +859,10 @@ extern "C" HRESULT CALLBACK registers(CIDebugClient *Client, PCSTR argsIn)
const StringList tokens = commandTokens<StringList>(argsIn, &token); const StringList tokens = commandTokens<StringList>(argsIn, &token);
const bool humanReadable = !tokens.empty() && tokens.front() == "-h"; const bool humanReadable = !tokens.empty() && tokens.front() == "-h";
const std::string regs = gdbmiRegisters(exc.registers(), exc.control(), humanReadable, IncludePseudoRegisters, &errorMessage); const std::string regs = gdbmiRegisters(exc.registers(), exc.control(), humanReadable, IncludePseudoRegisters, &errorMessage);
if (regs.empty()) { if (regs.empty())
ExtensionContext::instance().report('N', token, 0, "registers", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "registers", errorMessage.c_str());
} else { else
ExtensionContext::instance().reportLong('R', token, "registers", regs); ExtensionContext::instance().reportLong('R', token, "registers", regs);
}
return S_OK; return S_OK;
} }
@@ -888,11 +878,10 @@ extern "C" HRESULT CALLBACK modules(CIDebugClient *Client, PCSTR argsIn)
const StringList tokens = commandTokens<StringList>(argsIn, &token); const StringList tokens = commandTokens<StringList>(argsIn, &token);
const bool humanReadable = !tokens.empty() && tokens.front() == "-h"; const bool humanReadable = !tokens.empty() && tokens.front() == "-h";
const std::string modules = gdbmiModules(exc.symbols(), humanReadable, &errorMessage); const std::string modules = gdbmiModules(exc.symbols(), humanReadable, &errorMessage);
if (modules.empty()) { if (modules.empty())
ExtensionContext::instance().report('N', token, 0, "modules", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "modules", errorMessage.c_str());
} else { else
ExtensionContext::instance().reportLong('R', token, "modules", modules); ExtensionContext::instance().reportLong('R', token, "modules", modules);
}
return S_OK; return S_OK;
} }
@@ -969,11 +958,10 @@ extern "C" HRESULT CALLBACK expression(CIDebugClient *Client, PCSTR argsIn)
break; break;
} while (false); } while (false);
if (errorMessage.empty()) { if (errorMessage.empty())
ExtensionContext::instance().reportLong('R', token, "expression", toString(value)); ExtensionContext::instance().reportLong('R', token, "expression", toString(value));
} else { else
ExtensionContext::instance().report('N', token, 0, "expression", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "expression", errorMessage.c_str());
}
return S_OK; return S_OK;
} }
@@ -1000,11 +988,10 @@ extern "C" HRESULT CALLBACK stack(CIDebugClient *Client, PCSTR argsIn)
const std::string stack = gdbmiStack(exc.control(), exc.symbols(), const std::string stack = gdbmiStack(exc.control(), exc.symbols(),
maxFrames, humanReadable, &errorMessage); maxFrames, humanReadable, &errorMessage);
if (stack.empty()) { if (stack.empty())
ExtensionContext::instance().report('N', token, 0, "stack", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "stack", errorMessage.c_str());
} else { else
ExtensionContext::instance().reportLong('R', token, "stack", stack); ExtensionContext::instance().reportLong('R', token, "stack", stack);
}
return S_OK; return S_OK;
} }
@@ -1041,11 +1028,10 @@ extern "C" HRESULT CALLBACK widgetat(CIDebugClient *client, PCSTR argsIn)
x, y, &errorMessage); x, y, &errorMessage);
} while (false); } while (false);
if (widgetAddress.empty()) { if (widgetAddress.empty())
ExtensionContext::instance().report('N', token, 0, "widgetat", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "widgetat", errorMessage.c_str());
} else { else
ExtensionContext::instance().reportLong('R', token, "widgetat", widgetAddress); ExtensionContext::instance().reportLong('R', token, "widgetat", widgetAddress);
}
return S_OK; return S_OK;
} }
@@ -1070,11 +1056,10 @@ extern "C" HRESULT CALLBACK breakpoints(CIDebugClient *client, PCSTR argsIn)
} }
const std::string bp = gdbmiBreakpoints(exc.control(), exc.symbols(), exc.dataSpaces(), const std::string bp = gdbmiBreakpoints(exc.control(), exc.symbols(), exc.dataSpaces(),
humanReadable, verbose, &errorMessage); humanReadable, verbose, &errorMessage);
if (bp.empty()) { if (bp.empty())
ExtensionContext::instance().report('N', token, 0, "breakpoints", errorMessage.c_str()); ExtensionContext::instance().report('N', token, 0, "breakpoints", errorMessage.c_str());
} else { else
ExtensionContext::instance().reportLong('R', token, "breakpoints", bp); ExtensionContext::instance().reportLong('R', token, "breakpoints", bp);
}
return S_OK; return S_OK;
} }
+2 -3
View File
@@ -268,11 +268,10 @@ std::string dumpMemory(const unsigned char *p, size_t size,
case '\n': case '\n':
str << "\\n"; str << "\\n";
default: default:
if (u >= 32 && u < 128) { if (u >= 32 && u < 128)
str << (char(u)); str << (char(u));
} else { else
str << '\\' << std::setw(3) << unsigned(u); str << '\\' << std::setw(3) << unsigned(u);
}
} }
} }
if (wantQuotes) if (wantQuotes)
+2 -3
View File
@@ -239,11 +239,10 @@ std::string SymbolGroup::debug(const std::string &iname,
if (iname.empty()) { if (iname.empty()) {
accept(*visitor); accept(*visitor);
} else { } else {
if (AbstractSymbolGroupNode *const node = find(iname)) { if (AbstractSymbolGroupNode *const node = find(iname))
node->accept(*visitor, SymbolGroupNodeVisitor::parentIname(iname), 0, 0); node->accept(*visitor, SymbolGroupNodeVisitor::parentIname(iname), 0, 0);
} else { else
str << msgNotFound(iname); str << msgNotFound(iname);
}
} }
return str.str(); return str.str();
} }
+13 -20
View File
@@ -251,11 +251,10 @@ void BaseSymbolGroupNode::addChild(AbstractSymbolGroupNode *c)
std::ostream &operator<<(std::ostream &str, const DEBUG_SYMBOL_PARAMETERS &parameters) std::ostream &operator<<(std::ostream &str, const DEBUG_SYMBOL_PARAMETERS &parameters)
{ {
str << "parent="; str << "parent=";
if (parameters.ParentSymbol == DEBUG_ANY_ID) { if (parameters.ParentSymbol == DEBUG_ANY_ID)
str << "DEBUG_ANY_ID"; str << "DEBUG_ANY_ID";
} else { else
str << parameters.ParentSymbol ; str << parameters.ParentSymbol ;
}
if (parameters.Flags != 0 && parameters.Flags != 1) if (parameters.Flags != 0 && parameters.Flags != 1)
str << " flags=" << parameters.Flags; str << " flags=" << parameters.Flags;
// Detailed flags: // Detailed flags:
@@ -669,17 +668,15 @@ bool SymbolGroupNode::notifyIndexesMoved(ULONG index, bool inserted, ULONG offse
if (m_index == DEBUG_ANY_ID || m_index < index) if (m_index == DEBUG_ANY_ID || m_index < index)
return false; return false;
if (inserted) { if (inserted)
m_index += offset; m_index += offset;
} else { else
m_index -= offset; m_index -= offset;
}
if (m_parameters.ParentSymbol != DEBUG_ANY_ID && m_parameters.ParentSymbol >= index) { if (m_parameters.ParentSymbol != DEBUG_ANY_ID && m_parameters.ParentSymbol >= index) {
if (inserted) { if (inserted)
m_parameters.ParentSymbol += offset; m_parameters.ParentSymbol += offset;
} else { else
m_parameters.ParentSymbol -= offset; m_parameters.ParentSymbol -= offset;
}
} }
return true; return true;
} }
@@ -732,9 +729,8 @@ static inline void fixNames(bool isTopLevel, StringVector *names, StringVector *
* 3) For toplevels: Fix shadowed variables in the order the debugger expects them: * 3) For toplevels: Fix shadowed variables in the order the debugger expects them:
\code \code
int x; // Occurrence (1), should be reported as name="x <shadowed 1>"/iname="x#1" int x; // Occurrence (1), should be reported as name="x <shadowed 1>"/iname="x#1"
if (true) { if (true)
int x = 5; (2) // Occurrence (2), should be reported as name="x"/iname="x" int x = 5; (2) // Occurrence (2), should be reported as name="x"/iname="x"
}
\endcode */ \endcode */
StringVector::iterator nameIt = names->begin(); StringVector::iterator nameIt = names->begin();
const StringVector::iterator namesEnd = names->end(); const StringVector::iterator namesEnd = names->end();
@@ -1103,11 +1099,10 @@ int SymbolGroupNode::dumpNode(std::ostream &str,
// Emulate gdb's behaviour of returning the referenced address // Emulate gdb's behaviour of returning the referenced address
// for pointers. // for pointers.
str << std::hex << std::showbase; str << std::hex << std::showbase;
if (referencedAddr) { if (referencedAddr)
str << ",addr=\"" << referencedAddr << "\",origaddr=\"" << addr << '"'; str << ",addr=\"" << referencedAddr << "\",origaddr=\"" << addr << '"';
} else { else
str << ",addr=\"" << addr << '"'; str << ",addr=\"" << addr << '"';
}
str << std::noshowbase << std::dec; str << std::noshowbase << std::dec;
} }
const ULONG s = size(); const ULONG s = size();
@@ -1141,11 +1136,10 @@ int SymbolGroupNode::dumpNode(std::ostream &str,
if (m_dumperContainerSize > 0) { if (m_dumperContainerSize > 0) {
childCountGuess = m_dumperContainerSize; // See Obscured handling childCountGuess = m_dumperContainerSize; // See Obscured handling
} else { } else {
if (children().empty()) { if (children().empty())
childCountGuess = m_parameters.SubElements; // Guess childCountGuess = m_parameters.SubElements; // Guess
} else { else
childCountGuess = unsigned(children().size()); childCountGuess = unsigned(children().size());
}
} }
} }
// No children..suppose we are editable and enabled. // No children..suppose we are editable and enabled.
@@ -1646,11 +1640,10 @@ SymbolGroupNodeVisitor::VisitResult
if (!realNode->isExpanded() || realNode->testFlags(SymbolGroupNode::Uninitialized|SymbolGroupNode::ExpandedByDumper)) if (!realNode->isExpanded() || realNode->testFlags(SymbolGroupNode::Uninitialized|SymbolGroupNode::ExpandedByDumper))
visitChildren = false; visitChildren = false;
// Comma between same level children given obscured children // Comma between same level children given obscured children
if (depth == m_lastDepth) { if (depth == m_lastDepth)
m_os << ','; m_os << ',';
} else { else
m_lastDepth = depth; m_lastDepth = depth;
}
if (m_parameters.humanReadable()) { if (m_parameters.humanReadable()) {
m_os << '\n'; m_os << '\n';
indentStream(m_os, depth * 2); indentStream(m_os, depth * 2);
+12 -18
View File
@@ -701,11 +701,10 @@ const QtInfo &QtInfo::get(const SymbolGroupValueContext &ctx)
} }
rc.libInfix = qualifiedSymbol.substr(libPos + 4, exclPos - libPos - 4); rc.libInfix = qualifiedSymbol.substr(libPos + 4, exclPos - libPos - 4);
// 'Qt5Cored!qstrdup' or 'QtCored4!qstrdup'. // 'Qt5Cored!qstrdup' or 'QtCored4!qstrdup'.
if (isdigit(qualifiedSymbol.at(2))) { if (isdigit(qualifiedSymbol.at(2)))
rc.version = qualifiedSymbol.at(2) - '0'; rc.version = qualifiedSymbol.at(2) - '0';
} else { else
rc.version = qualifiedSymbol.at(exclPos - 1) - '0'; rc.version = qualifiedSymbol.at(exclPos - 1) - '0';
}
// Any namespace? 'QtCored4!nsp::qstrdup' // Any namespace? 'QtCored4!nsp::qstrdup'
const std::string::size_type nameSpaceStart = exclPos + 1; const std::string::size_type nameSpaceStart = exclPos + 1;
const std::string::size_type colonPos = qualifiedSymbol.find(':', nameSpaceStart); const std::string::size_type colonPos = qualifiedSymbol.find(':', nameSpaceStart);
@@ -1585,11 +1584,10 @@ static inline bool dumpQString(const SymbolGroupValue &v, std::wostream &str,
} else { } else {
str << L"\"\""; str << L"\"\"";
} }
if (memoryHandle) { if (memoryHandle)
*memoryHandle = new MemoryHandle(memory, size); *memoryHandle = new MemoryHandle(memory, size);
} else { else
delete [] memory; delete [] memory;
}
return true; return true;
} }
@@ -1691,11 +1689,10 @@ static inline bool dumpQByteArray(const SymbolGroupValue &v, std::wostream &str,
} else { } else {
str << L"<empty>"; str << L"<empty>";
} }
if (memoryHandle) { if (memoryHandle)
*memoryHandle = new MemoryHandle(reinterpret_cast<unsigned char *>(memory), size); *memoryHandle = new MemoryHandle(reinterpret_cast<unsigned char *>(memory), size);
} else { else
delete [] memory; delete [] memory;
}
return true; return true;
} }
@@ -2012,13 +2009,12 @@ static inline bool dumpQFlags(const SymbolGroupValue &v, std::wostream &str)
static bool dumpJulianDate(int julianDay, std::wostream &str) static bool dumpJulianDate(int julianDay, std::wostream &str)
{ {
if (julianDay < 0) { if (julianDay < 0)
return false; return false;
} else if (!julianDay) { else if (!julianDay)
str << L"<null>"; str << L"<null>";
} else { else
formatJulianDate(str, julianDay); formatJulianDate(str, julianDay);
}
return true; return true;
} }
@@ -2292,11 +2288,10 @@ static bool dumpStd_W_String(const SymbolGroupValue &v, int type, std::wostream
str << (type == KT_StdString ? str << (type == KT_StdString ?
quotedWStringFromCharData(memory, memSize) : quotedWStringFromCharData(memory, memSize) :
quotedWStringFromWCharData(memory, memSize)); quotedWStringFromWCharData(memory, memSize));
if (memoryHandle) { if (memoryHandle)
*memoryHandle = new MemoryHandle(memory, memSize); *memoryHandle = new MemoryHandle(memory, memSize);
} else { else
delete [] memory; delete [] memory;
}
return true; return true;
} }
@@ -2403,9 +2398,8 @@ static bool dumpQVariant(const SymbolGroupValue &v, std::wostream &str, void **s
break; break;
case 10: // String case 10: // String
str << L"(QString) "; str << L"(QString) ";
if (const SymbolGroupValue sv = dataV.typeCast(qtInfo.prependQtCoreModule("QString *").c_str())) { if (const SymbolGroupValue sv = dataV.typeCast(qtInfo.prependQtCoreModule("QString *").c_str()))
dumpQString(sv, str); dumpQString(sv, str);
}
break; break;
case 11: //StringList: Dump container size case 11: //StringList: Dump container size
str << L"(QStringList) "; str << L"(QStringList) ";
+1 -2
View File
@@ -472,9 +472,8 @@ void SshConnectionPrivate::handleKeyExchangeInitPacket()
// If the server sends a guessed packet, the guess must be wrong, // If the server sends a guessed packet, the guess must be wrong,
// because the algorithms we support require us to initiate the // because the algorithms we support require us to initiate the
// key exchange. // key exchange.
if (m_keyExchange->sendDhInitPacket(m_incomingPacket)) { if (m_keyExchange->sendDhInitPacket(m_incomingPacket))
m_ignoreNextPacket = true; m_ignoreNextPacket = true;
}
m_keyExchangeState = DhInitSent; m_keyExchangeState = DhInitSent;
} }
+2 -3
View File
@@ -81,11 +81,10 @@ void SshKeyCreationDialog::generateKeys()
m_ui->comboBox->currentText().toUShort()); m_ui->comboBox->currentText().toUShort());
QApplication::restoreOverrideCursor(); QApplication::restoreOverrideCursor();
if (success) { if (success)
saveKeys(); saveKeys();
} else { else
QMessageBox::critical(this, tr("Key Generation Failed"), m_keyGenerator->error()); QMessageBox::critical(this, tr("Key Generation Failed"), m_keyGenerator->error());
}
} }
void SshKeyCreationDialog::handleBrowseButtonClicked() void SshKeyCreationDialog::handleBrowseButtonClicked()
+2 -4
View File
@@ -56,9 +56,8 @@ Utils::FileName BuildableHelperLibrary::findSystemQt(const Utils::Environment &e
foreach (const QString &possibleCommand, possibleQMakeCommands()) { foreach (const QString &possibleCommand, possibleQMakeCommands()) {
const QFileInfo qmake(prefix + possibleCommand); const QFileInfo qmake(prefix + possibleCommand);
if (qmake.exists()) { if (qmake.exists()) {
if (!qtVersionForQMake(qmake.absoluteFilePath()).isNull()) { if (!qtVersionForQMake(qmake.absoluteFilePath()).isNull())
return Utils::FileName(qmake); return Utils::FileName(qmake);
}
} }
} }
} }
@@ -158,9 +157,8 @@ bool BuildableHelperLibrary::copyFiles(const QString &sourcePath,
return false; return false;
} }
} }
if (!destInfo.dir().exists()) { if (!destInfo.dir().exists())
QDir().mkpath(destInfo.dir().absolutePath()); QDir().mkpath(destInfo.dir().absolutePath());
}
if (!QFile::copy(source, dest)) { if (!QFile::copy(source, dest)) {
*errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary", "The file %1 could not be copied to %2.").arg(source, dest); *errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary", "The file %1 could not be copied to %2.").arg(source, dest);
+8 -11
View File
@@ -124,27 +124,24 @@ void CrumblePathButton::paintEvent(QPaintEvent *)
} }
if (m_isEnd) { if (m_isEnd) {
if (m_isPressed || m_isSelected) { if (m_isPressed || m_isSelected)
Utils::StyleHelper::drawCornerImage(m_segmentSelectedEnd, &p, geom, 2, 0, 2, 0); Utils::StyleHelper::drawCornerImage(m_segmentSelectedEnd, &p, geom, 2, 0, 2, 0);
} else if (m_isHovering) { else if (m_isHovering)
Utils::StyleHelper::drawCornerImage(m_segmentHoverEnd, &p, geom, 2, 0, 2, 0); Utils::StyleHelper::drawCornerImage(m_segmentHoverEnd, &p, geom, 2, 0, 2, 0);
} else { else
Utils::StyleHelper::drawCornerImage(m_segmentEnd, &p, geom, 2, 0, 2, 0); Utils::StyleHelper::drawCornerImage(m_segmentEnd, &p, geom, 2, 0, 2, 0);
}
} else { } else {
if (m_isPressed || m_isSelected) { if (m_isPressed || m_isSelected)
Utils::StyleHelper::drawCornerImage(m_segmentSelected, &p, geom, 2, 0, 12, 0); Utils::StyleHelper::drawCornerImage(m_segmentSelected, &p, geom, 2, 0, 12, 0);
} else if (m_isHovering) { else if (m_isHovering)
Utils::StyleHelper::drawCornerImage(m_segmentHover, &p, geom, 2, 0, 12, 0); Utils::StyleHelper::drawCornerImage(m_segmentHover, &p, geom, 2, 0, 12, 0);
} else { else
Utils::StyleHelper::drawCornerImage(m_segment, &p, geom, 2, 0, 12, 0); Utils::StyleHelper::drawCornerImage(m_segment, &p, geom, 2, 0, 12, 0);
}
} }
if (isEnabled()) { if (isEnabled())
p.setPen(StyleHelper::panelTextColor()); p.setPen(StyleHelper::panelTextColor());
} else { else
p.setPen(StyleHelper::panelTextColor().darker()); p.setPen(StyleHelper::panelTextColor().darker());
}
QFontMetrics fm(p.font()); QFontMetrics fm(p.font());
QString textToDraw = fm.elidedText(text(), Qt::ElideRight, geom.width() - m_textPos.x()); QString textToDraw = fm.elidedText(text(), Qt::ElideRight, geom.width() - m_textPos.x());
+1 -2
View File
@@ -48,9 +48,8 @@ public:
// Add removed variables again and mark them as "<UNSET>" so // Add removed variables again and mark them as "<UNSET>" so
// that the user can actually see those removals: // that the user can actually see those removals:
foreach (const Utils::EnvironmentItem &item, m_items) { foreach (const Utils::EnvironmentItem &item, m_items) {
if (item.unset) { if (item.unset)
m_resultEnvironment.set(item.name, EnvironmentModel::tr("<UNSET>")); m_resultEnvironment.set(item.name, EnvironmentModel::tr("<UNSET>"));
}
} }
} }
+4 -6
View File
@@ -58,18 +58,16 @@ static void execMenuAtWidget(QMenu *menu, QWidget *widget)
QSize sh = menu->sizeHint(); QSize sh = menu->sizeHint();
QRect rect = widget->rect(); QRect rect = widget->rect();
if (widget->isRightToLeft()) { if (widget->isRightToLeft()) {
if (widget->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) { if (widget->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height())
p = widget->mapToGlobal(rect.bottomRight()); p = widget->mapToGlobal(rect.bottomRight());
} else { else
p = widget->mapToGlobal(rect.topRight() - QPoint(0, sh.height())); p = widget->mapToGlobal(rect.topRight() - QPoint(0, sh.height()));
}
p.rx() -= sh.width(); p.rx() -= sh.width();
} else { } else {
if (widget->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) { if (widget->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height())
p = widget->mapToGlobal(rect.bottomLeft()); p = widget->mapToGlobal(rect.bottomLeft());
} else { else
p = widget->mapToGlobal(rect.topLeft() - QPoint(0, sh.height())); p = widget->mapToGlobal(rect.topLeft() - QPoint(0, sh.height()));
}
} }
p.rx() = qMax(screen.left(), qMin(p.x(), screen.right() - sh.width())); p.rx() = qMax(screen.left(), qMin(p.x(), screen.right() - sh.width()));
p.ry() += 1; p.ry() += 1;
+2 -3
View File
@@ -105,11 +105,10 @@ QDockWidget *FancyMainWindow::addDockForWidget(QWidget *widget)
dockWidget->setWidget(widget); dockWidget->setWidget(widget);
// Set an object name to be used in settings, derive from widget name // Set an object name to be used in settings, derive from widget name
const QString objectName = widget->objectName(); const QString objectName = widget->objectName();
if (objectName.isEmpty()) { if (objectName.isEmpty())
dockWidget->setObjectName(QLatin1String("dockWidget") + QString::number(dockWidgets().size() + 1)); dockWidget->setObjectName(QLatin1String("dockWidget") + QString::number(dockWidgets().size() + 1));
} else { else
dockWidget->setObjectName(objectName + QLatin1String("DockWidget")); dockWidget->setObjectName(objectName + QLatin1String("DockWidget"));
}
connect(dockWidget->toggleViewAction(), SIGNAL(triggered()), connect(dockWidget->toggleViewAction(), SIGNAL(triggered()),
this, SLOT(onDockActionTriggered()), Qt::QueuedConnection); this, SLOT(onDockActionTriggered()), Qt::QueuedConnection);
connect(dockWidget, SIGNAL(visibilityChanged(bool)), connect(dockWidget, SIGNAL(visibilityChanged(bool)),
@@ -114,11 +114,10 @@ bool FileNameValidatingLineEdit::validateFileName(const QString &name,
if (name.contains(QLatin1Char(*c))) { if (name.contains(QLatin1Char(*c))) {
if (errorMessage) { if (errorMessage) {
const QChar qc = QLatin1Char(*c); const QChar qc = QLatin1Char(*c);
if (qc.isSpace()) { if (qc.isSpace())
*errorMessage = tr("Name contains white space."); *errorMessage = tr("Name contains white space.");
} else { else
*errorMessage = tr("Invalid character '%1'.").arg(qc); *errorMessage = tr("Invalid character '%1'.").arg(qc);
}
} }
return false; return false;
} }
@@ -171,17 +170,15 @@ bool FileNameValidatingLineEdit::validateFileNameExtension(const QString &fileNa
if (!requiredExtensions.isEmpty()) { if (!requiredExtensions.isEmpty()) {
foreach (const QString &requiredExtension, requiredExtensions) { foreach (const QString &requiredExtension, requiredExtensions) {
QString extension = QLatin1String(".") + requiredExtension; QString extension = QLatin1String(".") + requiredExtension;
if (fileName.endsWith(extension, Qt::CaseSensitive) && extension.count() < fileName.count()) { if (fileName.endsWith(extension, Qt::CaseSensitive) && extension.count() < fileName.count())
return true; return true;
}
} }
if (errorMessage) { if (errorMessage) {
if (requiredExtensions.count() == 1) { if (requiredExtensions.count() == 1)
*errorMessage = tr("File extension %1 is required:").arg(requiredExtensions.first()); *errorMessage = tr("File extension %1 is required:").arg(requiredExtensions.first());
} else { else
*errorMessage = tr("File extensions %1 are required:").arg(requiredExtensions.join(QLatin1String(", "))); *errorMessage = tr("File extensions %1 are required:").arg(requiredExtensions.join(QLatin1String(", ")));
}
} }
return false; return false;
+1 -2
View File
@@ -499,9 +499,8 @@ bool SubDirFileIterator::hasNext() const
const bool processed = m_processedValues.pop(); const bool processed = m_processedValues.pop();
if (dir.exists()) { if (dir.exists()) {
QStringList subDirs; QStringList subDirs;
if (!processed) { if (!processed)
subDirs = dir.entryList(QDir::Dirs|QDir::Hidden|QDir::NoDotAndDotDot); subDirs = dir.entryList(QDir::Dirs|QDir::Hidden|QDir::NoDotAndDotDot);
}
if (subDirs.isEmpty()) { if (subDirs.isEmpty()) {
QStringList fileEntries = dir.entryList(m_filters, QStringList fileEntries = dir.entryList(m_filters,
QDir::Files|QDir::Hidden); QDir::Files|QDir::Hidden);
+2 -4
View File
@@ -284,9 +284,8 @@ void FileSystemWatcher::removeFiles(const QStringList &files)
const int count = --(d->m_staticData->m_fileCount[file]); const int count = --(d->m_staticData->m_fileCount[file]);
Q_ASSERT(count >= 0); Q_ASSERT(count >= 0);
if (!count) { if (!count)
toRemove << file; toRemove << file;
}
} }
if (!toRemove.isEmpty()) if (!toRemove.isEmpty())
@@ -362,9 +361,8 @@ void FileSystemWatcher::removeDirectories(const QStringList &directories)
const int count = --d->m_staticData->m_directoryCount[directory]; const int count = --d->m_staticData->m_directoryCount[directory];
Q_ASSERT(count >= 0); Q_ASSERT(count >= 0);
if (!count) { if (!count)
toRemove << directory; toRemove << directory;
}
} }
if (!toRemove.isEmpty()) if (!toRemove.isEmpty())
d->m_staticData->m_watcher->removePaths(toRemove); d->m_staticData->m_watcher->removePaths(toRemove);
+4 -6
View File
@@ -61,20 +61,18 @@ void FlowLayout::addItem(QLayoutItem *item)
int FlowLayout::horizontalSpacing() const int FlowLayout::horizontalSpacing() const
{ {
if (m_hSpace >= 0) { if (m_hSpace >= 0)
return m_hSpace; return m_hSpace;
} else { else
return smartSpacing(QStyle::PM_LayoutHorizontalSpacing); return smartSpacing(QStyle::PM_LayoutHorizontalSpacing);
}
} }
int FlowLayout::verticalSpacing() const int FlowLayout::verticalSpacing() const
{ {
if (m_vSpace >= 0) { if (m_vSpace >= 0)
return m_vSpace; return m_vSpace;
} else { else
return smartSpacing(QStyle::PM_LayoutVerticalSpacing); return smartSpacing(QStyle::PM_LayoutVerticalSpacing);
}
} }
int FlowLayout::count() const int FlowLayout::count() const
+1 -2
View File
@@ -730,9 +730,8 @@ JsonSchema *JsonSchemaManager::parseSchema(const QString &schemaFileName) const
if (reader.fetch(schemaFileName, QIODevice::Text)) { if (reader.fetch(schemaFileName, QIODevice::Text)) {
const QString &contents = QString::fromUtf8(reader.data()); const QString &contents = QString::fromUtf8(reader.data());
JsonValue *json = JsonValue::create(contents); JsonValue *json = JsonValue::create(contents);
if (json && json->kind() == JsonValue::Object) { if (json && json->kind() == JsonValue::Object)
return new JsonSchema(json->toObject(), this); return new JsonSchema(json->toObject(), this);
}
} }
return 0; return 0;
+2 -3
View File
@@ -93,11 +93,10 @@ void ParameterAction::setEnablingMode(EnablingMode m)
void ParameterAction::setParameter(const QString &p) void ParameterAction::setParameter(const QString &p)
{ {
const bool enabled = !p.isEmpty(); const bool enabled = !p.isEmpty();
if (enabled) { if (enabled)
setText(m_parameterText.arg(p)); setText(m_parameterText.arg(p));
} else { else
setText(m_emptyText); setText(m_emptyText);
}
if (m_enablingMode == EnabledWithParameter) if (m_enablingMode == EnabledWithParameter)
setEnabled(enabled); setEnabled(enabled);
} }
+2 -3
View File
@@ -174,11 +174,10 @@ QAction *PathListEditor::insertAction(int index /* -1 */, const QString &text, Q
beforeAction = actions.at(index); beforeAction = actions.at(index);
} }
QAction *rc = createAction(this, text, receiver, slotFunc); QAction *rc = createAction(this, text, receiver, slotFunc);
if (beforeAction) { if (beforeAction)
d->buttonMenu->insertAction(beforeAction, rc); d->buttonMenu->insertAction(beforeAction, rc);
} else { else
d->buttonMenu->addAction(rc); d->buttonMenu->addAction(rc);
}
return rc; return rc;
} }
+3 -4
View File
@@ -97,12 +97,11 @@ QTCREATOR_UTILS_EXPORT Utils::FileDeletedPromptAnswer
box.setDefaultButton(saveas); box.setDefaultButton(saveas);
box.exec(); box.exec();
QAbstractButton *clickedbutton = box.clickedButton(); QAbstractButton *clickedbutton = box.clickedButton();
if (clickedbutton == close) { if (clickedbutton == close)
return FileDeletedClose; return FileDeletedClose;
} else if (clickedbutton == saveas) { else if (clickedbutton == saveas)
return FileDeletedSaveAs; return FileDeletedSaveAs;
} else if (clickedbutton == save) { else if (clickedbutton == save)
return FileDeletedSave; return FileDeletedSave;
}
return FileDeletedClose; return FileDeletedClose;
} }
+2 -3
View File
@@ -256,11 +256,10 @@ SynchronousProcess::~SynchronousProcess()
void SynchronousProcess::setTimeout(int timeoutMS) void SynchronousProcess::setTimeout(int timeoutMS)
{ {
if (timeoutMS >= 0) { if (timeoutMS >= 0)
d->m_maxHangTimerCount = qMax(2, timeoutMS / 1000); d->m_maxHangTimerCount = qMax(2, timeoutMS / 1000);
} else { else
d->m_maxHangTimerCount = INT_MAX; d->m_maxHangTimerCount = INT_MAX;
}
} }
int SynchronousProcess::timeout() const int SynchronousProcess::timeout() const
+5 -7
View File
@@ -103,13 +103,12 @@ TextFileFormat TextFileFormat::detect(const QByteArray &data)
} }
// end code taken from qtextstream // end code taken from qtextstream
const int newLinePos = data.indexOf('\n'); const int newLinePos = data.indexOf('\n');
if (newLinePos == -1) { if (newLinePos == -1)
result.lineTerminationMode = NativeLineTerminator; result.lineTerminationMode = NativeLineTerminator;
} else if (newLinePos == 0) { else if (newLinePos == 0)
result.lineTerminationMode = LFLineTerminator; result.lineTerminationMode = LFLineTerminator;
} else { else
result.lineTerminationMode = data.at(newLinePos - 1) == '\r' ? CRLFLineTerminator : LFLineTerminator; result.lineTerminationMode = data.at(newLinePos - 1) == '\r' ? CRLFLineTerminator : LFLineTerminator;
}
return result; return result;
} }
@@ -286,11 +285,10 @@ bool TextFileFormat::writeFile(const QString &fileName, QString plainText, QStri
// let QFile do the work, else manually add. // let QFile do the work, else manually add.
QIODevice::OpenMode fileMode = QIODevice::NotOpen; QIODevice::OpenMode fileMode = QIODevice::NotOpen;
if (lineTerminationMode == CRLFLineTerminator) { if (lineTerminationMode == CRLFLineTerminator) {
if (NativeLineTerminator == CRLFLineTerminator) { if (NativeLineTerminator == CRLFLineTerminator)
fileMode |= QIODevice::Text; fileMode |= QIODevice::Text;
} else { else
plainText.replace(QLatin1Char('\n'), QLatin1String("\r\n")); plainText.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
}
} }
Utils::FileSaver saver(fileName, fileMode); Utils::FileSaver saver(fileName, fileMode);
+1 -2
View File
@@ -553,9 +553,8 @@ QList<WizardProgressItem *> WizardProgressPrivate::singlePathBetween(WizardProgr
if (itItem.value().count() != 1) if (itItem.value().count() != 1)
return QList<WizardProgressItem *>(); return QList<WizardProgressItem *>();
it = itItem.value().constBegin().key(); it = itItem.value().constBegin().key();
if (it == item) { if (it == item)
return path; return path;
}
itItem = visitedItemsToParents.constFind(it); itItem = visitedItemsToParents.constFind(it);
} }
return QList<WizardProgressItem *>(); return QList<WizardProgressItem *>();
+1 -2
View File
@@ -506,9 +506,8 @@ extern "C" void cAvahiBrowseReply(
} }
ServiceBrowserPrivate *browser = reinterpret_cast<ServiceBrowserPrivate *>(context); ServiceBrowserPrivate *browser = reinterpret_cast<ServiceBrowserPrivate *>(context);
if (browser == 0) { if (browser == 0)
qDebug() << "Error context is null in cAvahiBrowseReply"; qDebug() << "Error context is null in cAvahiBrowseReply";
}
switch (event) { switch (event) {
case AVAHI_BROWSER_FAILURE: case AVAHI_BROWSER_FAILURE:
browser->browseReply(kDNSServiceFlagsMoreComing, 0, protocol, kDNSServiceErr_Unknown, browser->browseReply(kDNSServiceFlagsMoreComing, 0, protocol, kDNSServiceErr_Unknown,
+11 -21
View File
@@ -113,9 +113,8 @@ int fromFullNameC(const char * const fullName, QString &service, QString &regtyp
fullNameDecoded[decodedI++] = c; fullNameDecoded[decodedI++] = c;
} }
} else if (c == '.') { } else if (c == '.') {
if (iPos < 4) { if (iPos < 4)
oldPos[iPos++] = decodedI; oldPos[iPos++] = decodedI;
}
fullNameDecoded[decodedI++] = c; fullNameDecoded[decodedI++] = c;
} else { } else {
fullNameDecoded[decodedI++] = c; fullNameDecoded[decodedI++] = c;
@@ -387,11 +386,10 @@ QDebug operator<<(QDebug dbg, const Service &service)
} }
QDebug operator<<(QDebug dbg, const Service::ConstPtr &service){ QDebug operator<<(QDebug dbg, const Service::ConstPtr &service){
if (service.data() == 0){ if (service.data() == 0)
dbg << "Service{*NULL*}"; dbg << "Service{*NULL*}";
} else { else
dbg << *service.data(); dbg << *service.data();
}
return dbg; return dbg;
} }
@@ -718,9 +716,8 @@ extern "C" void DNSSD_API cAddrReply(DNSServiceRef sdRef,
<< interfaceIndex << ", " << ((int)errorCode) << ", " << hostname << ", " << interfaceIndex << ", " << ((int)errorCode) << ", " << hostname << ", "
<< QHostAddress(address).toString() << ", " << ttl << ", " << ((size_t)context); << QHostAddress(address).toString() << ", " << ttl << ", " << ((size_t)context);
ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context); ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context);
if (ctxGatherer){ if (ctxGatherer)
ctxGatherer->addrReply(flags, errorCode, hostname, address, ttl); ctxGatherer->addrReply(flags, errorCode, hostname, address, ttl);
}
} }
/// callback for service browsing /// callback for service browsing
@@ -856,9 +853,8 @@ void ServiceGatherer::restartResolve(ZK_IP_Protocol protocol)
changed = true; changed = true;
} }
} }
if (changed) { if (changed)
currentService->m_host->setAddresses(addrNow); currentService->m_host->setAddresses(addrNow);
}
} }
DNSServiceErrorType err = lib()->resolve( DNSServiceErrorType err = lib()->resolve(
serviceBrowser->mainRef(), serviceBrowser->mainRef(),
@@ -889,9 +885,8 @@ void ServiceGatherer::restartResolve(ZK_IP_Protocol protocol)
changed = true; changed = true;
} }
} }
if (changed) { if (changed)
currentService->m_host->setAddresses(addrNow); currentService->m_host->setAddresses(addrNow);
}
} }
} }
DNSServiceErrorType err = lib()->resolve( DNSServiceErrorType err = lib()->resolve(
@@ -1085,9 +1080,8 @@ void ServiceGatherer::serviceResolveReply(DNSServiceFlags fl
else else
currentService->m_host->setAddresses(QList<QHostAddress>()); currentService->m_host->setAddresses(QList<QHostAddress>());
currentService->m_host->setHostName(hostName); currentService->m_host->setHostName(hostName);
if (serviceBrowser->autoResolveAddresses){ if (serviceBrowser->autoResolveAddresses)
restartHostResolution(); restartHostResolution();
}
} }
if (currentServiceCanBePublished()) if (currentServiceCanBePublished())
serviceBrowser->pendingGathererAdd(gatherer()); serviceBrowser->pendingGathererAdd(gatherer());
@@ -1144,9 +1138,8 @@ void ServiceGatherer::txtRecordReply(DNSServiceFlags flags,
currentService->m_txtRecord.remove(QString::fromUtf8(keyBuf)); // check value??? currentService->m_txtRecord.remove(QString::fromUtf8(keyBuf)); // check value???
} }
} }
if ((flags & kDNSServiceFlagsAdd) != 0) { if ((flags & kDNSServiceFlagsAdd) != 0)
status |= TxtConnectionSuccess; status |= TxtConnectionSuccess;
}
if (currentService->m_txtRecord.count() != 0 && currentServiceCanBePublished()) if (currentService->m_txtRecord.count() != 0 && currentServiceCanBePublished())
serviceBrowser->pendingGathererAdd(gatherer()); serviceBrowser->pendingGathererAdd(gatherer());
} }
@@ -1373,12 +1366,10 @@ ServiceBrowserPrivate::~ServiceBrowserPrivate()
{ {
if (DEBUG_ZEROCONF) if (DEBUG_ZEROCONF)
qDebug() << "destroying ServiceBrowserPrivate " << serviceType; qDebug() << "destroying ServiceBrowserPrivate " << serviceType;
if (browsing){ if (browsing)
stopBrowsing(); stopBrowsing();
} if (mainConnection)
if (mainConnection){
mainConnection->removeBrowser(this); mainConnection->removeBrowser(this);
}
} }
void ServiceBrowserPrivate::insertGatherer(const QString &fullName) void ServiceBrowserPrivate::insertGatherer(const QString &fullName)
@@ -1498,9 +1489,8 @@ void ServiceBrowserPrivate::browseReply(DNSServiceFlags flag
if (pos == knownServices.end() || *pos != fullName) if (pos == knownServices.end() || *pos != fullName)
knownServices.insert(pos, fullName); knownServices.insert(pos, fullName);
} else { } else {
if (gatherers.contains(fullName)){ if (gatherers.contains(fullName))
gatherers[fullName]->maybeRemove(); gatherers[fullName]->maybeRemove();
}
knownServices.removeOne(fullName); knownServices.removeOne(fullName);
} }
maybeUpdateLists(); // avoid? maybeUpdateLists(); // avoid?
@@ -209,11 +209,10 @@ void AnalyzerRunConfigurationAspect::setUsingGlobalSettings(bool value)
if (value == m_useGlobalSettings) if (value == m_useGlobalSettings)
return; return;
m_useGlobalSettings = value; m_useGlobalSettings = value;
if (m_useGlobalSettings) { if (m_useGlobalSettings)
m_subConfigs = AnalyzerGlobalSettings::instance()->subConfigs(); m_subConfigs = AnalyzerGlobalSettings::instance()->subConfigs();
} else { else
m_subConfigs = m_customConfigurations; m_subConfigs = m_customConfigurations;
}
} }
void AnalyzerRunConfigurationAspect::resetCustomToGlobalSettings() void AnalyzerRunConfigurationAspect::resetCustomToGlobalSettings()
+2 -3
View File
@@ -606,11 +606,10 @@ QStringList AndroidManager::availableQtLibs(ProjectExplorer::Target *target)
int it = 0; int it = 0;
while (it < mapLibs[key].dependencies.size()) { while (it < mapLibs[key].dependencies.size()) {
const QString &dependName = mapLibs[key].dependencies[it]; const QString &dependName = mapLibs[key].dependencies[it];
if (!mapLibs.keys().contains(dependName) && dependName.startsWith(QLatin1String("lib")) && dependName.endsWith(QLatin1String(".so"))) { if (!mapLibs.keys().contains(dependName) && dependName.startsWith(QLatin1String("lib")) && dependName.endsWith(QLatin1String(".so")))
mapLibs[key].dependencies.removeAt(it); mapLibs[key].dependencies.removeAt(it);
} else { else
++it; ++it;
}
} }
if (!mapLibs[key].dependencies.size()) if (!mapLibs[key].dependencies.size())
mapLibs[key].level = 0; mapLibs[key].level = 0;
@@ -315,11 +315,10 @@ void AutotoolsProject::buildFileNodeTree(const QDir &directory,
// Add file node // Add file node
const QString filePath = directory.absoluteFilePath(file); const QString filePath = directory.absoluteFilePath(file);
if (nodeHash.contains(filePath)) { if (nodeHash.contains(filePath))
nodeHash.remove(filePath); nodeHash.remove(filePath);
} else { else
fileNodes.append(new FileNode(filePath, ResourceType, false)); fileNodes.append(new FileNode(filePath, ResourceType, false));
}
} }
if (!fileNodes.isEmpty()) if (!fileNodes.isEmpty())
+4 -7
View File
@@ -73,9 +73,8 @@ static QByteArray calculateHexPattern(const QByteArray &pattern)
int i = 0; int i = 0;
while (i < pattern.size()) { while (i < pattern.size()) {
ushort s = pattern.mid(i, 2).toUShort(&ok, 16); ushort s = pattern.mid(i, 2).toUShort(&ok, 16);
if (!ok) { if (!ok)
return QByteArray(); return QByteArray();
}
result.append(s); result.append(s);
i += 2; i += 2;
} }
@@ -1061,11 +1060,10 @@ bool BinEditor::event(QEvent *e)
case QEvent::ToolTip: { case QEvent::ToolTip: {
const QHelpEvent *helpEvent = static_cast<const QHelpEvent *>(e); const QHelpEvent *helpEvent = static_cast<const QHelpEvent *>(e);
const QString tt = toolTip(helpEvent); const QString tt = toolTip(helpEvent);
if (tt.isEmpty()) { if (tt.isEmpty())
QToolTip::hideText(); QToolTip::hideText();
} else { else
QToolTip::showText(helpEvent->globalPos(), tt, this); QToolTip::showText(helpEvent->globalPos(), tt, this);
}
e->accept(); e->accept();
return true; return true;
} }
@@ -1437,9 +1435,8 @@ void BinEditor::changeData(int position, uchar character, bool highNibble)
changeDataAt(position, (char) character); changeDataAt(position, (char) character);
bool emitModificationChanged = (m_undoStack.size() == m_unmodifiedState); bool emitModificationChanged = (m_undoStack.size() == m_unmodifiedState);
m_undoStack.push(cmd); m_undoStack.push(cmd);
if (emitModificationChanged) { if (emitModificationChanged)
emit modificationChanged(m_undoStack.size() != m_unmodifiedState); emit modificationChanged(m_undoStack.size() != m_unmodifiedState);
}
if (m_undoStack.size() == 1) if (m_undoStack.size() == 1)
emit undoAvailable(true); emit undoAvailable(true);
+2 -3
View File
@@ -803,11 +803,10 @@ void BookmarkManager::operateTooltip(TextEditor::ITextEditor *textEditor, const
if (!mark) if (!mark)
return; return;
if (mark->note().isEmpty()) { if (mark->note().isEmpty())
TextEditor::ToolTip::instance()->hide(); TextEditor::ToolTip::instance()->hide();
} else { else
TextEditor::ToolTip::instance()->show(pos, TextEditor::TextContent(mark->note()), textEditor->widget()); TextEditor::ToolTip::instance()->show(pos, TextEditor::TextContent(mark->note()), textEditor->widget());
}
} }
/* Loads the bookmarks from the session settings. */ /* Loads the bookmarks from the session settings. */
+1 -2
View File
@@ -82,9 +82,8 @@ QSet<SymbolLocation> Utils::roleToLocations(const QList<QVariant> &locationsVar)
{ {
QSet<SymbolLocation> locations; QSet<SymbolLocation> locations;
foreach (const QVariant &loc, locationsVar) { foreach (const QVariant &loc, locationsVar) {
if (loc.canConvert<SymbolLocation>()) { if (loc.canConvert<SymbolLocation>())
locations.insert(loc.value<SymbolLocation>()); locations.insert(loc.value<SymbolLocation>());
}
} }
return locations; return locations;
@@ -260,9 +260,8 @@ ProjectExplorer::BuildConfiguration::BuildType CMakeBuildConfiguration::buildTyp
while (!cmakeCache.atEnd()) { while (!cmakeCache.atEnd()) {
QByteArray line = cmakeCache.readLine(); QByteArray line = cmakeCache.readLine();
if (line.startsWith("CMAKE_BUILD_TYPE")) { if (line.startsWith("CMAKE_BUILD_TYPE")) {
if (int pos = line.indexOf('=')) { if (int pos = line.indexOf('='))
cmakeBuildType = QString::fromLocal8Bit(line.mid(pos + 1).trimmed()); cmakeBuildType = QString::fromLocal8Bit(line.mid(pos + 1).trimmed());
}
break; break;
} }
} }
@@ -284,9 +284,8 @@ bool CMakeProject::parseCMakeLists()
while (!cmakeCache.atEnd()) { while (!cmakeCache.atEnd()) {
QByteArray line = cmakeCache.readLine(); QByteArray line = cmakeCache.readLine();
if (line.startsWith("QT_UIC_EXECUTABLE")) { if (line.startsWith("QT_UIC_EXECUTABLE")) {
if (int pos = line.indexOf('=')) { if (int pos = line.indexOf('='))
m_uicCommand = QString::fromLocal8Bit(line.mid(pos + 1).trimmed()); m_uicCommand = QString::fromLocal8Bit(line.mid(pos + 1).trimmed());
}
break; break;
} }
} }
@@ -977,11 +976,10 @@ bool CMakeCbpParser::parseCbpFile(const QString &fileName)
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (name() == QLatin1String("CodeBlocks_project_file")) { if (name() == QLatin1String("CodeBlocks_project_file"))
parseCodeBlocks_project_file(); parseCodeBlocks_project_file();
} else if (isStartElement()) { else if (isStartElement())
parseUnknownElement(); parseUnknownElement();
}
} }
fi.close(); fi.close();
m_includeFiles.sort(); m_includeFiles.sort();
@@ -995,13 +993,12 @@ void CMakeCbpParser::parseCodeBlocks_project_file()
{ {
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement())
return; return;
} else if (name() == QLatin1String("Project")) { else if (name() == QLatin1String("Project"))
parseProject(); parseProject();
} else if (isStartElement()) { else if (isStartElement())
parseUnknownElement(); parseUnknownElement();
}
} }
} }
@@ -1009,17 +1006,16 @@ void CMakeCbpParser::parseProject()
{ {
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement())
return; return;
} else if (name() == QLatin1String("Option")) { else if (name() == QLatin1String("Option"))
parseOption(); parseOption();
} else if (name() == QLatin1String("Unit")) { else if (name() == QLatin1String("Unit"))
parseUnit(); parseUnit();
} else if (name() == QLatin1String("Build")) { else if (name() == QLatin1String("Build"))
parseBuild(); parseBuild();
} else if (isStartElement()) { else if (isStartElement())
parseUnknownElement(); parseUnknownElement();
}
} }
} }
@@ -1027,13 +1023,12 @@ void CMakeCbpParser::parseBuild()
{ {
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement())
return; return;
} else if (name() == QLatin1String("Target")) { else if (name() == QLatin1String("Target"))
parseBuildTarget(); parseBuildTarget();
} else if (isStartElement()) { else if (isStartElement())
parseUnknownElement(); parseUnknownElement();
}
} }
} }
@@ -1047,9 +1042,8 @@ void CMakeCbpParser::parseBuildTarget()
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement()) {
if (m_buildTargetType || m_buildTarget.title == QLatin1String("all") || m_buildTarget.title == QLatin1String("install")) { if (m_buildTargetType || m_buildTarget.title == QLatin1String("all") || m_buildTarget.title == QLatin1String("install"))
m_buildTargets.append(m_buildTarget); m_buildTargets.append(m_buildTarget);
}
return; return;
} else if (name() == QLatin1String("Compiler")) { } else if (name() == QLatin1String("Compiler")) {
parseCompiler(); parseCompiler();
@@ -1079,13 +1073,12 @@ void CMakeCbpParser::parseBuildTargetOption()
} }
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement())
return; return;
} else if (name() == QLatin1String("MakeCommand")) { else if (name() == QLatin1String("MakeCommand"))
parseMakeCommand(); parseMakeCommand();
} else if (isStartElement()) { else if (isStartElement())
parseUnknownElement(); parseUnknownElement();
}
} }
} }
@@ -1104,11 +1097,10 @@ void CMakeCbpParser::parseOption()
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement())
return; return;
} else if (isStartElement()) { else if (isStartElement())
parseUnknownElement(); parseUnknownElement();
}
} }
} }
@@ -1116,15 +1108,14 @@ void CMakeCbpParser::parseMakeCommand()
{ {
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement())
return; return;
} else if (name() == QLatin1String("Build")) { else if (name() == QLatin1String("Build"))
parseBuildTargetBuild(); parseBuildTargetBuild();
} else if (name() == QLatin1String("Clean")) { else if (name() == QLatin1String("Clean"))
parseBuildTargetClean(); parseBuildTargetClean();
} else if (isStartElement()) { else if (isStartElement())
parseUnknownElement(); parseUnknownElement();
}
} }
} }
@@ -1134,11 +1125,10 @@ void CMakeCbpParser::parseBuildTargetBuild()
m_buildTarget.makeCommand = attributes().value(QLatin1String("command")).toString(); m_buildTarget.makeCommand = attributes().value(QLatin1String("command")).toString();
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement())
return; return;
} else if (isStartElement()) { else if (isStartElement())
parseUnknownElement(); parseUnknownElement();
}
} }
} }
@@ -1148,11 +1138,10 @@ void CMakeCbpParser::parseBuildTargetClean()
m_buildTarget.makeCleanCommand = attributes().value(QLatin1String("command")).toString(); m_buildTarget.makeCleanCommand = attributes().value(QLatin1String("command")).toString();
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement())
return; return;
} else if (isStartElement()) { else if (isStartElement())
parseUnknownElement(); parseUnknownElement();
}
} }
} }
@@ -1160,13 +1149,12 @@ void CMakeCbpParser::parseCompiler()
{ {
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement())
return; return;
} else if (name() == QLatin1String("Add")) { else if (name() == QLatin1String("Add"))
parseAdd(); parseAdd();
} else if (isStartElement()) { else if (isStartElement())
parseUnknownElement(); parseUnknownElement();
}
} }
} }
@@ -1177,9 +1165,8 @@ void CMakeCbpParser::parseAdd()
const QString includeDirectory = addAttributes.value(QLatin1String("directory")).toString(); const QString includeDirectory = addAttributes.value(QLatin1String("directory")).toString();
// allow adding multiple times because order happens // allow adding multiple times because order happens
if (!includeDirectory.isEmpty()) { if (!includeDirectory.isEmpty())
m_includeFiles.append(includeDirectory); m_includeFiles.append(includeDirectory);
}
QString compilerOption = addAttributes.value(QLatin1String("option")).toString(); QString compilerOption = addAttributes.value(QLatin1String("option")).toString();
// defining multiple times a macro to the same value makes no sense // defining multiple times a macro to the same value makes no sense
@@ -1188,9 +1175,8 @@ void CMakeCbpParser::parseAdd()
int macroNameIndex = compilerOption.indexOf(QLatin1String("-D")) + 2; int macroNameIndex = compilerOption.indexOf(QLatin1String("-D")) + 2;
if (macroNameIndex != 1) { if (macroNameIndex != 1) {
int assignIndex = compilerOption.indexOf(QLatin1Char('='), macroNameIndex); int assignIndex = compilerOption.indexOf(QLatin1Char('='), macroNameIndex);
if (assignIndex != -1) { if (assignIndex != -1)
compilerOption[assignIndex] = ' '; compilerOption[assignIndex] = ' ';
}
m_defines.append("#define "); m_defines.append("#define ");
m_defines.append(compilerOption.mid(macroNameIndex).toLatin1()); m_defines.append(compilerOption.mid(macroNameIndex).toLatin1());
m_defines.append('\n'); m_defines.append('\n');
@@ -1199,11 +1185,10 @@ void CMakeCbpParser::parseAdd()
while (!atEnd()) { while (!atEnd()) {
readNext(); readNext();
if (isEndElement()) { if (isEndElement())
return; return;
} else if (isStartElement()) { else if (isStartElement())
parseUnknownElement(); parseUnknownElement();
}
} }
} }
@@ -180,17 +180,15 @@ static void extractKeywords(const QByteArray &input, QStringList *destination)
keyword += chr; keyword += chr;
} else { } else {
if (!keyword.isEmpty()) { if (!keyword.isEmpty()) {
if (keyword.size() > 1) { if (keyword.size() > 1)
*destination << keyword; *destination << keyword;
}
keyword.clear(); keyword.clear();
} }
} }
} }
} }
if (keyword.size() > 1) { if (keyword.size() > 1)
*destination << keyword; *destination << keyword;
}
} }
void CMakeValidator::parseFunctionOutput(const QByteArray &output) void CMakeValidator::parseFunctionOutput(const QByteArray &output)
@@ -462,11 +462,10 @@ void Action::removeOverrideAction(QAction *action)
QMutableMapIterator<int, QPointer<QAction> > it(m_contextActionMap); QMutableMapIterator<int, QPointer<QAction> > it(m_contextActionMap);
while (it.hasNext()) { while (it.hasNext()) {
it.next(); it.next();
if (it.value() == 0) { if (it.value() == 0)
it.remove(); it.remove();
} else if (it.value() == action) { else if (it.value() == action)
it.remove(); it.remove();
}
} }
setCurrentContext(m_context); setCurrentContext(m_context);
} }
@@ -181,9 +181,8 @@ QModelIndex ExternalToolModel::index(int row, int column, const QModelIndex &par
QString category = categoryForIndex(parent, &found); QString category = categoryForIndex(parent, &found);
if (found) { if (found) {
QList<ExternalTool *> items = m_tools.value(category); QList<ExternalTool *> items = m_tools.value(category);
if (row < items.count()) { if (row < items.count())
return createIndex(row, 0, items.at(row)); return createIndex(row, 0, items.at(row));
}
} }
} else if (column == 0 && row < m_tools.keys().count()) { } else if (column == 0 && row < m_tools.keys().count()) {
return createIndex(row, 0); return createIndex(row, 0);
@@ -210,14 +209,12 @@ int ExternalToolModel::rowCount(const QModelIndex &parent) const
{ {
if (!parent.isValid()) if (!parent.isValid())
return m_tools.keys().count(); return m_tools.keys().count();
if (toolForIndex(parent)) { if (toolForIndex(parent))
return 0; return 0;
}
bool found; bool found;
QString category = categoryForIndex(parent, &found); QString category = categoryForIndex(parent, &found);
if (found) { if (found)
return m_tools.value(category).count(); return m_tools.value(category).count();
}
return 0; return 0;
} }
+4 -7
View File
@@ -262,9 +262,8 @@ void NewDialog::setWizards(QList<IWizard*> wizards)
parentItem->appendRow(projectKindItem); parentItem->appendRow(projectKindItem);
parentItem->appendRow(filesClassesKindItem); parentItem->appendRow(filesClassesKindItem);
if (m_dummyIcon.isNull()) { if (m_dummyIcon.isNull())
m_dummyIcon = QIcon(QLatin1String(Core::Constants::ICON_NEWFILE)); m_dummyIcon = QIcon(QLatin1String(Core::Constants::ICON_NEWFILE));
}
QStringList availablePlatforms = IWizard::allAvailablePlatforms(); QStringList availablePlatforms = IWizard::allAvailablePlatforms();
@@ -312,9 +311,8 @@ Core::IWizard *NewDialog::showDialog()
if (!lastCategory.isEmpty()) if (!lastCategory.isEmpty())
foreach (QStandardItem* item, m_categoryItems) { foreach (QStandardItem* item, m_categoryItems) {
if (item->data(Qt::UserRole) == lastCategory) { if (item->data(Qt::UserRole) == lastCategory)
idx = m_twoLevelProxyModel->mapToSource(m_model->indexFromItem(item)); idx = m_twoLevelProxyModel->mapToSource(m_model->indexFromItem(item));
}
} }
if (!idx.isValid()) if (!idx.isValid())
idx = m_twoLevelProxyModel->index(0,0, m_twoLevelProxyModel->index(0,0)); idx = m_twoLevelProxyModel->index(0,0, m_twoLevelProxyModel->index(0,0));
@@ -390,11 +388,10 @@ void NewDialog::addItem(QStandardItem *topLEvelCategoryItem, IWizard *wizard)
QIcon wizardIcon; QIcon wizardIcon;
// spacing hack. Add proper icons instead // spacing hack. Add proper icons instead
if (wizard->icon().isNull()) { if (wizard->icon().isNull())
wizardIcon = m_dummyIcon; wizardIcon = m_dummyIcon;
} else { else
wizardIcon = wizard->icon(); wizardIcon = wizard->icon();
}
wizardItem->setIcon(wizardIcon); wizardItem->setIcon(wizardIcon);
wizardItem->setData(QVariant::fromValue(WizardContainer(wizard, 0)), Qt::UserRole); wizardItem->setData(QVariant::fromValue(WizardContainer(wizard, 0)), Qt::UserRole);
wizardItem->setFlags(Qt::ItemIsEnabled|Qt::ItemIsSelectable); wizardItem->setFlags(Qt::ItemIsEnabled|Qt::ItemIsSelectable);
@@ -127,11 +127,10 @@ void PromptOverwriteDialog::setFileEnabled(const QString &f, bool e)
{ {
if (QStandardItem *item = itemForFile(f)) { if (QStandardItem *item = itemForFile(f)) {
Qt::ItemFlags flags = item->flags(); Qt::ItemFlags flags = item->flags();
if (e) { if (e)
flags |= Qt::ItemIsEnabled; flags |= Qt::ItemIsEnabled;
} else { else
flags &= ~Qt::ItemIsEnabled; flags &= ~Qt::ItemIsEnabled;
}
item->setFlags(flags); item->setFlags(flags);
} }
} }
+4 -7
View File
@@ -244,10 +244,9 @@ static void addFileInfo(const QString &fileName, IDocument *document, bool isLin
state.modified = fi.lastModified(); state.modified = fi.lastModified();
state.permissions = fi.permissions(); state.permissions = fi.permissions();
// Add watcher if we don't have that already // Add watcher if we don't have that already
if (!d->m_states.contains(fileName)) { if (!d->m_states.contains(fileName))
d->m_states.insert(fileName, FileState()); d->m_states.insert(fileName, FileState());
}
QFileSystemWatcher *watcher = 0; QFileSystemWatcher *watcher = 0;
if (isLink) if (isLink)
watcher = d->linkWatcher(); watcher = d->linkWatcher();
@@ -860,9 +859,8 @@ void DocumentManager::changedFile(const QString &fileName)
if (d->m_states.contains(fileName)) if (d->m_states.contains(fileName))
d->m_changedFiles.insert(fileName); d->m_changedFiles.insert(fileName);
if (wasempty && !d->m_changedFiles.isEmpty()) { if (wasempty && !d->m_changedFiles.isEmpty())
QTimer::singleShot(200, this, SLOT(checkForReload())); QTimer::singleShot(200, this, SLOT(checkForReload()));
}
} }
void DocumentManager::mainWindowActivated() void DocumentManager::mainWindowActivated()
@@ -963,11 +961,10 @@ void DocumentManager::checkForReload()
// find out the type // find out the type
IDocument::ChangeType fileChange = changeTypes.value(fileName); IDocument::ChangeType fileChange = changeTypes.value(fileName);
if (fileChange == IDocument::TypeRemoved) { if (fileChange == IDocument::TypeRemoved)
type = IDocument::TypeRemoved; type = IDocument::TypeRemoved;
} else if (fileChange == IDocument::TypeContents && type == IDocument::TypePermissions) { else if (fileChange == IDocument::TypeContents && type == IDocument::TypePermissions)
type = IDocument::TypeContents; type = IDocument::TypeContents;
}
} }
if (!changed) // probably because the change was blocked with (un)blockFileChange if (!changed) // probably because the change was blocked with (un)blockFileChange
@@ -506,11 +506,10 @@ void EditorManager::handleContextChange(Core::IContext *context)
if (debugEditorManager) if (debugEditorManager)
qDebug() << Q_FUNC_INFO; qDebug() << Q_FUNC_INFO;
IEditor *editor = context ? qobject_cast<IEditor*>(context) : 0; IEditor *editor = context ? qobject_cast<IEditor*>(context) : 0;
if (editor) { if (editor)
setCurrentEditor(editor); setCurrentEditor(editor);
} else { else
updateActions(); updateActions();
}
} }
void EditorManager::setCurrentEditor(IEditor *editor, bool ignoreNavigationHistory) void EditorManager::setCurrentEditor(IEditor *editor, bool ignoreNavigationHistory)
@@ -645,9 +644,8 @@ void EditorManager::closeView(Core::Internal::EditorView *view)
*/ */
if (!d->m_editorModel->isDuplicate(e)) { if (!d->m_editorModel->isDuplicate(e)) {
QList<IEditor *> duplicates = d->m_editorModel->duplicatesFor(e); QList<IEditor *> duplicates = d->m_editorModel->duplicatesFor(e);
if (!duplicates.isEmpty()) { if (!duplicates.isEmpty())
d->m_editorModel->makeOriginal(duplicates.first()); d->m_editorModel->makeOriginal(duplicates.first());
}
} }
} }
@@ -665,11 +663,10 @@ void EditorManager::closeView(Core::Internal::EditorView *view)
SplitterOrView *newCurrent = splitter->findFirstView(); SplitterOrView *newCurrent = splitter->findFirstView();
if (newCurrent) { if (newCurrent) {
if (IEditor *e = newCurrent->editor()) { if (IEditor *e = newCurrent->editor())
activateEditor(newCurrent->view(), e); activateEditor(newCurrent->view(), e);
} else { else
setCurrentView(newCurrent); setCurrentView(newCurrent);
}
} }
} }
@@ -680,9 +677,8 @@ QList<IEditor*>
QSet<IEditor *> found; QSet<IEditor *> found;
foreach (IDocument *document, documents) { foreach (IDocument *document, documents) {
foreach (IEditor *editor, editors) { foreach (IEditor *editor, editors) {
if (editor->document() == document && !found.contains(editor)) { if (editor->document() == document && !found.contains(editor))
found << editor; found << editor;
}
} }
} }
return found.toList(); return found.toList();
@@ -1045,9 +1041,8 @@ Core::IEditor *EditorManager::placeEditor(Core::Internal::EditorView *view, Core
view->addEditor(editor); view->addEditor(editor);
view->setCurrentEditor(editor); view->setCurrentEditor(editor);
if (!sourceView->editor()) { if (!sourceView->editor()) {
if (IEditor *replacement = pickUnusedEditor()) { if (IEditor *replacement = pickUnusedEditor())
sourceView->view()->addEditor(replacement); sourceView->view()->addEditor(replacement);
}
} }
return editor; return editor;
} else if (duplicateSupported) { } else if (duplicateSupported) {
@@ -1085,9 +1080,8 @@ Core::IEditor *EditorManager::activateEditor(Core::Internal::EditorView *view, C
if (!(flags & NoActivate)) { if (!(flags & NoActivate)) {
setCurrentEditor(editor, (flags & IgnoreNavigationHistory)); setCurrentEditor(editor, (flags & IgnoreNavigationHistory));
if (flags & ModeSwitch) { if (flags & ModeSwitch)
switchToPreferedMode(); switchToPreferedMode();
}
if (isVisible()) if (isVisible())
editor->widget()->setFocus(); editor->widget()->setFocus();
} }
@@ -1456,11 +1450,10 @@ IEditor *EditorManager::openEditorWithContents(const Id &editorId,
QSet<QString> docnames; QSet<QString> docnames;
foreach (IEditor *editor, m_instance->openedEditors()) { foreach (IEditor *editor, m_instance->openedEditors()) {
QString name = editor->document()->fileName(); QString name = editor->document()->fileName();
if (name.isEmpty()) { if (name.isEmpty())
name = editor->displayName(); name = editor->displayName();
} else { else
name = QFileInfo(name).completeBaseName(); name = QFileInfo(name).completeBaseName();
}
docnames << name; docnames << name;
} }
@@ -1547,9 +1540,8 @@ bool EditorManager::saveDocument(IDocument *documentParam)
success = DocumentManager::saveDocument(document); success = DocumentManager::saveDocument(document);
} }
if (success) { if (success)
addDocumentToRecentFiles(document); addDocumentToRecentFiles(document);
}
return success; return success;
} }
@@ -1629,9 +1621,8 @@ bool EditorManager::saveDocumentAs(IDocument *documentParam)
if (absoluteFilePath != document->fileName()) { if (absoluteFilePath != document->fileName()) {
// close existing editors for the new file name // close existing editors for the new file name
const QList<IEditor *> existList = editorsForFileName(absoluteFilePath); const QList<IEditor *> existList = editorsForFileName(absoluteFilePath);
if (!existList.isEmpty()) { if (!existList.isEmpty())
closeEditors(existList, false); closeEditors(existList, false);
}
} }
const bool success = DocumentManager::saveDocument(document, absoluteFilePath); const bool success = DocumentManager::saveDocument(document, absoluteFilePath);
@@ -1720,9 +1711,8 @@ void EditorManager::updateWindowTitle()
{ {
QString windowTitle = tr("Qt Creator"); QString windowTitle = tr("Qt Creator");
const QString dashSep = QLatin1String(" - "); const QString dashSep = QLatin1String(" - ");
if (!d->m_titleAddition.isEmpty()) { if (!d->m_titleAddition.isEmpty())
windowTitle.prepend(d->m_titleAddition + dashSep); windowTitle.prepend(d->m_titleAddition + dashSep);
}
IEditor *curEditor = currentEditor(); IEditor *curEditor = currentEditor();
if (curEditor) { if (curEditor) {
QString editorName = curEditor->displayName(); QString editorName = curEditor->displayName();
@@ -1896,9 +1886,8 @@ QList<IEditor*> EditorManager::visibleEditors() const
} while (view && view != firstView); } while (view && view != firstView);
} }
} else { } else {
if (d->m_splitter->editor()) { if (d->m_splitter->editor())
editors.append(d->m_splitter->editor()); editors.append(d->m_splitter->editor());
}
} }
return editors; return editors;
} }
@@ -2029,11 +2018,10 @@ bool EditorManager::restoreState(const QByteArray &state)
if (!fi.exists()) if (!fi.exists())
continue; continue;
QFileInfo rfi(autoSaveName(fileName)); QFileInfo rfi(autoSaveName(fileName));
if (rfi.exists() && fi.lastModified() < rfi.lastModified()) { if (rfi.exists() && fi.lastModified() < rfi.lastModified())
openEditor(fileName, Id(QString::fromUtf8(id))); openEditor(fileName, Id(QString::fromUtf8(id)));
} else { else
d->m_editorModel->addRestoredEditor(fileName, displayName, Id(QString::fromUtf8(id))); d->m_editorModel->addRestoredEditor(fileName, displayName, Id(QString::fromUtf8(id)));
}
} }
} }
@@ -320,9 +320,8 @@ QRect EditorView::editorArea() const
void EditorView::addCurrentPositionToNavigationHistory(IEditor *editor, const QByteArray &saveState) void EditorView::addCurrentPositionToNavigationHistory(IEditor *editor, const QByteArray &saveState)
{ {
if (editor && editor != currentEditor()) { if (editor && editor != currentEditor())
return; // we only save editor sate for the current editor, when the user interacts return; // we only save editor sate for the current editor, when the user interacts
}
if (!editor) if (!editor)
editor = currentEditor(); editor = currentEditor();
@@ -334,11 +333,10 @@ void EditorView::addCurrentPositionToNavigationHistory(IEditor *editor, const QB
return; return;
QByteArray state; QByteArray state;
if (saveState.isNull()) { if (saveState.isNull())
state = editor->saveState(); state = editor->saveState();
} else { else
state = saveState; state = saveState;
}
EditLocation location; EditLocation location;
location.document = document; location.document = document;
@@ -606,9 +604,8 @@ SplitterOrView *SplitterOrView::findNextView(SplitterOrView *view)
SplitterOrView *SplitterOrView::findNextView_helper(SplitterOrView *view, bool *found) SplitterOrView *SplitterOrView::findNextView_helper(SplitterOrView *view, bool *found)
{ {
if (*found && m_view) { if (*found && m_view)
return this; return this;
}
if (this == view) { if (this == view) {
*found = true; *found = true;
@@ -721,9 +718,8 @@ void SplitterOrView::unsplitAll_helper()
ICore::editorManager()->emptyView(m_view); ICore::editorManager()->emptyView(m_view);
if (m_splitter) { if (m_splitter) {
for (int i = 0; i < m_splitter->count(); ++i) { for (int i = 0; i < m_splitter->count(); ++i) {
if (SplitterOrView *splitterOrView = qobject_cast<SplitterOrView*>(m_splitter->widget(i))) { if (SplitterOrView *splitterOrView = qobject_cast<SplitterOrView*>(m_splitter->widget(i)))
splitterOrView->unsplitAll_helper(); splitterOrView->unsplitAll_helper();
}
} }
} }
} }
@@ -235,9 +235,8 @@ QList<OpenEditorsModel::Entry> OpenEditorsModel::restoredEditors() const
{ {
QList<Entry> result; QList<Entry> result;
for (int i = d->m_editors.count()-1; i >= 0; --i) { for (int i = d->m_editors.count()-1; i >= 0; --i) {
if (!d->m_editors.at(i).editor) { if (!d->m_editors.at(i).editor)
result.append(d->m_editors.at(i)); result.append(d->m_editors.at(i));
}
} }
return result; return result;
} }
@@ -178,11 +178,10 @@ bool OpenEditorsWidget::eventFilter(QObject *obj, QEvent *event)
void OpenEditorsWidget::handlePressed(const QModelIndex &index) void OpenEditorsWidget::handlePressed(const QModelIndex &index)
{ {
if (index.column() == 0) { if (index.column() == 0)
activateEditor(index); activateEditor(index);
} else if (index.column() == 1) { else if (index.column() == 1)
m_delegate->pressedIndex = index; m_delegate->pressedIndex = index;
}
} }
void OpenEditorsWidget::handleClicked(const QModelIndex &index) void OpenEditorsWidget::handleClicked(const QModelIndex &index)
@@ -88,9 +88,8 @@ void OpenEditorsWindow::selectAndHide()
void OpenEditorsWindow::setVisible(bool visible) void OpenEditorsWindow::setVisible(bool visible)
{ {
QWidget::setVisible(visible); QWidget::setVisible(visible);
if (visible) { if (visible)
setFocus(); setFocus();
}
} }
bool OpenEditorsWindow::isCentering() bool OpenEditorsWindow::isCentering()
+1 -2
View File
@@ -337,9 +337,8 @@ void EditorToolBar::listContextMenu(QPoint pos)
menu.addSeparator(); menu.addSeparator();
EditorManager::instance()->addNativeDirActions(&menu, index); EditorManager::instance()->addNativeDirActions(&menu, index);
QAction *result = menu.exec(d->m_editorList->mapToGlobal(pos)); QAction *result = menu.exec(d->m_editorList->mapToGlobal(pos));
if (result == copyPath) { if (result == copyPath)
QApplication::clipboard()->setText(QDir::toNativeSeparators(fileName)); QApplication::clipboard()->setText(QDir::toNativeSeparators(fileName));
}
} }
void EditorToolBar::makeEditorWritable() void EditorToolBar::makeEditorWritable()
+10 -17
View File
@@ -441,9 +441,8 @@ ExternalTool * ExternalTool::createFromFile(const QString &fileName, QString *er
if (!reader.fetch(absFileName, errorMessage)) if (!reader.fetch(absFileName, errorMessage))
return 0; return 0;
ExternalTool *tool = ExternalTool::createFromXml(reader.data(), errorMessage, locale); ExternalTool *tool = ExternalTool::createFromXml(reader.data(), errorMessage, locale);
if (!tool) { if (!tool)
return 0; return 0;
}
tool->m_fileName = absFileName; tool->m_fileName = absFileName;
return tool; return tool;
} }
@@ -624,9 +623,8 @@ void ExternalToolRunner::run()
void ExternalToolRunner::started() void ExternalToolRunner::started()
{ {
if (!m_resolvedInput.isEmpty()) { if (!m_resolvedInput.isEmpty())
m_process->write(m_resolvedInput.toLocal8Bit()); m_process->write(m_resolvedInput.toLocal8Bit());
}
m_process->closeWriteChannel(); m_process->closeWriteChannel();
} }
@@ -637,9 +635,8 @@ void ExternalToolRunner::finished(int exitCode, QProcess::ExitStatus status)
|| m_tool->errorHandling() == ExternalTool::ReplaceSelection) { || m_tool->errorHandling() == ExternalTool::ReplaceSelection) {
emit ExternalToolManager::instance()->replaceSelectionRequested(m_processOutput); emit ExternalToolManager::instance()->replaceSelectionRequested(m_processOutput);
} }
if (m_tool->modifiesCurrentDocument()) { if (m_tool->modifiesCurrentDocument())
DocumentManager::unexpectFileChange(m_expectedFileName); DocumentManager::unexpectFileChange(m_expectedFileName);
}
} }
ICore::messageManager()->printToOutputPane( ICore::messageManager()->printToOutputPane(
tr("'%1' finished").arg(m_resolvedExecutable), false); tr("'%1' finished").arg(m_resolvedExecutable), false);
@@ -661,11 +658,10 @@ void ExternalToolRunner::readStandardOutput()
return; return;
QByteArray data = m_process->readAllStandardOutput(); QByteArray data = m_process->readAllStandardOutput();
QString output = m_outputCodec->toUnicode(data.constData(), data.length(), &m_outputCodecState); QString output = m_outputCodec->toUnicode(data.constData(), data.length(), &m_outputCodecState);
if (m_tool->outputHandling() == ExternalTool::ShowInPane) { if (m_tool->outputHandling() == ExternalTool::ShowInPane)
ICore::messageManager()->printToOutputPane(output, true); ICore::messageManager()->printToOutputPane(output, true);
} else if (m_tool->outputHandling() == ExternalTool::ReplaceSelection) { else if (m_tool->outputHandling() == ExternalTool::ReplaceSelection)
m_processOutput.append(output); m_processOutput.append(output);
}
} }
void ExternalToolRunner::readStandardError() void ExternalToolRunner::readStandardError()
@@ -674,11 +670,10 @@ void ExternalToolRunner::readStandardError()
return; return;
QByteArray data = m_process->readAllStandardError(); QByteArray data = m_process->readAllStandardError();
QString output = m_outputCodec->toUnicode(data.constData(), data.length(), &m_errorCodecState); QString output = m_outputCodec->toUnicode(data.constData(), data.length(), &m_errorCodecState);
if (m_tool->errorHandling() == ExternalTool::ShowInPane) { if (m_tool->errorHandling() == ExternalTool::ShowInPane)
ICore::messageManager()->printToOutputPane(output, true); ICore::messageManager()->printToOutputPane(output, true);
} else if (m_tool->errorHandling() == ExternalTool::ReplaceSelection) { else if (m_tool->errorHandling() == ExternalTool::ReplaceSelection)
m_processOutput.append(output); m_processOutput.append(output);
}
} }
// #pragma mark -- ExternalToolManager // #pragma mark -- ExternalToolManager
@@ -777,9 +772,8 @@ void ExternalToolManager::menuActivated()
ExternalTool *tool = m_tools.value(action->data().toString()); ExternalTool *tool = m_tools.value(action->data().toString());
QTC_ASSERT(tool, return); QTC_ASSERT(tool, return);
ExternalToolRunner *runner = new ExternalToolRunner(tool); ExternalToolRunner *runner = new ExternalToolRunner(tool);
if (runner->hasError()) { if (runner->hasError())
ICore::messageManager()->printToOutputPane(runner->errorString(), true); ICore::messageManager()->printToOutputPane(runner->errorString(), true);
}
} }
QMap<QString, QList<Internal::ExternalTool *> > ExternalToolManager::toolsByCategory() const QMap<QString, QList<Internal::ExternalTool *> > ExternalToolManager::toolsByCategory() const
@@ -839,11 +833,10 @@ void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<Internal:
if (containerName.isEmpty()) { // no displayCategory, so put into external tools menu directly if (containerName.isEmpty()) { // no displayCategory, so put into external tools menu directly
container = mexternaltools; container = mexternaltools;
} else { } else {
if (m_containers.contains(containerName)) { if (m_containers.contains(containerName))
container = m_containers.take(containerName); // remove to avoid deletion below container = m_containers.take(containerName); // remove to avoid deletion below
} else { else
container = ActionManager::createMenu(Id(QLatin1String("Tools.External.Category.") + containerName)); container = ActionManager::createMenu(Id(QLatin1String("Tools.External.Category.") + containerName));
}
newContainers.insert(containerName, container); newContainers.insert(containerName, container);
mexternaltools->addMenu(container, Constants::G_DEFAULT_ONE); mexternaltools->addMenu(container, Constants::G_DEFAULT_ONE);
container->menu()->setTitle(containerName); container->menu()->setTitle(containerName);
+2 -3
View File
@@ -109,11 +109,10 @@ static QVector<QString> splitInTwoLines(const QString &text, const QFontMetrics
nextSplitPos - text.length() - 1); nextSplitPos - text.length() - 1);
if (nextSplitPos != -1) { if (nextSplitPos != -1) {
int splitCandidate = nextSplitPos + rx.matchedLength(); int splitCandidate = nextSplitPos + rx.matchedLength();
if (fontMetrics.width(text.mid(splitCandidate)) <= availableWidth) { if (fontMetrics.width(text.mid(splitCandidate)) <= availableWidth)
splitPos = splitCandidate; splitPos = splitCandidate;
} else { else
break; break;
}
} }
} while (nextSplitPos > 0 && fontMetrics.width(text.left(nextSplitPos)) > availableWidth); } while (nextSplitPos > 0 && fontMetrics.width(text.left(nextSplitPos)) > availableWidth);
// check if we could split at white space at all // check if we could split at white space at all
+2 -3
View File
@@ -180,11 +180,10 @@ void FileIconProvider::registerIconOverlayForSuffix(const QIcon &icon,
const QPixmap fileIconPixmap = overlayIcon(QStyle::SP_FileIcon, icon, QSize(16, 16)); const QPixmap fileIconPixmap = overlayIcon(QStyle::SP_FileIcon, icon, QSize(16, 16));
// replace old icon, if it exists // replace old icon, if it exists
const CacheIterator it = findBySuffix(suffix, d->m_cache.begin(), d->m_cache.end()); const CacheIterator it = findBySuffix(suffix, d->m_cache.begin(), d->m_cache.end());
if (it == d->m_cache.end()) { if (it == d->m_cache.end())
d->m_cache.append(StringIconPair(suffix, fileIconPixmap)); d->m_cache.append(StringIconPair(suffix, fileIconPixmap));
} else { else
(*it).second = fileIconPixmap; (*it).second = fileIconPixmap;
}
} }
/*! /*!
+7 -11
View File
@@ -430,11 +430,10 @@ static bool isDesktopFileManagerDrop(const QMimeData *d, QStringList *files = 0)
const QString fileName = it->toLocalFile(); const QString fileName = it->toLocalFile();
if (!fileName.isEmpty()) { if (!fileName.isEmpty()) {
hasFiles = true; hasFiles = true;
if (files) { if (files)
files->push_back(fileName); files->push_back(fileName);
} else { else
break; // No result list, sufficient for checking break; // No result list, sufficient for checking
}
} }
} }
return hasFiles; return hasFiles;
@@ -442,11 +441,10 @@ static bool isDesktopFileManagerDrop(const QMimeData *d, QStringList *files = 0)
void MainWindow::dragEnterEvent(QDragEnterEvent *event) void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{ {
if (isDesktopFileManagerDrop(event->mimeData()) && m_filesToOpenDelayed.isEmpty()) { if (isDesktopFileManagerDrop(event->mimeData()) && m_filesToOpenDelayed.isEmpty())
event->accept(); event->accept();
} else { else
event->ignore(); event->ignore();
}
} }
void MainWindow::dropEvent(QDropEvent *event) void MainWindow::dropEvent(QDropEvent *event)
@@ -992,11 +990,10 @@ void MainWindow::openFileWith()
const Id editorId = editorManager()->getOpenWithEditorId(fileName, &isExternal); const Id editorId = editorManager()->getOpenWithEditorId(fileName, &isExternal);
if (!editorId.isValid()) if (!editorId.isValid())
continue; continue;
if (isExternal) { if (isExternal)
EditorManager::openExternalEditor(fileName, editorId); EditorManager::openExternalEditor(fileName, editorId);
} else { else
EditorManager::openEditor(fileName, editorId, Core::EditorManager::ModeSwitch); EditorManager::openEditor(fileName, editorId, Core::EditorManager::ModeSwitch);
}
} }
} }
@@ -1178,9 +1175,8 @@ void MainWindow::readSettings()
QColor(Utils::StyleHelper::DEFAULT_BASE_COLOR)).value<QColor>()); QColor(Utils::StyleHelper::DEFAULT_BASE_COLOR)).value<QColor>());
} }
if (!restoreGeometry(m_settings->value(QLatin1String(windowGeometryKey)).toByteArray())) { if (!restoreGeometry(m_settings->value(QLatin1String(windowGeometryKey)).toByteArray()))
resize(1008, 700); // size without window decoration resize(1008, 700); // size without window decoration
}
restoreState(m_settings->value(QLatin1String(windowStateKey)).toByteArray()); restoreState(m_settings->value(QLatin1String(windowStateKey)).toByteArray());
m_settings->endGroup(); m_settings->endGroup();
+1 -2
View File
@@ -865,9 +865,8 @@ void ManhattanStyle::drawComplexControl(ComplexControl control, const QStyleOpti
State bflags = toolbutton->state; State bflags = toolbutton->state;
if (bflags & State_AutoRaise) { if (bflags & State_AutoRaise) {
if (!(bflags & State_MouseOver)) { if (!(bflags & State_MouseOver))
bflags &= ~State_Raised; bflags &= ~State_Raised;
}
} }
State mflags = bflags; State mflags = bflags;
+8 -12
View File
@@ -1073,11 +1073,10 @@ bool BaseMimeTypeParser::parse(QIODevice *dev, const QString &fileName, QString
switch (ps) { switch (ps) {
case ParseMimeType: { // start parsing a type case ParseMimeType: { // start parsing a type
const QString type = atts.value(QLatin1String(mimeTypeAttributeC)).toString(); const QString type = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
if (type.isEmpty()) { if (type.isEmpty())
reader.raiseError(QString::fromLatin1("Missing 'type'-attribute")); reader.raiseError(QString::fromLatin1("Missing 'type'-attribute"));
} else { else
data.type = type; data.type = type;
}
} }
break; break;
case ParseGlobPattern: case ParseGlobPattern:
@@ -1094,11 +1093,10 @@ bool BaseMimeTypeParser::parse(QIODevice *dev, const QString &fileName, QString
// comments have locale attributes. We want the default, English one // comments have locale attributes. We want the default, English one
QString locale = atts.value(QLatin1String(localeAttributeC)).toString(); QString locale = atts.value(QLatin1String(localeAttributeC)).toString();
const QString comment = QCoreApplication::translate("MimeType", reader.readElementText().toLatin1()); const QString comment = QCoreApplication::translate("MimeType", reader.readElementText().toLatin1());
if (locale.isEmpty()) { if (locale.isEmpty())
data.comment = comment; data.comment = comment;
} else { else
data.localeComments.insert(locale, comment); data.localeComments.insert(locale, comment);
}
} }
break; break;
case ParseAlias: { case ParseAlias: {
@@ -1467,11 +1465,10 @@ MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f) const
qDebug() << '>' << Q_FUNC_INFO << f.absoluteFilePath(); qDebug() << '>' << Q_FUNC_INFO << f.absoluteFilePath();
const MimeType rc = findByFile(f, &priority); const MimeType rc = findByFile(f, &priority);
if (debugMimeDB) { if (debugMimeDB) {
if (rc) { if (rc)
qDebug() << "<MimeDatabase::findByFile: match prio=" << priority << rc.type(); qDebug() << "<MimeDatabase::findByFile: match prio=" << priority << rc.type();
} else { else
qDebug() << "<MimeDatabase::findByFile: no match"; qDebug() << "<MimeDatabase::findByFile: no match";
}
} }
return rc; return rc;
} }
@@ -1536,11 +1533,10 @@ MimeType MimeDatabasePrivate::findByData(const QByteArray &data) const
qDebug() << '>' << Q_FUNC_INFO << data.left(20).toHex(); qDebug() << '>' << Q_FUNC_INFO << data.left(20).toHex();
const MimeType rc = findByData(data, &priority); const MimeType rc = findByData(data, &priority);
if (debugMimeDB) { if (debugMimeDB) {
if (rc) { if (rc)
qDebug() << "<MimeDatabase::findByData: match prio=" << priority << rc.type(); qDebug() << "<MimeDatabase::findByData: match prio=" << priority << rc.type();
} else { else
qDebug() << "<MimeDatabase::findByData: no match"; qDebug() << "<MimeDatabase::findByData: no match";
}
} }
return rc; return rc;
} }
+1 -2
View File
@@ -420,9 +420,8 @@ void NavigationWidget::setSuppressed(bool b)
int NavigationWidget::factoryIndex(const Id &id) int NavigationWidget::factoryIndex(const Id &id)
{ {
for (int row = 0; row < d->m_factoryModel->rowCount(); ++row) { for (int row = 0; row < d->m_factoryModel->rowCount(); ++row) {
if (d->m_factoryModel->data(d->m_factoryModel->index(row, 0), FactoryIdRole).value<Core::Id>() == id) { if (d->m_factoryModel->data(d->m_factoryModel->index(row, 0), FactoryIdRole).value<Core::Id>() == id)
return row; return row;
}
} }
return -1; return -1;
} }
+2 -3
View File
@@ -317,11 +317,10 @@ void OutputPaneManager::shortcutTriggered()
// then just give it focus. // then just give it focus.
int current = currentIndex(); int current = currentIndex();
if (OutputPanePlaceHolder::isCurrentVisible() && current == idx) { if (OutputPanePlaceHolder::isCurrentVisible() && current == idx) {
if (!outputPane->hasFocus() && outputPane->canFocus()) { if (!outputPane->hasFocus() && outputPane->canFocus())
outputPane->setFocus(); outputPane->setFocus();
} else { else
slotHide(); slotHide();
}
} else { } else {
// Else do the same as clicking on the button does. // Else do the same as clicking on the button does.
buttonTriggered(idx); buttonTriggered(idx);
+1 -2
View File
@@ -174,9 +174,8 @@ void OutputWindow::setFormatter(OutputFormatter *formatter)
void OutputWindow::showEvent(QShowEvent *e) void OutputWindow::showEvent(QShowEvent *e)
{ {
QPlainTextEdit::showEvent(e); QPlainTextEdit::showEvent(e);
if (m_scrollToBottom) { if (m_scrollToBottom)
verticalScrollBar()->setValue(verticalScrollBar()->maximum()); verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
m_scrollToBottom = false; m_scrollToBottom = false;
} }
@@ -247,11 +247,10 @@ void FutureProgress::setFinished()
d->m_progress->setFinished(true); d->m_progress->setFinished(true);
if (d->m_watcher.future().isCanceled()) { if (d->m_watcher.future().isCanceled())
d->m_progress->setError(true); d->m_progress->setError(true);
} else { else
d->m_progress->setError(false); d->m_progress->setError(false);
}
emit finished(); emit finished();
d->tryToFadeAway(); d->tryToFadeAway();
} }
@@ -363,15 +362,13 @@ QString FutureProgress::type() const
void FutureProgress::setKeepOnFinish(KeepOnFinishType keepType) void FutureProgress::setKeepOnFinish(KeepOnFinishType keepType)
{ {
if (d->m_keep == keepType) { if (d->m_keep == keepType)
return; return;
}
d->m_keep = keepType; d->m_keep = keepType;
//if it is not finished tryToFadeAway is called by setFinished at the end //if it is not finished tryToFadeAway is called by setFinished at the end
if (d->m_watcher.isFinished()) { if (d->m_watcher.isFinished())
d->tryToFadeAway(); d->tryToFadeAway();
}
} }
bool FutureProgress::keepOnFinish() const bool FutureProgress::keepOnFinish() const
@@ -272,9 +272,8 @@ void ProgressManagerPrivate::cancelTasks(const QString &type)
delete task.key(); delete task.key();
task = m_runningTasks.erase(task); task = m_runningTasks.erase(task);
} }
if (found) { if (found)
emit allTasksFinished(type); emit allTasksFinished(type);
}
} }
void ProgressManagerPrivate::cancelAllRunningTasks() void ProgressManagerPrivate::cancelAllRunningTasks()
@@ -330,9 +329,8 @@ void ProgressManagerPrivate::taskFinished()
m_runningTasks.remove(task); m_runningTasks.remove(task);
delete task; delete task;
if (!m_runningTasks.key(type, 0)) { if (!m_runningTasks.key(type, 0))
emit allTasksFinished(type); emit allTasksFinished(type);
}
} }
void ProgressManagerPrivate::disconnectApplicationTask() void ProgressManagerPrivate::disconnectApplicationTask()

Some files were not shown because too many files have changed in this diff Show More