Merge remote-tracking branch 'origin/4.1'

Change-Id: Ia90424d479936a898705c433e5810c77ae088b2c
This commit is contained in:
Orgad Shaneh
2016-07-22 15:17:36 +03:00
203 changed files with 2781 additions and 2174 deletions
+12
View File
@@ -333,3 +333,15 @@ SQLite (https://www.sqlite.org) is in the Public Domain.
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
### Source Code Pro font
Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/),
with Reserved Font Name 'Source'. All Rights Reserved. Source is a
trademark of Adobe Systems Incorporated in the United States
and/or other countries.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
The font and license files can be found in QtCreator/src/libs/3rdparty/fonts.
+15 -15
View File
@@ -10,23 +10,23 @@ you can check out from the public Git repository. For example:
General
* Added `Flat Dark` and `Flat Light` themes
* Added `Ctrl+N` and `Ctrl+P` shortcuts for navigating in Locator
* Added experimental support for the `Nim` programming language
* Added `Ctrl+N` and `Ctrl+P` shortcuts for navigating in locator
* Added experimental support for `Nim` programming language
Editing
* Added automatic release of resources for unmodified documents that have
not been visible a long time (QTCREATORBUG-10016)
not been visible recently (QTCREATORBUG-10016)
* Added separate options for automatically inserted characters
* Added highlighting of automatically inserted characters
* Added option for skipping automatically inserted character, and changed
it to do this only as long as the cursor stays before it
* Fixed that replacing could change the selection (QTCREATORBUG-15623)
it to be done only if the cursor stays before the character
* Fixed that replacing could change selection (QTCREATORBUG-15623)
All Projects
* Improved feedback when build results in errors and there
are issues with the kit (QTCREATORBUG-16079)
* Improved feedback when building results in errors, because of issues with
kits (QTCREATORBUG-16079)
* Fixed issue with building in paths with non-ASCII characters
(QTCREATORBUG-15855)
* Fixed that `%{buildDir}` and `%{sourceDir}` stopped working in
@@ -44,12 +44,12 @@ CMake Projects
* Improved parsing of errors
* Added workaround for CMake issue that include paths are in random order
(QTCREATORBUG-16432)
* Added option for disabling automatic running of CMake to Build & Run > CMake
(QTCREATORBUG-15934)
* Fixed that CMake was automatically run even if the Qt Creator application
is not in the foreground (QTCREATORBUG-16354)
* Added option for disabling automatic running of CMake to `Build & Run` >
`CMake` (QTCREATORBUG-15934)
* Fixed that CMake was automatically run even if Qt Creator application
is not in foreground (QTCREATORBUG-16354)
* QML_IMPORT_PATH can now be set in CMakeLists.txt files. This information
will be passed on to the QmlJS code model (QTCREATORBUG-11328)
will be passed on to QmlJS code model (QTCREATORBUG-11328)
Example CMakeLists.txt code:
`set(QML_IMPORT_PATH ${CMAKE_SOURCE_DIR}/qml ${CMAKE_BINARY_DIR}/imports CACHE string "" FORCE)`
@@ -69,7 +69,7 @@ C++ Support
QML Support
* Added formal parameters of JavaScript functions to outline and Locator
* Added formal parameters of JavaScript functions to outline and locator
Debugging
@@ -89,7 +89,7 @@ Qt Quick Designer
* Added support for Qt Quick Controls 2 styles
* Added `Move to Component` action
* Added `Add new Signal Handler` action
* Added `Add New Signal Handler` action
* Improved performance
* Improved error dialog (QTCREATORBUG-15772)
* Fixed crumble bar for component navigation
@@ -144,9 +144,9 @@ Remote Linux
iOS
* Added human readable error messages (QTCREATORBUG-16328)
* Fixed that deployment could fail if device and host are in same WiFi network
(QTCREATORBUG-16061)
* Fixed missing human readable error messages (QTCREATORBUG-16328)
Credits for these changes go to:
Albert Astals Cid
+2 -2
View File
@@ -159,10 +159,10 @@
width (\uicontrol W) and height (\uicontrol H) of the button in the
\uicontrol Properties pane.
\li Select \uicontrol Connections > \uicontrol {Dynamic Properties} >
\li Select \uicontrol Connections > \uicontrol {Properties} >
\uicontrol Add to add properties for the item:
\image qmldesigner-borderimage-properties.png "Dynamic properties"
\image qmldesigner-borderimage-properties.png "Properties"
\list a
@@ -80,7 +80,7 @@
\list 1
\li Select the \uicontrol {Dynamic Properties} tab.
\li Select the \uicontrol {Properties} tab.
\li Select \uicontrol Item to select the object to specify the property for.
+327 -151
View File
@@ -344,6 +344,7 @@ class DumperBase:
self.displayStringLimit = 100
self.resetCaches()
self.resetStats()
self.childrenPrefix = 'children=['
self.childrenSuffix = '],'
@@ -376,6 +377,35 @@ class DumperBase:
# to not be QObject derived, it contains a 0 value.
self.knownStaticMetaObjects = {}
self.counts = {}
self.pretimings = {}
self.timings = []
def resetStats(self):
# Timing collection
self.pretimings = {}
self.timings = []
pass
def dumpStats(self):
msg = [self.counts, self.timings]
self.resetStats()
return msg
def bump(self, key):
if key in self.counts:
self.counts[key] += 1
else:
self.counts[key] = 1
def preping(self, key):
import time
self.pretimings[key] = time.time()
def ping(self, key):
import time
elapsed = int(1000000 * (time.time() - self.pretimings[key]))
self.timings.append([key, elapsed])
def putNewline(self):
pass
@@ -1260,67 +1290,171 @@ class DumperBase:
pass
def extractStaticMetaObjectHelper(self, typeobj):
"""
Checks whether type has a Q_OBJECT macro.
Returns the staticMetaObject, or 0.
"""
def extractMetaObjectPtr(self, objectPtr, typeobj):
""" objectPtr - address of *potential* instance of QObject derived class
typeobj - type of *objectPtr if known, None otherwise. """
if self.isSimpleType(typeobj):
def canBePointer(p):
if ptrSize == 4:
return p > 100000 and (p & 0x3 == 0)
else:
return p > 100000 and (p & 0x7 == 0) and (p < 0x7fffffffffff)
def couldBeQObject():
(vtablePtr, dd) \
= self.extractStruct('PP', objectPtr, 2 * ptrSize)
if not canBePointer(vtablePtr):
self.bump("vtable")
return False
if not canBePointer(dd):
self.bump("d_d_ptr")
return False
(dvtablePtr, qptr, parentPtr, childrenDPtr, flags) \
= self.extractStruct('PPPPI', dd, 4 * ptrSize + 4)
#warn("STRUCT DD: %s %s" % (self.currentIName, x))
if not canBePointer(dvtablePtr):
self.bump("dvtable")
#warn("DVT: 0x%x" % dvtablePtr)
return False
# Check d_ptr.d.q_ptr == objectPtr
if qptr != objectPtr:
#warn("QPTR: 0x%x 0x%x" % (qptr, objectPtr))
self.bump("q_ptr")
return False
if parentPtr and not canBePointer(parentPtr):
#warn("PAREN")
self.bump("parent")
return False
if not canBePointer(childrenDPtr):
#warn("CHILD")
self.bump("children")
return False
#if flags >= 0x80: # Only 7 flags are defined
# warn("FLAGS: 0x%x %s" % (flags, self.currentIName))
# self.bump("flags")
# return False
#warn("OK")
#if dynMetaObjectPtr and not canBePointer(dynMetaObjectPtr):
# self.bump("dynmo")
# return False
self.bump("couldBeQObject")
return True
def extractMetaObjectPtrFromAddress():
# Try vtable, metaObject() is the first entry.
vtablePtr = self.extractPointer(objectPtr)
metaObjectFunc = self.extractPointer(vtablePtr)
cmd = "((void*(*)(void *))0x%x)(0x%x)" % (metaObjectFunc, objectPtr)
try:
#warn("MO CMD: %s" % cmd)
res = self.parseAndEvaluate(cmd)
#warn("MO RES: %s" % res)
self.bump("successfulMetaObjectCall")
return toInteger(res)
except:
self.bump("failedMetaObjectCall")
#warn("COULD NOT EXECUTE: %s" % cmd)
return 0
typeName = str(typeobj)
isQObjectProper = typeName == self.qtNamespace() + "QObject"
if not isQObjectProper:
if self.directBaseClass(typeobj, 0) is None:
def extractStaticMetaObjectFromTypeHelper(typeobj):
if self.isSimpleType(typeobj):
return 0
# No templates for now.
if typeName.find('<') >= 0:
typeName = str(typeobj)
isQObjectProper = typeName == self.qtNamespace() + "QObject"
if not isQObjectProper:
if self.directBaseClass(typeobj, 0) is None:
return 0
# No templates for now.
if typeName.find('<') >= 0:
return 0
result = self.findStaticMetaObject(typeName)
# We need to distinguish Q_OBJECT from Q_GADGET:
# a Q_OBJECT SMO has a non-null superdata (unless it's QObject itself),
# a Q_GADGET SMO has a null superdata (hopefully)
if result and not isQObjectProper:
superdata = self.extractPointer(result)
if superdata == 0:
# This looks like a Q_GADGET
return 0
return result
def extractStaticMetaObjectPtrFromType(someTypeObj):
if someTypeObj is None:
return 0
someTypeName = str(someTypeObj)
self.bump('metaObjectFromType')
known = self.knownStaticMetaObjects.get(someTypeName, None)
if known is not None: # Is 0 or the static metaobject.
return known
result = self.findStaticMetaObject(typeName)
result = 0
#try:
result = extractStaticMetaObjectFromTypeHelper(someTypeObj)
#except RuntimeError as error:
# warn("METAOBJECT EXTRACTION FAILED: %s" % error)
#except:
# warn("METAOBJECT EXTRACTION FAILED FOR UNKNOWN REASON")
# We need to distinguish Q_OBJECT from Q_GADGET:
# a Q_OBJECT SMO has a non-null superdata (unless it's QObject itself),
# a Q_GADGET SMO has a null superdata (hopefully)
if result and not isQObjectProper:
superdata = self.extractPointer(result)
if toInteger(superdata) == 0:
# This looks like a Q_GADGET
return 0
if not result:
base = self.directBaseClass(typeobj, 0)
if base != someTypeObj: # sanity check
result = extractStaticMetaObjectPtrFromType(base)
self.knownStaticMetaObjects[someTypeName] = result
return result
return result
def extractStaticMetaObject(self, typeobj):
"""
Checks recursively whether a type derives from QObject.
"""
if not self.useFancy:
return 0
ptrSize = self.ptrSize()
typeName = str(typeobj)
result = self.knownStaticMetaObjects.get(typeName, None)
if result is not None: # Is 0 or the static metaobject.
self.bump("typecached")
#warn("CACHED RESULT: %s %s 0x%x" % (self.currentIName, typeName, result))
return result
try:
result = self.extractStaticMetaObjectHelper(typeobj)
except RuntimeError as error:
warn("METAOBJECT EXTRACTION FAILED: %s" % error)
result = 0
except:
warn("METAOBJECT EXTRACTION FAILED FOR UNKNOWN REASON")
result = 0
if not couldBeQObject():
self.bump('cannotBeQObject')
#warn("DOES NOT LOOK LIKE A QOBJECT: %s" % self.currentIName)
return 0
if not result:
base = self.directBaseClass(typeobj, 0)
if base:
result = self.extractStaticMetaObject(base)
metaObjectPtr = 0
if not metaObjectPtr:
# measured: 3 ms (example had one level of inheritance)
self.preping("metaObjectType-" + self.currentIName)
metaObjectPtr = extractStaticMetaObjectPtrFromType(typeobj)
self.ping("metaObjectType-" + self.currentIName)
self.knownStaticMetaObjects[typeName] = result
return result
if not metaObjectPtr:
# measured: 200 ms (example had one level of inheritance)
self.preping("metaObjectCall-" + self.currentIName)
metaObjectPtr = extractMetaObjectPtrFromAddress()
self.ping("metaObjectCall-" + self.currentIName)
#if metaObjectPtr:
# self.bump('foundMetaObject')
# self.knownStaticMetaObjects[typeName] = metaObjectPtr
return metaObjectPtr
def extractStruct(self, pattern, base, size):
#warn("PATTERN: '%s'" % pattern)
pointerReplacement = 'Q' if self.ptrSize() == 8 else 'I'
pattern = pattern.replace('P', pointerReplacement)
mem = self.readRawMemory(base, size)
#warn("OUT: '%s'" % str(struct.unpack_from(pattern, mem)))
return struct.unpack_from(pattern, mem)
def extractCString(self, addr):
result = bytearray()
@@ -1361,88 +1495,74 @@ class DumperBase:
def putStructGuts(self, value):
self.putEmptyValue()
#metaObjectPtr = self.extractMetaObjectPtr(self.addressOf(value), value.type)
if self.showQObjectNames:
staticMetaObject = self.extractStaticMetaObject(value.type)
if staticMetaObject:
self.preping(self.currentIName)
metaObjectPtr = self.extractMetaObjectPtr(self.addressOf(value), value.type)
self.ping(self.currentIName)
if metaObjectPtr:
self.context = value
self.putQObjectNameValue(value)
#warn("STRUCT GUTS: %s MO: 0x%x " % (self.currentIName, metaObjectPtr))
if self.isExpanded():
self.put('sortable="1"')
with Children(self, 1, childType=None):
self.putFields(value)
if not self.showQObjectNames:
staticMetaObject = self.extractStaticMetaObject(value.type)
if staticMetaObject:
self.putQObjectGuts(value, staticMetaObject)
metaObjectPtr = self.extractMetaObjectPtr(self.addressOf(value), value.type)
if metaObjectPtr:
self.putQObjectGuts(value, metaObjectPtr)
# This is called is when a QObject derived class is expanded
def putQObjectGuts(self, qobject, smo):
def putQObjectGuts(self, qobject, metaObjectPtr):
self.putQObjectGutsHelper(qobject, self.addressOf(qobject), -1, metaObjectPtr, "QObject")
def metaString(self, metaObjectPtr, index, revision = 7):
#stringData = self.extractPointer(metaObjectPtr["d"]["stringdata"])
ptrSize = self.ptrSize()
dd = self.extractPointer(qobject, offset=ptrSize)
# Parent and children.
try:
if qobject:
d_ptr = qobject["d_ptr"]["d"]
with SubItem(self, "[parent]"):
self.putItem(d_ptr["parent"])
self.put('sortgroup="9"')
with SubItem(self, "[children]"):
self.putItem(d_ptr["children"])
self.put('sortgroup="1"')
except:
pass
# dd = value["d_ptr"]["d"] is just behind the vtable.
isQt5 = self.qtVersion() >= 0x50000
extraDataOffset = 5 * ptrSize + 8 if isQt5 else 6 * ptrSize + 8
extraData = self.extractPointer(dd + extraDataOffset)
self.putQObjectGutsHelper(qobject, extraData, -1, smo, "QObject")
def metaString(self, metaObject, index, revision = 7):
sd = self.extractPointer(metaObject["d"]["stringdata"])
stringdata = self.extractPointer(toInteger(metaObjectPtr) + ptrSize)
if revision >= 7: # Qt 5.
byteArrayDataType = self.lookupQtType("QByteArrayData")
byteArrayDataSize = byteArrayDataType.sizeof
literal = toInteger(sd) + toInteger(index) * byteArrayDataSize
#byteArrayDataType = self.lookupQtType("QByteArrayData")
#byteArrayDataSize = byteArrayDataType.sizeof
byteArrayDataSize = 24 if ptrSize == 8 else 16
literal = stringdata + toInteger(index) * byteArrayDataSize
ldata, lsize, lalloc = self.byteArrayDataHelper(literal)
try:
return self.extractBlob(ldata, lsize).toString()
except:
return "<unavailable>"
return "<not available>"
else: # Qt 4.
ldata = sd + index
ldata = stringdata + index
return self.extractCString(ldata).decode("utf8")
def putQMetaStuff(self, value, origType):
metaObject = value["mobj"]
if not metaObject:
self.putEmptyValue()
if self.isExpanded():
with Children(self):
self.putFields(value)
else:
metaObjectPtr = value["mobj"]
if toInteger(metaObjectPtr):
handle = toInteger(value["handle"])
index = toInteger(metaObject["d"]["data"][handle])
name = self.metaString(metaObject.dereference(), index)
index = toInteger(metaObjectPtr["d"]["data"][handle])
name = self.metaString(metaObjectPtr, index)
self.putValue(name)
self.putNumChild(1)
if self.isExpanded():
with Children(self):
self.putFields(value)
self.putQObjectGutsHelper(0, 0, handle, metaObject, origType)
self.putQObjectGutsHelper(0, 0, handle, toInteger(metaObjectPtr), origType)
else:
self.putEmptyValue()
if self.isExpanded():
with Children(self):
self.putFields(value)
def putQObjectGutsHelper(self, qobject, extraData, handle, metaObject, origType):
# basically all meta things go through this here.
# qobject and qobjectPtr are non-null if coming from a real structure display
# qobject == 0, qobjectPtr != 0 is possible for builds without QObject debug info
# if qobject == 0, properties and d-ptr cannot be shown.
# handle is what's store in QMetaMethod etc, pass -1 for QObject/QMetaObject itself
# metaObjectPtr needs to point to a valid QMetaObject.
def putQObjectGutsHelper(self, qobject, qobjectPtr, handle, metaObjectPtr, origType):
intSize = self.intSize()
ptrSize = self.ptrSize()
data = metaObject["d"]["data"]
def walker(base):
ptr = toInteger(base)
while True:
yield self.extractInt(ptr)
ptr += intSize
def putt(name, value, typeName = ' '):
with SubItem(self, name):
@@ -1450,63 +1570,103 @@ class DumperBase:
self.putType(typeName)
self.putNumChild(0)
def superData(mo):
return mo['d']['superdata']
def extractSuperDataPtr(someMetaObjectPtr):
#return someMetaObjectPtr['d']['superdata']
return self.extractPointer(someMetaObjectPtr)
def extractDataPtr(someMetaObjectPtr):
# dataPtr = metaObjectPtr["d"]["data"]
return self.extractPointer(someMetaObjectPtr + 2 * ptrSize)
isQMetaObject = origType == "QMetaObject"
isQObject = origType == "QObject"
p = walker(data)
revision = p.next()
classname = p.next()
classinfo = p.next()
classinfo2 = p.next()
methodCount = p.next()
methods = p.next()
propertyCount = p.next()
properties = p.next()
enumCount = p.next()
enums = p.next()
constructorCount = p.next()
constructors = p.next()
flags = p.next()
signalCount = p.next()
globalOffset = 0
superdata = superData(metaObject)
while toInteger(superdata):
sdata = superdata["d"]["data"]
p = walker(sdata)
revision = p.next()
classname = p.next()
classinfo = p.next()
classinfo2 = p.next()
methodCount = p.next()
globalOffset += methodCount
superdata = superData(superdata)
#warn("OBJECT GUTS: %s 0x%x " % (self.currentIName, metaObjectPtr))
dataPtr = extractDataPtr(metaObjectPtr)
#warn("DATA PTRS: %s 0x%x " % (self.currentIName, dataPtr))
(revision, classname,
classinfo, classinfo2,
methodCount, methods,
propertyCount, properties,
enumCount, enums,
constructorCount, constructors,
flags, signalCount) = self.extractStruct('IIIIIIIIIIIIII', dataPtr, 56)
largestStringIndex = -1
for i in range(methodCount):
t = (p.next(), p.next(), p.next(), p.next(), p.next())
t = self.extractStruct('IIIII', dataPtr + 56 + i * 20, 20)
if largestStringIndex < t[0]:
largestStringIndex = t[0]
extraData = 0
if qobjectPtr:
isQt5 = self.qtVersion() >= 0x50000
extraDataOffset = 5 * ptrSize + 8 if isQt5 else 6 * ptrSize + 8
# dd = value["d_ptr"]["d"] is just behind the vtable.
dd = self.extractPointer(qobjectPtr + ptrSize)
extraData = self.extractPointer(dd + extraDataOffset)
if qobjectPtr:
qobjectType = self.lookupQtType("QObject")
badType = qobjectType is None
with SubItem(self, "[parent]"):
self.put('sortgroup="9"')
parentPtrType = self.voidPtrType() if badType else qobjectType.pointer()
self.putItem(self.createValue(dd + 2 * ptrSize, parentPtrType))
with SubItem(self, "[children]"):
self.put('sortgroup="8"')
base = self.extractPointer(dd + 3 * ptrSize) # It's a QList<QObject *>
begin = self.extractInt(base + 8)
end = self.extractInt(base + 12)
array = base + 16
if self.qtVersion() < 0x50000:
array += ptrSize
self.check(begin >= 0 and end >= 0 and end <= 1000 * 1000 * 1000)
size = end - begin
self.check(size >= 0)
self.putItemCount(size)
if self.isExpanded():
addrBase = array + begin * ptrSize
with Children(self, size):
for i in self.childRange():
with SubItem(self, i):
childPtr = self.extractPointer(addrBase + i * ptrSize)
if badType:
# release build
childMetaObjectPtr = self.extractMetaObjectPtr(childPtr, None)
if childMetaObjectPtr:
# release build + live process
self.putNumChild(1)
self.putAddress(childPtr)
if self.isExpanded():
with Children(self):
self.putQObjectGutsHelper(0, childPtr, -1, childMetaObjectPtr, "QObject")
else:
# release build + core dump
self.putItem(self.createValue(addrBase + i * ptrSize, self.voidPtrType()))
else:
# debug info
self.putItem(self.createValue(childPtr, qobjectType))
if isQMetaObject:
with SubItem(self, "[strings]"):
self.put('sortgroup="2"')
self.putSpecialValue("minimumitemcount", largestStringIndex + 1)
self.putNumChild(1)
if self.isExpanded():
with Children(self, largestStringIndex + 1):
for i in self.childRange():
with SubItem(self, i):
self.putValue(self.hexencode(self.metaString(metaObject, i)), "latin1")
self.putNumChild(0)
if largestStringIndex > 0:
self.putSpecialValue("minimumitemcount", largestStringIndex)
self.putNumChild(1)
if self.isExpanded():
with Children(self, largestStringIndex + 1):
for i in self.childRange():
with SubItem(self, i):
self.putValue(self.hexencode(self.metaString(metaObjectPtr, i)), "latin1")
self.putNumChild(0)
else:
self.putValue(" ")
self.putNumChild(0)
if isQMetaObject:
with SubItem(self, "[raw]"):
self.put('sortgroup="1"')
p = walker(data)
self.putEmptyValue()
self.putNumChild(1)
if self.isExpanded():
@@ -1520,9 +1680,8 @@ class DumperBase:
putt("constructors", "%d %d" % (constructorCount, constructors))
putt("flags", flags)
putt("signalCount", signalCount)
p = walker(toInteger(data) + 14 * 4)
for i in range(methodCount):
t = (p.next(), p.next(), p.next(), p.next(), p.next())
t = self.extractStruct('IIIII', dataPtr + 56 + i * 20, 20)
putt("method %d" % i, "%s %s %s %s %s" % t)
putt("[extraData]", "0x%x" % toInteger(extraData), "void *")
@@ -1535,10 +1694,9 @@ class DumperBase:
usesVector = self.qtVersion() >= 0x50700
with Children(self):
# Static properties.
p = walker(toInteger(data) + properties * 4)
for i in range(propertyCount):
t = (p.next(), p.next(), p.next())
name = self.metaString(metaObject, t[0])
t = self.extractStruct("III", dataPtr + properties * 4 + 12 * i, 12)
name = self.metaString(metaObjectPtr, t[0])
if qobject:
self.putCallItem(name, qobject, "property", '"' + name + '"')
else:
@@ -1563,8 +1721,17 @@ class DumperBase:
# We need a handle to [x] for the user to expand the item
# before we know whether there are actual children. Counting
# them is too expensive.
self.putNumChild(1)
self.putSpecialValue("minimumitemcount", propertyCount)
self.putNumChild(1)
superDataPtr = extractSuperDataPtr(metaObjectPtr)
globalOffset = 0
superDataIterator = superDataPtr
while superDataIterator:
sdata = extractDataPtr(superDataIterator)
globalOffset += self.extractInt(sdata + 16) # methodCount member
superDataIterator = extractSuperDataPtr(superDataIterator)
if isQMetaObject or isQObject:
with SubItem(self, "[methods]"):
@@ -1572,10 +1739,9 @@ class DumperBase:
self.putItemCount(methodCount)
if self.isExpanded():
with Children(self):
p = walker(toInteger(data) + 14 * 4)
for i in range(methodCount):
t = (p.next(), p.next(), p.next(), p.next(), p.next())
name = self.metaString(metaObject, t[0])
t = self.extractStruct("IIIII", dataPtr + 56 + 20 * i, 20)
name = self.metaString(metaObjectPtr, t[0])
with SubItem(self, i):
self.putValue(name)
self.putType(" ")
@@ -1602,29 +1768,39 @@ class DumperBase:
putt("[globalindex]", str(globalOffset + i))
if isQObject:
self.putSubItem("[metaObject]", metaObject)
with SubItem(self, "[metaObject]"):
self.putAddress(metaObjectPtr)
self.putNumChild(1)
if self.isExpanded():
with Children(self):
self.putQObjectGutsHelper(0, 0, -1, metaObjectPtr, "QMetaObject")
if isQObject:
with SubItem(self, "d"):
self.put('sortgroup="15"')
self.putItem(qobject["d_ptr"]["d"])
try:
self.putItem(qobject["d_ptr"]["d"])
except:
self.putNumChild(0)
self.putSpecialValue("notaccessible")
if isQMetaObject:
with SubItem(self, "[superdata]"):
self.put('sortgroup="12"')
superdata = superData(metaObject)
self.putValue("0x%x" % superdata)
if toInteger(superdata):
if superDataPtr:
self.putType(self.qtNamespace() + "QMetaObject")
self.putAddress(superDataPtr)
self.putNumChild(1)
if self.isExpanded():
with Children(self):
self.putSubItem('*', superdata)
self.putQObjectGutsHelper(0, 0, -1, superDataPtr, "QMetaObject")
else:
self.putType(self.qtNamespace() + "QMetaObject *")
self.putValue("0x0")
self.putNumChild(0)
self.putType(superdata.type)
if handle >= 0:
localIndex = (handle - methods) / 5
localIndex = int((handle - methods) / 5)
with SubItem(self, "[localindex]"):
self.put('sortgroup="12"')
self.putValue(localIndex)
+16 -11
View File
@@ -383,13 +383,9 @@ class Dumper(DumperBase):
def canCallLocale(self):
return False if self.is32bit() else True
def reportTime(self, hint):
#from datetime import datetime
#warn("%s: %s" % (hint, datetime.now().time().isoformat()))
pass
def fetchVariables(self, args):
self.reportTime("begin fetch")
self.resetStats()
self.preping("locals")
self.prepare(args)
partialVariable = args.get("partialvar", "")
isPartial = len(partialVariable) > 0
@@ -425,7 +421,7 @@ class Dumper(DumperBase):
else:
locals = self.listOfLocals()
self.reportTime("locals")
self.ping("locals")
# Take care of the return value of the last function call.
if len(self.resultVarName) > 0:
@@ -449,12 +445,16 @@ class Dumper(DumperBase):
else:
# A "normal" local variable or parameter.
with TopLevelItem(self, item.iname):
self.preping("all-" + item.iname)
self.put('iname="%s",' % item.iname)
self.put('name="%s",' % item.name)
self.putItem(value)
self.ping("all-" + item.iname)
self.preping("watches")
with OutputSafer(self):
self.handleWatches(args)
self.ping("watches")
self.output.append('],typeinfo=[')
for name in self.typesToReport.keys():
@@ -475,9 +475,10 @@ class Dumper(DumperBase):
self.output.append(',partial="%d"' % isPartial)
self.reportTime("before print: %s" % len(self.output))
self.preping('safePrint')
safePrint(''.join(self.output))
self.reportTime("after print")
self.ping('safePrint')
safePrint('"%s"' % str(self.dumpStats()))
def enterSubItem(self, item):
if not item.iname:
@@ -800,10 +801,12 @@ class Dumper(DumperBase):
return struct.unpack("b", self.readRawMemory(address, 1))[0]
def findStaticMetaObject(self, typename):
return self.findSymbol(typename + "::staticMetaObject")
symbol = gdb.lookup_global_symbol(typename + "::staticMetaObject")
return toInteger(symbol.value().address) if symbol else 0
def findSymbol(self, symbolName):
try:
self.bump('findSymbol1')
result = gdb.lookup_global_symbol(symbolName)
return result.value() if result else 0
except:
@@ -812,9 +815,11 @@ class Dumper(DumperBase):
try:
address = gdb.parse_and_eval("&'%s'" % symbolName)
typeobj = gdb.lookup_type(self.qtNamespace() + "QMetaObject")
self.bump('findSymbol2')
return self.createPointerValue(address, typeobj)
except:
return 0
self.bump('findSymbol3')
return 0
def put(self, value):
self.output.append(value)
+13 -1
View File
@@ -900,6 +900,10 @@ class Dumper(DumperBase):
# logview pane feature.
self.report('token(\"%s\")' % args["token"])
def readRawMemory(self, address, size):
error = lldb.SBError()
return self.process.ReadMemory(address, size, error)
def extractBlob(self, base, size):
if size == 0:
return Blob("")
@@ -923,7 +927,8 @@ class Dumper(DumperBase):
def findStaticMetaObject(self, typeName):
symbolName = self.mangleName(typeName + '::staticMetaObject')
return self.target.FindFirstGlobalVariable(symbolName)
symbol = self.target.FindFirstGlobalVariable(symbolName)
return int(symbol.AddressOf()) if symbol.IsValid() else 0
def findSymbol(self, symbolName):
return self.target.FindFirstGlobalVariable(symbolName)
@@ -1205,6 +1210,13 @@ class Dumper(DumperBase):
else:
shadowed[name] = 1
if not value.IsInScope():
with SubItem(self, name):
self.put('iname="%s",' % self.currentIName)
self.putSpecialValue('outofscope')
self.putNumChild(0)
continue
if name == "argv" and value.GetType().GetName() == "char **":
self.putSpecialArgv(value)
else:
+1 -1
View File
@@ -1106,7 +1106,7 @@ def qdump__QMetaObject(d, value):
d.putNumChild(1)
if d.isExpanded():
with Children(d):
d.putQObjectGutsHelper(0, 0, -1, value, "QMetaObject")
d.putQObjectGutsHelper(0, 0, -1, d.addressOf(value), "QMetaObject")
d.putMembersItem(value)
@@ -298,13 +298,9 @@ Item {
elide: Text.ElideRight
anchors.verticalCenter: parent.verticalCenter
}
SliderSpinBox {
DoubleSpinBox {
id: hueSlider2
//value: colorButton.hue
decimals: 2
stepSize: 0.1
minimumValue: 0
maximumValue: 1
onValueChanged: {
if (colorButton.hue !== value && !colorButton.block) {
colorButton.hue = value
@@ -325,13 +321,9 @@ Item {
anchors.verticalCenter: parent.verticalCenter
}
SliderSpinBox {
DoubleSpinBox {
id: saturationSlider
//value: colorButton.saturation
decimals: 2
stepSize: 0.1
minimumValue: 0
maximumValue: 1
onValueChanged: {
if (colorButton.saturation !== value && !colorButton.block) {
colorButton.saturation = value
@@ -351,13 +343,9 @@ Item {
elide: Text.ElideRight
anchors.verticalCenter: parent.verticalCenter
}
SliderSpinBox {
DoubleSpinBox {
id: lightnessSlider
//value: colorButton.lightness
decimals: 2
stepSize: 0.1
minimumValue: 0
maximumValue: 1
onValueChanged: {
if (colorButton.lightness !== value && !colorButton.block) {
colorButton.lightness = value
@@ -378,13 +366,9 @@ Item {
anchors.verticalCenter: parent.verticalCenter
}
SliderSpinBox {
DoubleSpinBox {
id: alphaSlider
decimals: 2
stepSize: 0.1
//value: colorButton.alpha
minimumValue: 0
maximumValue: 1
onValueChanged: {
if (colorButton.alpha !== value && !colorButton.block) {
colorButton.alpha = value
@@ -29,8 +29,12 @@ import QtQuick.Controls 1.0
SpinBox {
id: spinBox
width: 76
decimals: 2
stepSize: 0.1
minimumValue: 0
maximumValue: 1
property color textColor: colorLogic.textColor
property color textColor: creatorTheme.PanelTextColorLight
style: CustomSpinBoxStyle {
@@ -25,6 +25,7 @@
import QtQuick 2.1
import HelperWidgets 2.0
import QtQuick.Controls.Private 1.0 // showing a ToolTip
Item {
width: 300
@@ -100,7 +101,9 @@ Item {
var gradientObject = Qt.createQmlObject(gradientString, gradientRectangle, "test");
for (i = 0; i < gradientModel.count; i++) {
repeater.itemAt(i).item.y = 20 //fixes corner case for dragging overlapped items
if (repeater.itemAt(i) !== null)
repeater.itemAt(i).item.y = 20 //fixes corner case for dragging overlapped items
gradientObject.stops[i].color = gradientModel.getColor(i)
gradientObject.stops[i].position = gradientModel.getPosition(i)
}
@@ -199,6 +202,7 @@ Item {
Component {
id: component
Item {
id: gradientStopHandle
y: 20
width: 10
height: 20
@@ -206,6 +210,26 @@ Item {
property alias color: rectangle.color
property alias highlighted: canvas.highlighted
property bool toolTipVisible: false
function refreshToolTip(showToolTip) {
toolTipVisible = showToolTip;
if (showToolTip) {
var currentPoint = Qt.point(gradientStopHandleMouseArea.mouseX, gradientStopHandleMouseArea.mouseY);
var fixedGradiantStopPosition = currentGradiantStopPosition();
Tooltip.showText(gradientStopHandleMouseArea, currentPoint, fixedGradiantStopPosition.toFixed(3));
} else {
Tooltip.hideText()
}
}
function currentGradiantStopPosition() {
return x / colorLine.effectiveWidth;
}
onXChanged: {
refreshToolTip(toolTipVisible)
}
Rectangle {
id: rectangle
width: 10
@@ -272,21 +296,41 @@ Item {
duration: 100
}
}
MouseArea {
id: gradientStopHandleMouseArea
anchors.fill: parent
drag.target: parent
drag.minimumX: 0
drag.maximumX: colorLine.effectiveWidth
drag.minimumY: !readOnly ? 0 : 20
drag.maximumY: 20
// using pressed property instead of drag.active which was not working
onExited: {
gradientStopHandle.refreshToolTip(pressed);
}
onCanceled: {
gradientStopHandle.refreshToolTip(pressed);
}
hoverEnabled: true
Timer {
interval: 1000
running: gradientStopHandleMouseArea.containsMouse
onTriggered: {
gradientStopHandle.refreshToolTip(true);
}
}
onPressed: {
colorLine.select(index);
gradientStopHandle.refreshToolTip(true);
}
onReleased: {
if (drag.active) {
gradientModel.setPosition(colorLine.selectedIndex, parent.x / colorLine.effectiveWidth)
gradientModel.setPosition(colorLine.selectedIndex, gradientStopHandle.currentGradiantStopPosition())
gradientStopHandle.refreshToolTip(false);
if (parent.y < 10) {
if (!readOnly) {
Binary file not shown.

After

Width:  |  Height:  |  Size: 80 B

@@ -31,7 +31,7 @@ ScrollView 2.0 ScrollView.qml
SecondColumnLayout 2.0 SecondColumnLayout.qml
Section 2.0 Section.qml
SectionLayout 2.0 SectionLayout.qml
SliderSpinBox 2.0 SliderSpinBox.qml
DoubleSpinBox 2.0 DoubleSpinBox.qml
SpinBox 2.0 SpinBox.qml
StandardTextSection 2.0 StandardTextSection.qml
Tab 2.0 Tab.qml
+63
View File
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<style-scheme version="1.0" name="Qt Creator Dark">
<style name="Text" foreground="#d6cf9a" background="#2e2f30"/>
<style name="Link" foreground="#d6c540"/>
<style name="Selection" background="#1d545c"/>
<style name="LineNumber" foreground="#bec0c2" background="#404244"/>
<style name="SearchResult" background="#8a7f2c"/>
<style name="SearchScope" background="#8a602c"/>
<style name="Parentheses" foreground="#bec0c2" background="#1d545c"/>
<style name="ParenthesesMismatch" background="#d64564"/>
<style name="AutoComplete" foreground="#2c408a" background="#9aa7d6"/>
<style name="CurrentLine" background="#373737"/>
<style name="CurrentLineNumber" foreground="#d6c540" bold="true"/>
<style name="Occurrences" background="#8a402c"/>
<style name="Occurrences.Unused" foreground="#8a7f2c"/>
<style name="Occurrences.Rename" foreground="#ffaaaa" background="#553636"/>
<style name="Number" foreground="#8a602c"/>
<style name="String" foreground="#d69545"/>
<style name="Type" foreground="#ff8080"/>
<style name="Local" foreground="#d6bb9a"/>
<style name="Global" foreground="#9aa7d6"/>
<style name="Field"/>
<style name="Static" foreground="#66a334" italic="true"/>
<style name="VirtualMethod" italic="true"/>
<style name="Function"/>
<style name="Keyword" foreground="#45c6d6" italic="true"/>
<style name="PrimitiveType" foreground="#d69aa7"/>
<style name="Operator" foreground="#d6bb9a"/>
<style name="Preprocessor" foreground="#d64564"/>
<style name="Label" foreground="#d6c540"/>
<style name="Comment" foreground="#a8abb0" italic="true"/>
<style name="Doxygen.Comment" foreground="#65676a" bold="true" italic="true"/>
<style name="Doxygen.Tag" foreground="#66a334"/>
<style name="VisualWhitespace" foreground="#bec0c2"/>
<style name="QmlLocalId" foreground="#9acfd6" italic="true"/>
<style name="QmlExternalId" foreground="#9aa7d6" italic="true"/>
<style name="QmlTypeId" foreground="#66a334"/>
<style name="QmlRootObjectProperty" italic="true"/>
<style name="QmlScopeObjectProperty" italic="true"/>
<style name="QmlExternalObjectProperty" foreground="#9aa7d6" italic="true"/>
<style name="JsScopeVar" foreground="#9acfd6" italic="true"/>
<style name="JsImportVar" foreground="#4564d6" italic="true"/>
<style name="JsGlobalVar" foreground="#4564d6" italic="true"/>
<style name="QmlStateName" foreground="#45c6d6" italic="true"/>
<style name="Binding" foreground="#d64564"/>
<style name="DisabledCode" foreground="#969696" background="#474747"/>
<style name="AddedLine" foreground="#45c6d6"/>
<style name="RemovedLine" foreground="#d65645"/>
<style name="DiffFile" foreground="#66a334"/>
<style name="DiffLocation" foreground="#d6c540"/>
<style name="DiffFileLine" foreground="#2e2f30" background="#d6c540"/>
<style name="DiffContextLine" foreground="#2e2f30" background="#65676a"/>
<style name="DiffSourceLine" background="#8a2c40"/>
<style name="DiffSourceChar" foreground="#2e2f30" background="#c34141"/>
<style name="DiffDestLine" background="#588a2c"/>
<style name="DiffDestChar" foreground="#2e2f30" background="#7cc33e"/>
<style name="LogChangeLine" foreground="#d65645"/>
<style name="Warning" underlineColor="#d6c545" underlineStyle="SingleUnderline"/>
<style name="WarningContext" underlineColor="#d6c545" underlineStyle="DotLine"/>
<style name="Error" underlineColor="#d65645" underlineStyle="SingleUnderline"/>
<style name="ErrorContext" underlineColor="#d65645" underlineStyle="DotLine"/>
<style name="Declaration"/>
</style-scheme>
+27 -3
View File
@@ -12,13 +12,16 @@ selectedBackground=46ffffff
normalBackground=ff333333
alternateBackground=ff515151
error=ffff0000
textColorLink=ff007af4
textColorLinkVisited=ffa57aff
backgroundColorDisabled=ff444444
[Colors]
BackgroundColorAlternate=alternateBackground
BackgroundColorDark=shadowBackground
BackgroundColorHover=hoverBackground
BackgroundColorNormal=normalBackground
BackgroundColorDisabled=ff444444
BackgroundColorDisabled=backgroundColorDisabled
BackgroundColorSelected=selectedBackground
BadgeLabelBackgroundColorChecked=normalBackground
BadgeLabelBackgroundColorUnchecked=selectedBackground
@@ -112,8 +115,8 @@ SplitterColor=ff313131
TextColorDisabled=textDisabled
TextColorError=ffff4040
TextColorHighlight=ffff0000
TextColorLink=ff007af4
TextColorLinkVisited=ffa57aff
TextColorLink=textColorLink
TextColorLinkVisited=textColorLinkVisited
TextColorNormal=text
TodoItemTextColor=ff000000
ToggleButtonBackgroundColor=shadowBackground
@@ -177,6 +180,26 @@ ProjectExplorer_TaskWarn_TextMarkColor=ffffff40
ClangCodeModel_Error_TextMarkColor=ffff882f
ClangCodeModel_Warning_TextMarkColor=ffceff40
PaletteWindow=normalBackground
PaletteWindowText=text
PaletteBase=normalBackground
PaletteAlternateBase=alternateBackground
PaletteButton=shadowBackground
PaletteBrightText=ffff0000
PaletteText=text
PaletteButtonText=text
PaletteToolTipBase=selectedBackground
PaletteHighlight=selectedBackground
PaletteDark=shadowBackground
PaletteHighlightedText=ffffffff
PaletteToolTipText=text
PaletteLink=textColorLink
PaletteLinkVisited=textColorLinkVisited
PaletteWindowDisabled=backgroundColorDisabled
PaletteWindowTextDisabled=textDisabled
PaletteBaseDisabled=backgroundColorDisabled
PaletteTextDisabled=textDisabled
[Flags]
ComboBoxDrawTextShadow=false
DerivePaletteFromTheme=true
@@ -184,6 +207,7 @@ DrawIndicatorBranch=true
DrawSearchResultWidgetFrame=false
DrawTargetSelectorBottom=false
DrawToolBarHighlights=true
DrawToolBarBorders=false
ApplyThemePaletteGlobally=true
FlatToolBars=true
FlatSideBarIcons=true
@@ -178,6 +178,7 @@ DrawIndicatorBranch=false
DrawSearchResultWidgetFrame=true
DrawTargetSelectorBottom=true
DrawToolBarHighlights=true
DrawToolBarBorders=false
ApplyThemePaletteGlobally=false
FlatToolBars=false
FlatSideBarIcons=false
+28 -4
View File
@@ -1,7 +1,7 @@
[General]
ThemeName=Flat Dark
PreferredStyles=Fusion
DefaultTextEditorColorScheme=inkpot.xml
DefaultTextEditorColorScheme=creator-dark.xml
[Palette]
shadowBackground=ff404244
@@ -17,13 +17,16 @@ normalBackground=ff2E2F30
alternateBackground=ff353637
error=ffe41e25
splitter=ff06080A
textColorLink=ff007af4
textColorLinkVisited=ffa57aff
backgroundColorDisabled=ff444444
[Colors]
BackgroundColorAlternate=alternateBackground
BackgroundColorDark=shadowBackground
BackgroundColorHover=hoverBackground
BackgroundColorNormal=normalBackground
BackgroundColorDisabled=ff444444
BackgroundColorDisabled=backgroundColorDisabled
BackgroundColorSelected=selectedBackground
BadgeLabelBackgroundColorChecked=ffe0e0e0
BadgeLabelBackgroundColorUnchecked=ff808080
@@ -117,8 +120,8 @@ SplitterColor=splitter
TextColorDisabled=textDisabled
TextColorError=ffff4040
TextColorHighlight=ffff0000
TextColorLink=ff007af4
TextColorLinkVisited=ffa57aff
TextColorLink=textColorLink
TextColorLinkVisited=textColorLinkVisited
TextColorNormal=text
TodoItemTextColor=text
ToggleButtonBackgroundColor=shadowBackground
@@ -182,6 +185,26 @@ ProjectExplorer_TaskWarn_TextMarkColor=ffffff40
ClangCodeModel_Error_TextMarkColor=ffff882f
ClangCodeModel_Warning_TextMarkColor=ffceff40
PaletteWindow=normalBackground
PaletteWindowText=text
PaletteBase=normalBackground
PaletteAlternateBase=alternateBackground
PaletteButton=shadowBackground
PaletteBrightText=ffff0000
PaletteText=text
PaletteButtonText=text
PaletteToolTipBase=selectedBackground
PaletteHighlight=selectedBackground
PaletteDark=shadowBackground
PaletteHighlightedText=ffffffff
PaletteToolTipText=text
PaletteLink=textColorLink
PaletteLinkVisited=textColorLinkVisited
PaletteWindowDisabled=backgroundColorDisabled
PaletteWindowTextDisabled=textDisabled
PaletteBaseDisabled=backgroundColorDisabled
PaletteTextDisabled=textDisabled
[Flags]
ComboBoxDrawTextShadow=false
DerivePaletteFromTheme=true
@@ -189,6 +212,7 @@ DrawIndicatorBranch=true
DrawSearchResultWidgetFrame=false
DrawTargetSelectorBottom=false
DrawToolBarHighlights=false
DrawToolBarBorders=false
ApplyThemePaletteGlobally=true
FlatToolBars=true
FlatSideBarIcons=true
+12 -10
View File
@@ -14,7 +14,8 @@ hoverBackground=1a000000
selectedBackground=a8ffffff
normalBackground=ffffffff
alternateBackground=ff515151
error=ffe41e25
stop_error=ffec7373
run_success=ff52c23b
splitter=ffbdbebf
[Colors]
@@ -61,14 +62,14 @@ IconsWarningColor=ffecbc1c
IconsWarningToolBarColor=ffecbc1c
IconsErrorColor=ffdf4f4f
IconsErrorToolBarColor=ffdf4f4f
IconsRunColor=ff52c23b
IconsRunToolBarColor=ff52c23b
IconsStopColor=ffec7373
IconsStopToolBarColor=ffec7373
IconsRunColor=run_success
IconsRunToolBarColor=run_success
IconsStopColor=stop_error
IconsStopToolBarColor=stop_error
IconsInterruptColor=ff587ff7
IconsInterruptToolBarColor=ff6a7bc3
IconsDebugColor=toolBarItem
IconsNavigationArrowsColor=ffd5aa00
IconsNavigationArrowsColor=ff3dabe6
IconsBuildHammerHandleColor=ffc26b14
IconsBuildHammerHeadColor=ff868687
IconsModeWelcomeActiveColor=ff5caa15
@@ -107,11 +108,11 @@ PanelsWidgetSeparatorLineColor=0
PanelTextColorDark=text
PanelTextColorMid=ff666666
PanelTextColorLight=fancyBarsNormalTextColor
ProgressBarColorError=ffdb6f71
ProgressBarColorFinished=dda4d576
ProgressBarColorNormal=ff999999
ProgressBarColorError=stop_error
ProgressBarColorFinished=run_success
ProgressBarColorNormal=ff888888
ProgressBarTitleColor=fancyBarsBoldTextColor
ProgressBarBackgroundColor=a0606060
ProgressBarBackgroundColor=28000000
SplitterColor=splitter
TextColorDisabled=textDisabled
TextColorError=ffff4040
@@ -188,6 +189,7 @@ DrawIndicatorBranch=true
DrawSearchResultWidgetFrame=false
DrawTargetSelectorBottom=false
DrawToolBarHighlights=false
DrawToolBarBorders=true
ApplyThemePaletteGlobally=false
FlatToolBars=true
FlatSideBarIcons=true
+1
View File
@@ -188,6 +188,7 @@ DrawIndicatorBranch=true
DrawSearchResultWidgetFrame=false
DrawTargetSelectorBottom=false
DrawToolBarHighlights=false
DrawToolBarBorders=false
ApplyThemePaletteGlobally=false
FlatToolBars=true
FlatSideBarIcons=true
+12
View File
@@ -36,6 +36,7 @@
#include <QDebug>
#include <QDir>
#include <QFontDatabase>
#include <QFileInfo>
#include <QLibraryInfo>
#include <QLoggingCategory>
@@ -295,6 +296,15 @@ static inline QSettings *userSettings()
static const char *SHARE_PATH =
Utils::HostOsInfo::isMacHost() ? "/../Resources" : "/../share/qtcreator";
void loadFonts()
{
const QDir dir(QCoreApplication::applicationDirPath() + QLatin1String(SHARE_PATH)
+ QLatin1String("/fonts/"));
foreach (const QFileInfo &fileInfo, dir.entryInfoList(QStringList("*.ttf"), QDir::Files))
QFontDatabase::addApplicationFont(fileInfo.absoluteFilePath());
}
int main(int argc, char **argv)
{
const char *highDpiEnvironmentVariable = setHighDpiEnvironmentVariable();
@@ -311,6 +321,8 @@ int main(int argc, char **argv)
SharedTools::QtSingleApplication app((QLatin1String(appNameC)), argc, argv);
loadFonts();
if (highDpiEnvironmentVariable)
qunsetenv(highDpiEnvironmentVariable);
+29 -29
View File
@@ -581,7 +581,7 @@ again:
if (end - begin != chars.size() - 1) {
_errorCode = IllegalExponentIndicator;
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal syntax for exponential number");
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal syntax for exponential number.");
return T_ERROR;
}
@@ -674,7 +674,7 @@ again:
if (qmlMode())
break;
_errorCode = IllegalCharacter;
_errorMessage = QCoreApplication::translate("QmlParser", "Stray newline in string literal");
_errorMessage = QCoreApplication::translate("QmlParser", "Stray newline in string literal.");
return T_ERROR;
} else if (_char == QLatin1Char('\\')) {
break;
@@ -720,7 +720,7 @@ again:
u = decodeUnicodeEscapeCharacter(&ok);
if (! ok) {
_errorCode = IllegalUnicodeEscapeSequence;
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal unicode escape sequence");
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal unicode escape sequence.");
return T_ERROR;
}
} break;
@@ -731,7 +731,7 @@ again:
u = decodeHexEscapeCharacter(&ok);
if (!ok) {
_errorCode = IllegalHexadecimalEscapeSequence;
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal hexadecimal escape sequence");
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal hexadecimal escape sequence.");
return T_ERROR;
}
} break;
@@ -764,7 +764,7 @@ again:
case '8':
case '9':
_errorCode = IllegalEscapeSequence;
_errorMessage = QCoreApplication::translate("QmlParser", "Octal escape sequences are not allowed");
_errorMessage = QCoreApplication::translate("QmlParser", "Octal escape sequences are not allowed.");
return T_ERROR;
case '\r':
@@ -788,7 +788,7 @@ again:
}
_errorCode = UnclosedStringLiteral;
_errorMessage = QCoreApplication::translate("QmlParser", "Unclosed string at end of line");
_errorMessage = QCoreApplication::translate("QmlParser", "Unclosed string at end of line.");
return T_ERROR;
}
case '0':
@@ -812,7 +812,7 @@ again:
c = decodeUnicodeEscapeCharacter(&ok);
if (! ok) {
_errorCode = IllegalUnicodeEscapeSequence;
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal unicode escape sequence");
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal unicode escape sequence.");
return T_ERROR;
}
}
@@ -837,7 +837,7 @@ again:
c = decodeUnicodeEscapeCharacter(&ok);
if (! ok) {
_errorCode = IllegalUnicodeEscapeSequence;
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal unicode escape sequence");
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal unicode escape sequence.");
return T_ERROR;
}
if (isIdentifierPart(c))
@@ -900,7 +900,7 @@ int Lexer::scanNumber(QChar ch)
}
} else if (_char.isDigit() && !qmlMode()) {
_errorCode = IllegalCharacter;
_errorMessage = QCoreApplication::translate("QmlParser", "Decimal numbers can't start with '0'");
_errorMessage = QCoreApplication::translate("QmlParser", "Decimal numbers cannot start with \"0\".");
return T_ERROR;
}
@@ -921,7 +921,7 @@ int Lexer::scanNumber(QChar ch)
if (chars.size() < 3) {
_errorCode = IllegalHexNumber;
_errorMessage = QCoreApplication::translate("QmlParser", "At least one hexadecimal digit is required after '0%1'").arg(ch);
_errorMessage = QCoreApplication::translate("QmlParser", "At least one hexadecimal digit is required after \"0%1\".").arg(ch);
return T_ERROR;
}
@@ -997,7 +997,7 @@ int Lexer::scanNumber(QChar ch)
if (end - begin != chars.size() - 1) {
_errorCode = IllegalExponentIndicator;
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal syntax for exponential number");
_errorMessage = QCoreApplication::translate("QmlParser", "Illegal syntax for exponential number.");
return T_ERROR;
}
@@ -1023,7 +1023,7 @@ bool Lexer::scanRegExp(RegExpBodyPrefix prefix)
while (isIdentLetter(_char)) {
int flag = regExpFlagFromChar(_char);
if (flag == 0 || _patternFlags & flag) {
_errorMessage = QCoreApplication::translate("QmlParser", "Invalid regular expression flag '%0'")
_errorMessage = QCoreApplication::translate("QmlParser", "Invalid regular expression flag \"%0\".")
.arg(QChar(_char));
return false;
}
@@ -1040,7 +1040,7 @@ bool Lexer::scanRegExp(RegExpBodyPrefix prefix)
scanChar();
if (_codePtr > _endPtr || isLineTerminator()) {
_errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression backslash sequence");
_errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression backslash sequence.");
return false;
}
@@ -1062,7 +1062,7 @@ bool Lexer::scanRegExp(RegExpBodyPrefix prefix)
scanChar();
if (_codePtr > _endPtr || isLineTerminator()) {
_errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression backslash sequence");
_errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression backslash sequence.");
return false;
}
@@ -1075,7 +1075,7 @@ bool Lexer::scanRegExp(RegExpBodyPrefix prefix)
}
if (_char != QLatin1Char(']')) {
_errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression class");
_errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression class.");
return false;
}
@@ -1085,7 +1085,7 @@ bool Lexer::scanRegExp(RegExpBodyPrefix prefix)
default:
if (_codePtr > _endPtr || isLineTerminator()) {
_errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression literal");
_errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression literal.");
return false;
} else {
_tokenText += _char;
@@ -1289,7 +1289,7 @@ bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error)
if (! (directiveName == QLatin1String("pragma") ||
directiveName == QLatin1String("import"))) {
error->message = QCoreApplication::translate("QmlParser", "Syntax error");
error->message = QCoreApplication::translate("QmlParser", "Syntax error.");
error->loc.startLine = tokenStartLine();
error->loc.startColumn = tokenStartColumn();
return false; // not a valid directive name
@@ -1299,7 +1299,7 @@ bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error)
if (directiveName == QLatin1String("pragma")) {
// .pragma library
if (! (lex() == T_IDENTIFIER && tokenText() == QLatin1String("library"))) {
error->message = QCoreApplication::translate("QmlParser", "Syntax error");
error->message = QCoreApplication::translate("QmlParser", "Syntax error.");
error->loc.startLine = tokenStartLine();
error->loc.startColumn = tokenStartColumn();
return false; // expected `library
@@ -1323,7 +1323,7 @@ bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error)
pathOrUri = tokenText();
if (!pathOrUri.endsWith(QLatin1String("js"))) {
error->message = QCoreApplication::translate("QmlParser","Imported file must be a script");
error->message = QCoreApplication::translate("QmlParser","Imported file must be a script.");
error->loc.startLine = tokenStartLine();
error->loc.startColumn = tokenStartColumn();
return false;
@@ -1334,7 +1334,7 @@ bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error)
while (true) {
if (!isUriToken(_tokenKind)) {
error->message = QCoreApplication::translate("QmlParser","Invalid module URI");
error->message = QCoreApplication::translate("QmlParser","Invalid module URI.");
error->loc.startLine = tokenStartLine();
error->loc.startColumn = tokenStartColumn();
return false;
@@ -1344,7 +1344,7 @@ bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error)
lex();
if (tokenStartLine() != lineNumber) {
error->message = QCoreApplication::translate("QmlParser","Invalid module URI");
error->message = QCoreApplication::translate("QmlParser","Invalid module URI.");
error->loc.startLine = tokenStartLine();
error->loc.startColumn = tokenStartColumn();
return false;
@@ -1356,7 +1356,7 @@ bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error)
lex();
if (tokenStartLine() != lineNumber) {
error->message = QCoreApplication::translate("QmlParser","Invalid module URI");
error->message = QCoreApplication::translate("QmlParser","Invalid module URI.");
error->loc.startLine = tokenStartLine();
error->loc.startColumn = tokenStartColumn();
return false;
@@ -1364,7 +1364,7 @@ bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error)
}
if (_tokenKind != T_NUMERIC_LITERAL) {
error->message = QCoreApplication::translate("QmlParser","Module import requires a version");
error->message = QCoreApplication::translate("QmlParser","Module import requires a version.");
error->loc.startLine = tokenStartLine();
error->loc.startColumn = tokenStartColumn();
return false; // expected the module version number
@@ -1378,9 +1378,9 @@ bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error)
//
if (! (lex() == T_IDENTIFIER && tokenText() == QLatin1String("as") && tokenStartLine() == lineNumber)) {
if (fileImport)
error->message = QCoreApplication::translate("QmlParser", "File import requires a qualifier");
error->message = QCoreApplication::translate("QmlParser", "File import requires a qualifier.");
else
error->message = QCoreApplication::translate("QmlParser", "Module import requires a qualifier");
error->message = QCoreApplication::translate("QmlParser", "Module import requires a qualifier.");
if (tokenStartLine() != lineNumber) {
error->loc.startLine = lineNumber;
error->loc.startColumn = column;
@@ -1393,9 +1393,9 @@ bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error)
if (lex() != T_IDENTIFIER || tokenStartLine() != lineNumber) {
if (fileImport)
error->message = QCoreApplication::translate("QmlParser", "File import requires a qualifier");
error->message = QCoreApplication::translate("QmlParser", "File import requires a qualifier.");
else
error->message = QCoreApplication::translate("QmlParser", "Module import requires a qualifier");
error->message = QCoreApplication::translate("QmlParser", "Module import requires a qualifier.");
error->loc.startLine = tokenStartLine();
error->loc.startColumn = tokenStartColumn();
return false; // expected module name
@@ -1403,7 +1403,7 @@ bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error)
const QString module = tokenText();
if (!module.at(0).isUpper()) {
error->message = QCoreApplication::translate("QmlParser","Invalid import qualifier");
error->message = QCoreApplication::translate("QmlParser","Invalid import qualifier.");
error->loc.startLine = tokenStartLine();
error->loc.startColumn = tokenStartColumn();
return false;
@@ -1416,7 +1416,7 @@ bool Lexer::scanDirectives(Directives *directives, DiagnosticMessage *error)
}
if (tokenStartLine() != lineNumber) {
error->message = QCoreApplication::translate("QmlParser", "Syntax error");
error->message = QCoreApplication::translate("QmlParser", "Syntax error.");
error->loc.startLine = tokenStartLine();
error->loc.startColumn = tokenStartColumn();
return false; // the directives cannot span over multiple lines
+6 -6
View File
@@ -1799,7 +1799,7 @@ case 355: {
yylloc.startColumn += yylloc.length;
yylloc.length = 0;
//const QString msg = QCoreApplication::translate("QmlParser", "Missing `;'");
//const QString msg = QCoreApplication::translate("QmlParser", "Missing \";\".");
//diagnostic_messages.append(DiagnosticMessage(Severity::Warning, yylloc, msg));
first_token = &token_buffer[0];
@@ -1829,9 +1829,9 @@ case 355: {
QString msg;
int token = token_buffer[0].token;
if (token < 0 || token >= TERMINAL_COUNT)
msg = QCoreApplication::translate("QmlParser", "Syntax error");
msg = QCoreApplication::translate("QmlParser", "Syntax error.");
else
msg = QCoreApplication::translate("QmlParser", "Unexpected token `%1'").arg(QLatin1String(spell[token]));
msg = QCoreApplication::translate("QmlParser", "Unexpected token \"%1\".").arg(QLatin1String(spell[token]));
diagnostic_messages.append(DiagnosticMessage(Severity::Error, token_buffer[0].loc, msg));
action = errorState;
@@ -1859,7 +1859,7 @@ case 355: {
for (int *tk = tokens; *tk != EOF_SYMBOL; ++tk) {
int a = t_action(errorState, *tk);
if (a > 0 && t_action(a, yytoken)) {
const QString msg = QCoreApplication::translate("QmlParser", "Expected token `%1'").arg(QLatin1String(spell[*tk]));
const QString msg = QCoreApplication::translate("QmlParser", "Expected token \"%1\".").arg(QLatin1String(spell[*tk]));
diagnostic_messages.append(DiagnosticMessage(Severity::Error, token_buffer[0].loc, msg));
yytoken = *tk;
@@ -1883,7 +1883,7 @@ case 355: {
int a = t_action(errorState, tk);
if (a > 0 && t_action(a, yytoken)) {
const QString msg = QCoreApplication::translate("QmlParser", "Expected token `%1'").arg(QLatin1String(spell[tk]));
const QString msg = QCoreApplication::translate("QmlParser", "Expected token \"%1\".").arg(QLatin1String(spell[tk]));
diagnostic_messages.append(DiagnosticMessage(Severity::Error, token_buffer[0].loc, msg));
yytoken = tk;
@@ -1896,7 +1896,7 @@ case 355: {
}
}
const QString msg = QCoreApplication::translate("QmlParser", "Syntax error");
const QString msg = QCoreApplication::translate("QmlParser", "Syntax error.");
diagnostic_messages.append(DiagnosticMessage(Severity::Error, token_buffer[0].loc, msg));
}
+12 -6
View File
@@ -817,16 +817,17 @@ FindExportedCppTypes::FindExportedCppTypes(const CPlusPlus::Snapshot &snapshot)
{
}
void FindExportedCppTypes::operator()(const CPlusPlus::Document::Ptr &document)
QStringList FindExportedCppTypes::operator()(const CPlusPlus::Document::Ptr &document)
{
m_contextProperties.clear();
m_exportedTypes.clear();
QStringList fileNames;
// this check only guards against some input errors, if document's source and AST has not
// been guarded properly the source and AST may still become empty/null while this function is running
if (document->utf8Source().isEmpty()
|| !document->translationUnit()->ast())
return;
return fileNames;
FindExportsVisitor finder(document);
finder();
@@ -838,7 +839,7 @@ void FindExportedCppTypes::operator()(const CPlusPlus::Document::Ptr &document)
const QList<ContextProperty> contextPropertyDescriptions = finder.contextProperties();
const QList<ExportedQmlType> exports = finder.exportedTypes();
if (exports.isEmpty() && contextPropertyDescriptions.isEmpty())
return;
return fileNames;
// context properties need lookup inside function scope, and thus require a full check
CPlusPlus::Document::Ptr localDoc = document;
@@ -863,14 +864,19 @@ void FindExportedCppTypes::operator()(const CPlusPlus::Document::Ptr &document)
// convert to list of FakeMetaObject::ConstPtr
m_exportedTypes.reserve(fakeMetaObjects.size() + extraFakeMetaObjects.size());
foreach (const LanguageUtils::FakeMetaObject::Ptr &fmo, fakeMetaObjects) {
fmo->updateFingerprint();
m_exportedTypes += fmo;
fileNames.reserve(fakeMetaObjects.size());
for (auto it = fakeMetaObjects.constBegin(), end = fakeMetaObjects.constEnd(); it != end;
++it) {
it.value()->updateFingerprint();
m_exportedTypes += it.value();
fileNames += QLatin1String(it.key()->fileName());
}
foreach (const LanguageUtils::FakeMetaObject::Ptr &fmo, extraFakeMetaObjects) {
fmo->updateFingerprint();
m_exportedTypes += fmo;
}
return fileNames;
}
QList<LanguageUtils::FakeMetaObject::ConstPtr> FindExportedCppTypes::exportedTypes() const
+1 -1
View File
@@ -41,7 +41,7 @@ public:
FindExportedCppTypes(const CPlusPlus::Snapshot &snapshot);
// document must have a valid source and ast for the duration of the call
void operator()(const CPlusPlus::Document::Ptr &document);
QStringList operator()(const CPlusPlus::Document::Ptr &document);
QList<LanguageUtils::FakeMetaObject::ConstPtr> exportedTypes() const;
QHash<QString, QString> contextProperties() const;
+58 -24
View File
@@ -1259,6 +1259,37 @@ void ModelManagerInterface::asyncReset()
m_asyncResetTimer->start();
}
bool rescanExports(const QString &fileName, FindExportedCppTypes &finder,
ModelManagerInterface::CppDataHash &newData)
{
bool hasNewInfo = false;
QList<LanguageUtils::FakeMetaObject::ConstPtr> exported = finder.exportedTypes();
QHash<QString, QString> contextProperties = finder.contextProperties();
if (exported.isEmpty() && contextProperties.isEmpty()) {
hasNewInfo = hasNewInfo || newData.remove(fileName) > 0;
} else {
ModelManagerInterface::CppData &data = newData[fileName];
if (!hasNewInfo && (data.exportedTypes.size() != exported.size()
|| data.contextProperties != contextProperties))
hasNewInfo = true;
if (!hasNewInfo) {
QHash<QString, QByteArray> newFingerprints;
foreach (LanguageUtils::FakeMetaObject::ConstPtr newType, exported)
newFingerprints[newType->className()]=newType->fingerprint();
foreach (LanguageUtils::FakeMetaObject::ConstPtr oldType, data.exportedTypes) {
if (newFingerprints.value(oldType->className()) != oldType->fingerprint()) {
hasNewInfo = true;
break;
}
}
}
data.exportedTypes = exported;
data.contextProperties = contextProperties;
}
return hasNewInfo;
}
void ModelManagerInterface::updateCppQmlTypes(QFutureInterface<void> &interface,
ModelManagerInterface *qmlModelManager,
CPlusPlus::Snapshot snapshot,
@@ -1266,7 +1297,14 @@ void ModelManagerInterface::updateCppQmlTypes(QFutureInterface<void> &interface,
{
interface.setProgressRange(0, documents.size());
interface.setProgressValue(0);
CppDataHash newData = qmlModelManager->cppData();
CppDataHash newData;
QHash<QString, QStringList> newDeclarations;
{
QMutexLocker locker(&qmlModelManager->m_cppDataMutex);
newData = qmlModelManager->m_cppDataHash;
newDeclarations = qmlModelManager->m_cppDeclarationFiles;
}
FindExportedCppTypes finder(snapshot);
@@ -1281,41 +1319,37 @@ void ModelManagerInterface::updateCppQmlTypes(QFutureInterface<void> &interface,
const bool scan = pair.second;
const QString fileName = doc->fileName();
if (!scan) {
hasNewInfo = hasNewInfo || newData.remove(fileName) > 0;
hasNewInfo = newData.remove(fileName) > 0 || hasNewInfo;
foreach (const QString &file, newDeclarations[fileName]) {
finder(snapshot.document(file));
hasNewInfo = rescanExports(file, finder, newData) || hasNewInfo;
}
continue;
}
finder(doc);
QList<LanguageUtils::FakeMetaObject::ConstPtr> exported = finder.exportedTypes();
QHash<QString, QString> contextProperties = finder.contextProperties();
if (exported.isEmpty() && contextProperties.isEmpty()) {
hasNewInfo = hasNewInfo || newData.remove(fileName) > 0;
} else {
CppData &data = newData[fileName];
if (!hasNewInfo && (data.exportedTypes.size() != exported.size()
|| data.contextProperties != contextProperties))
hasNewInfo = true;
if (!hasNewInfo) {
QHash<QString, QByteArray> newFingerprints;
foreach (LanguageUtils::FakeMetaObject::ConstPtr newType, exported)
newFingerprints[newType->className()]=newType->fingerprint();
foreach (LanguageUtils::FakeMetaObject::ConstPtr oldType, data.exportedTypes) {
if (newFingerprints.value(oldType->className()) != oldType->fingerprint()) {
hasNewInfo = true;
break;
}
for (auto it = newDeclarations.begin(), end = newDeclarations.end(); it != end;) {
if (it->removeOne(fileName)) {
doc->releaseSourceAndAST();
if (it->isEmpty()) {
it = newDeclarations.erase(it);
continue;
}
}
data.exportedTypes = exported;
data.contextProperties = contextProperties;
++it;
}
foreach (const QString &declarationFile, finder(doc)) {
newDeclarations[declarationFile].append(fileName);
doc->keepSourceAndAST(); // keep for later reparsing when dependent doc changes
}
hasNewInfo = rescanExports(doc->fileName(), finder, newData) || hasNewInfo;
doc->releaseSourceAndAST();
}
QMutexLocker locker(&qmlModelManager->m_cppDataMutex);
qmlModelManager->m_cppDataHash = newData;
qmlModelManager->m_cppDeclarationFiles = newDeclarations;
if (hasNewInfo)
// one could get away with re-linking the cpp types...
QMetaObject::invokeMethod(qmlModelManager, "asyncReset");
@@ -275,6 +275,7 @@ private:
QrcCache m_qrcCache;
CppDataHash m_cppDataHash;
QHash<QString, QStringList> m_cppDeclarationFiles;
mutable QMutex m_cppDataMutex;
// project integration
+1 -1
View File
@@ -46,7 +46,7 @@ QString BuildableHelperLibrary::qtChooserToQmakePath(const QString &path)
SynchronousProcessResponse response = proc.runBlocking(path, QStringList(QLatin1String("-print-env")));
if (response.result != SynchronousProcessResponse::Finished)
return QString();
const QString output = response.stdOut;
const QString output = response.stdOut();
int pos = output.indexOf(toolDir);
if (pos == -1)
return QString();
+89 -135
View File
@@ -39,6 +39,7 @@
#include <QSharedPointer>
#include <QStringList>
#include <QTextCodec>
#include <QThread>
#include <QVariant>
/*!
@@ -277,8 +278,8 @@ void ShellCommand::run(QFutureInterface<void> &future)
Utils::SynchronousProcessResponse resp
= runCommand(job.binary, job.arguments, job.timeoutS, job.workingDirectory,
job.exitCodeInterpreter);
stdOut += resp.stdOut;
stdErr += resp.stdErr;
stdOut += resp.stdOut();
stdErr += resp.stdErr();
d->m_lastExecExitCode = resp.exitCode;
d->m_lastExecSuccess = resp.result == Utils::SynchronousProcessResponse::Finished;
if (!d->m_lastExecSuccess)
@@ -326,59 +327,10 @@ Utils::SynchronousProcessResponse ShellCommand::runCommand(const Utils::FileName
if (!(d->m_flags & SuppressCommandLogging))
proxy->appendCommand(dir, binary, arguments);
if (d->m_flags & FullySynchronously) {
response = runSynchronous(binary, arguments, timeoutS, dir, interpreter);
} else {
Utils::SynchronousProcess process;
process.setExitCodeInterpreter(interpreter);
connect(this, &ShellCommand::terminate, &process, &Utils::SynchronousProcess::terminate);
process.setWorkingDirectory(dir);
process.setProcessEnvironment(processEnvironment());
process.setTimeoutS(timeoutS);
if (d->m_codec)
process.setCodec(d->m_codec);
process.setFlags(processFlags());
// connect stderr to the output window if desired
if (d->m_flags & MergeOutputChannels) {
process.setProcessChannelMode(QProcess::MergedChannels);
} else if (d->m_progressiveOutput
|| !(d->m_flags & SuppressStdErr)) {
process.setStdErrBufferedSignalsEnabled(true);
connect(&process, &Utils::SynchronousProcess::stdErrBuffered,
this, [this, proxy](const QString &text)
{
if (!(d->m_flags & SuppressStdErr))
proxy->appendError(text);
if (d->m_progressiveOutput)
emit stdErrText(text);
});
}
// connect stdout to the output window if desired
if (d->m_progressParser || d->m_progressiveOutput || (d->m_flags & ShowStdOut)) {
process.setStdOutBufferedSignalsEnabled(true);
connect(&process, &Utils::SynchronousProcess::stdOutBuffered,
this, [this, proxy](const QString &text)
{
if (d->m_progressParser)
d->m_progressParser->parseProgress(text);
if (d->m_flags & ShowStdOut)
proxy->append(text);
if (d->m_progressiveOutput) {
emit stdOutText(text);
d->m_hadOutput = true;
}
});
}
process.setTimeOutMessageBoxEnabled(true);
// Run!
response = process.runBlocking(binary.toString(), arguments);
}
if (d->m_flags & FullySynchronously || QThread::currentThread() == QCoreApplication::instance()->thread())
response = runFullySynchronous(binary, arguments, proxy, timeoutS, dir, interpreter);
else
response = runSynchronous(binary, arguments, proxy, timeoutS, dir, interpreter);
if (!d->m_aborted) {
// Success/Fail message in appropriate window?
@@ -393,104 +345,106 @@ Utils::SynchronousProcessResponse ShellCommand::runCommand(const Utils::FileName
return response;
}
Utils::SynchronousProcessResponse ShellCommand::runSynchronous(const Utils::FileName &binary,
const QStringList &arguments,
int timeoutS,
const QString &workingDirectory,
const ExitCodeInterpreter &interpreter)
Utils::SynchronousProcessResponse ShellCommand::runFullySynchronous(const Utils::FileName &binary,
const QStringList &arguments,
QSharedPointer<OutputProxy> proxy,
int timeoutS,
const QString &workingDirectory,
const ExitCodeInterpreter &interpreter)
{
Utils::SynchronousProcessResponse response;
QScopedPointer<OutputProxy> proxy(d->m_proxyFactory());
// Set up process
QSharedPointer<QProcess> process = Utils::SynchronousProcess::createProcess(processFlags());
if (!d->m_defaultWorkingDirectory.isEmpty())
process->setWorkingDirectory(workDirectory(workingDirectory));
process->setProcessEnvironment(processEnvironment());
Utils::SynchronousProcess process;
process.setFlags(processFlags());
const QString dir = workDirectory(workingDirectory);
if (!dir.isEmpty())
process.setWorkingDirectory(dir);
process.setProcessEnvironment(processEnvironment());
if (d->m_flags & MergeOutputChannels)
process->setProcessChannelMode(QProcess::MergedChannels);
process.setProcessChannelMode(QProcess::MergedChannels);
if (d->m_codec)
process.setCodec(d->m_codec);
process.setTimeoutS(timeoutS);
process.setExitCodeInterpreter(interpreter);
// Start
process->start(binary.toString(), arguments, QIODevice::ReadOnly);
process->closeWriteChannel();
if (!process->waitForStarted()) {
response.result = Utils::SynchronousProcessResponse::StartFailed;
return response;
}
// process output
QByteArray stdOut;
QByteArray stdErr;
const bool timedOut =
!Utils::SynchronousProcess::readDataFromProcess(*process.data(), timeoutS,
&stdOut, &stdErr, true);
SynchronousProcessResponse resp = process.runBlocking(binary.toString(), arguments);
if (!d->m_aborted) {
if (!stdErr.isEmpty()) {
response.stdErr = Utils::SynchronousProcess::normalizeNewlines(
d->m_codec ? d->m_codec->toUnicode(stdErr) : QString::fromLocal8Bit(stdErr));
if (!(d->m_flags & SuppressStdErr))
proxy->append(response.stdErr);
}
const QString stdErr = resp.stdErr();
if (!stdErr.isEmpty() && !(d->m_flags & SuppressStdErr))
proxy->append(stdErr);
if (!stdOut.isEmpty()) {
response.stdOut = Utils::SynchronousProcess::normalizeNewlines(
d->m_codec ? d->m_codec->toUnicode(stdOut) : QString::fromLocal8Bit(stdOut));
if (d->m_flags & ShowStdOut) {
if (d->m_flags & SilentOutput)
proxy->appendSilently(response.stdOut);
else
proxy->append(response.stdOut);
}
const QString stdOut = resp.stdOut();
if (!stdOut.isEmpty() && d->m_flags & ShowStdOut) {
if (d->m_flags & SilentOutput)
proxy->appendSilently(stdOut);
else
proxy->append(stdOut);
}
}
// Result
if (timedOut)
response.result = Utils::SynchronousProcessResponse::Hang;
else if (process->exitStatus() != QProcess::NormalExit)
response.result = Utils::SynchronousProcessResponse::TerminatedAbnormally;
else
response.result = interpreter(process->exitCode());
return response;
return resp;
}
bool ShellCommand::runFullySynchronous(const Utils::FileName &binary, const QStringList &arguments,
int timeoutS, QByteArray *outputData, QByteArray *errorData,
const QString &workingDirectory)
SynchronousProcessResponse ShellCommand::runSynchronous(const FileName &binary,
const QStringList &arguments,
QSharedPointer<OutputProxy> proxy,
int timeoutS,
const QString &workingDirectory,
const ExitCodeInterpreter &interpreter)
{
QTC_ASSERT(!binary.isEmpty(), return false);
QScopedPointer<OutputProxy> proxy(d->m_proxyFactory());
Utils::SynchronousProcess process;
process.setExitCodeInterpreter(interpreter);
connect(this, &ShellCommand::terminate, &process, &Utils::SynchronousProcess::terminate);
process.setProcessEnvironment(processEnvironment());
process.setTimeoutS(timeoutS);
if (d->m_codec)
process.setCodec(d->m_codec);
process.setFlags(processFlags());
const QString dir = workDirectory(workingDirectory);
if (!(d->m_flags & SuppressCommandLogging))
proxy->appendCommand(dir, binary, arguments);
QProcess process;
process.setWorkingDirectory(dir);
process.setProcessEnvironment(d->m_environment);
process.start(binary.toString(), arguments);
process.closeWriteChannel();
if (!process.waitForStarted()) {
if (errorData) {
const QString msg = QString::fromLatin1("Unable to execute \"%1\": %2:")
.arg(binary.toUserOutput(), process.errorString());
*errorData = msg.toLocal8Bit();
}
return false;
if (!dir.isEmpty())
process.setWorkingDirectory(dir);
process.setProcessEnvironment(processEnvironment());
// connect stderr to the output window if desired
if (d->m_flags & MergeOutputChannels) {
process.setProcessChannelMode(QProcess::MergedChannels);
} else if (d->m_progressiveOutput
|| !(d->m_flags & SuppressStdErr)) {
process.setStdErrBufferedSignalsEnabled(true);
connect(&process, &Utils::SynchronousProcess::stdErrBuffered,
this, [this, proxy](const QString &text)
{
if (!(d->m_flags & SuppressStdErr))
proxy->appendError(text);
if (d->m_progressiveOutput)
emit stdErrText(text);
});
}
if (!Utils::SynchronousProcess::readDataFromProcess(process, timeoutS, outputData, errorData, true)) {
if (errorData)
errorData->append(tr("Error: Executable timed out after %1 s.").arg(timeoutS).toLocal8Bit());
Utils::SynchronousProcess::stopProcess(process);
return false;
// connect stdout to the output window if desired
if (d->m_progressParser || d->m_progressiveOutput || (d->m_flags & ShowStdOut)) {
process.setStdOutBufferedSignalsEnabled(true);
connect(&process, &Utils::SynchronousProcess::stdOutBuffered,
this, [this, proxy](const QString &text)
{
if (d->m_progressParser)
d->m_progressParser->parseProgress(text);
if (d->m_flags & ShowStdOut)
proxy->append(text);
if (d->m_progressiveOutput) {
emit stdOutText(text);
d->m_hadOutput = true;
}
});
}
return process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0;
process.setTimeOutMessageBoxEnabled(true);
if (d->m_codec)
process.setCodec(d->m_codec);
process.setTimeoutS(timeoutS);
process.setExitCodeInterpreter(interpreter);
return process.run(binary.toString(), arguments);
}
const QVariant &ShellCommand::cookie() const
+12 -6
View File
@@ -115,7 +115,7 @@ public:
const QString &workingDirectory = QString(), const ExitCodeInterpreter &interpreter = defaultExitCodeInterpreter);
void addJob(const FileName &binary, const QStringList &arguments, int timeoutS,
const QString &workingDirectory = QString(), const ExitCodeInterpreter &interpreter = defaultExitCodeInterpreter);
void execute();
void execute(); // Execute tasks asynchronously!
void abort();
bool lastExecutionSuccess() const;
int lastExecutionExitCode() const;
@@ -140,16 +140,14 @@ public:
void setOutputProxyFactory(const std::function<OutputProxy *()> &factory);
// This is called once per job in a thread.
// When called from the UI thread it will execute fully synchronously, so no signals will
// be triggered!
virtual SynchronousProcessResponse runCommand(const FileName &binary, const QStringList &arguments,
int timeoutS,
const QString &workingDirectory = QString(),
const ExitCodeInterpreter &interpreter = defaultExitCodeInterpreter);
// Make sure to not pass through the event loop at all:
virtual bool runFullySynchronous(const FileName &binary, const QStringList &arguments,
int timeoutS, QByteArray *outputData, QByteArray *errorData,
const QString &workingDirectory = QString());
public slots:
void cancel();
signals:
@@ -167,7 +165,15 @@ protected:
private:
void run(QFutureInterface<void> &future);
// Run without a event loop in fully blocking mode. No signals will be delivered.
SynchronousProcessResponse runFullySynchronous(const FileName &binary, const QStringList &arguments,
QSharedPointer<OutputProxy> proxy,
int timeoutS, const QString &workingDirectory,
const ExitCodeInterpreter &interpreter = defaultExitCodeInterpreter);
// Run with an event loop. Signals will be delivered.
SynchronousProcessResponse runSynchronous(const FileName &binary, const QStringList &arguments,
QSharedPointer<OutputProxy> proxy,
int timeoutS, const QString &workingDirectory,
const ExitCodeInterpreter &interpreter = defaultExitCodeInterpreter);
+11 -4
View File
@@ -93,10 +93,9 @@ QColor StyleHelper::notTooBrightHighlightColor()
QPalette StyleHelper::sidebarFontPalette(const QPalette &original)
{
QPalette palette = original;
palette.setColor(QPalette::Active, QPalette::Text, panelTextColor());
palette.setColor(QPalette::Active, QPalette::WindowText, panelTextColor());
palette.setColor(QPalette::Inactive, QPalette::Text, panelTextColor().darker());
palette.setColor(QPalette::Inactive, QPalette::WindowText, panelTextColor().darker());
const QColor textColor = creatorTheme()->color(Theme::ProgressBarTitleColor);
palette.setColor(QPalette::WindowText, textColor);
palette.setColor(QPalette::Text, textColor);
return palette;
}
@@ -153,6 +152,14 @@ QColor StyleHelper::borderColor(bool lightColored)
return result;
}
QColor StyleHelper::toolBarBorderColor()
{
const QColor base = baseColor();
return QColor::fromHsv(base.hue(),
base.saturation() ,
clamp(base.value() * 0.80f));
}
// We try to ensure that the actual color used are within
// reasonalbe bounds while generating the actual baseColor
// from the users request.
+1
View File
@@ -59,6 +59,7 @@ public:
static QColor highlightColor(bool lightColored = false);
static QColor shadowColor(bool lightColored = false);
static QColor borderColor(bool lightColored = false);
static QColor toolBarBorderColor();
static QColor buttonTextColor() { return QColor(0x4c4c4c); }
static QColor mergedColors(const QColor &colorA, const QColor &colorB, int factor = 50);
static QColor alphaBlendedColors(const QColor &colorA, const QColor &colorB);
+86 -81
View File
@@ -37,6 +37,7 @@
#include <QApplication>
#include <limits.h>
#include <memory>
#ifdef Q_OS_UNIX
# include <unistd.h>
@@ -105,18 +106,12 @@ void TerminalControllingProcess::setupChildProcess()
}
// ----------- SynchronousProcessResponse
SynchronousProcessResponse::SynchronousProcessResponse() :
result(StartFailed),
exitCode(-1)
{
}
void SynchronousProcessResponse::clear()
{
result = StartFailed;
exitCode = -1;
stdOut.clear();
stdErr.clear();
rawStdOut.clear();
rawStdErr.clear();
}
QString SynchronousProcessResponse::exitMessage(const QString &binary, int timeoutS) const
@@ -137,22 +132,48 @@ QString SynchronousProcessResponse::exitMessage(const QString &binary, int timeo
return QString();
}
QByteArray SynchronousProcessResponse::allRawOutput() const
{
if (!rawStdOut.isEmpty() && !rawStdErr.isEmpty()) {
QByteArray result = rawStdOut;
if (!result.endsWith('\n'))
result += '\n';
result += rawStdErr;
return result;
}
return !rawStdOut.isEmpty() ? rawStdOut : rawStdErr;
}
QString SynchronousProcessResponse::allOutput() const
{
if (!stdOut.isEmpty() && !stdErr.isEmpty()) {
if (stdOut.endsWith(QLatin1Char('\n')))
return stdOut + stdErr;
else
return stdOut + QLatin1Char('\n') + stdErr;
const QString out = stdOut();
const QString err = stdErr();
if (!out.isEmpty() && !err.isEmpty()) {
QString result = out;
if (!result.endsWith('\n'))
result += '\n';
result += err;
return result;
}
return !stdOut.isEmpty() ? stdOut : stdErr;
return !out.isEmpty() ? out : err;
}
QString SynchronousProcessResponse::stdOut() const
{
return SynchronousProcess::normalizeNewlines(codec->toUnicode(rawStdOut));
}
QString SynchronousProcessResponse::stdErr() const
{
return SynchronousProcess::normalizeNewlines(codec->toUnicode(rawStdErr));
}
QTCREATOR_UTILS_EXPORT QDebug operator<<(QDebug str, const SynchronousProcessResponse& r)
{
QDebug nsp = str.nospace();
nsp << "SynchronousProcessResponse: result=" << r.result << " ex=" << r.exitCode << '\n'
<< r.stdOut.size() << " bytes stdout, stderr=" << r.stdErr << '\n';
<< r.rawStdOut.size() << " bytes stdout, stderr=" << r.rawStdErr << '\n';
return str;
}
@@ -169,52 +190,62 @@ class ChannelBuffer : public QObject
public:
void clearForRun();
QString linesRead();
void append(const QString &text, bool emitSignals);
QString data;
int bufferPos = 0;
bool firstData = true;
QString linesRead();
void append(const QByteArray &text, bool emitSignals);
QByteArray rawData;
QString incompleteLineBuffer; // lines not yet signaled
QTextCodec *codec = nullptr; // Not owner
std::unique_ptr<QTextCodec::ConverterState> codecState;
int rawDataPos = 0;
bool bufferedSignalsEnabled = false;
bool firstBuffer = true;
signals:
void output(const QString &text, bool firstTime);
void outputBuffered(const QString &text, bool firstTime);
};
void ChannelBuffer::clearForRun()
{
firstData = true;
firstBuffer = true;
bufferPos = 0;
rawDataPos = 0;
rawData.clear();
codecState.reset(new QTextCodec::ConverterState);
incompleteLineBuffer.clear();
}
/* Check for complete lines read from the device and return them, moving the
* buffer position. */
QString ChannelBuffer::linesRead()
{
// Any new lines?
const int lastLineIndex = qMax(data.lastIndexOf(QLatin1Char('\n')),
data.lastIndexOf(QLatin1Char('\r')));
if (lastLineIndex == -1 || lastLineIndex <= bufferPos)
// Convert and append the new input to the buffer of incomplete lines
const char *start = rawData.constData() + rawDataPos;
const int len = rawData.size() - rawDataPos;
incompleteLineBuffer.append(codec->toUnicode(start, len, codecState.get()));
rawDataPos = rawData.size();
// Any completed lines in the incompleteLineBuffer?
const int lastLineIndex = qMax(incompleteLineBuffer.lastIndexOf('\n'),
incompleteLineBuffer.lastIndexOf('\r'));
if (lastLineIndex == -1)
return QString();
const int nextBufferPos = lastLineIndex + 1;
const QString lines = data.mid(bufferPos, nextBufferPos - bufferPos);
bufferPos = nextBufferPos;
// Get completed lines and remove them from the incompleteLinesBuffer:
const QString lines = SynchronousProcess::normalizeNewlines(incompleteLineBuffer.left(lastLineIndex + 1));
incompleteLineBuffer = incompleteLineBuffer.mid(lastLineIndex + 1);
return lines;
}
void ChannelBuffer::append(const QString &text, bool emitSignals)
void ChannelBuffer::append(const QByteArray &text, bool emitSignals)
{
if (text.isEmpty())
return;
data += text;
rawData += text;
if (!emitSignals)
return;
// Emit binary signals
emit output(text, firstData);
firstData = false;
// Buffered. Emit complete lines?
if (bufferedSignalsEnabled) {
const QString lines = linesRead();
@@ -226,13 +257,11 @@ void ChannelBuffer::append(const QString &text, bool emitSignals)
}
// ----------- SynchronousProcessPrivate
struct SynchronousProcessPrivate {
SynchronousProcessPrivate();
class SynchronousProcessPrivate {
public:
void clearForRun();
QTextCodec *m_codec;
QTextCodec::ConverterState m_stdOutState;
QTextCodec::ConverterState m_stdErrState;
QTextCodec *m_codec = QTextCodec::codecForLocale();
TerminalControllingProcess m_process;
QTimer m_timer;
QEventLoop m_eventLoop;
@@ -249,17 +278,15 @@ struct SynchronousProcessPrivate {
bool m_waitingForUser = false;
};
SynchronousProcessPrivate::SynchronousProcessPrivate() :
m_codec(QTextCodec::codecForLocale())
{
}
void SynchronousProcessPrivate::clearForRun()
{
m_hangTimerCount = 0;
m_stdOut.clearForRun();
m_stdOut.codec = m_codec;
m_stdErr.clearForRun();
m_stdErr.codec = m_codec;
m_result.clear();
m_result.codec = m_codec;
m_startFailure = false;
m_binary.clear();
}
@@ -276,12 +303,16 @@ SynchronousProcess::SynchronousProcess() :
connect(&d->m_process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error),
this, &SynchronousProcess::error);
connect(&d->m_process, &QProcess::readyReadStandardOutput,
this, &SynchronousProcess::stdOutReady);
this, [this]() {
d->m_hangTimerCount = 0;
processStdOut(true);
});
connect(&d->m_process, &QProcess::readyReadStandardError,
this, &SynchronousProcess::stdErrReady);
connect(&d->m_stdOut, &ChannelBuffer::output, this, &SynchronousProcess::stdOut);
this, [this]() {
d->m_hangTimerCount = 0;
processStdErr(true);
});
connect(&d->m_stdOut, &ChannelBuffer::outputBuffered, this, &SynchronousProcess::stdOutBuffered);
connect(&d->m_stdErr, &ChannelBuffer::output, this, &SynchronousProcess::stdErr);
connect(&d->m_stdErr, &ChannelBuffer::outputBuffered, this, &SynchronousProcess::stdErrBuffered);
}
@@ -436,8 +467,8 @@ SynchronousProcessResponse SynchronousProcess::run(const QString &binary,
processStdErr(false);
}
d->m_result.stdOut = d->m_stdOut.data;
d->m_result.stdErr = d->m_stdErr.data;
d->m_result.rawStdOut = d->m_stdOut.rawData;
d->m_result.rawStdErr = d->m_stdErr.rawData;
d->m_timer.stop();
if (isGuiThread())
@@ -485,8 +516,8 @@ SynchronousProcessResponse SynchronousProcess::runBlocking(const QString &binary
processStdOut(false);
processStdErr(false);
d->m_result.stdOut = d->m_stdOut.data;
d->m_result.stdErr = d->m_stdErr.data;
d->m_result.rawStdOut = d->m_stdOut.rawData;
d->m_result.rawStdErr = d->m_stdErr.rawData;
return d->m_result;
}
@@ -569,42 +600,16 @@ void SynchronousProcess::error(QProcess::ProcessError e)
d->m_eventLoop.quit();
}
void SynchronousProcess::stdOutReady()
{
d->m_hangTimerCount = 0;
processStdOut(true);
}
void SynchronousProcess::stdErrReady()
{
d->m_hangTimerCount = 0;
processStdErr(true);
}
QString SynchronousProcess::convertOutput(const QByteArray &ba,
QTextCodec::ConverterState *state) const
{
return normalizeNewlines(d->m_codec->toUnicode(ba, ba.size(), state));
}
void SynchronousProcess::processStdOut(bool emitSignals)
{
// Handle binary data
const QString stdOutput = convertOutput(d->m_process.readAllStandardOutput(),
&d->m_stdOutState);
if (debug > 1)
qDebug() << Q_FUNC_INFO << emitSignals << stdOutput;
d->m_stdOut.append(stdOutput, emitSignals);
d->m_stdOut.append(d->m_process.readAllStandardOutput(), emitSignals);
}
void SynchronousProcess::processStdErr(bool emitSignals)
{
// Handle binary data
const QString stdError = convertOutput(d->m_process.readAllStandardError(),
&d->m_stdErrState);
if (debug > 1)
qDebug() << Q_FUNC_INFO << emitSignals << stdError;
d->m_stdErr.append(stdError, emitSignals);
d->m_stdErr.append(d->m_process.readAllStandardError(), emitSignals);
}
QSharedPointer<QProcess> SynchronousProcess::createProcess(unsigned flags)
+17 -16
View File
@@ -37,11 +37,12 @@ QT_FORWARD_DECLARE_CLASS(QDebug)
namespace Utils {
struct SynchronousProcessPrivate;
class SynchronousProcessPrivate;
/* Result of SynchronousProcess execution */
struct QTCREATOR_UTILS_EXPORT SynchronousProcessResponse
class QTCREATOR_UTILS_EXPORT SynchronousProcessResponse
{
public:
enum Result {
// Finished with return code 0
Finished,
@@ -54,17 +55,23 @@ struct QTCREATOR_UTILS_EXPORT SynchronousProcessResponse
// Hang, no output after time out
Hang };
SynchronousProcessResponse();
void clear();
// Helper to format an exit message.
QString exitMessage(const QString &binary, int timeoutS) const;
QByteArray allRawOutput() const;
QString allOutput() const;
Result result;
int exitCode;
QString stdOut;
QString stdErr;
QString stdOut() const;
QString stdErr() const;
Result result = StartFailed;
int exitCode = -1;
QByteArray rawStdOut;
QByteArray rawStdErr;
QTextCodec *codec = QTextCodec::codecForLocale();
};
QTCREATOR_UTILS_EXPORT QDebug operator<<(QDebug str, const SynchronousProcessResponse &);
@@ -132,7 +139,7 @@ public:
// occurs on stderr/stdout as opposed to waitForFinished()). Returns false if a timeout
// occurs. Checking of the process' exit state/code still has to be done.
static bool readDataFromProcess(QProcess &p, int timeoutS,
QByteArray *stdOut = 0, QByteArray *stdErr = 0,
QByteArray *rawStdOut = 0, QByteArray *rawStdErr = 0,
bool timeOutMessageBox = false);
// Stop a process by first calling terminate() (allowing for signal handling) and
// then kill().
@@ -146,11 +153,8 @@ public:
static QString normalizeNewlines(const QString &text);
signals:
void stdOut(const QString &text, bool firstTime);
void stdErr(const QString &text, bool firstTime);
void stdOutBuffered(const QString &data, bool firstTime);
void stdErrBuffered(const QString &data, bool firstTime);
void stdOutBuffered(const QString &lines, bool firstTime);
void stdErrBuffered(const QString &lines, bool firstTime);
public slots:
bool terminate();
@@ -159,11 +163,8 @@ private:
void slotTimeout();
void finished(int exitCode, QProcess::ExitStatus e);
void error(QProcess::ProcessError);
void stdOutReady();
void stdErrReady();
void processStdOut(bool emitSignals);
void processStdErr(bool emitSignals);
QString convertOutput(const QByteArray &, QTextCodec::ConverterState *state) const;
SynchronousProcessPrivate *d;
};
+60 -22
View File
@@ -192,8 +192,9 @@ void Theme::readSettings(QSettings &settings)
for (int i = 0, total = e.keyCount(); i < total; ++i) {
const QString key = QLatin1String(e.key(i));
if (!settings.contains(key)) {
qWarning("Theme \"%s\" misses color setting for key \"%s\".",
qPrintable(d->fileName), qPrintable(key));
if (i < PaletteWindow || i > PaletteShadowDisabled)
qWarning("Theme \"%s\" misses color setting for key \"%s\".",
qPrintable(d->fileName), qPrintable(key));
continue;
}
d->colors[i] = readNamedColor(settings.value(key).toString());
@@ -253,27 +254,64 @@ QPalette Theme::palette() const
if (!flag(DerivePaletteFromTheme))
return pal;
// FIXME: introduce some more color roles for this
const static struct {
Color themeColor;
QPalette::ColorRole paletteColorRole;
QPalette::ColorGroup paletteColorGroup;
bool setColorRoleAsBrush;
} mapping[] = {
{ PaletteWindow, QPalette::Window, QPalette::All, false},
{ PaletteWindowDisabled, QPalette::Window, QPalette::Disabled, false},
{ PaletteWindowText, QPalette::WindowText, QPalette::All, true},
{ PaletteWindowTextDisabled, QPalette::WindowText, QPalette::Disabled, true},
{ PaletteBase, QPalette::Base, QPalette::All, false},
{ PaletteBaseDisabled, QPalette::Base, QPalette::Disabled, false},
{ PaletteAlternateBase, QPalette::AlternateBase, QPalette::All, false},
{ PaletteAlternateBaseDisabled, QPalette::AlternateBase, QPalette::Disabled, false},
{ PaletteToolTipBase, QPalette::ToolTipBase, QPalette::All, true},
{ PaletteToolTipBaseDisabled, QPalette::ToolTipBase, QPalette::Disabled, true},
{ PaletteToolTipText, QPalette::ToolTipText, QPalette::All, false},
{ PaletteToolTipTextDisabled, QPalette::ToolTipText, QPalette::Disabled, false},
{ PaletteText, QPalette::Text, QPalette::All, true},
{ PaletteTextDisabled, QPalette::Text, QPalette::Disabled, true},
{ PaletteButton, QPalette::Button, QPalette::All, false},
{ PaletteButtonDisabled, QPalette::Button, QPalette::Disabled, false},
{ PaletteButtonText, QPalette::ButtonText, QPalette::All, true},
{ PaletteButtonTextDisabled, QPalette::ButtonText, QPalette::Disabled, true},
{ PaletteBrightText, QPalette::BrightText, QPalette::All, false},
{ PaletteBrightTextDisabled, QPalette::BrightText, QPalette::Disabled, false},
{ PaletteHighlight, QPalette::Highlight, QPalette::All, true},
{ PaletteHighlightDisabled, QPalette::Highlight, QPalette::Disabled, true},
{ PaletteHighlightedText, QPalette::HighlightedText, QPalette::All, true},
{ PaletteHighlightedTextDisabled, QPalette::HighlightedText, QPalette::Disabled, true},
{ PaletteLink, QPalette::Link, QPalette::All, false},
{ PaletteLinkDisabled, QPalette::Link, QPalette::Disabled, false},
{ PaletteLinkVisited, QPalette::LinkVisited, QPalette::All, false},
{ PaletteLinkVisitedDisabled, QPalette::LinkVisited, QPalette::Disabled, false},
{ PaletteLight, QPalette::Light, QPalette::All, false},
{ PaletteLightDisabled, QPalette::Light, QPalette::Disabled, false},
{ PaletteMidlight, QPalette::Midlight, QPalette::All, false},
{ PaletteMidlightDisabled, QPalette::Midlight, QPalette::Disabled, false},
{ PaletteDark, QPalette::Dark, QPalette::All, false},
{ PaletteDarkDisabled, QPalette::Dark, QPalette::Disabled, false},
{ PaletteMid, QPalette::Mid, QPalette::All, false},
{ PaletteMidDisabled, QPalette::Mid, QPalette::Disabled, false},
{ PaletteShadow, QPalette::Shadow, QPalette::All, false},
{ PaletteShadowDisabled, QPalette::Shadow, QPalette::Disabled, false}
};
for (auto entry: mapping) {
const QColor themeColor = color(entry.themeColor);
// Use original color if color is not defined in theme.
if (themeColor.isValid()) {
if (entry.setColorRoleAsBrush)
// TODO: Find out why sometimes setBrush is used
pal.setBrush(entry.paletteColorGroup, entry.paletteColorRole, themeColor);
else
pal.setColor(entry.paletteColorGroup, entry.paletteColorRole, themeColor);
}
}
pal.setColor(QPalette::Window, color(Theme::BackgroundColorNormal));
pal.setBrush(QPalette::WindowText, color(Theme::TextColorNormal));
pal.setColor(QPalette::Base, color(Theme::BackgroundColorNormal));
pal.setColor(QPalette::AlternateBase, color(Theme::BackgroundColorAlternate));
pal.setColor(QPalette::Button, color(Theme::BackgroundColorDark));
pal.setColor(QPalette::BrightText, Qt::red);
pal.setBrush(QPalette::Text, color(Theme::TextColorNormal));
pal.setBrush(QPalette::ButtonText, color(Theme::TextColorNormal));
pal.setBrush(QPalette::ToolTipBase, color(Theme::BackgroundColorSelected));
pal.setColor(QPalette::Highlight, color(Theme::BackgroundColorSelected));
pal.setColor(QPalette::Dark, color(Theme::BackgroundColorDark));
pal.setColor(QPalette::HighlightedText, Qt::white);
pal.setColor(QPalette::ToolTipText, color(Theme::TextColorNormal));
pal.setColor(QPalette::Link, color(Theme::TextColorLink));
pal.setColor(QPalette::LinkVisited, color(Theme::TextColorLinkVisited));
pal.setColor(QPalette::Disabled, QPalette::Window, color(Theme::BackgroundColorDisabled));
pal.setBrush(QPalette::Disabled, QPalette::WindowText, color(Theme::TextColorDisabled));
pal.setColor(QPalette::Disabled, QPalette::Base, color(Theme::BackgroundColorDisabled));
pal.setBrush(QPalette::Disabled, QPalette::Text, color(Theme::TextColorDisabled));
return pal;
}
+47
View File
@@ -125,6 +125,52 @@ public:
TreeViewArrowColorNormal,
TreeViewArrowColorSelected,
/* Palette for QPalette */
PaletteWindow,
PaletteWindowText,
PaletteBase,
PaletteAlternateBase,
PaletteToolTipBase,
PaletteToolTipText,
PaletteText,
PaletteButton,
PaletteButtonText,
PaletteBrightText,
PaletteHighlight,
PaletteHighlightedText,
PaletteLink,
PaletteLinkVisited,
PaletteLight,
PaletteMidlight,
PaletteDark,
PaletteMid,
PaletteShadow,
PaletteWindowDisabled,
PaletteBackgroundDisabled,
PaletteWindowTextDisabled,
PaletteForegroundDisabled,
PaletteBaseDisabled,
PaletteAlternateBaseDisabled,
PaletteToolTipBaseDisabled,
PaletteToolTipTextDisabled,
PaletteTextDisabled,
PaletteButtonDisabled,
PaletteButtonTextDisabled,
PaletteBrightTextDisabled,
PaletteHighlightDisabled,
PaletteHighlightedTextDisabled,
PaletteLinkDisabled,
PaletteLinkVisitedDisabled,
PaletteLightDisabled,
PaletteMidlightDisabled,
PaletteDarkDisabled,
PaletteMidDisabled,
PaletteShadowDisabled,
/* Icons */
IconsBaseColor,
@@ -269,6 +315,7 @@ public:
DrawSearchResultWidgetFrame,
DrawIndicatorBranch,
DrawToolBarHighlights,
DrawToolBarBorders,
ComboBoxDrawTextShadow,
DerivePaletteFromTheme,
ApplyThemePaletteGlobally,
+1 -1
View File
@@ -308,7 +308,7 @@ QAbstractItemModel *AndroidBuildApkStep::keystoreCertificates()
QMessageBox::critical(0, tr("Error"), tr("Invalid password."));
m_keystorePasswd.clear();
}
rawCerts = response.stdOut;
rawCerts = response.stdOut();
}
return new CertificatesModel(rawCerts, this);
}
+10 -10
View File
@@ -110,8 +110,8 @@ bool BazaarClient::synchronousSetUserId()
args << QLatin1String("whoami")
<< (settings().stringValue(BazaarSettings::userNameKey) + QLatin1String(" <")
+ settings().stringValue(BazaarSettings::userEmailKey) + QLatin1Char('>'));
QByteArray stdOut;
return vcsFullySynchronousExec(QDir::currentPath(), args, &stdOut);
return vcsFullySynchronousExec(QDir::currentPath(), args).result
== SynchronousProcessResponse::Finished;
}
BranchInfo BazaarClient::synchronousBranchQuery(const QString &repositoryRoot) const
@@ -150,11 +150,10 @@ bool BazaarClient::synchronousUncommit(const QString &workingDir,
<< QLatin1String("--verbose") // Will print out what is being removed
<< revisionSpec(revision)
<< extraOptions;
QByteArray stdOut;
const bool success = vcsFullySynchronousExec(workingDir, args, &stdOut);
if (!stdOut.isEmpty())
VcsOutputWindow::append(QString::fromUtf8(stdOut));
return success;
const SynchronousProcessResponse result = vcsFullySynchronousExec(workingDir, args);
VcsOutputWindow::append(result.stdOut());
return result.result == SynchronousProcessResponse::Finished;
}
void BazaarClient::commit(const QString &repositoryRoot, const QStringList &files,
@@ -187,10 +186,11 @@ bool BazaarClient::managesFile(const QString &workingDirectory, const QString &f
{
QStringList args(QLatin1String("status"));
args << fileName;
QByteArray stdOut;
if (!vcsFullySynchronousExec(workingDirectory, args, &stdOut))
const SynchronousProcessResponse result = vcsFullySynchronousExec(workingDirectory, args);
if (result.result != SynchronousProcessResponse::Finished)
return false;
return !stdOut.startsWith("unknown");
return result.rawStdOut.startsWith("unknown");
}
void BazaarClient::view(const QString &source, const QString &id, const QStringList &extraOptions)
@@ -85,10 +85,10 @@ static int updateVersionHelper(const QString &command)
return 0;
// Astyle prints the version on stdout or stderr, depending on platform
const int version = parseVersion(response.stdOut.trimmed());
const int version = parseVersion(response.stdOut().trimmed());
if (version != 0)
return version;
return parseVersion(response.stdErr.trimmed());
return parseVersion(response.stdErr().trimmed());
}
void ArtisticStyleSettings::updateVersion()
@@ -176,7 +176,7 @@ void ArtisticStyleSettings::createDocumentationFile() const
stream.writeStartElement(Constants::DOCUMENTATION_XMLROOT);
// astyle writes its output to 'error'...
const QStringList lines = response.stdErr.split(QLatin1Char('\n'));
const QStringList lines = response.stdErr().split(QLatin1Char('\n'));
QStringList keys;
QStringList docu;
for (QString line : lines) {
+1 -1
View File
@@ -104,7 +104,7 @@ FormatTask format(FormatTask task)
task.error = BeautifierPlugin::tr("Failed to format: %1.").arg(response.exitMessage(executable, 5));
return task;
}
const QString output = response.stdErr;
const QString output = response.stdErr();
if (!output.isEmpty())
task.error = executable + QLatin1String(": ") + output;
+1 -1
View File
@@ -20,7 +20,7 @@
<bool>true</bool>
</property>
<property name="title">
<string>Automatic formatting on file save</string>
<string>Automatic Formatting on File Save</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="2">
+2 -2
View File
@@ -78,7 +78,7 @@ void Bookmark::updateFileName(const QString &fileName)
void Bookmark::setNote(const QString &note)
{
m_note = note;
setToolTip(note);
}
void Bookmark::updateNote(const QString &note)
@@ -94,5 +94,5 @@ QString Bookmark::lineText() const
QString Bookmark::note() const
{
return m_note;
return toolTip();
}
+6 -6
View File
@@ -37,13 +37,14 @@ class Bookmark : public TextEditor::TextMark
public:
Bookmark(int lineNumber, BookmarkManager *manager);
void updateLineNumber(int lineNumber);
void move(int line);
void updateBlock(const QTextBlock &block);
void updateFileName(const QString &fileName);
void updateLineNumber(int lineNumber) override;
void move(int line) override;
void updateBlock(const QTextBlock &block) override;
void updateFileName(const QString &fileName) override;
void removedFromEditor() override;
void setNote(const QString &note);
void updateNote(const QString &note);
void removedFromEditor();
QString lineText() const;
QString note() const;
@@ -51,7 +52,6 @@ public:
private:
BookmarkManager *m_manager;
QString m_lineText;
QString m_note;
};
} // namespace Internal
-18
View File
@@ -38,7 +38,6 @@
#include <projectexplorer/session.h>
#include <texteditor/texteditor.h>
#include <utils/icon.h>
#include <utils/tooltip/tooltip.h>
#include <utils/qtcassert.h>
#include <utils/checkablemessagebox.h>
#include <utils/theme/theme.h>
@@ -845,17 +844,6 @@ void BookmarkManager::saveBookmarks()
SessionManager::setValue(QLatin1String("Bookmarks"), list);
}
void BookmarkManager::operateTooltip(QWidget *widget, const QPoint &pos, Bookmark *mark)
{
if (!mark)
return;
if (mark->note().isEmpty())
ToolTip::hide();
else
ToolTip::show(pos, mark->note(), widget);
}
/* Loads the bookmarks from the session settings. */
void BookmarkManager::loadBookmarks()
{
@@ -867,12 +855,6 @@ void BookmarkManager::loadBookmarks()
updateActionStatus();
}
void BookmarkManager::handleBookmarkTooltipRequest(IEditor *editor, const QPoint &pos, int line)
{
Bookmark *mark = findBookmark(editor->document()->filePath().toString(), line);
operateTooltip(editor->widget(), pos, mark);
}
// BookmarkViewFactory
BookmarkViewFactory::BookmarkViewFactory(BookmarkManager *bm)
+2 -4
View File
@@ -26,7 +26,6 @@
#pragma once
#include <utils/itemviews.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/inavigationwidgetfactory.h>
#include <QAbstractItemModel>
@@ -36,6 +35,8 @@
#include <QPixmap>
#include <QStyledItemDelegate>
namespace Core { class IContext; }
namespace Bookmarks {
namespace Internal {
@@ -87,8 +88,6 @@ public:
Note = Qt::UserRole + 4
};
void handleBookmarkTooltipRequest(Core::IEditor *editor, const QPoint &pos, int line);
void toggleBookmark(const QString &fileName, int lineNumber);
void nextInDocument();
void prevInDocument();
@@ -117,7 +116,6 @@ private:
bool removeBookmarkFromMap(Bookmark *bookmark, const QString &fileName = QString());
static QString bookmarkToString(const Bookmark *b);
void saveBookmarks();
void operateTooltip(QWidget *widget, const QPoint &pos, Bookmark *mark);
typedef QMultiMap<QString, Bookmark *> FileNameBookmarksMap;
typedef QMap<QString, FileNameBookmarksMap *> DirectoryFileBookmarksMap;
@@ -170,13 +170,6 @@ void BookmarksPlugin::editorOpened(IEditor *editor)
m_bookmarkManager->toggleBookmark(editor->document()->filePath().toString(), line);
});
connect(widget, &TextEditorWidget::markTooltipRequested, m_bookmarkManager,
[this, editor](TextEditorWidget *, const QPoint &pos, int line) {
if (editor->document())
m_bookmarkManager->handleBookmarkTooltipRequest(editor, pos, line);
});
connect(widget, &TextEditorWidget::markContextMenuRequested,
this, &BookmarksPlugin::requestContextMenu);
}
@@ -243,11 +243,23 @@ ClangDiagnosticManager::ClangDiagnosticManager(TextEditor::TextDocument *textDoc
{
}
ClangDiagnosticManager::~ClangDiagnosticManager()
{
cleanMarks();
}
void ClangDiagnosticManager::cleanMarks()
{
for (ClangTextMark *textMark : m_clangTextMarks) {
m_textDocument->removeMark(textMark);
delete textMark;
}
m_clangTextMarks.clear();
}
void ClangDiagnosticManager::generateTextMarks()
{
m_clangTextMarks.clear();
cleanMarks();
m_clangTextMarks.reserve(m_warningDiagnostics.size() + m_errorDiagnostics.size());
addClangTextMarks(m_warningDiagnostics);
addClangTextMarks(m_errorDiagnostics);
}
@@ -332,18 +344,13 @@ ClangDiagnosticManager::diagnosticsWithFixIts() const
void ClangDiagnosticManager::addClangTextMarks(
const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics)
{
QTC_ASSERT(m_clangTextMarks.size() + diagnostics.size() <= m_clangTextMarks.capacity(), return);
for (auto &&diagnostic : diagnostics) {
m_clangTextMarks.emplace_back(filePath(),
diagnostic.location().line(),
diagnostic.severity());
ClangTextMark &textMark = m_clangTextMarks.back();
textMark.setBaseTextDocument(m_textDocument);
m_textDocument->addMark(&textMark);
for (const ClangBackEnd::DiagnosticContainer &diagnostic : diagnostics) {
auto textMark = new ClangTextMark(filePath(),
diagnostic.location().line(),
diagnostic.severity());
textMark->setToolTip(diagnostic.text());
m_clangTextMarks.push_back(textMark);
m_textDocument->addMark(textMark);
}
}
@@ -47,6 +47,7 @@ class ClangDiagnosticManager
{
public:
ClangDiagnosticManager(TextEditor::TextDocument *textDocument);
~ClangDiagnosticManager();
void processNewDiagnostics(const QVector<ClangBackEnd::DiagnosticContainer> &allDiagnostics);
@@ -60,6 +61,7 @@ public:
void clearDiagnosticsWithFixIts();
private:
void cleanMarks();
QString filePath() const;
void filterDiagnostics(const QVector<ClangBackEnd::DiagnosticContainer> &diagnostics);
void generateEditorSelections();
@@ -77,7 +79,7 @@ private:
QVector<ClangBackEnd::DiagnosticContainer> m_fixItdiagnostics;
QList<QTextEdit::ExtraSelection> m_extraSelections;
TextEditor::RefactorMarkers m_fixItAvailableMarkers;
std::vector<ClangTextMark> m_clangTextMarks;
std::vector<ClangTextMark *> m_clangTextMarks;
};
} // namespace Internal
@@ -79,10 +79,5 @@ void ClangTextMark::setIcon(ClangBackEnd::DiagnosticSeverity severity)
TextMark::setIcon(errorIcon);
}
ClangTextMark::ClangTextMark(ClangTextMark &&other) Q_DECL_NOEXCEPT
: TextMark(std::move(other))
{
}
} // namespace ClangCodeModel
@@ -36,11 +36,6 @@ class ClangTextMark : public TextEditor::TextMark
public:
ClangTextMark(const QString &fileName, int lineNumber, ClangBackEnd::DiagnosticSeverity severity);
ClangTextMark(ClangTextMark &&other) Q_DECL_NOEXCEPT;
ClangTextMark(ClangTextMark &other) = delete;
ClangTextMark &operator=(ClangTextMark &other) = delete;
private:
void setIcon(ClangBackEnd::DiagnosticSeverity severity);
};
@@ -47,7 +47,7 @@ ClangStaticAnalyzerConfigWidget::ClangStaticAnalyzerConfigWidget(
chooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
chooser->setHistoryCompleter(QLatin1String("ClangStaticAnalyzer.ClangCommand.History"));
chooser->setPromptDialogTitle(tr("Clang Command"));
const auto validator = [chooser](Utils::FancyLineEdit *edit, QString *errorMessage) {
const auto validator = [chooser, this](Utils::FancyLineEdit *edit, QString *errorMessage) {
const QString currentFilePath = chooser->fileName().toString();
Utils::PathChooser pc;
Utils::PathChooser *helperPathChooser;
@@ -58,8 +58,17 @@ ClangStaticAnalyzerConfigWidget::ClangStaticAnalyzerConfigWidget(
} else {
helperPathChooser = chooser;
}
return chooser->defaultValidationFunction()(helperPathChooser->lineEdit(), errorMessage)
const bool isExecutableValid =
chooser->defaultValidationFunction()(helperPathChooser->lineEdit(), errorMessage)
&& isClangExecutableUsable(helperPathChooser->fileName().toString(), errorMessage);
const ClangExecutableVersion detectedVersion = isExecutableValid
? clangExecutableVersion(helperPathChooser->fileName().toString())
: ClangExecutableVersion();
updateDetectedVersionLabel(isExecutableValid, detectedVersion);
return isExecutableValid;
};
chooser->setValidationFunction(validator);
bool clangExeIsSet;
@@ -90,5 +99,29 @@ ClangStaticAnalyzerConfigWidget::~ClangStaticAnalyzerConfigWidget()
delete m_ui;
}
void ClangStaticAnalyzerConfigWidget::updateDetectedVersionLabel(
bool isExecutableValid,
const ClangExecutableVersion &providedVersion)
{
QLabel &label = *m_ui->detectedVersionLabel;
if (isExecutableValid) {
if (providedVersion.isValid()) {
if (providedVersion.isSupportedVersion()) {
label.setText(tr("Version: %1, supported.")
.arg(providedVersion.toString()));
} else {
label.setText(tr("Version: %1, unsupported (supported version is %2).")
.arg(providedVersion.toString())
.arg(ClangExecutableVersion::supportedVersionAsString()));
}
} else {
label.setText(tr("Version: Could not determine version."));
}
} else {
label.setText(tr("Version: Set valid executable first."));
}
}
} // namespace Internal
} // namespace ClangStaticAnalyzer
@@ -34,6 +34,8 @@ namespace Internal {
namespace Ui { class ClangStaticAnalyzerConfigWidget; }
class ClangExecutableVersion;
class ClangStaticAnalyzerConfigWidget : public QWidget
{
Q_OBJECT
@@ -43,6 +45,9 @@ public:
QWidget *parent = 0);
~ClangStaticAnalyzerConfigWidget();
void updateDetectedVersionLabel(bool executableIsValid,
const ClangExecutableVersion &providedVersion);
private:
Ui::ClangStaticAnalyzerConfigWidget *m_ui;
ClangStaticAnalyzerSettings *m_settings;
@@ -34,14 +34,21 @@
</item>
</layout>
</item>
<item row="1" column="0">
<item row="1" column="1">
<widget class="QLabel" name="detectedVersionLabel">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Simultaneous processes:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<item row="2" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QSpinBox" name="simultaneousProccessesSpinBox">
@@ -469,6 +469,28 @@ void ClangStaticAnalyzerRunControl::start()
emit finished();
return;
}
// Check clang version
const ClangExecutableVersion version = clangExecutableVersion(executable);
if (!version.isValid()) {
const QString warningMessage
= tr("Clang Static Analyzer: Running with possibly unsupported version, "
"could not determine version from executable \"%1\".")
.arg(executable);
appendMessage(warningMessage + QLatin1Char('\n'), Utils::StdErrFormat);
TaskHub::addTask(Task::Warning, warningMessage, Debugger::Constants::ANALYZERTASK_ID);
TaskHub::requestPopup();
} else if (!version.isSupportedVersion()) {
const QString warningMessage
= tr("Clang Static Analyzer: Running with unsupported version %1, "
"supported version is %2.")
.arg(version.toString())
.arg(ClangExecutableVersion::supportedVersionAsString());
appendMessage(warningMessage + QLatin1Char('\n'), Utils::StdErrFormat);
TaskHub::addTask(Task::Warning, warningMessage, Debugger::Constants::ANALYZERTASK_ID);
TaskHub::requestPopup();
}
m_clangExecutable = executable;
// Create log dir
@@ -32,9 +32,11 @@
#include <utils/hostosinfo.h>
#include <utils/environment.h>
#include <utils/synchronousprocess.h>
#include <QCoreApplication>
#include <QFileInfo>
#include <QRegularExpression>
static bool isFileExecutable(const QString &executablePath)
{
@@ -108,5 +110,53 @@ bool isClangExecutableUsable(const QString &filePath, QString *errorMessage)
return true;
}
ClangExecutableVersion clangExecutableVersion(const QString &executable)
{
const ClangExecutableVersion invalidVersion;
// Sanity checks
const QFileInfo fileInfo(executable);
const bool isExecutableFile = fileInfo.isFile() && fileInfo.isExecutable();
if (!isExecutableFile)
return invalidVersion;
// Get version output
Utils::Environment environment = Utils::Environment::systemEnvironment();
Utils::Environment::setupEnglishOutput(&environment);
Utils::SynchronousProcess runner;
runner.setEnvironment(environment.toStringList());
runner.setTimeoutS(10);
// We would prefer "-dumpversion", but that one returns some old version number.
const QStringList arguments(QLatin1String(("--version")));
const Utils::SynchronousProcessResponse response = runner.runBlocking(executable, arguments);
if (response.result != Utils::SynchronousProcessResponse::Finished)
return invalidVersion;
const QString output = response.stdOut();
// Parse version output
const QRegularExpression re(QLatin1String("clang version (\\d+)\\.(\\d+)\\.(\\d+)"));
const QRegularExpressionMatch reMatch = re.match(output);
if (re.captureCount() != 3)
return invalidVersion;
const QString majorString = reMatch.captured(1);
bool convertedSuccessfully = false;
const int major = majorString.toInt(&convertedSuccessfully);
if (!convertedSuccessfully)
return invalidVersion;
const QString minorString = reMatch.captured(2);
const int minor = minorString.toInt(&convertedSuccessfully);
if (!convertedSuccessfully)
return invalidVersion;
const QString patchString = reMatch.captured(3);
const int patch = patchString.toInt(&convertedSuccessfully);
if (!convertedSuccessfully)
return invalidVersion;
return ClangExecutableVersion(major, minor, patch);
}
} // namespace Internal
} // namespace ClangStaticAnalyzer
@@ -44,5 +44,40 @@ QString clangExecutableFromSettings(Core::Id toolchainType, bool *isValid);
QString createFullLocationString(const Debugger::DiagnosticLocation &location);
// TODO: Use QVersionNumber once we can use >= Qt 5.6.0
class ClangExecutableVersion {
public:
ClangExecutableVersion() : majorNumber(-1) , minorNumber(-1) , patchNumber(-1) {}
ClangExecutableVersion(int major, int minor, int patch)
: majorNumber(major) , minorNumber(minor) , patchNumber(patch) {}
bool isValid() const
{
return majorNumber >= 0 && minorNumber >= 0 && patchNumber >= 0;
}
bool isSupportedVersion() const
{
return majorNumber == 3 && minorNumber == 8;
}
static QString supportedVersionAsString()
{
return QLatin1String("3.8");
}
QString toString() const
{
return QString::fromLatin1("%1.%2.%3").arg(majorNumber).arg(minorNumber).arg(patchNumber);
}
public:
int majorNumber;
int minorNumber;
int patchNumber;
};
ClangExecutableVersion clangExecutableVersion(const QString &absolutePath);
} // namespace Internal
} // namespace ClangStaticAnalyzer
+2 -2
View File
@@ -1480,8 +1480,8 @@ ClearCasePlugin::runCleartool(const QString &workingDir,
response.error = sp_resp.result != SynchronousProcessResponse::Finished;
if (response.error)
response.message = sp_resp.exitMessage(executable, timeOutS);
response.stdErr = sp_resp.stdErr;
response.stdOut = sp_resp.stdOut;
response.stdErr = sp_resp.stdErr();
response.stdOut = sp_resp.stdOut();
return response;
}
@@ -35,6 +35,7 @@
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/algorithm.h>
#include <utils/elidinglabel.h>
#include <utils/qtcassert.h>
#include <QBoxLayout>
@@ -278,7 +279,7 @@ QString CMakeGeneratorKitConfigWidget::toolTip() const
CMakeConfigurationKitConfigWidget::CMakeConfigurationKitConfigWidget(Kit *kit,
const KitInformation *ki) :
KitConfigWidget(kit, ki),
m_summaryLabel(new QLabel),
m_summaryLabel(new Utils::ElidingLabel),
m_manageButton(new QPushButton)
{
refresh();
@@ -303,13 +304,9 @@ void CMakeConfigurationKitConfigWidget::refresh()
{
const QStringList current = CMakeConfigurationKitInformation::toStringList(kit());
QString shortSummary = current.join(QLatin1String("; "));
QFontMetrics fm(m_summaryLabel->font());
shortSummary = fm.elidedText(shortSummary, Qt::ElideRight, m_summaryLabel->width());
m_summaryLabel->setText(current.isEmpty() ? tr("<No Changes to Apply>") : shortSummary);
m_summaryLabel->setText(current.join("; "));
if (m_editor)
m_editor->setPlainText(current.join(QLatin1Char('\n')));
m_editor->setPlainText(current.join('\n'));
}
QWidget *CMakeConfigurationKitConfigWidget::mainWidget() const
@@ -344,6 +341,7 @@ void CMakeConfigurationKitConfigWidget::editConfigurationChanges()
m_editor->setToolTip(tr("Enter one variable per line with the variable name "
"separated from the variable value by \"=\".<br>"
"You may provide a type hint by adding \":TYPE\" before the \"=\"."));
m_editor->setMinimumSize(800, 200);
auto chooser = new Core::VariableChooser(m_dialog);
chooser->addSupportedWidget(m_editor);
@@ -153,7 +153,7 @@ QStringList CMakeTool::supportedGenerators() const
Utils::SynchronousProcessResponse response = run(QLatin1String("--help"));
if (response.result == Utils::SynchronousProcessResponse::Finished) {
bool inGeneratorSection = false;
const QStringList lines = response.stdOut.split(QLatin1Char('\n'));
const QStringList lines = response.stdOut().split(QLatin1Char('\n'));
foreach (const QString &line, lines) {
if (line.isEmpty())
continue;
@@ -188,19 +188,19 @@ TextEditor::Keywords CMakeTool::keywords()
Utils::SynchronousProcessResponse response;
response = run(QLatin1String("--help-command-list"));
if (response.result == Utils::SynchronousProcessResponse::Finished)
m_functions = response.stdOut.split(QLatin1Char('\n'));
m_functions = response.stdOut().split(QLatin1Char('\n'));
response = run(QLatin1String("--help-commands"));
if (response.result == Utils::SynchronousProcessResponse::Finished)
parseFunctionDetailsOutput(response.stdOut);
parseFunctionDetailsOutput(response.stdOut());
response = run(QLatin1String("--help-property-list"));
if (response.result == Utils::SynchronousProcessResponse::Finished)
m_variables = parseVariableOutput(response.stdOut);
m_variables = parseVariableOutput(response.stdOut());
response = run(QLatin1String("--help-variable-list"));
if (response.result == Utils::SynchronousProcessResponse::Finished) {
m_variables.append(parseVariableOutput(response.stdOut));
m_variables.append(parseVariableOutput(response.stdOut()));
m_variables = Utils::filteredUnique(m_variables);
Utils::sort(m_variables);
}
@@ -337,6 +337,7 @@ public:
{
setFrameStyle(QFrame::NoFrame | QFrame::Plain);
viewport()->setAutoFillBackground(false);
setWidgetResizable(true);
}
private:
void resizeEvent(QResizeEvent *event) override
@@ -385,7 +386,6 @@ private:
return 0;
return list.first()->sizeHint().width();
}
};
+16 -9
View File
@@ -413,11 +413,12 @@ public:
{
QWidget::paintEvent(event);
// Some Themes do not want highlights and shadows in the toolbars.
// Some Themes do not want highlights, shadows and borders in the toolbars.
// But we definitely want a separator between FancyColorButton and FancyTabBar
if (!creatorTheme()->flag(Theme::DrawToolBarHighlights)) {
if (!creatorTheme()->flag(Theme::DrawToolBarHighlights)
&& !creatorTheme()->flag(Theme::DrawToolBarBorders)) {
QPainter p(this);
p.setPen(StyleHelper::borderColor());
p.setPen(StyleHelper::toolBarBorderColor());
const QRectF innerRect = QRectF(rect()).adjusted(0.5, 0.5, -0.5, -0.5);
p.drawLine(innerRect.bottomLeft(), innerRect.bottomRight());
}
@@ -527,13 +528,19 @@ void FancyTabWidget::paintEvent(QPaintEvent *event)
QRect rect = m_selectionWidget->rect().adjusted(0, 0, 1, 0);
rect = style()->visualRect(layoutDirection(), geometry(), rect);
const QRectF boderRect = QRectF(rect).adjusted(0.5, 0.5, -0.5, -0.5);
StyleHelper::verticalGradient(&painter, rect, rect);
painter.setPen(StyleHelper::borderColor());
painter.drawLine(boderRect.topRight(), boderRect.bottomRight());
QColor light = StyleHelper::sidebarHighlight();
painter.setPen(light);
painter.drawLine(boderRect.bottomLeft(), boderRect.bottomRight());
if (creatorTheme()->flag(Theme::FlatToolBars)) {
painter.setPen(StyleHelper::toolBarBorderColor());
painter.drawLine(boderRect.topRight(), boderRect.bottomRight());
} else {
StyleHelper::verticalGradient(&painter, rect, rect);
painter.setPen(StyleHelper::borderColor());
painter.drawLine(boderRect.topRight(), boderRect.bottomRight());
QColor light = StyleHelper::sidebarHighlight();
painter.setPen(light);
painter.drawLine(boderRect.bottomLeft(), boderRect.bottomRight());
}
}
}
+16 -5
View File
@@ -527,20 +527,24 @@ void ManhattanStyle::drawPrimitive(PrimitiveElement element, const QStyleOption
case PE_PanelStatusBar:
{
const QRectF borderRect = QRectF(rect).adjusted(0.5, 0.5, -0.5, -0.5);
painter->save();
if (creatorTheme()->flag(Theme::FlatToolBars)) {
painter->fillRect(rect, StyleHelper::baseColor());
} else {
painter->save();
QLinearGradient grad = StyleHelper::statusBarGradient(rect);
painter->fillRect(rect, grad);
const QRectF borderRect = QRectF(rect).adjusted(0.5, 0.5, -0.5, -0.5);
painter->setPen(QColor(255, 255, 255, 60));
painter->drawLine(borderRect.topLeft() + QPointF(0, 1),
borderRect.topRight()+ QPointF(0, 1));
painter->setPen(StyleHelper::borderColor().darker(110)); //TODO: make themable
painter->drawLine(borderRect.topLeft(), borderRect.topRight());
painter->restore();
}
if (creatorTheme()->flag(Theme::DrawToolBarBorders)) {
painter->setPen(StyleHelper::toolBarBorderColor());
painter->drawLine(borderRect.topLeft(), borderRect.topRight());
}
painter->restore();
}
break;
@@ -796,7 +800,7 @@ void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *opt
StyleHelper::menuGradient(painter, option->rect, option->rect);
painter->save();
painter->setPen(StyleHelper::borderColor());
painter->setPen(StyleHelper::toolBarBorderColor());
painter->drawLine(option->rect.bottomLeft() + QPointF(0.5, 0.5),
option->rect.bottomRight() + QPointF(0.5, 0.5));
painter->restore();
@@ -828,7 +832,7 @@ void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *opt
if (creatorTheme()->flag(Theme::DrawToolBarHighlights)) {
if (!drawLightColored)
painter->setPen(StyleHelper::borderColor());
painter->setPen(StyleHelper::toolBarBorderColor());
else
painter->setPen(QColor(0x888888));
@@ -855,6 +859,13 @@ void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *opt
painter->drawLine(borderRect.topRight(), borderRect.bottomRight());
}
}
if (creatorTheme()->flag(Theme::DrawToolBarBorders)) {
painter->setPen(StyleHelper::toolBarBorderColor());
if (widget && widget->property("topBorder").toBool())
painter->drawLine(borderRect.topLeft(), borderRect.topRight());
else
painter->drawLine(borderRect.bottomLeft(), borderRect.bottomRight());
}
}
break;
+26 -13
View File
@@ -670,12 +670,6 @@ QSize OutputPaneToggleButton::sizeHint() const
void OutputPaneToggleButton::paintEvent(QPaintEvent*)
{
static const QImage panelButton(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button.png")));
static const QImage panelButtonHover(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_hover.png")));
static const QImage panelButtonPressed(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_pressed.png")));
static const QImage panelButtonChecked(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_checked.png")));
static const QImage panelButtonCheckedHover(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_checked_hover.png")));
const QFontMetrics fm = fontMetrics();
const int baseLine = (height() - fm.height() + 1) / 2 + fm.ascent();
const int numberWidth = fm.width(m_number);
@@ -686,7 +680,6 @@ void OutputPaneToggleButton::paintEvent(QPaintEvent*)
styleOption.initFrom(this);
const bool hovered = !HostOsInfo::isMacHost() && (styleOption.state & QStyle::State_MouseOver);
const QImage *image = 0;
if (creatorTheme()->flag(Theme::FlatToolBars)) {
Theme::Color c = Theme::BackgroundColorDark;
@@ -698,12 +691,32 @@ void OutputPaneToggleButton::paintEvent(QPaintEvent*)
if (c != Theme::BackgroundColorDark)
p.fillRect(rect(), creatorTheme()->color(c));
} else {
if (isDown())
image = &panelButtonPressed;
else if (isChecked())
image = hovered ? &panelButtonCheckedHover : &panelButtonChecked;
else
image = hovered ? &panelButtonHover : &panelButton;
const QImage *image = 0;
if (isDown()) {
static const QImage pressed(
StyleHelper::dpiSpecificImageFile(":/core/images/panel_button_pressed.png"));
image = &pressed;
} else if (isChecked()) {
if (hovered) {
static const QImage checkedHover(
StyleHelper::dpiSpecificImageFile(":/core/images/panel_button_checked_hover.png"));
image = &checkedHover;
} else {
static const QImage checked(
StyleHelper::dpiSpecificImageFile(":/core/images/panel_button_checked.png"));
image = &checked;
}
} else {
if (hovered) {
static const QImage hover(
StyleHelper::dpiSpecificImageFile(":/core/images/panel_button_hover.png"));
image = &hover;
} else {
static const QImage button(
StyleHelper::dpiSpecificImageFile(":/core/images/panel_button.png"));
image = &button;
}
}
if (image)
StyleHelper::drawCornerImage(*image, &p, rect(), numberAreaWidth(), buttonBorderWidth, buttonBorderWidth, buttonBorderWidth);
}
+1
View File
@@ -167,6 +167,7 @@ private slots:
void test_quickfix_MoveFuncDefOutside_respectWsInOperatorNames1();
void test_quickfix_MoveFuncDefOutside_respectWsInOperatorNames2();
void test_quickfix_MoveFuncDefOutside_macroUses();
void test_quickfix_MoveFuncDefOutside_template();
void test_quickfix_MoveAllFuncDefOutside_MemberFuncToCpp();
void test_quickfix_MoveAllFuncDefOutside_MemberFuncOutside();
@@ -4018,6 +4018,23 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_macroUses()
ProjectPartHeaderPaths(), 0, "QTCREATORBUG-12314");
}
void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_template()
{
QByteArray original =
"template<class T>\n"
"class Foo { void fu@nc() {} };\n";
QByteArray expected =
"template<class T>\n"
"class Foo { void fu@nc(); };\n"
"\n"
"template<class T>\n"
"void Foo<T>::func() {}\n";
;
MoveFuncDefOutside factory;
QuickFixOperationTest(singleDocument(original, expected), &factory, {}, 0, "QTCREATORBUG-16649");
}
/// Check: revert test_quickfix_MoveFuncDefOutside_MemberFuncToCpp()
void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFunc()
{
@@ -75,7 +75,8 @@ void CppCodeModelSettingsWidget::setupClangCodeModelWidgets()
{
const bool isClangActive = CppModelManager::instance()->isClangCodeModelActive();
m_ui->activateClangCodeModelPluginHint->setVisible(!isClangActive);
m_ui->clangCodeModelIsDisabledHint->setVisible(!isClangActive);
m_ui->clangCodeModelIsEnabledHint->setVisible(isClangActive);
m_ui->clangSettingsGroupBox->setEnabled(isClangActive);
ClangDiagnosticConfigsModel diagnosticConfigsModel(m_settings->clangCustomDiagnosticConfigs());
@@ -15,9 +15,16 @@
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QLabel" name="activateClangCodeModelPluginHint">
<widget class="QLabel" name="clangCodeModelIsEnabledHint">
<property name="text">
<string>&lt;i&gt;Activate the Clang Code Model plugin to enable the options here.&lt;/i&gt;</string>
<string>&lt;i&gt;The Clang Code Model is enabled because the corresponding plugin is loaded.&lt;/i&gt;</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="clangCodeModelIsDisabledHint">
<property name="text">
<string>&lt;i&gt;The Clang Code Model is disabled because the corresponding plugin is not loaded.&lt;/i&gt;</string>
</property>
</widget>
</item>
+2 -2
View File
@@ -1140,8 +1140,8 @@ CvsResponse CvsPlugin::runCvs(const QString &workingDirectory,
timeOutS, flags, outputCodec);
response.result = CvsResponse::OtherError;
response.stdErr = sp_resp.stdErr;
response.stdOut = sp_resp.stdOut;
response.stdErr = sp_resp.stdErr();
response.stdOut = sp_resp.stdOut();
switch (sp_resp.result) {
case SynchronousProcessResponse::Finished:
response.result = CvsResponse::Ok;
@@ -312,6 +312,7 @@ QWidget *ConsoleItemDelegate::createEditor(QWidget *parent,
editor->setStyleSheet(QLatin1String("QTextEdit {"
"margin-left: 24px;"
"margin-top: 4px;"
"color: black;"
"background-color: white;"
"background-image: url(:/qmljstools/images/prompt.png);"
"background-position: baseline left;"
+3 -1
View File
@@ -98,7 +98,9 @@ ConsoleView::ConsoleView(ConsoleItemModel *model, QWidget *parent) :
"QTreeView::branch:open:has-children:!has-siblings,"
"QTreeView::branch:open:has-children:has-siblings {"
"border-image: none;"
"image: none; }"));
"image: none; }"
"QTreeView {"
"background-color: white; }"));
QString baseName = QApplication::style()->objectName();
if (Utils::HostOsInfo::isAnyUnixHost() && !Utils::HostOsInfo::isMacHost()
+13 -9
View File
@@ -719,6 +719,10 @@ public:
}
}
void reloadSourceFiles() { if (m_currentEngine) m_currentEngine->reloadSourceFiles(); }
void reloadRegisters() { if (m_currentEngine) m_currentEngine->reloadRegisters(); }
void reloadModules() { if (m_currentEngine) m_currentEngine->reloadModules(); }
void editorOpened(IEditor *editor);
void updateBreakMenuItem(IEditor *editor);
void setBusyCursor(bool busy);
@@ -1340,17 +1344,17 @@ bool DebuggerPluginPrivate::initialize(const QStringList &arguments,
m_modulesView = new BaseTreeView;
m_modulesView->setSortingEnabled(true);
m_modulesView->setSettings(settings, "Debugger.ModulesView");
connect(m_modulesView, &BaseTreeView::aboutToShow, this, [this] {
m_currentEngine->reloadModules();
}, Qt::QueuedConnection);
connect(m_modulesView, &BaseTreeView::aboutToShow,
this, &DebuggerPluginPrivate::reloadModules,
Qt::QueuedConnection);
m_modulesWindow = addSearch(m_modulesView, tr("Modules"), DOCKWIDGET_MODULES);
m_registerView = new BaseTreeView;
m_registerView->setRootIsDecorated(true);
m_registerView->setSettings(settings, "Debugger.RegisterView");
connect(m_registerView, &BaseTreeView::aboutToShow, this, [this] {
m_currentEngine->reloadRegisters();
}, Qt::QueuedConnection);
connect(m_registerView, &BaseTreeView::aboutToShow,
this, &DebuggerPluginPrivate::reloadRegisters,
Qt::QueuedConnection);
m_registerWindow = addSearch(m_registerView, tr("Registers"), DOCKWIDGET_REGISTER);
m_stackView = new StackTreeView;
@@ -1360,9 +1364,9 @@ bool DebuggerPluginPrivate::initialize(const QStringList &arguments,
m_sourceFilesView = new BaseTreeView;
m_sourceFilesView->setSortingEnabled(true);
m_sourceFilesView->setSettings(settings, "Debugger.SourceFilesView");
connect(m_sourceFilesView, &BaseTreeView::aboutToShow, this, [this] {
m_currentEngine->reloadSourceFiles();
}, Qt::QueuedConnection);
connect(m_sourceFilesView, &BaseTreeView::aboutToShow,
this, &DebuggerPluginPrivate::reloadSourceFiles,
Qt::QueuedConnection);
m_sourceFilesWindow = addSearch(m_sourceFilesView, tr("Source Files"), DOCKWIDGET_SOURCE_FILES);
m_threadsView = new BaseTreeView;
@@ -583,6 +583,8 @@ QString decodeData(const QString &ba, const QString &encoding)
return QCoreApplication::translate("Debugger::Internal::WatchHandler", "<invalid>");
if (encoding == "notcallable")
return QCoreApplication::translate("Debugger::Internal::WatchHandler", "<not callable>");
if (encoding == "outofscope")
return QCoreApplication::translate("Debugger::Internal::WatchHandler", "<out of scope>");
DebuggerEncoding enc(encoding);
QString result;
+1 -1
View File
@@ -142,7 +142,7 @@ GdbCoreEngine::readExecutableNameFromCore(const QString &debuggerCommand, const
SynchronousProcessResponse response = proc.runBlocking(debuggerCommand, args);
if (response.result == SynchronousProcessResponse::Finished) {
QString output = response.stdOut;
QString output = response.stdOut();
// Core was generated by `/data/dev/creator-2.6/bin/qtcreator'.
// Program terminated with signal 11, Segmentation fault.
int pos1 = output.indexOf("Core was generated by");
+3 -2
View File
@@ -121,8 +121,9 @@ void GdbPlainEngine::setupEngine()
}
gdbArgs.append("--tty=" + m_outputCollector.serverName());
if (!runParameters().inferior.workingDirectory.isEmpty())
m_gdbProc.setWorkingDirectory(runParameters().inferior.workingDirectory);
QString workingDirectory = runParameters().inferior.workingDirectory;
if (!workingDirectory.isEmpty() && QFileInfo::exists(workingDirectory))
m_gdbProc.setWorkingDirectory(workingDirectory);
startGdb(gdbArgs);
}
+10
View File
@@ -428,6 +428,16 @@ LogWindow::LogWindow(QWidget *parent)
this, &LogWindow::doOutput);
setMinimumHeight(60);
showOutput(LogWarning,
tr("NOTE: This log contains possibly confidential information about your machine, "
"environment variables, in-memory data of the processes you are debugging, and more. "
"It is never transferred over the internet by Qt Creator, and only stored "
"to disk if you manually use the respective option from the context menu, or through "
"mechanisms that are not under Qt Creator's control, for instance in swap files.\n"
"You may be asked to share the contents of this log when reporting bugs related "
"to debugger operation. In this case, make sure your submission does not "
"contain data you do not want to or you are not allowed to share.\n\n"));
}
void LogWindow::executeLine()
@@ -663,6 +663,12 @@ void QmlInspectorAgent::addWatchData(const ObjectReference &obj,
propertiesWatch->appendChild(propertyWatch);
}
if (boolSetting(SortStructMembers)) {
propertiesWatch->sortChildren([](const WatchItem *item1, const WatchItem *item2) {
return item1->name < item2->name;
});
}
m_qmlEngine->watchHandler()->insertItem(propertiesWatch);
}
+1 -4
View File
@@ -25,15 +25,12 @@
#include "annotationhighlighter.h"
#include <QDebug>
namespace Git {
namespace Internal {
GitAnnotationHighlighter::GitAnnotationHighlighter(const ChangeNumbers &changeNumbers,
QTextDocument *document) :
VcsBase::BaseAnnotationHighlighter(changeNumbers, document),
m_blank(QLatin1Char(' '))
VcsBase::BaseAnnotationHighlighter(changeNumbers, document)
{
}
+1 -1
View File
@@ -41,7 +41,7 @@ public:
private:
QString changeNumber(const QString &block) const override;
const QChar m_blank;
const QChar m_blank = ' ';
};
} // namespace Internal
+18 -22
View File
@@ -46,20 +46,20 @@ class BranchNameValidator : public QValidator
public:
BranchNameValidator(const QStringList &localBranches, QObject *parent = 0) :
QValidator(parent),
m_invalidChars(QLatin1String(
"\\s" // no whitespace
"|~" // no "~"
"|\\^" // no "^"
"|\\[" // no "["
"|\\.\\." // no ".."
"|/\\." // no slashdot
"|:" // no ":"
"|@\\{" // no "@{" sequence
"|\\\\" // no backslash
"|//" // no double slash
"|^[/-]" // no leading slash or dash
"|\"" // no quotes
)),
m_invalidChars(
"\\s" // no whitespace
"|~" // no "~"
"|\\^" // no "^"
"|\\[" // no "["
"|\\.\\." // no ".."
"|/\\." // no slashdot
"|:" // no ":"
"|@\\{" // no "@{" sequence
"|\\\\" // no backslash
"|//" // no double slash
"|^[/-]" // no leading slash or dash
"|\"" // no quotes
),
m_localBranches(localBranches)
{
}
@@ -68,21 +68,17 @@ public:
{
Q_UNUSED(pos)
// NoGos
if (input.contains(m_invalidChars))
return Invalid;
input.replace(m_invalidChars, "_");
// "Intermediate" patterns, may change to Acceptable when user edits further:
if (input.endsWith(QLatin1String(".lock"))) //..may not end with ".lock"
if (input.endsWith(".lock")) //..may not end with ".lock"
return Intermediate;
if (input.endsWith(QLatin1Char('.'))) // no dot at the end (but allowed in the middle)
if (input.endsWith('.')) // no dot at the end (but allowed in the middle)
return Intermediate;
if (input.endsWith(QLatin1Char('/'))) // no slash at the end (but allowed in the middle)
if (input.endsWith('/')) // no slash at the end (but allowed in the middle)
return Intermediate;
if (m_localBranches.contains(input, Utils::HostOsInfo::isWindowsHost()
+7 -9
View File
@@ -172,7 +172,7 @@ void BranchDialog::add()
QString suggestedName;
if (!isTag) {
QString suggestedNameBase;
suggestedNameBase = trackedBranch.mid(trackedBranch.lastIndexOf(QLatin1Char('/')) + 1);
suggestedNameBase = trackedBranch.mid(trackedBranch.lastIndexOf('/') + 1);
suggestedName = suggestedNameBase;
int i = 2;
while (localNames.contains(suggestedName)) {
@@ -208,7 +208,7 @@ void BranchDialog::checkout()
const QString currentBranch = m_model->fullName(m_model->currentBranch());
const QString nextBranch = m_model->fullName(idx);
const QString popMessageStart = QCoreApplication::applicationName() +
QLatin1Char(' ') + nextBranch + QLatin1String("-AutoStash ");
' ' + nextBranch + "-AutoStash ";
BranchCheckoutDialog branchCheckoutDialog(this, currentBranch, nextBranch);
GitClient *client = GitPlugin::client();
@@ -232,12 +232,10 @@ void BranchDialog::checkout()
} else if (branchCheckoutDialog.exec() == QDialog::Accepted) {
if (branchCheckoutDialog.makeStashOfCurrentBranch()) {
if (client->synchronousStash(m_repository,
currentBranch + QLatin1String("-AutoStash")).isEmpty()) {
if (client->synchronousStash(m_repository, currentBranch + "-AutoStash").isEmpty())
return;
}
} else if (branchCheckoutDialog.moveLocalChangesToNextBranch()) {
if (!client->beginStashScope(m_repository, QLatin1String("Checkout"), NoPrompt))
if (!client->beginStashScope(m_repository, "Checkout", NoPrompt))
return;
} else if (branchCheckoutDialog.discardLocalChanges()) {
if (!client->synchronousReset(m_repository))
@@ -351,7 +349,7 @@ void BranchDialog::reset()
if (QMessageBox::question(this, tr("Git Reset"), tr("Hard reset branch \"%1\" to \"%2\"?")
.arg(currentName).arg(branchName),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) {
GitPlugin::client()->reset(m_repository, QLatin1String("--hard"), branchName);
GitPlugin::client()->reset(m_repository, "--hard", branchName);
}
}
@@ -374,7 +372,7 @@ void BranchDialog::merge()
return;
allowFastForward = (chosen == fastForward);
}
if (client->beginStashScope(m_repository, QLatin1String("merge"), AllowUnstashed))
if (client->beginStashScope(m_repository, "merge", AllowUnstashed))
client->synchronousMerge(m_repository, branch, allowFastForward);
}
@@ -387,7 +385,7 @@ void BranchDialog::rebase()
const QString baseBranch = m_model->fullName(idx, true);
GitClient *client = GitPlugin::client();
if (client->beginStashScope(m_repository, QLatin1String("rebase")))
if (client->beginStashScope(m_repository, "rebase"))
client->rebase(m_repository, baseBranch);
}
+37 -44
View File
@@ -54,7 +54,7 @@ class BranchNode
public:
BranchNode() :
parent(0),
name(QLatin1String("<ROOT>"))
name("<ROOT>")
{ }
BranchNode(const QString &n, const QString &s = QString(), const QString &t = QString(),
@@ -172,7 +172,7 @@ public:
}
return names;
}
return QStringList(fullName().join(QLatin1Char('/')));
return QStringList(fullName().join('/'));
}
int rowOf(BranchNode *node)
@@ -202,8 +202,8 @@ BranchModel::BranchModel(GitClient *client, QObject *parent) :
QTC_CHECK(m_client);
// Abuse the sha field for ref prefix
m_rootNode->append(new BranchNode(tr("Local Branches"), QLatin1String("refs/heads")));
m_rootNode->append(new BranchNode(tr("Remote Branches"), QLatin1String("refs/remotes")));
m_rootNode->append(new BranchNode(tr("Local Branches"), "refs/heads"));
m_rootNode->append(new BranchNode(tr("Remote Branches"), "refs/remotes"));
}
BranchModel::~BranchModel()
@@ -260,7 +260,7 @@ QVariant BranchModel::data(const QModelIndex &index, int role) const
case 0: {
res = node->name;
if (!node->tracking.isEmpty())
res += QLatin1String(" [") + node->tracking + QLatin1Char(']');
res += " [" + node->tracking + ']';
break;
}
case 1:
@@ -316,9 +316,7 @@ bool BranchModel::setData(const QModelIndex &index, const QVariant &value, int r
QString output;
QString errorMessage;
if (!m_client->synchronousBranchCmd(m_workingDirectory,
QStringList() << QLatin1String("-m")
<< oldFullName.last()
<< newFullName.last(),
{ "-m", oldFullName.last(), newFullName.last() },
&output, &errorMessage)) {
node->name = oldFullName.last();
VcsOutputWindow::appendError(errorMessage);
@@ -362,15 +360,14 @@ bool BranchModel::refresh(const QString &workingDirectory, QString *errorMessage
}
m_currentSha = m_client->synchronousTopRevision(workingDirectory);
QStringList args;
args << QLatin1String("--format=%(objectname)\t%(refname)\t%(upstream:short)\t"
"%(*objectname)\t%(committerdate:raw)\t%(*committerdate:raw)");
const QStringList args = { "--format=%(objectname)\t%(refname)\t%(upstream:short)\t"
"%(*objectname)\t%(committerdate:raw)\t%(*committerdate:raw)" };
QString output;
if (!m_client->synchronousForEachRefCmd(workingDirectory, args, &output, errorMessage))
VcsOutputWindow::appendError(*errorMessage);
m_workingDirectory = workingDirectory;
const QStringList lines = output.split(QLatin1Char('\n'));
const QStringList lines = output.split('\n');
foreach (const QString &l, lines)
parseOutputLine(l);
@@ -403,8 +400,7 @@ void BranchModel::renameBranch(const QString &oldName, const QString &newName)
{
QString errorMessage;
QString output;
if (!m_client->synchronousBranchCmd(m_workingDirectory,
QStringList() << QLatin1String("-m") << oldName << newName,
if (!m_client->synchronousBranchCmd(m_workingDirectory, { "-m", oldName, newName },
&output, &errorMessage))
VcsOutputWindow::appendError(errorMessage);
else
@@ -415,11 +411,10 @@ void BranchModel::renameTag(const QString &oldName, const QString &newName)
{
QString errorMessage;
QString output;
if (!m_client->synchronousTagCmd(m_workingDirectory, QStringList() << newName << oldName,
if (!m_client->synchronousTagCmd(m_workingDirectory, { newName, oldName },
&output, &errorMessage)
|| !m_client->synchronousTagCmd(m_workingDirectory,
QStringList() << QLatin1String("-d") << oldName,
&output, &errorMessage)) {
|| !m_client->synchronousTagCmd(m_workingDirectory, { "-d", oldName },
&output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
} else {
refresh(m_workingDirectory, &errorMessage);
@@ -451,7 +446,7 @@ QString BranchModel::fullName(const QModelIndex &idx, bool includePrefix) const
if (!node || !node->isLeaf())
return QString();
QStringList path = node->fullName(includePrefix);
return path.join(QLatin1Char('/'));
return path.join('/');
}
QStringList BranchModel::localBranchNames() const
@@ -514,10 +509,8 @@ void BranchModel::removeBranch(const QModelIndex &idx)
QString errorMessage;
QString output;
QStringList args;
args << QLatin1String("-D") << branch;
if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage)) {
if (!m_client->synchronousBranchCmd(m_workingDirectory, { "-D", branch }, &output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
return;
}
@@ -532,10 +525,8 @@ void BranchModel::removeTag(const QModelIndex &idx)
QString errorMessage;
QString output;
QStringList args;
args << QLatin1String("-d") << tag;
if (!m_client->synchronousTagCmd(m_workingDirectory, args, &output, &errorMessage)) {
if (!m_client->synchronousTagCmd(m_workingDirectory, { "-d", tag }, &output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
return;
}
@@ -561,13 +552,13 @@ bool BranchModel::branchIsMerged(const QModelIndex &idx)
QString errorMessage;
QString output;
QStringList args;
args << QLatin1String("-a") << QLatin1String("--contains") << sha(idx);
if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage))
if (!m_client->synchronousBranchCmd(m_workingDirectory, { "-a", "--contains", sha(idx) },
&output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
}
QStringList lines = output.split(QLatin1Char('\n'), QString::SkipEmptyParts);
QStringList lines = output.split('\n', QString::SkipEmptyParts);
foreach (const QString &l, lines) {
QString currentBranch = l.mid(2); // remove first letters (those are either
// " " or "* " depending on whether it is
@@ -600,9 +591,7 @@ QModelIndex BranchModel::addBranch(const QString &name, bool track, const QModel
QString errorMessage;
QDateTime branchDateTime;
QStringList args;
args << (track ? QLatin1String("--track") : QLatin1String("--no-track"));
args << name;
QStringList args = { QLatin1String(track ? "--track" : "--no-track"), name };
if (!fullTrackedBranch.isEmpty()) {
args << fullTrackedBranch;
startSha = sha(startPoint);
@@ -625,7 +614,7 @@ QModelIndex BranchModel::addBranch(const QString &name, bool track, const QModel
}
BranchNode *local = m_rootNode->children.at(LocalBranches);
const int slash = name.indexOf(QLatin1Char('/'));
const int slash = name.indexOf('/');
const QString leafName = slash == -1 ? name : name.mid(slash + 1);
bool added = false;
if (slash != -1) {
@@ -675,7 +664,7 @@ void BranchModel::parseOutputLine(const QString &line)
return;
// objectname, refname, upstream:short, *objectname, committerdate:raw, *committerdate:raw
QStringList lineParts = line.split(QLatin1Char('\t'));
QStringList lineParts = line.split('\t');
const QString shaDeref = lineParts.at(3);
const QString sha = shaDeref.isEmpty() ? lineParts.at(0) : shaDeref;
const QString fullName = lineParts.at(1);
@@ -686,29 +675,33 @@ void BranchModel::parseOutputLine(const QString &line)
if (strDateTime.isEmpty())
strDateTime = lineParts.at(4);
if (!strDateTime.isEmpty()) {
const uint timeT = strDateTime.leftRef(strDateTime.indexOf(QLatin1Char(' '))).toUInt();
const uint timeT = strDateTime.leftRef(strDateTime.indexOf(' ')).toUInt();
dateTime = QDateTime::fromTime_t(timeT);
}
if (!m_oldBranchesIncluded && !current && dateTime.isValid()) {
const int age = dateTime.daysTo(QDateTime::currentDateTime());
if (age > Constants::OBSOLETE_COMMIT_AGE_IN_DAYS)
const qint64 age = dateTime.daysTo(QDateTime::currentDateTime());
if (age > Constants::OBSOLETE_COMMIT_AGE_IN_DAYS) {
const QString heads = "refs/heads/";
if (fullName.startsWith(heads))
m_obsoleteLocalBranches.append(fullName.mid(heads.size()));
return;
}
}
bool showTags = m_client->settings().boolValue(GitSettings::showTagsKey);
// insert node into tree:
QStringList nameParts = fullName.split(QLatin1Char('/'));
QStringList nameParts = fullName.split('/');
nameParts.removeFirst(); // remove refs...
BranchNode *root = 0;
if (nameParts.first() == QLatin1String("heads")) {
if (nameParts.first() == "heads") {
root = m_rootNode->children.at(LocalBranches);
} else if (nameParts.first() == QLatin1String("remotes")) {
} else if (nameParts.first() == "remotes") {
root = m_rootNode->children.at(RemoteBranches);
} else if (showTags && nameParts.first() == QLatin1String("tags")) {
} else if (showTags && nameParts.first() == "tags") {
if (!hasTags()) // Tags is missing, add it
m_rootNode->append(new BranchNode(tr("Tags"), QLatin1String("refs/tags")));
m_rootNode->append(new BranchNode(tr("Tags"), "refs/tags"));
root = m_rootNode->children.at(Tags);
} else {
return;
@@ -719,7 +712,7 @@ void BranchModel::parseOutputLine(const QString &line)
// limit depth of list. Git basically only ever wants one / and considers the rest as part of
// the name.
while (nameParts.count() > 3) {
nameParts[2] = nameParts.at(2) + QLatin1Char('/') + nameParts.at(3);
nameParts[2] = nameParts.at(2) + '/' + nameParts.at(3);
nameParts.removeAt(3);
}
@@ -770,7 +763,7 @@ QString BranchModel::toolTip(const QString &sha) const
// Show the sha description excluding diff as toolTip
QString output;
QString errorMessage;
QStringList arguments(QLatin1String("-n1"));
QStringList arguments("-n1");
arguments << sha;
if (!m_client->synchronousLog(m_workingDirectory, arguments, &output, &errorMessage,
VcsCommand::SuppressCommandLogging)) {
+5 -9
View File
@@ -119,7 +119,7 @@ void ChangeSelectionDialog::selectCommitFromRecentHistory()
return;
QString commit = change();
int tilde = commit.indexOf(QLatin1Char('~'));
int tilde = commit.indexOf('~');
if (tilde != -1)
commit.truncate(tilde);
LogChangeDialog dialog(false, this);
@@ -219,12 +219,11 @@ void ChangeSelectionDialog::recalculateCompletion()
return;
GitClient *client = GitPlugin::client();
QStringList args;
args << QLatin1String("--format=%(refname:short)");
VcsBase::VcsCommand *command = client->asyncForEachRefCmd(workingDir, args);
VcsBase::VcsCommand *command = client->asyncForEachRefCmd(
workingDir, { "--format=%(refname:short)" });
connect(this, &QObject::destroyed, command, &VcsBase::VcsCommand::abort);
connect(command, &VcsBase::VcsCommand::stdOutText, [this](const QString &output) {
m_changeModel->setStringList(output.split(QLatin1Char('\n')));
m_changeModel->setStringList(output.split('\n'));
});
}
@@ -245,9 +244,6 @@ void ChangeSelectionDialog::recalculateDetails()
return;
}
QStringList args;
args << QLatin1String("show") << QLatin1String("--stat=80") << ref;
m_process = new QProcess(this);
m_process->setWorkingDirectory(workingDir);
m_process->setProcessEnvironment(m_gitEnvironment);
@@ -255,7 +251,7 @@ void ChangeSelectionDialog::recalculateDetails()
connect(m_process, static_cast<void (QProcess::*)(int)>(&QProcess::finished),
this, &ChangeSelectionDialog::setDetails);
m_process->start(m_gitExecutable.toString(), args);
m_process->start(m_gitExecutable.toString(), { "show", "--stat=80", ref });
m_process->closeWriteChannel();
if (!m_process->waitForStarted())
m_ui->detailsText->setPlainText(tr("Error: Could not start Git."));
+8 -8
View File
@@ -54,9 +54,9 @@ QString GitSubmitEditorPanelData::authorString() const
if (email.isEmpty())
return rc;
rc += QLatin1String(" <");
rc += " <";
rc += email;
rc += QLatin1Char('>');
rc += '>';
return rc;
}
@@ -114,7 +114,7 @@ bool CommitData::checkLine(const QString &stateInfo, const QString &file)
{
QTC_ASSERT(stateInfo.count() == 2, return false);
if (stateInfo == QLatin1String("??")) {
if (stateInfo == "??") {
files.append(qMakePair(FileStates(UntrackedFile), file));
return true;
}
@@ -143,7 +143,7 @@ bool CommitData::checkLine(const QString &stateInfo, const QString &file)
if (yState != EmptyFileState) {
QString newFile = file;
if (xState & (RenamedFile | CopiedFile))
newFile = file.mid(file.indexOf(QLatin1String(" -> ")) + 4);
newFile = file.mid(file.indexOf(" -> ") + 4);
files.append(qMakePair(yState, newFile));
}
@@ -159,20 +159,20 @@ bool CommitData::checkLine(const QString &stateInfo, const QString &file)
\endcode */
bool CommitData::parseFilesFromStatus(const QString &output)
{
const QStringList lines = output.split(QLatin1Char('\n'));
const QStringList lines = output.split('\n');
foreach (const QString &line, lines) {
if (line.isEmpty())
continue;
if (line.startsWith(QLatin1String("## "))) {
if (line.startsWith("## ")) {
// Branch indication:
panelInfo.branch = line.mid(3);
continue;
}
QTC_ASSERT(line.at(2) == QLatin1Char(' '), continue);
QTC_ASSERT(line.at(2) == ' ', continue);
QString file = line.mid(3);
if (file.startsWith(QLatin1Char('"')))
if (file.startsWith('"'))
file.remove(0, 1).chop(1);
if (!checkLine(line.mid(0, 2), file))
return false;
+6 -6
View File
@@ -39,16 +39,16 @@ void BranchComboBox::init(const QString &repository)
QString currentBranch = GitPlugin::client()->synchronousCurrentLocalBranch(repository);
if (currentBranch.isEmpty()) {
m_detached = true;
currentBranch = QLatin1String("HEAD");
currentBranch = "HEAD";
addItem(currentBranch);
}
QString output;
const QString branchPrefix(QLatin1String("refs/heads/"));
QStringList args;
args << QLatin1String("--format=%(refname)") << branchPrefix;
if (!GitPlugin::client()->synchronousForEachRefCmd(m_repository, args, &output))
const QString branchPrefix("refs/heads/");
if (!GitPlugin::client()->synchronousForEachRefCmd(
m_repository, { "--format=%(refname)", branchPrefix }, &output)) {
return;
QStringList branches = output.trimmed().split(QLatin1Char('\n'));
}
QStringList branches = output.trimmed().split('\n');
foreach (const QString &ref, branches) {
const QString branch = ref.mid(branchPrefix.size());
addItem(branch);
+2 -2
View File
@@ -69,7 +69,7 @@ GerritDialog::GerritDialog(const QSharedPointer<GerritParameters> &p,
, m_filterLineEdit(new Utils::FancyLineEdit)
, m_repositoryChooser(new Utils::PathChooser)
, m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Close))
, m_repositoryChooserLabel(new QLabel(tr("Apply in:") + QLatin1Char(' '), this))
, m_repositoryChooserLabel(new QLabel(tr("Apply in:") + ' ', this))
, m_fetchRunning(false)
{
setWindowTitle(tr("Gerrit %1@%2").arg(p->user, p->host));
@@ -144,7 +144,7 @@ GerritDialog::GerritDialog(const QSharedPointer<GerritParameters> &p,
detailsLayout->addWidget(m_detailsBrowser);
m_repositoryChooser->setExpectedKind(Utils::PathChooser::Directory);
m_repositoryChooser->setHistoryCompleter(QLatin1String("Git.RepoDir.History"));
m_repositoryChooser->setHistoryCompleter("Git.RepoDir.History");
QHBoxLayout *repoPathLayout = new QHBoxLayout;
repoPathLayout->addWidget(m_repositoryChooserLabel);
repoPathLayout->addWidget(m_repositoryChooser);
+39 -39
View File
@@ -86,9 +86,9 @@ QDebug operator<<(QDebug d, const GerritChange &c)
// Format default Url for a change
static inline QString defaultUrl(const QSharedPointer<GerritParameters> &p, int gerritNumber)
{
QString result = p->https ? QLatin1String("https://") : QLatin1String("http://");
QString result = QLatin1String(p->https ? "https://" : "http://");
result += p->host;
result += QLatin1Char('/');
result += '/';
result += QString::number(gerritNumber);
return result;
}
@@ -146,7 +146,7 @@ QString GerritPatchSet::approvalsColumn() const
TypeReviewMap reviews; // Sort approvals into a map by type character
foreach (const GerritApproval &a, approvals) {
if (a.type != QLatin1String("STGN")) { // Qt-Project specific: Ignore "STGN" (Staged)
if (a.type != "STGN") { // Qt-Project specific: Ignore "STGN" (Staged)
const QChar typeChar = a.type.at(0);
TypeReviewMapIterator it = reviews.find(typeChar);
if (it == reviews.end())
@@ -183,7 +183,7 @@ int GerritPatchSet::approvalLevel() const
QString GerritChange::filterString() const
{
const QChar blank = QLatin1Char(' ');
const QChar blank = ' ';
QString result = QString::number(number) + blank + title + blank
+ owner + blank + project + blank
+ branch + blank + status;
@@ -197,10 +197,10 @@ QString GerritChange::filterString() const
QStringList GerritChange::gitFetchArguments(const QSharedPointer<GerritParameters> &p) const
{
QStringList arguments;
const QString url = QLatin1String("ssh://") + p->sshHostArgument()
+ QLatin1Char(':') + QString::number(p->port) + QLatin1Char('/')
const QString url = "ssh://" + p->sshHostArgument()
+ ':' + QString::number(p->port) + '/'
+ project;
arguments << QLatin1String("fetch") << url << currentPatchSet.ref;
arguments << "fetch" << url << currentPatchSet.ref;
return arguments;
}
@@ -276,9 +276,9 @@ QueryContext::QueryContext(const QStringList &queries,
m_progress.setProgressRange(0, m_queries.size());
// Determine binary and common command line arguments.
m_baseArguments << QLatin1String("query") << QLatin1String("--dependencies")
<< QLatin1String("--current-patch-set")
<< QLatin1String("--format=JSON");
m_baseArguments << "query" << "--dependencies"
<< "--current-patch-set"
<< "--format=JSON";
m_binary = m_baseArguments.front();
m_baseArguments.pop_front();
@@ -404,7 +404,7 @@ GerritModel::GerritModel(const QSharedPointer<GerritParameters> &p, QObject *par
, m_parameters(p)
{
QStringList headers; // Keep in sync with GerritChange::toHtml()
headers << QLatin1String("#") << tr("Subject") << tr("Owner")
headers << "#" << tr("Subject") << tr("Owner")
<< tr("Updated") << tr("Project")
<< tr("Approvals") << tr("Status");
setHorizontalHeaderLabels(headers);
@@ -463,7 +463,7 @@ QString GerritModel::toHtml(const QModelIndex& index) const
if (!index.isValid())
return QString();
const GerritChangePtr c = change(index);
const QString serverPrefix = c->url.left(c->url.lastIndexOf(QLatin1Char('/')) + 1);
const QString serverPrefix = c->url.left(c->url.lastIndexOf('/') + 1);
QString result;
QTextStream str(&result);
str << "<html><head/><body><table>"
@@ -522,14 +522,14 @@ void GerritModel::refresh(const QString &query)
queries.push_back(query);
else
{
const QString statusOpenQuery = QLatin1String("status:open");
const QString statusOpenQuery = "status:open";
if (m_parameters->user.isEmpty()) {
queries.push_back(statusOpenQuery);
} else {
// Owned by:
queries.push_back(statusOpenQuery + QLatin1String(" owner:") + m_parameters->user);
queries.push_back(statusOpenQuery + " owner:" + m_parameters->user);
// For Review by:
queries.push_back(statusOpenQuery + QLatin1String(" reviewer:") + m_parameters->user);
queries.push_back(statusOpenQuery + " reviewer:" + m_parameters->user);
}
}
@@ -578,27 +578,27 @@ static bool parseOutput(const QSharedPointer<GerritParameters> &parameters,
QList<GerritChangePtr> &result)
{
// The output consists of separate lines containing a document each
const QString typeKey = QLatin1String("type");
const QString dependsOnKey = QLatin1String("dependsOn");
const QString neededByKey = QLatin1String("neededBy");
const QString branchKey = QLatin1String("branch");
const QString numberKey = QLatin1String("number");
const QString ownerKey = QLatin1String("owner");
const QString ownerNameKey = QLatin1String("name");
const QString ownerEmailKey = QLatin1String("email");
const QString statusKey = QLatin1String("status");
const QString projectKey = QLatin1String("project");
const QString titleKey = QLatin1String("subject");
const QString urlKey = QLatin1String("url");
const QString patchSetKey = QLatin1String("currentPatchSet");
const QString refKey = QLatin1String("ref");
const QString approvalsKey = QLatin1String("approvals");
const QString approvalsValueKey = QLatin1String("value");
const QString approvalsByKey = QLatin1String("by");
const QString lastUpdatedKey = QLatin1String("lastUpdated");
const QString typeKey = "type";
const QString dependsOnKey = "dependsOn";
const QString neededByKey = "neededBy";
const QString branchKey = "branch";
const QString numberKey = "number";
const QString ownerKey = "owner";
const QString ownerNameKey = "name";
const QString ownerEmailKey = "email";
const QString statusKey = "status";
const QString projectKey = "project";
const QString titleKey = "subject";
const QString urlKey = "url";
const QString patchSetKey = "currentPatchSet";
const QString refKey = "ref";
const QString approvalsKey = "approvals";
const QString approvalsValueKey = "value";
const QString approvalsByKey = "by";
const QString lastUpdatedKey = "lastUpdated";
const QList<QByteArray> lines = output.split('\n');
const QString approvalsTypeKey = QLatin1String("type");
const QString approvalsDescriptionKey = QLatin1String("description");
const QString approvalsTypeKey = "type";
const QString approvalsDescriptionKey = "description";
bool res = true;
result.clear();
@@ -712,8 +712,8 @@ QList<QStandardItem *> GerritModel::changeToRow(const GerritChangePtr &c) const
row[DateColumn]->setData(c->lastUpdated, SortRole);
QString project = c->project;
if (c->branch != QLatin1String("master"))
project += QLatin1String(" (") + c->branch + QLatin1Char(')');
if (c->branch != "master")
project += " (" + c->branch + ')';
row[ProjectColumn]->setText(project);
row[StatusColumn]->setText(c->status);
row[ApprovalsColumn]->setText(c->currentPatchSet.approvalsColumn());
@@ -759,7 +759,7 @@ void GerritModel::queryFinished(const QByteArray &output)
changes.at(i)->depth = 0;
} else {
const int dependsOnIndex = numberIndexHash.value(changes.at(i)->dependsOnNumber, -1);
if (dependsOnIndex < 0 || changes.at(dependsOnIndex)->status != QLatin1String("NEW"))
if (dependsOnIndex < 0 || changes.at(dependsOnIndex)->status != "NEW")
changes.at(i)->depth = 0;
}
}
@@ -798,7 +798,7 @@ void GerritModel::queryFinished(const QByteArray &output)
for (; changeFromItem(parent)->depth >= 1; parent = parent->parent()) {}
parent->appendRow(newRow);
QString parentFilterString = parent->data(FilterRole).toString();
parentFilterString += QLatin1Char(' ');
parentFilterString += ' ';
parentFilterString += newRow.first()->data(FilterRole).toString();
parent->setData(QVariant(parentFilterString), FilterRole);
} else {
+2 -2
View File
@@ -93,8 +93,8 @@ GerritOptionsWidget::GerritOptionsWidget(QWidget *parent)
formLayout->addRow(tr("&Host:"), m_hostLineEdit);
formLayout->addRow(tr("&User:"), m_userLineEdit);
m_sshChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
m_sshChooser->setCommandVersionArguments(QStringList(QLatin1String("-V")));
m_sshChooser->setHistoryCompleter(QLatin1String("Git.SshCommand.History"));
m_sshChooser->setCommandVersionArguments(QStringList("-V"));
m_sshChooser->setHistoryCompleter("Git.SshCommand.History");
formLayout->addRow(tr("&ssh:"), m_sshChooser);
m_portSpinBox->setMinimum(1);
m_portSpinBox->setMaximum(65535);
+27 -27
View File
@@ -57,13 +57,13 @@ static inline QString detectSsh()
const QByteArray gitSsh = qgetenv("GIT_SSH");
if (!gitSsh.isEmpty())
return QString::fromLocal8Bit(gitSsh);
QString ssh = QStandardPaths::findExecutable(QLatin1String(defaultSshC));
QString ssh = QStandardPaths::findExecutable(defaultSshC);
if (!ssh.isEmpty())
return ssh;
if (Utils::HostOsInfo::isWindowsHost()) { // Windows: Use ssh.exe from git if it cannot be found.
Utils::FileName path = GerritPlugin::gitBinDirectory();
if (!path.isEmpty())
ssh = path.appendPath(QLatin1String(defaultSshC)).toString();
ssh = path.appendPath(defaultSshC).toString();
}
return ssh;
}
@@ -72,17 +72,17 @@ void GerritParameters::setPortFlagBySshType()
{
bool isPlink = false;
if (!ssh.isEmpty()) {
const QString version = Utils::PathChooser::toolVersion(ssh, QStringList(QLatin1String("-V")));
isPlink = version.contains(QLatin1String("plink"), Qt::CaseInsensitive);
const QString version = Utils::PathChooser::toolVersion(ssh, QStringList("-V"));
isPlink = version.contains("plink", Qt::CaseInsensitive);
}
portFlag = isPlink ? QLatin1String("-P") : QLatin1String(defaultPortFlag);
portFlag = isPlink ? "-P" : defaultPortFlag;
}
GerritParameters::GerritParameters()
: host(QLatin1String(defaultHostC))
: host(defaultHostC)
, port(defaultPort)
, https(true)
, portFlag(QLatin1String(defaultPortFlag))
, portFlag(defaultPortFlag)
{
}
@@ -90,13 +90,13 @@ QStringList GerritParameters::baseCommandArguments() const
{
QStringList result;
result << ssh << portFlag << QString::number(port)
<< sshHostArgument() << QLatin1String("gerrit");
<< sshHostArgument() << "gerrit";
return result;
}
QString GerritParameters::sshHostArgument() const
{
return user.isEmpty() ? host : (user + QLatin1Char('@') + host);
return user.isEmpty() ? host : (user + '@' + host);
}
bool GerritParameters::equals(const GerritParameters &rhs) const
@@ -107,34 +107,34 @@ bool GerritParameters::equals(const GerritParameters &rhs) const
void GerritParameters::toSettings(QSettings *s) const
{
s->beginGroup(QLatin1String(settingsGroupC));
s->setValue(QLatin1String(hostKeyC), host);
s->setValue(QLatin1String(userKeyC), user);
s->setValue(QLatin1String(portKeyC), port);
s->setValue(QLatin1String(portFlagKeyC), portFlag);
s->setValue(QLatin1String(sshKeyC), ssh);
s->setValue(QLatin1String(httpsKeyC), https);
s->beginGroup(settingsGroupC);
s->setValue(hostKeyC, host);
s->setValue(userKeyC, user);
s->setValue(portKeyC, port);
s->setValue(portFlagKeyC, portFlag);
s->setValue(sshKeyC, ssh);
s->setValue(httpsKeyC, https);
s->endGroup();
}
void GerritParameters::saveQueries(QSettings *s) const
{
s->beginGroup(QLatin1String(settingsGroupC));
s->setValue(QLatin1String(savedQueriesKeyC), savedQueries.join(QLatin1Char(',')));
s->beginGroup(settingsGroupC);
s->setValue(savedQueriesKeyC, savedQueries.join(','));
s->endGroup();
}
void GerritParameters::fromSettings(const QSettings *s)
{
const QString rootKey = QLatin1String(settingsGroupC) + QLatin1Char('/');
host = s->value(rootKey + QLatin1String(hostKeyC), QLatin1String(defaultHostC)).toString();
user = s->value(rootKey + QLatin1String(userKeyC), QString()).toString();
ssh = s->value(rootKey + QLatin1String(sshKeyC), QString()).toString();
port = s->value(rootKey + QLatin1String(portKeyC), QVariant(int(defaultPort))).toInt();
portFlag = s->value(rootKey + QLatin1String(portFlagKeyC), QLatin1String(defaultPortFlag)).toString();
savedQueries = s->value(rootKey + QLatin1String(savedQueriesKeyC), QString()).toString()
.split(QLatin1Char(','));
https = s->value(rootKey + QLatin1String(httpsKeyC), QVariant(true)).toBool();
const QString rootKey = QLatin1String(settingsGroupC) + '/';
host = s->value(rootKey + hostKeyC, defaultHostC).toString();
user = s->value(rootKey + userKeyC, QString()).toString();
ssh = s->value(rootKey + sshKeyC, QString()).toString();
port = s->value(rootKey + portKeyC, QVariant(int(defaultPort))).toInt();
portFlag = s->value(rootKey + portFlagKeyC, defaultPortFlag).toString();
savedQueries = s->value(rootKey + savedQueriesKeyC, QString()).toString()
.split(',');
https = s->value(rootKey + httpsKeyC, QVariant(true)).toBool();
if (ssh.isEmpty())
ssh = detectSsh();
}
+22 -27
View File
@@ -243,9 +243,9 @@ void FetchContext::processError(QProcess::ProcessError e)
void FetchContext::show()
{
const QString title = QString::number(m_change->number) + QLatin1Char('/')
const QString title = QString::number(m_change->number) + '/'
+ QString::number(m_change->currentPatchSet.patchSetNumber);
GitPlugin::client()->show(m_repository, QLatin1String("FETCH_HEAD"), title);
GitPlugin::client()->show(m_repository, "FETCH_HEAD", title);
}
void FetchContext::cherryPick()
@@ -253,12 +253,12 @@ void FetchContext::cherryPick()
// Point user to errors.
VcsBase::VcsOutputWindow::instance()->popup(IOutputPane::ModeSwitch
| IOutputPane::WithFocus);
GitPlugin::client()->synchronousCherryPick(m_repository, QLatin1String("FETCH_HEAD"));
GitPlugin::client()->synchronousCherryPick(m_repository, "FETCH_HEAD");
}
void FetchContext::checkout()
{
GitPlugin::client()->stashAndCheckout(m_repository, QLatin1String("FETCH_HEAD"));
GitPlugin::client()->stashAndCheckout(m_repository, "FETCH_HEAD");
}
void FetchContext::terminate()
@@ -326,31 +326,26 @@ void GerritPlugin::push(const QString &topLevel)
if (dialog.exec() == QDialog::Rejected)
return;
QStringList args;
m_reviewers = dialog.reviewers();
args << dialog.selectedRemoteName();
QString target = dialog.selectedCommit();
if (target.isEmpty())
target = QLatin1String("HEAD");
target += QLatin1String(":refs/") + dialog.selectedPushType() +
QLatin1Char('/') + dialog.selectedRemoteBranchName();
target = "HEAD";
target += ":refs/" + dialog.selectedPushType() +
'/' + dialog.selectedRemoteBranchName();
const QString topic = dialog.selectedTopic();
if (!topic.isEmpty())
target += QLatin1Char('/') + topic;
target += '/' + topic;
QStringList options;
const QStringList reviewers = m_reviewers.split(QLatin1Char(','), QString::SkipEmptyParts);
const QStringList reviewers = m_reviewers.split(',', QString::SkipEmptyParts);
foreach (const QString &reviewer, reviewers)
options << QLatin1String("r=") + reviewer;
options << "r=" + reviewer;
if (!options.isEmpty())
target += QLatin1Char('%') + options.join(QLatin1Char(','));
target += '%' + options.join(',');
args << target;
GitPlugin::client()->push(topLevel, args);
GitPlugin::client()->push(topLevel, { dialog.selectedRemoteName(), target });
}
// Open or raise the Gerrit dialog window.
@@ -432,7 +427,7 @@ void GerritPlugin::fetch(const QSharedPointer<GerritChange> &change, int mode)
if (!remotesList.isEmpty()) {
QStringList remotes = remotesList.values();
foreach (QString remote, remotes) {
if (remote.endsWith(QLatin1String(".git")))
if (remote.endsWith(".git"))
remote.chop(4);
if (remote.contains(m_parameters->host) && remote.endsWith(change->project)) {
verifiedRepository = true;
@@ -444,11 +439,11 @@ void GerritPlugin::fetch(const QSharedPointer<GerritChange> &change, int mode)
SubmoduleDataMap submodules = GitPlugin::client()->submoduleList(repository);
foreach (const SubmoduleData &submoduleData, submodules) {
QString remote = submoduleData.url;
if (remote.endsWith(QLatin1String(".git")))
if (remote.endsWith(".git"))
remote.chop(4);
if (remote.contains(m_parameters->host) && remote.endsWith(change->project)
&& QFile::exists(repository + QLatin1Char('/') + submoduleData.dir)) {
repository = QDir::cleanPath(repository + QLatin1Char('/')
&& QFile::exists(repository + '/' + submoduleData.dir)) {
repository = QDir::cleanPath(repository + '/'
+ submoduleData.dir);
verifiedRepository = true;
break;
@@ -504,18 +499,18 @@ QString GerritPlugin::findLocalRepository(QString project, const QString &branch
{
const QStringList gitRepositories = VcsManager::repositories(GitPlugin::instance()->gitVersionControl());
// Determine key (file name) to look for (qt/qtbase->'qtbase').
const int slashPos = project.lastIndexOf(QLatin1Char('/'));
const int slashPos = project.lastIndexOf('/');
if (slashPos != -1)
project.remove(0, slashPos + 1);
// When looking at branch 1.7, try to check folders
// "qtbase_17", 'qtbase1.7' with a semi-smart regular expression.
QScopedPointer<QRegExp> branchRegexp;
if (!branch.isEmpty() && branch != QLatin1String("master")) {
if (!branch.isEmpty() && branch != "master") {
QString branchPattern = branch;
branchPattern.replace(QLatin1Char('.'), QLatin1String("[\\.-_]?"));
const QString pattern = QLatin1Char('^') + project
+ QLatin1String("[-_]?")
+ branchPattern + QLatin1Char('$');
branchPattern.replace('.', "[\\.-_]?");
const QString pattern = '^' + project
+ "[-_]?"
+ branchPattern + '$';
branchRegexp.reset(new QRegExp(pattern));
if (!branchRegexp->isValid())
branchRegexp.reset(); // Oops.
+25 -29
View File
@@ -45,7 +45,7 @@ class PushItemDelegate : public IconItemDelegate
{
public:
PushItemDelegate(LogChangeWidget *widget)
: IconItemDelegate(widget, QLatin1String(":/git/images/arrowup.png"))
: IconItemDelegate(widget, ":/git/images/arrowup.png")
{
}
@@ -62,17 +62,16 @@ QString GerritPushDialog::determineRemoteBranch(const QString &localBranch)
QString output;
QString error;
QStringList args;
args << QLatin1String("-r") << QLatin1String("--contains")
<< earliestCommit + QLatin1Char('^');
if (!GitPlugin::client()->synchronousBranchCmd(m_workingDir, args, &output, &error))
if (!GitPlugin::client()->synchronousBranchCmd(
m_workingDir, { "-r", "--contains", earliestCommit + '^' }, &output, &error)) {
return QString();
const QString head = QLatin1String("/HEAD");
QStringList refs = output.split(QLatin1Char('\n'));
}
const QString head = "/HEAD";
QStringList refs = output.split('\n');
QString remoteTrackingBranch;
if (localBranch != QLatin1String("HEAD"))
if (localBranch != "HEAD")
remoteTrackingBranch = GitPlugin::client()->synchronousTrackingBranch(m_workingDir, localBranch);
QString remoteBranch;
@@ -94,31 +93,30 @@ QString GerritPushDialog::determineRemoteBranch(const QString &localBranch)
void GerritPushDialog::initRemoteBranches()
{
QString output;
QStringList args;
const QString head = QLatin1String("/HEAD");
const QString head = "/HEAD";
QString remotesPrefix(QLatin1String("refs/remotes/"));
args << QLatin1String("--format=%(refname)\t%(committerdate:raw)")
<< remotesPrefix;
if (!GitPlugin::client()->synchronousForEachRefCmd(m_workingDir, args, &output))
QString remotesPrefix("refs/remotes/");
if (!GitPlugin::client()->synchronousForEachRefCmd(
m_workingDir, { "--format=%(refname)\t%(committerdate:raw)", remotesPrefix }, &output)) {
return;
}
const QStringList refs = output.split(QLatin1String("\n"));
const QStringList refs = output.split("\n");
foreach (const QString &reference, refs) {
QStringList entries = reference.split(QLatin1Char('\t'));
QStringList entries = reference.split('\t');
if (entries.count() < 2 || entries.first().endsWith(head))
continue;
const QString ref = entries.at(0).mid(remotesPrefix.size());
int refBranchIndex = ref.indexOf(QLatin1Char('/'));
int timeT = entries.at(1).leftRef(entries.at(1).indexOf(QLatin1Char(' '))).toInt();
int refBranchIndex = ref.indexOf('/');
int timeT = entries.at(1).leftRef(entries.at(1).indexOf(' ')).toInt();
BranchDate bd(ref.mid(refBranchIndex + 1), QDateTime::fromTime_t(timeT).date());
m_remoteBranches.insertMulti(ref.left(refBranchIndex), bd);
}
QStringList remotes = GitPlugin::client()->synchronousRemotesList(m_workingDir).keys();
remotes.removeDuplicates();
{
const QString origin = QLatin1String("origin");
const QString gerrit = QLatin1String("gerrit");
const QString origin = "origin";
const QString gerrit = "gerrit";
if (remotes.removeOne(origin))
remotes.prepend(origin);
if (remotes.removeOne(gerrit))
@@ -155,7 +153,7 @@ GerritPushDialog::GerritPushDialog(const QString &workingDir, const QString &rev
updateCommits(m_ui->localBranchComboBox->currentIndex());
setRemoteBranches();
QRegExpValidator *noSpaceValidator = new QRegExpValidator(QRegExp(QLatin1String("^\\S+$")), this);
QRegExpValidator *noSpaceValidator = new QRegExpValidator(QRegExp("^\\S+$"), this);
m_ui->reviewersLineEdit->setText(reviewerList);
m_ui->reviewersLineEdit->setValidator(noSpaceValidator);
m_ui->topicLineEdit->setValidator(noSpaceValidator);
@@ -179,16 +177,14 @@ QString GerritPushDialog::selectedCommit() const
QString GerritPushDialog::calculateChangeRange(const QString &branch)
{
QString remote = selectedRemoteName();
remote += QLatin1Char('/');
remote += '/';
remote += selectedRemoteBranchName();
QStringList args(remote + QLatin1String("..") + branch);
args << QLatin1String("--count");
QString number;
QString error;
GitPlugin::client()->synchronousRevListCmd(m_workingDir, args, &number, &error);
GitPlugin::client()->synchronousRevListCmd(m_workingDir, { remote + ".." + branch, "--count" },
&number, &error);
number.chop(1);
return number;
@@ -210,7 +206,7 @@ void GerritPushDialog::setChangeRange()
return;
}
m_ui->infoLabel->show();
const QString remote = selectedRemoteName() + QLatin1Char('/') + remoteBranchName;
const QString remote = selectedRemoteName() + '/' + remoteBranchName;
m_ui->infoLabel->setText(
tr("Number of commits between %1 and %2: %3").arg(branch, remote, range));
}
@@ -259,7 +255,7 @@ void GerritPushDialog::updateCommits(int index)
const QString remoteBranch = determineRemoteBranch(branch);
if (!remoteBranch.isEmpty()) {
const int slash = remoteBranch.indexOf(QLatin1Char('/'));
const int slash = remoteBranch.indexOf('/');
m_suggestedRemoteBranch = remoteBranch.mid(slash + 1);
const QString remote = remoteBranch.left(slash);
@@ -285,7 +281,7 @@ QString GerritPushDialog::selectedRemoteBranchName() const
QString GerritPushDialog::selectedPushType() const
{
return m_ui->draftCheckBox->isChecked() ? QLatin1String("drafts") : QLatin1String("for");
return QLatin1String(m_ui->draftCheckBox->isChecked() ? "drafts" : "for");
}
QString GerritPushDialog::selectedTopic() const
File diff suppressed because it is too large Load Diff
+1 -4
View File
@@ -121,8 +121,6 @@ public:
PushAction m_pushAction = NoPush;
};
static const char *stashNamePrefix;
explicit GitClient();
Utils::FileName vcsBinary() const override;
@@ -242,7 +240,6 @@ public:
bool isRemoteCommit(const QString &workingDirectory, const QString &commit);
bool isFastForwardMerge(const QString &workingDirectory, const QString &branch);
bool cloneRepository(const QString &directory, const QByteArray &url);
void fetch(const QString &workingDirectory, const QString &remote);
bool synchronousPull(const QString &workingDirectory, bool rebase);
void push(const QString &workingDirectory, const QStringList &pushArgs = QStringList());
@@ -278,7 +275,7 @@ public:
QString readGitVar(const QString &workingDirectory, const QString &configVar) const;
QString readConfigValue(const QString &workingDirectory, const QString &configVar) const;
QTextCodec *encoding(const QString &workingDirectory, const QByteArray &configVar) const;
QTextCodec *encoding(const QString &workingDirectory, const QString &configVar) const;
bool readDataFromCommit(const QString &repoDirectory, const QString &commit,
CommitData &commitData, QString *errorMessage = nullptr,
QString *commitTemplate = nullptr);
+15 -18
View File
@@ -59,7 +59,7 @@ namespace Git {
namespace Internal {
GitEditorWidget::GitEditorWidget() :
m_changeNumberPattern(QLatin1String(CHANGE_PATTERN))
m_changeNumberPattern(CHANGE_PATTERN)
{
QTC_ASSERT(m_changeNumberPattern.isValid(), return);
/* Diff format:
@@ -68,8 +68,8 @@ GitEditorWidget::GitEditorWidget() :
--- a/src/plugins/git/giteditor.cpp
+++ b/src/plugins/git/giteditor.cpp
*/
setDiffFilePattern(QRegExp(QLatin1String("^(?:diff --git a/|index |[+-]{3} (?:/dev/null|[ab]/(.+$)))")));
setLogEntryPattern(QRegExp(QLatin1String("^commit ([0-9a-f]{8})[0-9a-f]{32}")));
setDiffFilePattern(QRegExp("^(?:diff --git a/|index |[+-]{3} (?:/dev/null|[ab]/(.+$)))"));
setLogEntryPattern(QRegExp("^commit ([0-9a-f]{8})[0-9a-f]{32}"));
setAnnotateRevisionTextFormat(tr("&Blame %1"));
setAnnotatePreviousRevisionTextFormat(tr("Blame &Parent Revision %1"));
}
@@ -81,11 +81,11 @@ QSet<QString> GitEditorWidget::annotationChanges() const
if (txt.isEmpty())
return changes;
// Hunt for first change number in annotation: "<change>:"
QRegExp r(QLatin1String("^(" CHANGE_PATTERN ") "));
QRegExp r("^(" CHANGE_PATTERN ") ");
QTC_ASSERT(r.isValid(), return changes);
if (r.indexIn(txt) != -1) {
changes.insert(r.cap(1));
r.setPattern(QLatin1String("\n(" CHANGE_PATTERN ") "));
r.setPattern("\n(" CHANGE_PATTERN ") ");
QTC_ASSERT(r.isValid(), return changes);
int pos = 0;
while ((pos = r.indexIn(txt, pos)) != -1) {
@@ -126,8 +126,8 @@ static QString sanitizeBlameOutput(const QString &b)
const bool omitDate = GitPlugin::client()->settings().boolValue(
GitSettings::omitAnnotationDateKey);
const QChar space(QLatin1Char(' '));
const int parenPos = b.indexOf(QLatin1Char(')'));
const QChar space(' ');
const int parenPos = b.indexOf(')');
if (parenPos == -1)
return b;
@@ -154,7 +154,7 @@ static QString sanitizeBlameOutput(const QString &b)
// Copy over the parts that have not changed into a new byte array
QString result;
int prevPos = 0;
int pos = b.indexOf(QLatin1Char('\n'), 0) + 1;
int pos = b.indexOf('\n', 0) + 1;
forever {
QTC_CHECK(prevPos < pos);
int afterParen = prevPos + parenPos;
@@ -165,7 +165,7 @@ static QString sanitizeBlameOutput(const QString &b)
if (pos == b.size())
break;
pos = b.indexOf(QLatin1Char('\n'), pos) + 1;
pos = b.indexOf('\n', pos) + 1;
if (pos == 0) // indexOf returned -1
pos = b.size();
}
@@ -190,8 +190,7 @@ void GitEditorWidget::setPlainText(const QString &text)
void GitEditorWidget::checkoutChange()
{
GitPlugin::client()->stashAndCheckout(
sourceWorkingDirectory(), m_currentChange);
GitPlugin::client()->stashAndCheckout(sourceWorkingDirectory(), m_currentChange);
}
void GitEditorWidget::resetChange(const QByteArray &resetType)
@@ -202,14 +201,12 @@ void GitEditorWidget::resetChange(const QByteArray &resetType)
void GitEditorWidget::cherryPickChange()
{
GitPlugin::client()->synchronousCherryPick(
sourceWorkingDirectory(), m_currentChange);
GitPlugin::client()->synchronousCherryPick(sourceWorkingDirectory(), m_currentChange);
}
void GitEditorWidget::revertChange()
{
GitPlugin::client()->synchronousRevert(
sourceWorkingDirectory(), m_currentChange);
GitPlugin::client()->synchronousRevert(sourceWorkingDirectory(), m_currentChange);
}
void GitEditorWidget::logChange()
@@ -229,9 +226,9 @@ void GitEditorWidget::applyDiffChunk(const DiffChunk& chunk, bool revert)
patchFile.write(chunk.chunk);
patchFile.close();
QStringList args = QStringList() << QLatin1String("--cached");
QStringList args = { "--cached" };
if (revert)
args << QLatin1String("--reverse");
args << "--reverse";
QString errorMessage;
if (GitPlugin::client()->synchronousApplyPatch(baseDir, patchFile.fileName(), &errorMessage, args)) {
if (errorMessage.isEmpty())
@@ -362,7 +359,7 @@ QString GitEditorWidget::fileNameForLine(int line) const
// 7971b6e7 share/qtcreator/dumper/dumper.py (hjk
QTextBlock block = document()->findBlockByLineNumber(line - 1);
QTC_ASSERT(block.isValid(), return source());
static QRegExp renameExp(QLatin1String("^" CHANGE_PATTERN "\\s+([^(]+)"));
static QRegExp renameExp("^" CHANGE_PATTERN "\\s+([^(]+)");
if (renameExp.indexIn(block.text()) != -1) {
const QString fileName = renameExp.cap(1).trimmed();
if (!fileName.isEmpty())
+17 -16
View File
@@ -94,7 +94,7 @@ public:
QString filePath = line.left(lineSeparator);
if (!m_ref.isEmpty() && filePath.startsWith(m_ref))
filePath.remove(0, m_ref.length());
single.fileName = m_directory + QLatin1Char('/') + filePath;
single.fileName = m_directory + '/' + filePath;
const int textSeparator = line.indexOf(QChar::Null, lineSeparator + 1);
single.lineNumber = line.mid(lineSeparator + 1, textSeparator - lineSeparator - 1).toInt();
QString text = line.mid(textSeparator + 1);
@@ -133,24 +133,25 @@ public:
void exec()
{
QStringList arguments;
arguments << QLatin1String("-c") << QLatin1String("color.grep.match=bold red")
<< QLatin1String("grep") << QLatin1String("-zn")
<< QLatin1String("--color=always");
arguments << "-c" << "color.grep.match=bold red"
<< "grep" << "-zn"
<< "--no-full-name"
<< "--color=always";
if (!(m_parameters.flags & FindCaseSensitively))
arguments << QLatin1String("-i");
arguments << "-i";
if (m_parameters.flags & FindWholeWords)
arguments << QLatin1String("-w");
arguments << "-w";
if (m_parameters.flags & FindRegularExpression)
arguments << QLatin1String("-P");
arguments << "-P";
else
arguments << QLatin1String("-F");
arguments << "-F";
arguments << m_parameters.text;
GitGrepParameters params = m_parameters.extensionParameters.value<GitGrepParameters>();
if (!params.ref.isEmpty()) {
arguments << params.ref;
m_ref = params.ref + QLatin1Char(':');
m_ref = params.ref + ':';
}
arguments << QLatin1String("--") << m_parameters.nameFilters;
arguments << "--" << m_parameters.nameFilters;
QScopedPointer<VcsCommand> command(GitPlugin::client()->createCommand(m_directory));
command->addFlags(VcsCommand::SilentOutput | VcsCommand::SuppressFailMessage);
command->setProgressiveOutput(true);
@@ -211,7 +212,7 @@ GitGrep::GitGrep()
m_treeLineEdit->setPlaceholderText(tr("Tree (optional)"));
m_treeLineEdit->setToolTip(tr("Can be HEAD, tag, local or remote branch, or a commit hash.\n"
"Leave empty to search through the file system."));
const QRegularExpression refExpression(QLatin1String("[\\S]*"));
const QRegularExpression refExpression("[\\S]*");
m_treeLineEdit->setValidator(new QRegularExpressionValidator(refExpression, this));
layout->addWidget(m_treeLineEdit);
TextEditor::FindInFiles *findInFiles = TextEditor::FindInFiles::instance();
@@ -266,14 +267,14 @@ QVariant GitGrep::parameters() const
void GitGrep::readSettings(QSettings *settings)
{
m_enabledCheckBox->setChecked(settings->value(QLatin1String(EnableGitGrep), false).toBool());
m_treeLineEdit->setText(settings->value(QLatin1String(GitGrepRef)).toString());
m_enabledCheckBox->setChecked(settings->value(EnableGitGrep, false).toBool());
m_treeLineEdit->setText(settings->value(GitGrepRef).toString());
}
void GitGrep::writeSettings(QSettings *settings) const
{
settings->setValue(QLatin1String(EnableGitGrep), m_enabledCheckBox->isChecked());
settings->setValue(QLatin1String(GitGrepRef), m_treeLineEdit->text());
settings->setValue(EnableGitGrep, m_enabledCheckBox->isChecked());
settings->setValue(GitGrepRef, m_treeLineEdit->text());
}
QFuture<FileSearchResultList> GitGrep::executeSearch(
@@ -292,7 +293,7 @@ IEditor *GitGrep::openEditor(const SearchResultItem &item,
QByteArray content;
const QString topLevel = parameters.additionalParameters.toString();
const QString relativePath = QDir(topLevel).relativeFilePath(path);
if (!GitPlugin::client()->synchronousShow(topLevel, params.ref + QLatin1String(":./") + relativePath,
if (!GitPlugin::client()->synchronousShow(topLevel, params.ref + ":./" + relativePath,
&content, nullptr)) {
return nullptr;
}
+10 -10
View File
@@ -42,8 +42,8 @@ GitSubmitHighlighter::GitSubmitHighlighter(QTextEdit * parent) :
categories << TextEditor::C_COMMENT;
setTextFormatCategories(categories);
m_keywordPattern.setPattern(QLatin1String("^[\\w-]+:"));
m_hashChar = QLatin1Char('#');
m_keywordPattern.setPattern("^[\\w-]+:");
m_hashChar = '#';
QTC_CHECK(m_keywordPattern.isValid());
}
@@ -95,8 +95,8 @@ GitRebaseHighlighter::RebaseAction::RebaseAction(const QString &regexp,
GitRebaseHighlighter::GitRebaseHighlighter(QTextDocument *parent) :
TextEditor::SyntaxHighlighter(parent),
m_hashChar(QLatin1Char('#')),
m_changeNumberPattern(QLatin1String(CHANGE_PATTERN))
m_hashChar('#'),
m_changeNumberPattern(CHANGE_PATTERN)
{
static QVector<TextEditor::TextStyle> categories;
if (categories.isEmpty()) {
@@ -112,12 +112,12 @@ GitRebaseHighlighter::GitRebaseHighlighter(QTextDocument *parent) :
}
setTextFormatCategories(categories);
m_actions << RebaseAction(QLatin1String("^(p|pick)\\b"), Format_Pick);
m_actions << RebaseAction(QLatin1String("^(r|reword)\\b"), Format_Reword);
m_actions << RebaseAction(QLatin1String("^(e|edit)\\b"), Format_Edit);
m_actions << RebaseAction(QLatin1String("^(s|squash)\\b"), Format_Squash);
m_actions << RebaseAction(QLatin1String("^(f|fixup)\\b"), Format_Fixup);
m_actions << RebaseAction(QLatin1String("^(x|exec)\\b"), Format_Exec);
m_actions << RebaseAction("^(p|pick)\\b", Format_Pick);
m_actions << RebaseAction("^(r|reword)\\b", Format_Reword);
m_actions << RebaseAction("^(e|edit)\\b", Format_Edit);
m_actions << RebaseAction("^(s|squash)\\b", Format_Squash);
m_actions << RebaseAction("^(f|fixup)\\b", Format_Fixup);
m_actions << RebaseAction("^(x|exec)\\b", Format_Exec);
}
void GitRebaseHighlighter::highlightBlock(const QString &text)
+21 -21
View File
@@ -294,7 +294,7 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
addAutoReleasedObject(new VcsSubmitEditorFactory(&submitParameters,
[]() { return new GitSubmitEditor(&submitParameters); }));
const QString prefix = QLatin1String("git");
const QString prefix = "git";
m_commandLocator = new CommandLocator("Git", prefix, prefix);
addAutoReleasedObject(m_commandLocator);
@@ -623,7 +623,7 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
connect(VcsManager::instance(), &VcsManager::repositoryChanged,
this, &GitPlugin::updateBranches, Qt::QueuedConnection);
Utils::MimeDatabase::addMimeTypes(QLatin1String(RC_GIT_MIME_XML));
Utils::MimeDatabase::addMimeTypes(RC_GIT_MIME_XML);
/* "Gerrit" */
m_gerritPlugin = new Gerrit::Internal::GerritPlugin(this);
@@ -718,7 +718,7 @@ void GitPlugin::logRepository()
void GitPlugin::undoFileChanges(bool revertStaging)
{
if (IDocument *document = EditorManager::currentDocument()) {
if (!DocumentManager::saveModifiedDocument(document))
if (!DocumentManager::saveModifiedDocumentSilently(document))
return;
}
const VcsBasePluginState state = currentState();
@@ -783,7 +783,7 @@ void GitPlugin::startRebase()
dialog.setWindowTitle(tr("Interactive Rebase"));
if (!dialog.runDialog(topLevel))
return;
if (m_gitClient->beginStashScope(topLevel, QLatin1String("Rebase-i")))
if (m_gitClient->beginStashScope(topLevel, "Rebase-i"))
m_gitClient->interactiveRebase(topLevel, dialog.commit(), false);
}
@@ -857,7 +857,7 @@ void GitPlugin::gitkForCurrentFolder()
/*
* entire lower part of the code can be easily replaced with one line:
*
* m_gitClient->launchGitK(dir.currentFileDirectory(), QLatin1String("."));
* m_gitClient->launchGitK(dir.currentFileDirectory(), ".");
*
* However, there is a bug in gitk in version 1.7.9.5, and if you run above
* command, there will be no documents listed in lower right section.
@@ -869,7 +869,7 @@ void GitPlugin::gitkForCurrentFolder()
*
*/
QDir dir(state.currentFileDirectory());
if (QFileInfo(dir,QLatin1String(".git")).exists() || dir.cd(QLatin1String(".git"))) {
if (QFileInfo(dir,".git").exists() || dir.cd(".git")) {
m_gitClient->launchGitK(state.currentFileDirectory());
} else {
QString folderName = dir.absolutePath();
@@ -1044,7 +1044,7 @@ bool GitPlugin::submitEditorAboutToClose()
return false;
cleanCommitMessageFile();
if (commitType == FixupCommit) {
if (!m_gitClient->beginStashScope(m_submitRepository, QLatin1String("Rebase-fixup"),
if (!m_gitClient->beginStashScope(m_submitRepository, "Rebase-fixup",
NoPrompt, editor->panelData().pushAction)) {
return false;
}
@@ -1077,13 +1077,13 @@ void GitPlugin::pull()
if (!rebase) {
QString currentBranch = m_gitClient->synchronousCurrentLocalBranch(topLevel);
if (!currentBranch.isEmpty()) {
currentBranch.prepend(QLatin1String("branch."));
currentBranch.append(QLatin1String(".rebase"));
rebase = (m_gitClient->readConfigValue(topLevel, currentBranch) == QLatin1String("true"));
currentBranch.prepend("branch.");
currentBranch.append(".rebase");
rebase = (m_gitClient->readConfigValue(topLevel, currentBranch) == "true");
}
}
if (!m_gitClient->beginStashScope(topLevel, QLatin1String("Pull"), rebase ? Default : AllowUnstashed))
if (!m_gitClient->beginStashScope(topLevel, "Pull", rebase ? Default : AllowUnstashed))
return;
m_gitClient->synchronousPull(topLevel, rebase);
}
@@ -1111,19 +1111,19 @@ void GitPlugin::continueOrAbortCommand()
QObject *action = QObject::sender();
if (action == m_abortMergeAction)
m_gitClient->synchronousMerge(state.topLevel(), QLatin1String("--abort"));
m_gitClient->synchronousMerge(state.topLevel(), "--abort");
else if (action == m_abortRebaseAction)
m_gitClient->rebase(state.topLevel(), QLatin1String("--abort"));
m_gitClient->rebase(state.topLevel(), "--abort");
else if (action == m_abortCherryPickAction)
m_gitClient->synchronousCherryPick(state.topLevel(), QLatin1String("--abort"));
m_gitClient->synchronousCherryPick(state.topLevel(), "--abort");
else if (action == m_abortRevertAction)
m_gitClient->synchronousRevert(state.topLevel(), QLatin1String("--abort"));
m_gitClient->synchronousRevert(state.topLevel(), "--abort");
else if (action == m_continueRebaseAction)
m_gitClient->rebase(state.topLevel(), QLatin1String("--continue"));
m_gitClient->rebase(state.topLevel(), "--continue");
else if (action == m_continueCherryPickAction)
m_gitClient->cherryPick(state.topLevel(), QLatin1String("--continue"));
m_gitClient->cherryPick(state.topLevel(), "--continue");
else if (action == m_continueRevertAction)
m_gitClient->revert(state.topLevel(), QLatin1String("--continue"));
m_gitClient->revert(state.topLevel(), "--continue");
updateContinueAndAbortCommands();
}
@@ -1201,7 +1201,7 @@ void GitPlugin::promptApplyPatch()
void GitPlugin::applyPatch(const QString &workingDirectory, QString file)
{
// Ensure user has been notified about pending changes
if (!m_gitClient->beginStashScope(workingDirectory, QLatin1String("Apply-Patch"), AllowUnstashed))
if (!m_gitClient->beginStashScope(workingDirectory, "Apply-Patch", AllowUnstashed))
return;
// Prompt for file
if (file.isEmpty()) {
@@ -1427,8 +1427,8 @@ void GitPlugin::testStatusParsing()
CommitData data;
QFETCH(FileStates, first);
QFETCH(FileStates, second);
QString output = QLatin1String("## master...origin/master [ahead 1]\n");
output += QString::fromLatin1(QTest::currentDataTag()) + QLatin1String(" main.cpp\n");
QString output = "## master...origin/master [ahead 1]\n";
output += QString::fromLatin1(QTest::currentDataTag()) + " main.cpp\n";
data.parseFilesFromStatus(output);
QCOMPARE(data.files.at(0).first, first);
if (second == UnknownFileState)
+2 -2
View File
@@ -48,9 +48,9 @@ const QLatin1String GitSettings::lastResetIndexKey("LastResetIndex");
GitSettings::GitSettings()
{
setSettingsGroup(QLatin1String("Git"));
setSettingsGroup("Git");
declareKey(binaryPathKey, QLatin1String("git"));
declareKey(binaryPathKey, "git");
declareKey(timeoutKey, Utils::HostOsInfo::isWindowsHost() ? 60 : 30);
declareKey(pullRebaseKey, false);
declareKey(showTagsKey, false);
+2 -2
View File
@@ -189,7 +189,7 @@ void GitSubmitEditor::slotDiffSelected(const QList<int> &rows)
unmergedFiles.push_back(fileName);
} else if (state & StagedFile) {
if (state & (RenamedFile | CopiedFile)) {
const int arrow = fileName.indexOf(QLatin1String(" -> "));
const int arrow = fileName.indexOf(" -> ");
if (arrow != -1) {
stagedFiles.push_back(fileName.left(arrow));
stagedFiles.push_back(fileName.mid(arrow + 4));
@@ -198,7 +198,7 @@ void GitSubmitEditor::slotDiffSelected(const QList<int> &rows)
}
stagedFiles.push_back(fileName);
} else if (state == UntrackedFile) {
Core::EditorManager::openEditor(m_workingDirectory + QLatin1Char('/') + fileName);
Core::EditorManager::openEditor(m_workingDirectory + '/' + fileName);
} else {
unstagedFiles.push_back(fileName);
}
+4 -4
View File
@@ -51,7 +51,7 @@ GitSubmitEditorWidget::GitSubmitEditorWidget() :
m_gitSubmitPanelUi.setupUi(m_gitSubmitPanel);
new GitSubmitHighlighter(descriptionEdit());
m_emailValidator = new QRegExpValidator(QRegExp(QLatin1String("[^@ ]+@[^@ ]+\\.[a-zA-Z]+")), this);
m_emailValidator = new QRegExpValidator(QRegExp("[^@ ]+@[^@ ]+\\.[a-zA-Z]+"), this);
const QPixmap error = Core::Icons::ERROR.pixmap();
m_gitSubmitPanelUi.invalidAuthorLabel->setPixmap(error);
m_gitSubmitPanelUi.invalidEmailLabel->setToolTip(tr("Provide a valid email to commit."));
@@ -66,7 +66,7 @@ GitSubmitEditorWidget::GitSubmitEditorWidget() :
void GitSubmitEditorWidget::setPanelInfo(const GitSubmitEditorPanelInfo &info)
{
m_gitSubmitPanelUi.repositoryLabel->setText(QDir::toNativeSeparators(info.repository));
if (info.branch.contains(QLatin1String("(no branch)")))
if (info.branch.contains("(no branch)"))
m_gitSubmitPanelUi.branchLabel->setText(QString::fromLatin1("<span style=\"color:red\">%1</span>")
.arg(tr("Detached HEAD")));
else
@@ -163,8 +163,8 @@ QString GitSubmitEditorWidget::cleanupDescription(const QString &input) const
{
// We need to manually purge out comment lines starting with
// hash '#' since git does not do that when using -F.
const QChar newLine = QLatin1Char('\n');
const QChar hash = QLatin1Char('#');
const QChar newLine = '\n';
const QChar hash = '#';
QString message = input;
for (int pos = 0; pos < message.size(); ) {
const int newLinePos = message.indexOf(newLine, pos);
+2 -2
View File
@@ -47,7 +47,7 @@ stash@{2}: On <branch>: <message>
bool Stash::parseStashLine(const QString &l)
{
const QChar colon = QLatin1Char(':');
const QChar colon = ':';
const int branchPos = l.indexOf(colon);
if (branchPos < 0)
return false;
@@ -55,7 +55,7 @@ bool Stash::parseStashLine(const QString &l)
if (messagePos < 0)
return false;
// Branch spec
const int onIndex = l.indexOf(QLatin1String("on "), branchPos + 2, Qt::CaseInsensitive);
const int onIndex = l.indexOf("on ", branchPos + 2, Qt::CaseInsensitive);
if (onIndex == -1 || onIndex >= messagePos)
return false;
// Happy!
+5 -4
View File
@@ -47,7 +47,7 @@ protected:
QString trackFile(const QString &repository) override
{
const QString gitDir = m_client->findGitDirForRepository(repository);
return gitDir.isEmpty() ? QString() : (gitDir + QLatin1String("/HEAD"));
return gitDir.isEmpty() ? QString() : (gitDir + "/HEAD");
}
QString refreshTopic(const QString &repository) override
@@ -131,7 +131,7 @@ QString GitVersionControl::vcsTopic(const QString &directory)
QString topic = Core::IVersionControl::vcsTopic(directory);
const QString commandInProgress = m_client->commandInProgressDescription(directory);
if (!commandInProgress.isEmpty())
topic += QLatin1String(" (") + commandInProgress + QLatin1Char(')');
topic += " (" + commandInProgress + ')';
return topic;
}
@@ -140,10 +140,11 @@ Core::ShellCommand *GitVersionControl::createInitialCheckoutCommand(const QStrin
const QString &localName,
const QStringList &extraArgs)
{
QStringList args;
args << QLatin1String("clone") << QLatin1String("--progress") << extraArgs << url << localName;
QStringList args = { "clone", "--progress" };
args << extraArgs << url << localName;
auto command = new VcsBase::VcsCommand(baseDirectory.toString(), m_client->processEnvironment());
command->addFlags(VcsBase::VcsCommand::SuppressStdErr);
command->addJob(m_client->vcsBinary(), args, -1);
return command;
}

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