本文整理汇总了C++中QStack类的典型用法代码示例。如果您正苦于以下问题:C++ QStack类的具体用法?C++ QStack怎么用?C++ QStack使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QStack类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: toXserverRegion
//.........这里部分代码省略.........
case 1:
renderformats[ 1 ] = XRenderFindStandardFormat(display(), PictStandardA1);
break;
case 8:
renderformats[ 8 ] = XRenderFindStandardFormat(display(), PictStandardA8);
break;
case 24:
renderformats[ 24 ] = XRenderFindStandardFormat(display(), PictStandardRGB24);
break;
case 32:
renderformats[ 32 ] = XRenderFindStandardFormat(display(), PictStandardARGB32);
break;
default: {
XRenderPictFormat req;
long mask = PictFormatType | PictFormatDepth;
req.type = PictTypeDirect;
req.depth = depth;
renderformats[ depth ] = XRenderFindFormat(display(), mask, &req, 0);
break;
}
}
if (renderformats[ depth ] == NULL) {
kWarning(1212) << "Could not find XRender format for depth" << depth;
return None;
}
}
return XRenderCreatePicture(display(), pix, renderformats[ depth ], 0, NULL);
}
XRenderPicture::XRenderPicture(QPixmap pix)
{
if (Extensions::nonNativePixmaps()) {
Pixmap xPix = XCreatePixmap(display(), rootWindow(), pix.width(), pix.height(), pix.depth());
QPixmap tempPix = QPixmap::fromX11Pixmap(xPix, QPixmap::ExplicitlyShared);
tempPix.fill(Qt::transparent);
QPainter p(&tempPix);
p.drawPixmap(QPoint(0, 0), pix);
p.end();
d = new XRenderPictureData(createPicture(tempPix.handle(), tempPix.depth()));
XFreePixmap(display(), xPix);
} else {
d = new XRenderPictureData(createPicture(pix.handle(), pix.depth()));
}
}
XRenderPicture::XRenderPicture(Pixmap pix, int depth)
: d(new XRenderPictureData(createPicture(pix, depth)))
{
}
static QPixmap *s_offscreenTarget = 0;
static QStack<XRenderPicture*> s_scene_offscreenTargetStack;
static int s_renderOffscreen = 0;
void scene_setXRenderOffscreenTarget(QPixmap *pix)
{
s_offscreenTarget = pix;
}
XRenderPicture *scene_xRenderOffscreenTarget()
{
return s_scene_offscreenTargetStack.isEmpty() ? 0 : s_scene_offscreenTargetStack.top();
}
void setXRenderOffscreen(bool b)
{
b ? ++s_renderOffscreen : --s_renderOffscreen;
if (s_renderOffscreen < 0) {
s_renderOffscreen = 0;
qWarning("*** SOMETHING IS MESSED UP WITH YOUR setXRenderOffscreen() USAGE ***");
}
}
void xRenderPushTarget(XRenderPicture *pic)
{
s_scene_offscreenTargetStack.push(pic);
++s_renderOffscreen;
}
void xRenderPopTarget()
{
s_scene_offscreenTargetStack.pop();
--s_renderOffscreen;
if (s_renderOffscreen < 0) {
s_renderOffscreen = 0;
qWarning("*** SOMETHING IS MESSED UP WITH YOUR xRenderPopTarget() USAGE ***");
}
}
bool xRenderOffscreen()
{
return s_renderOffscreen;
}
QPixmap *xRenderOffscreenTarget()
{
return s_offscreenTarget;
}
} // namespace
示例2: text
void FlatTextarea::parseLinks() { // some code is duplicated in text.cpp!
LinkRanges newLinks;
QString text(toPlainText());
if (text.isEmpty()) {
if (!_links.isEmpty()) {
_links.clear();
emit linksChanged();
}
return;
}
initLinkSets();
int32 len = text.size();
const QChar *start = text.unicode(), *end = start + text.size();
for (int32 offset = 0, matchOffset = offset; offset < len;) {
QRegularExpressionMatch m = reDomain().match(text, matchOffset);
if (!m.hasMatch()) break;
int32 domainOffset = m.capturedStart();
QString protocol = m.captured(1).toLower();
QString topDomain = m.captured(3).toLower();
bool isProtocolValid = protocol.isEmpty() || validProtocols().contains(hashCrc32(protocol.constData(), protocol.size() * sizeof(QChar)));
bool isTopDomainValid = !protocol.isEmpty() || validTopDomains().contains(hashCrc32(topDomain.constData(), topDomain.size() * sizeof(QChar)));
if (protocol.isEmpty() && domainOffset > offset + 1 && *(start + domainOffset - 1) == QChar('@')) {
QString forMailName = text.mid(offset, domainOffset - offset - 1);
QRegularExpressionMatch mMailName = reMailName().match(forMailName);
if (mMailName.hasMatch()) {
offset = matchOffset = m.capturedEnd();
continue;
}
}
if (!isProtocolValid || !isTopDomainValid) {
offset = matchOffset = m.capturedEnd();
continue;
}
QStack<const QChar*> parenth;
const QChar *domainEnd = start + m.capturedEnd(), *p = domainEnd;
for (; p < end; ++p) {
QChar ch(*p);
if (chIsLinkEnd(ch)) break; // link finished
if (chIsAlmostLinkEnd(ch)) {
const QChar *endTest = p + 1;
while (endTest < end && chIsAlmostLinkEnd(*endTest)) {
++endTest;
}
if (endTest >= end || chIsLinkEnd(*endTest)) {
break; // link finished at p
}
p = endTest;
ch = *p;
}
if (ch == '(' || ch == '[' || ch == '{' || ch == '<') {
parenth.push(p);
} else if (ch == ')' || ch == ']' || ch == '}' || ch == '>') {
if (parenth.isEmpty()) break;
const QChar *q = parenth.pop(), open(*q);
if ((ch == ')' && open != '(') || (ch == ']' && open != '[') || (ch == '}' && open != '{') || (ch == '>' && open != '<')) {
p = q;
break;
}
}
}
if (p > domainEnd) { // check, that domain ended
if (domainEnd->unicode() != '/' && domainEnd->unicode() != '?') {
matchOffset = domainEnd - start;
continue;
}
}
newLinks.push_back(qMakePair(domainOffset - 1, p - start - domainOffset + 2));
offset = matchOffset = p - start;
}
if (newLinks != _links) {
_links = newLinks;
emit linksChanged();
}
}
示例3: emptyRe
void EditStringCell::setPreviewText()
{
ui.stringPreview->clear();
// text is white by default + stupid HTML with its newlines and spaces
QString text = colorStrings.at(1) + ui.stringEdit->toPlainText().replace('<', "<").replace('>', ">").replace('\n', "<br>");
int emptyMatchIndex;
QRegExp emptyRe(" {2,}");
while ((emptyMatchIndex = emptyRe.indexIn(text)) != -1)
{
int matchedLength = emptyRe.matchedLength();
text.replace(emptyMatchIndex, matchedLength, QString(" ").repeated(matchedLength));
}
if (ui.reversePreviewTextCheckBox->isChecked())
{
QList<QPair<int, int> > colorStringsIndeces; // <index_of_color_string_in_array, position_in_string>
for (int i = 0; i < colors.size(); i++)
{
QString colorString = colorStrings.at(i + 1);
int occurencesCount = text.count(colorString), position = 0, length = colorString.length();
for (int j = 0; j < occurencesCount; j++, position += length)
{
position = text.indexOf(colorString, position);
colorStringsIndeces.append(qMakePair(i + 1, position));
}
}
// sort colorStringsIndeces by position in ascending order
qSort(colorStringsIndeces.begin(), colorStringsIndeces.end(), colorStringsIndecesLessThan);
QStack<QString> colorStringsStack;
for (int i = 0, colorsNumberInString = colorStringsIndeces.size(); i < colorsNumberInString; i++)
{
int index = colorStringsIndeces.at(i).first;
int position = colorStringsIndeces.at(i).second + colorStrings.at(index).length(); // skip colorString
QString coloredText = text.mid(position, i != colorsNumberInString - 1 ? colorStringsIndeces.at(i + 1).second - position : -1);
QStringList lines = coloredText.split("<br>");
std::reverse(lines.begin(), lines.end());
QString reversedText = lines.join("<br>");
if (!reversedText.isEmpty())
colorStringsStack.push(QString("<font color = \"%1\">%2</font>").arg(colorHexString(colors.at(index - 1)), reversedText));
}
// empty the stack
while (!colorStringsStack.isEmpty())
ui.stringPreview->insertHtml(colorStringsStack.pop());
}
else
{
for (int i = 0; i < colors.size(); i++) // replace color codes with their hex values for HTML
text.replace(colorStrings.at(i + 1), QString("</font><font color = \"%1\">").arg(colorHexString(colors.at(i))));
ui.stringPreview->setHtml(text);
}
int length = ui.stringPreview->toPlainText().length();
ui.charsPreviewCountLabel->setText(QString::number(length));
// show warning only once
static bool showWarning = true;
if (showWarning)
{
showWarning = false;
const int kMaxLengthPatch110 = 255;
if (length > kMaxLengthPatch110)
emit maxLengthExceededFor110(tr("Patch 1.10 has limitation of %1 characters per string").arg(kMaxLengthPatch110));
}
}
示例4: Q_ASSERT
void OwncloudPropagator::start(const SyncFileItemVector& items)
{
Q_ASSERT(std::is_sorted(items.begin(), items.end()));
/* Check and log the transmission checksum type */
ConfigFile cfg;
const QString checksumType = cfg.transmissionChecksum();
/* if the checksum type is empty, it is not sent. No error */
if( !checksumType.isEmpty() ) {
if( checksumType == checkSumAdlerC ||
checksumType == checkSumMD5C ||
checksumType == checkSumSHA1C ) {
qDebug() << "Client sends transmission checksum type" << checksumType;
} else {
qWarning() << "Unknown transmission checksum type from config" << checksumType;
}
}
/* This builds all the jobs needed for the propagation.
* Each directory is a PropagateDirectory job, which contains the files in it.
* In order to do that we loop over the items. (which are sorted by destination)
* When we enter a directory, we can create the directory job and push it on the stack. */
_rootJob.reset(new PropagateDirectory(this));
QStack<QPair<QString /* directory name */, PropagateDirectory* /* job */> > directories;
directories.push(qMakePair(QString(), _rootJob.data()));
QVector<PropagatorJob*> directoriesToRemove;
QString removedDirectory;
foreach(const SyncFileItemPtr &item, items) {
if (!removedDirectory.isEmpty() && item->_file.startsWith(removedDirectory)) {
// this is an item in a directory which is going to be removed.
PropagateDirectory *delDirJob = dynamic_cast<PropagateDirectory*>(directoriesToRemove.last());
if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
// already taken care of. (by the removal of the parent directory)
// increase the number of subjobs that would be there.
if( delDirJob ) {
delDirJob->increaseAffectedCount();
}
continue;
} else if (item->_instruction == CSYNC_INSTRUCTION_NEW && item->_isDirectory) {
// create a new directory within a deleted directory? That can happen if the directory
// etag was not fetched properly on the previous sync because the sync was aborted
// while uploading this directory (which is now removed). We can ignore it.
if( delDirJob ) {
delDirJob->increaseAffectedCount();
}
continue;
} else if (item->_instruction == CSYNC_INSTRUCTION_IGNORE) {
continue;
}
qWarning() << "WARNING: Job within a removed directory? This should not happen!"
<< item->_file << item->_instruction;
}
while (!item->destination().startsWith(directories.top().first)) {
directories.pop();
}
if (item->_isDirectory) {
PropagateDirectory *dir = new PropagateDirectory(this, item);
dir->_firstJob.reset(createJob(item));
if (item->_instruction == CSYNC_INSTRUCTION_REMOVE) {
// We do the removal of directories at the end, because there might be moves from
// these directories that will happen later.
directoriesToRemove.append(dir);
removedDirectory = item->_file + "/";
// We should not update the etag of parent directories of the removed directory
// since it would be done before the actual remove (issue #1845)
// NOTE: Currently this means that we don't update those etag at all in this sync,
// but it should not be a problem, they will be updated in the next sync.
for (int i = 0; i < directories.size(); ++i) {
directories[i].second->_item->_should_update_metadata = false;
}
} else {
PropagateDirectory* currentDirJob = directories.top().second;
currentDirJob->append(dir);
}
directories.push(qMakePair(item->destination() + "/" , dir));
} else if (PropagateItemJob* current = createJob(item)) {
directories.top().second->append(current);
}
}
foreach(PropagatorJob* it, directoriesToRemove) {
_rootJob->append(it);
}
示例5: xmlReader
bool OsmAnd::RoutingConfiguration::parseConfiguration( QIODevice* data, RoutingConfiguration& outConfig )
{
QXmlStreamReader xmlReader(data);
std::shared_ptr<RoutingProfile> routingProfile;
auto rulesetType = RoutingRuleset::Type::Invalid;
QStack< std::shared_ptr<RoutingRule> > ruleset;
while (!xmlReader.atEnd() && !xmlReader.hasError())
{
xmlReader.readNext();
const auto tagName = xmlReader.name();
if (xmlReader.isStartElement())
{
if (tagName == "osmand_routing_config")
{
outConfig._defaultRoutingProfileName = xmlReader.attributes().value("defaultProfile").toString();
}
else if (tagName == "routingProfile")
{
routingProfile.reset(new RoutingProfile());
parseRoutingProfile(&xmlReader, routingProfile.get());
if(routingProfile->_name == outConfig._defaultRoutingProfileName)
outConfig._defaultRoutingProfile = routingProfile;
outConfig._routingProfiles.insert(routingProfile->_name, routingProfile);
}
else if (tagName == "attribute")
{
auto name = xmlReader.attributes().value("name").toString();
auto value = xmlReader.attributes().value("value").toString();
if(routingProfile)
routingProfile->addAttribute(name, value);
else
outConfig._attributes.insert(name, value);
}
else if (tagName == "parameter")
{
if(!routingProfile)
{
LogPrintf(LogSeverityLevel::Warning, "<parameter> is not inside <routingProfile> (%d, %d)", xmlReader.lineNumber(), xmlReader.columnNumber());
return false;
}
parseRoutingParameter(&xmlReader, routingProfile.get());
}
else if (tagName == "point" || tagName == "way")
{
assert(rulesetType == RoutingRuleset::Type::Invalid);
auto attributeName = xmlReader.attributes().value("attribute");
if (attributeName == "priority")
rulesetType = RoutingRuleset::Type::RoadPriorities;
else if (attributeName == "speed")
rulesetType = RoutingRuleset::Type::RoadSpeed;
else if (attributeName == "access")
rulesetType = RoutingRuleset::Type::Access;
else if (attributeName == "obstacle_time")
rulesetType = RoutingRuleset::Type::Obstacles;
else if (attributeName == "obstacle")
rulesetType = RoutingRuleset::Type::RoutingObstacles;
else if (attributeName == "oneway")
rulesetType = RoutingRuleset::Type::OneWay;
OSMAND_ASSERT(rulesetType != RoutingRuleset::Type::Invalid, QString("Route data object attribute '%1' is unknown").arg(attributeName.toString()));
}
else if(rulesetType != RoutingRuleset::Type::Invalid)
{
if(isConditionTag(tagName))
parseRoutingRuleset(&xmlReader, routingProfile.get(), rulesetType, ruleset);
}
}
else if (xmlReader.isEndElement())
{
if(tagName == "routingProfile")
{
routingProfile.reset();
}
else if (tagName == "point" || tagName == "way")
{
rulesetType = RoutingRuleset::Type::Invalid;
}
else if(isConditionTag(tagName))
{
ruleset.pop();
}
}
}
if(xmlReader.hasError())
{
LogPrintf(LogSeverityLevel::Warning, "XML error: %s (%d, %d)", qPrintable(xmlReader.errorString()), xmlReader.lineNumber(), xmlReader.columnNumber());
return false;
}
return true;
}
示例6: fromPage
// Print a range of lines to a printer.
int QsciPrinter::printRange(QsciScintillaBase *qsb, int from, int to)
{
// Sanity check.
if (!qsb)
return false;
// Setup the printing area.
QRect def_area;
def_area.setX(0);
def_area.setY(0);
def_area.setWidth(width());
def_area.setHeight(height());
// Get the page range.
int pgFrom, pgTo;
pgFrom = fromPage();
pgTo = toPage();
// Find the position range.
long startPos, endPos;
endPos = qsb->SendScintilla(QsciScintillaBase::SCI_GETLENGTH);
startPos = (from > 0 ? qsb -> SendScintilla(QsciScintillaBase::SCI_POSITIONFROMLINE,from) : 0);
if (to >= 0)
{
long toPos = qsb -> SendScintilla(QsciScintillaBase::SCI_POSITIONFROMLINE,to + 1);
if (endPos > toPos)
endPos = toPos;
}
if (startPos >= endPos)
return false;
QPainter painter(this);
bool reverse = (pageOrder() == LastPageFirst);
bool needNewPage = false;
qsb -> SendScintilla(QsciScintillaBase::SCI_SETPRINTMAGNIFICATION,mag);
qsb -> SendScintilla(QsciScintillaBase::SCI_SETPRINTWRAPMODE,wrap);
for (int i = 1; i <= numCopies(); ++i)
{
// If we are printing in reverse page order then remember the start
// position of each page.
QStack<long> pageStarts;
int currPage = 1;
long pos = startPos;
while (pos < endPos)
{
// See if we have finished the requested page range.
if (pgTo > 0 && pgTo < currPage)
break;
// See if we are going to render this page, or just see how much
// would fit onto it.
bool render = false;
if (pgFrom == 0 || pgFrom <= currPage)
{
if (reverse)
pageStarts.push(pos);
else
{
render = true;
if (needNewPage)
{
if (!newPage())
return false;
}
else
needNewPage = true;
}
}
QRect area = def_area;
formatPage(painter,render,area,currPage);
pos = qsb -> SendScintilla(QsciScintillaBase::SCI_FORMATRANGE,render,&painter,area,pos,endPos);
++currPage;
}
// All done if we are printing in normal page order.
if (!reverse)
continue;
// Now go through each page on the stack and really print it.
while (!pageStarts.isEmpty())
{
--currPage;
//.........这里部分代码省略.........
示例7: fileInfo
Profile::Ptr ProfileManager::loadProfile(const QString& shortPath)
{
// the fallback profile has a 'special' path name, "FALLBACK/"
if (shortPath == _fallbackProfile->path())
return _fallbackProfile;
QString path = shortPath;
// add a suggested suffix and relative prefix if missing
QFileInfo fileInfo(path);
if (fileInfo.isDir())
return Profile::Ptr();
if (fileInfo.suffix() != QLatin1String("profile"))
path.append(".profile");
if (fileInfo.path().isEmpty() || fileInfo.path() == QLatin1String("."))
path.prepend(QLatin1String("konsole") + QDir::separator());
// if the file is not an absolute path, look it up
if (!fileInfo.isAbsolute())
path = QStandardPaths::locate(QStandardPaths::GenericDataLocation, path);
// if the file is not found, return immediately
if (path.isEmpty()) {
return Profile::Ptr();
}
// check that we have not already loaded this profile
foreach(const Profile::Ptr& profile, _profiles) {
if (profile->path() == path)
return profile;
}
// guard to prevent problems if a profile specifies itself as its parent
// or if there is recursion in the "inheritance" chain
// (eg. two profiles, A and B, specifying each other as their parents)
static QStack<QString> recursionGuard;
PopStackOnExit<QString> popGuardOnExit(recursionGuard);
if (recursionGuard.contains(path)) {
qWarning() << "Ignoring attempt to load profile recursively from" << path;
return _fallbackProfile;
} else {
recursionGuard.push(path);
}
// load the profile
ProfileReader* reader = new KDE4ProfileReader;
Profile::Ptr newProfile = Profile::Ptr(new Profile(fallbackProfile()));
newProfile->setProperty(Profile::Path, path);
QString parentProfilePath;
bool result = reader->readProfile(path, newProfile, parentProfilePath);
if (!parentProfilePath.isEmpty()) {
Profile::Ptr parentProfile = loadProfile(parentProfilePath);
newProfile->setParent(parentProfile);
}
delete reader;
if (!result) {
qWarning() << "Could not load profile from " << path;
return Profile::Ptr();
} else {
addProfile(newProfile);
return newProfile;
}
}
示例8: QStringList
void MessageLinksParser::parse() {
const auto &textWithTags = _field->getTextWithTags();
const auto &text = textWithTags.text;
const auto &tags = textWithTags.tags;
const auto &markdownTags = _field->getMarkdownTags();
if (text.isEmpty()) {
_list = QStringList();
return;
}
auto ranges = QVector<LinkRange>();
auto tag = tags.begin();
const auto tagsEnd = tags.end();
const auto processTag = [&] {
Expects(tag != tagsEnd);
if (Ui::InputField::IsValidMarkdownLink(tag->id)
&& !IsMentionLink(tag->id)) {
ranges.push_back({ tag->offset, tag->length, tag->id });
}
++tag;
};
const auto processTagsBefore = [&](int offset) {
while (tag != tagsEnd && tag->offset + tag->length <= offset) {
processTag();
}
};
const auto hasTagsIntersection = [&](int till) {
if (tag == tagsEnd || tag->offset >= till) {
return false;
}
while (tag != tagsEnd && tag->offset < till) {
processTag();
}
return true;
};
auto markdownTag = markdownTags.begin();
const auto markdownTagsEnd = markdownTags.end();
const auto markdownTagsAllow = [&](int from, int length) {
while (markdownTag != markdownTagsEnd
&& (markdownTag->adjustedStart
+ markdownTag->adjustedLength <= from
|| !markdownTag->closed)) {
++markdownTag;
continue;
}
if (markdownTag == markdownTagsEnd
|| markdownTag->adjustedStart >= from + length) {
return true;
}
// Ignore http-links that are completely inside some tags.
// This will allow sending http://test.com/__test__/test correctly.
return (markdownTag->adjustedStart > from)
|| (markdownTag->adjustedStart
+ markdownTag->adjustedLength < from + length);
};
const auto len = text.size();
const QChar *start = text.unicode(), *end = start + text.size();
for (auto offset = 0, matchOffset = offset; offset < len;) {
auto m = TextUtilities::RegExpDomain().match(text, matchOffset);
if (!m.hasMatch()) break;
auto domainOffset = m.capturedStart();
auto protocol = m.captured(1).toLower();
auto topDomain = m.captured(3).toLower();
auto isProtocolValid = protocol.isEmpty() || TextUtilities::IsValidProtocol(protocol);
auto isTopDomainValid = !protocol.isEmpty() || TextUtilities::IsValidTopDomain(topDomain);
if (protocol.isEmpty() && domainOffset > offset + 1 && *(start + domainOffset - 1) == QChar('@')) {
auto forMailName = text.mid(offset, domainOffset - offset - 1);
auto mMailName = TextUtilities::RegExpMailNameAtEnd().match(forMailName);
if (mMailName.hasMatch()) {
offset = matchOffset = m.capturedEnd();
continue;
}
}
if (!isProtocolValid || !isTopDomainValid) {
offset = matchOffset = m.capturedEnd();
continue;
}
QStack<const QChar*> parenth;
const QChar *domainEnd = start + m.capturedEnd(), *p = domainEnd;
for (; p < end; ++p) {
QChar ch(*p);
if (chIsLinkEnd(ch)) break; // link finished
if (chIsAlmostLinkEnd(ch)) {
const QChar *endTest = p + 1;
while (endTest < end && chIsAlmostLinkEnd(*endTest)) {
++endTest;
}
if (endTest >= end || chIsLinkEnd(*endTest)) {
break; // link finished at p
}
p = endTest;
ch = *p;
//.........这里部分代码省略.........
示例9: while
void Highlighter::iterateThroughRules(const QString &text,
const int length,
ProgressData *progress,
const bool childRule,
const QList<QSharedPointer<Rule> > &rules)
{
typedef QList<QSharedPointer<Rule> >::const_iterator RuleIterator;
bool contextChanged = false;
bool atLeastOneMatch = false;
RuleIterator it = rules.begin();
RuleIterator endIt = rules.end();
bool detlaDeptn = false;
while (it != endIt && progress->offset() < length) {
int startOffset = progress->offset();
const QSharedPointer<Rule> &rule = *it;
if (rule->itemData() == "String" ||
rule->itemData() == "Comment") {
m_stringOrComment = true;
} else {
m_stringOrComment = false;
}
if (rule->matchSucceed(text, length, progress)) {
atLeastOneMatch = true;
if (!m_stringOrComment) {
if (!rule->beginRegion().isEmpty()) {
QChar ch = text.at(startOffset);
if (ch == '{' || ch == '(' || ch == '[' ) {
blockData(currentBlockUserData())->appendParenthese(Parenthesis(Parenthesis::Opened,ch,startOffset));
}
}
if (!rule->endRegion().isEmpty()) {
QChar ch = text.at(startOffset);
if (ch == '}' || ch == ')' || ch == ']' ) {
blockData(currentBlockUserData())->appendParenthese(Parenthesis(Parenthesis::Closed,ch,startOffset));
}
}
}
if (!m_indentationBasedFolding) {
if (!rule->endRegion().isEmpty()) {
QStack<QString> *currentRegions =
&blockData(currentBlockUserData())->m_foldingRegions;
if (!currentRegions->isEmpty() && rule->endRegion() == currentRegions->top()) {
currentRegions->pop();
--m_regionDepth;
if (m_lastRegionDepth > m_regionDepth) {
detlaDeptn = true;
}
if (!m_stringOrComment && progress->isClosingBraceMatchAtNonEnd()) {
--blockData(currentBlockUserData())->m_foldingIndentDelta;
}
}
}
if (!rule->beginRegion().isEmpty()) {
blockData(currentBlockUserData())->m_foldingRegions.push(rule->beginRegion());
++m_regionDepth;
if (!m_stringOrComment && progress->isOpeningBraceMatchAtFirstNonSpace()) {
++blockData(currentBlockUserData())->m_foldingIndentDelta;
}
}
progress->clearBracesMatches();
}
if (progress->isWillContinueLine()) {
createWillContinueBlock();
progress->setWillContinueLine(false);
} else {
if (rule->hasChildren())
iterateThroughRules(text, length, progress, true, rule->children());
if (!rule->context().isEmpty() && contextChangeRequired(rule->context())) {
m_currentCaptures = progress->captures();
changeContext(rule->context(), rule->definition());
contextChanged = true;
}
}
// Format is not applied to child rules directly (but relative to the offset of their
// parent) nor to look ahead rules.
if (!childRule && !rule->isLookAhead()) {
if (rule->itemData().isEmpty())
applyFormat(startOffset, progress->offset() - startOffset,
m_currentContext->itemData(), m_currentContext->definition());
else
applyFormat(startOffset, progress->offset() - startOffset, rule->itemData(),
rule->definition());
}
// When there is a match of one child rule the others should be skipped. Otherwise
// the highlighting would be incorret in a case like 9ULLLULLLUULLULLUL, for example.
if (contextChanged || childRule) {
break;
} else {
it = rules.begin();
continue;
}
//.........这里部分代码省略.........
示例10: cursor
void ScCodeEditor::indent( const QTextCursor & selection, EditBlockMode editBlockMode )
{
if (selection.isNull())
return;
QTextCursor cursor(selection);
if (editBlockMode == NewEditBlock)
cursor.beginEditBlock();
else
cursor.joinPreviousEditBlock();
QTextDocument *doc = QPlainTextEdit::document();
int startBlockNum = doc->findBlock(cursor.selectionStart()).blockNumber();
int endBlockNum = cursor.hasSelection() ?
doc->findBlock(cursor.selectionEnd()).blockNumber() : startBlockNum;
QStack<int> stack;
int global_level = 0;
int blockNum = 0;
bool in_string = false;
QTextBlock block = QPlainTextEdit::document()->begin();
while (block.isValid())
{
int initialStackSize = stack.size();
int level = 0;
bool block_start_in_string = in_string;
TextBlockData *data = static_cast<TextBlockData*>(block.userData());
if (data)
{
int count = data->tokens.size();
for (int idx = 0; idx < count; ++idx)
{
const Token & token = data->tokens[idx];
switch (token.type)
{
case Token::OpeningBracket:
if (token.character != '(' || stack.size() || token.positionInBlock)
++level;
break;
case Token::ClosingBracket:
if (level)
--level;
else if (global_level) {
--global_level;
if (!stack.isEmpty() && global_level < stack.top())
stack.pop();
}
break;
case Token::StringMark:
in_string = !in_string;
break;
default:
break;
}
}
}
if(blockNum >= startBlockNum) {
int indentLevel;
if (data && data->tokens.size() && data->tokens[0].type == Token::ClosingBracket)
indentLevel = stack.size();
else if (!block_start_in_string)
indentLevel = initialStackSize;
else
indentLevel = 0;
block = indent(block, indentLevel);
}
if(blockNum == endBlockNum)
break;
block = block.next();
++blockNum;
if (level) {
global_level += level;
stack.push(global_level);
}
}
cursor.endEditBlock();
}
示例11: source
void RecursiveDirJobHelper::recursiveCpDir(const QString & sourcePath, const QString & destPath,
RecursiveDirJob::CopyOptions options)
{
QDir source(sourcePath);
if ( !source.exists() ) {
emit errorOccured(Error(Error::NoSuchFileOrDirectory, sourcePath));
return;
}
QDir dest(destPath);
if ( dest.exists() ) {
if ( options & RecursiveDirJob::RemoveDestination ) {
//in case the destination is a symlink to another directory, we remove first
//the symlink target (returned by dest.canonicalPath()) and then the symlink itself.
recursiveRmDir(dest.canonicalPath());
if ( QFileInfo(destPath).isSymLink() ) {
QFile::remove(destPath);
}
} else if ( !(options & RecursiveDirJob::OverWrite) ) {
emit errorOccured(Error(Error::FileOrDirectoryExists, destPath));
return;
}
}
if ( dest.mkdir(dest.absolutePath()) ) {
QFile::setPermissions(destPath, QFile::permissions(sourcePath));
}
QFileInfoList currentList = source.entryInfoList(dirFilters);
QFileInfo currentItem;
QStack<QFileInfoList> stack;
QString currentName;
quint64 bytesCopied = 0;
if ( m_reportProgress ) {
quint64 dirSize = calculateDirSize(sourcePath);
emit setLabelText(tr("Copying files from \"%1\" to \"%2\"...").arg(sourcePath).arg(destPath));
if (dirSize > 0) {
emit setMaximum(dirSize);
//the directory special file is already (almost) copied in dest.mkdir() above
bytesCopied += stat_size(sourcePath);
emit setValue(bytesCopied);
} else {
//no files to be copied, so set the progressbar to 100%
emit setMaximum(1);
emit setValue(1);
}
}
while(1)
{
if ( !currentList.isEmpty() )
{
currentItem = currentList.takeFirst();
currentName = currentItem.fileName();
if ( currentItem.isSymLink() )
{
if ( options & RecursiveDirJob::OverWrite ) {
if ( !QFile::remove(dest.absoluteFilePath(currentName)) )
emit errorOccured(Error(Error::RmFail, dest.absoluteFilePath(currentName)));
}
if ( !QFile::link( DirOperations::relativeSymLinkTarget(source.absoluteFilePath(currentName)),
dest.absoluteFilePath(currentName) ) )
emit errorOccured(Error(Error::CopyFail, source.absoluteFilePath(currentName)));
}
else if ( currentItem.isDir() )
{
bool ok = false;
QFile::Permissions sourcePermissions = QFile::permissions(source.absoluteFilePath(currentName));
if ( !(ok = source.cd(currentName)) ) {
emit errorOccured(Error(Error::AccessDenied, source.absoluteFilePath(currentName)));
}
if ( ok && !dest.cd(currentName) ) {
//if the target dir doesn't exist, create it and try again.
if ( !dest.mkdir(currentName) ) {
emit errorOccured(Error(Error::MkdirFail, dest.absoluteFilePath(currentName)));
}
//preserve permissions of the directory
QFile::setPermissions(dest.absoluteFilePath(currentName), sourcePermissions);
if ( !dest.cd(currentName) ) {
//quite impossible to happen
emit errorOccured(Error(Error::AccessDenied, dest.absoluteFilePath(currentName)));
ok = false;
source.cdUp(); //revert the state of source, as we are not going to copy this dir.
}
}
if (ok) {
stack.push(currentList);
currentList = source.entryInfoList(dirFilters);
}
}
else if ( currentItem.isFile() )
{
if ( options & RecursiveDirJob::OverWrite ) {
if ( !QFile::remove(dest.absoluteFilePath(currentName)) )
//.........这里部分代码省略.........
示例12: currentDir
void RecursiveDirJobHelper::recursiveRmDir(const QString & dir)
{
QDir currentDir(dir);
if ( !currentDir.exists() ) {
qWarning() << "recursiveRmDir: trying to remove non-existent directory" << dir;
if (m_reportProgress) {
//no files to be removed, so set the progressbar to 100%
emit setMaximum(1);
emit setValue(1);
}
return; // directory gone, no work to do
}
QFileInfoList currentList = currentDir.entryInfoList(dirFilters);
QFileInfo currentItem;
QStack<QFileInfoList> stack;
quint64 bytesRemoved = 0;
if (m_reportProgress) {
quint64 dirSize = calculateDirSize(dir);
emit setLabelText(tr("Removing directory \"%1\"...").arg(dir));
if (dirSize > 0) {
emit setMaximum(dirSize);
//start with the size of the directory to be removed.
//we do this before starting removing files, because on some filesystems
//(like reiserfs) the directory size is variable and will be smaller
//when all files have been removed
bytesRemoved += stat_size(dir);
emit setValue(bytesRemoved);
} else {
//no files to be removed, so set the progressbar to 100%
emit setMaximum(1);
emit setValue(1);
}
}
while(1)
{
if ( !currentList.isEmpty() ){
currentItem = currentList.takeFirst();
if ( m_reportProgress ) {
bytesRemoved += stat_size(currentItem.absoluteFilePath());
emit setValue(bytesRemoved);
}
if ( currentItem.isDir() && !currentItem.isSymLink() )
{
if ( !currentDir.cd(currentItem.fileName()) ) {
emit errorOccured(Error(Error::AccessDenied, currentItem.absoluteFilePath()));
} else {
stack.push(currentList);
currentList = currentDir.entryInfoList(dirFilters);
}
}
else
{
if ( !currentDir.remove(currentItem.fileName()) )
emit errorOccured(Error(Error::RmFail, currentItem.absoluteFilePath()));
}
}
else // list is empty
{
bool quit = false;
if ( !stack.isEmpty() )
currentList = stack.pop();
else
quit = true;
//if quit == true, we remove the original dir itself, now that it is empty for sure...
QString tmpname = currentDir.dirName();
currentDir.cdUp();
if ( !currentDir.rmdir(tmpname) )
emit errorOccured(Error(Error::RmFail, currentDir.absoluteFilePath(tmpname)));
if ( quit )
break;
}
}
}
示例13: clear
void QmlProfilerEventsModelProxy::loadData(qint64 rangeStart, qint64 rangeEnd)
{
clear();
qint64 qmlTime = 0;
qint64 lastEndTime = 0;
QHash <QString, QVector<qint64> > durations;
const bool checkRanges = (rangeStart != -1) && (rangeEnd != -1);
const QVector<QmlProfilerDataModel::QmlEventData> eventList
= d->modelManager->qmlModel()->getEvents();
// used by binding loop detection
typedef QPair<QString, const QmlProfilerDataModel::QmlEventData*> CallStackEntry;
QStack<CallStackEntry> callStack;
callStack.push(CallStackEntry(QString(), 0)); // artificial root
for (int i = 0; i < eventList.size(); ++i) {
const QmlProfilerDataModel::QmlEventData *event = &eventList[i];
if (!d->acceptedTypes.contains((QmlDebug::QmlEventType)event->eventType))
continue;
if (checkRanges) {
if ((event->startTime + event->duration < rangeStart)
|| (event->startTime > rangeEnd))
continue;
}
// put event in hash
QString hash = QmlProfilerDataModel::getHashString(*event);
if (!d->data.contains(hash)) {
QmlEventStats stats = {
event->displayName,
hash,
event->data.join(QLatin1String(" ")),
event->location,
event->eventType,
event->bindingType,
event->duration,
1, //calls
event->duration, //minTime
event->duration, // maxTime
0, //timePerCall
0, //percentOfTime
0, //medianTime
false //isBindingLoop
};
d->data.insert(hash, stats);
// for median computing
durations.insert(hash, QVector<qint64>());
durations[hash].append(event->duration);
} else {
// update stats
QmlEventStats *stats = &d->data[hash];
stats->duration += event->duration;
if (event->duration < stats->minTime)
stats->minTime = event->duration;
if (event->duration > stats->maxTime)
stats->maxTime = event->duration;
stats->calls++;
// for median computing
durations[hash].append(event->duration);
}
// qml time computation
if (event->startTime > lastEndTime) { // assume parent event if starts before last end
qmlTime += event->duration;
lastEndTime = event->startTime + event->duration;
}
//
// binding loop detection
//
const QmlProfilerDataModel::QmlEventData *potentialParent = callStack.top().second;
while (potentialParent
&& !(potentialParent->startTime + potentialParent->duration > event->startTime)) {
callStack.pop();
potentialParent = callStack.top().second;
}
// check whether event is already in stack
bool inLoop = false;
for (int ii = 1; ii < callStack.size(); ++ii) {
if (callStack.at(ii).first == hash)
inLoop = true;
if (inLoop)
d->eventsInBindingLoop.insert(hash);
}
CallStackEntry newEntry(hash, event);
callStack.push(newEntry);
//.........这里部分代码省略.........
示例14: ModelNode
void QDeclarativeListModelParser::setCustomData(QObject *obj, const QByteArray &d)
{
QDeclarativeListModel *rv = static_cast<QDeclarativeListModel *>(obj);
ModelNode *root = new ModelNode(rv->m_nested);
rv->m_nested->_root = root;
QStack<ModelNode *> nodes;
nodes << root;
bool processingSet = false;
const ListModelData *lmd = (const ListModelData *)d.constData();
const char *data = ((const char *)lmd) + lmd->dataOffset;
for (int ii = 0; ii < lmd->instrCount; ++ii) {
const ListInstruction &instr = lmd->instructions()[ii];
switch(instr.type) {
case ListInstruction::Push:
{
ModelNode *n = nodes.top();
ModelNode *n2 = new ModelNode(rv->m_nested);
n->values << QVariant::fromValue(n2);
nodes.push(n2);
if (processingSet)
n->isArray = true;
}
break;
case ListInstruction::Pop:
nodes.pop();
break;
case ListInstruction::Value:
{
ModelNode *n = nodes.top();
switch (QDeclarativeParser::Variant::Type(data[instr.dataIdx])) {
case QDeclarativeParser::Variant::Invalid:
n->isArray = true;
break;
case QDeclarativeParser::Variant::Boolean:
n->values.append(bool(data[1 + instr.dataIdx]));
break;
case QDeclarativeParser::Variant::Number:
n->values.append(QByteArray(data + 1 + instr.dataIdx).toDouble());
break;
case QDeclarativeParser::Variant::String:
n->values.append(QString::fromUtf8(data + 1 + instr.dataIdx));
break;
default:
Q_ASSERT("Format error in ListInstruction");
}
processingSet = false;
}
break;
case ListInstruction::Set:
{
ModelNode *n = nodes.top();
ModelNode *n2 = new ModelNode(rv->m_nested);
n->properties.insert(QString::fromUtf8(data + instr.dataIdx), n2);
nodes.push(n2);
processingSet = true;
}
break;
}
}
ModelNode *rootNode = rv->m_nested->_root;
for (int i=0; i<rootNode->values.count(); ++i) {
ModelNode *node = qvariant_cast<ModelNode *>(rootNode->values[i]);
node->listIndex = i;
node->updateListIndexes();
}
}
示例15: if
void stackShow::In2Post(QStringList &phrase)
{
static QStack <QString> stack;
static QStringList result;
QString r , q;
QString l[6]={"+" , "-" , "*" , "/" , "(" , ")"};
for (int i=0 ; i<phrase.size() ; i++)
for (int j=0 ; j<6 ; j++)
{
if ( phrase.at(i)!=l[j] && j==5 )
{
result.append(phrase.at(i));
ui->lneRes->insert(phrase.at(i) + " ");
phrase.removeFirst();
r = phrase.join(" ");
ui->lneExp->setText(r);
return;
}
else if (phrase.at(i)==l[j])
{
if (stack.isEmpty() || phrase.at(i)=="(" || bozorgtarAz( phrase.at(i) , stack.top() ) )
{
stack.push(phrase.at(i));
ui->lneStack->insert(phrase.at(i) + " ");
phrase.removeFirst();
r = phrase.join(" ");
ui->lneExp->setText(r);
return;
}
else if (phrase.at(i)==")")
{
while (stack.top()!="(")
{
q=stack.pop();
result.append(q);
ui->lneRes->insert(q + " ");
q=ui->lneStack->text();
q.remove(q.size()-2,2);
ui->lneStack->setText(q);
return;
}
stack.pop();
q=ui->lneStack->text();
q.remove(q.size()-2,2);
ui->lneStack->setText(q);
phrase.removeFirst();
QString r = phrase.join(" ");
ui->lneExp->setText(r);
return;
}
else
{
while (!stack.isEmpty() && !bozorgtarAz( phrase.at(i) , stack.top() ))
{
q=stack.pop();
result.append(q);
ui->lneRes->insert(q + " ");
q=ui->lneStack->text();
q.remove(q.size()-2,2);
ui->lneStack->setText(q);
return;
}
}
break;
}
}
while (! stack.isEmpty())
{
q=stack.pop();
result.append(q);
ui->lneRes->insert(q + " ");
q=ui->lneStack->text();
q.remove(q.size()-2,2);
ui->lneStack->setText(q);
return;
}
ui->btnGo->setText("Close");
}