Theme::Theme(const QString& name) : m_name(name) { if (m_name.isEmpty()) { QString untitled; int count = 0; do { count++; untitled = tr("Untitled %1").arg(count); } while (QFile::exists(filePath(untitled))); setValue(m_name, untitled); } QSettings settings(filePath(m_name), QSettings::IniFormat); // Load background settings m_background_type = settings.value("Background/Type", 0).toInt(); m_background_color = settings.value("Background/Color", "#cccccc").toString(); m_background_path = settings.value("Background/Image").toString(); m_background_image = settings.value("Background/ImageFile").toString(); if (!m_background_path.isEmpty() && m_background_image.isEmpty()) { setValue(m_background_image, copyImage(m_background_path)); } // Load foreground settings m_foreground_color = settings.value("Foreground/Color", "#cccccc").toString(); m_foreground_opacity = qBound(0, settings.value("Foreground/Opacity", 100).toInt(), 100); m_foreground_width = qBound(500, settings.value("Foreground/Width", 700).toInt(), 2000); m_foreground_rounding = qBound(0, settings.value("Foreground/Rounding", 0).toInt(), 100); m_foreground_margin = qBound(0, settings.value("Foreground/Margin", 65).toInt(), 250); m_foreground_padding = qBound(0, settings.value("Foreground/Padding", 0).toInt(), 250); m_foreground_position = qBound(0, settings.value("Foreground/Position", 1).toInt(), 3); // Load text settings m_text_color = settings.value("Text/Color", "#000000").toString(); m_text_font.fromString(settings.value("Text/Font", QFont().toString()).toString()); m_misspelled_color = settings.value("Text/Misspelled", "#ff0000").toString(); QStringList blocktypes; blocktypes<<"default"<<"H1"<<"H2"<<"H3"<<"H4"<<"H5"<<"BLOCKQUOTE"<<"ATTRIBUTION"<<"DIVIDER1"<<"DIVIDER2"<<"DIVIDER3"<<"DIVIDER4"<<"DIVIDER5"<<"PRE"; QStringListIterator it(blocktypes); while(it.hasNext()) { QString thetype=it.next(); QTextBlockFormat format; if(settings.contains(QString("Styles/")+thetype+QString("/FontWeight"))) { int weight=settings.value(QString("Styles/")+thetype+QString("/FontWeight")).toInt(); if(weight!=0) format.setProperty(QTextFormat::FontWeight,QFont::Bold); } else if(thetype.startsWith("H")&&thetype.at(1).isDigit()) format.setProperty(QTextFormat::FontWeight,QFont::Bold); if(settings.contains(QString("Styles/")+thetype+QString("/FontItalic"))) { bool italic=settings.value(QString("Styles/")+thetype+QString("/FontItalic")).toBool(); if(italic) format.setProperty(QTextFormat::FontItalic,true); } else if(thetype=="BLOCKQUOTE" || thetype=="ATTRIBUTION") format.setProperty(QTextFormat::FontItalic,true); if(settings.contains(QString("Styles/")+thetype+QString("/FontSizeAdjustment"))) { int adjustment=settings.value(QString("Styles/")+thetype+QString("/FontSizeAdjustment")).toInt(); if(adjustment!=0) format.setProperty(QTextFormat::FontSizeAdjustment,adjustment); } else if(thetype.startsWith("H")&&thetype.at(1).isDigit()) format.setProperty(QTextFormat::FontSizeAdjustment,4-QString(thetype.at(1)).toInt()); if(settings.contains(QString("Styles/")+thetype+QString("/BlockLeftMargin"))) { double margin=settings.value(QString("Styles/")+thetype+QString("/BlockLeftMargin")).toDouble(); if(margin!=0) format.setProperty(QTextFormat::BlockLeftMargin,margin); } else if(thetype=="BLOCKQUOTE" || thetype=="ATTRIBUTION") format.setProperty(QTextFormat::BlockLeftMargin,50.0); if(settings.contains(QString("Styles/")+thetype+QString("/BlockRightMargin"))) { double margin=settings.value(QString("Styles/")+thetype+QString("/BlockRightMargin")).toDouble(); if(margin!=0) format.setProperty(QTextFormat::BlockRightMargin,margin); } else if(thetype=="BLOCKQUOTE" || thetype=="ATTRIBUTION") format.setProperty(QTextFormat::BlockRightMargin,50.0); if(settings.contains(QString("Styles/")+thetype+QString("/BlockTopMargin"))) { double margin=settings.value(QString("Styles/")+thetype+QString("/BlockTopMargin")).toDouble(); if(margin!=0) format.setProperty(QTextFormat::BlockTopMargin,margin); } else if(thetype.startsWith("DIVIDER")) { double arr[]={0.0,5.0,5.0,10.0,15.0}; int dl=QString(thetype.at(7)).toInt(); format.setProperty(QTextFormat::BlockTopMargin,arr[dl-1]); } if(settings.contains(QString("Styles/")+thetype+QString("/BlockBottomMargin"))) { double margin=settings.value(QString("Styles/")+thetype+QString("/BlockBottomMargin")).toDouble(); if(margin!=0) format.setProperty(QTextFormat::BlockBottomMargin,margin); } else if(thetype.startsWith("DIVIDER")) { double arr[]={0.0,5.0,10.0,15.0,25.0}; int dl=QString(thetype.at(7)).toInt(); format.setProperty(QTextFormat::BlockBottomMargin,arr[dl-1]); } else if(thetype!="PRE") format.setProperty(QTextFormat::BlockBottomMargin,10.0); if(settings.contains(QString("Styles/")+thetype+QString("/BlockAlignment"))) { int align=settings.value(QString("Styles/")+thetype+QString("/BlockAlignment")).toInt(); format.setProperty(QTextFormat::BlockAlignment,align); } else if(thetype=="ATTRIBUTION") format.setProperty(QTextFormat::BlockAlignment,Qt::AlignRight); else format.setProperty(QTextFormat::BlockAlignment,Qt::AlignLeft); if(settings.contains(QString("Styles/")+thetype+QString("/BlockTrailingHorizontalRulerWidth"))) { double rulewidth=settings.value(QString("Styles/")+thetype+QString("/BlockTrailingHorizontalRulerWidth")).toDouble(); if(rulewidth!=0) format.setProperty(QTextFormat::BlockTrailingHorizontalRulerWidth,QTextLength(QTextLength::PercentageLength,rulewidth)); } else if(thetype.startsWith("DIVIDER")) { double arr[]={0.0,0.0,20.0,50.0,100.0}; int dl=QString(thetype.at(7)).toInt(); format.setProperty(QTextFormat::BlockTrailingHorizontalRulerWidth,QTextLength(QTextLength::PercentageLength,arr[dl-1])); } if(settings.contains(QString("Styles/")+thetype+QString("/BlockNonBreakableLines"))) { bool nobreak=settings.value(QString("Styles/")+thetype+QString("/BlockNonBreakableLines")).toBool(); if(nobreak) format.setProperty(QTextFormat::BlockNonBreakableLines,nobreak); } else if(thetype=="ATTRIBUTION"||thetype=="PRE") format.setProperty(QTextFormat::BlockNonBreakableLines,true); if(thetype!="default") format.setProperty(QTextFormat::UserProperty,thetype); m_block_default_format.insert(thetype,format); } //setup paragraph styles // QTextBlockFormat baseformat; // baseformat.setBottomMargin(10.0); // baseformat.setAlignment(Qt::AlignLeft); // m_block_default_format.insert("default",baseformat); // QTextBlockFormat h1format=QTextBlockFormat(baseformat),h2format=QTextBlockFormat(baseformat),h3format=QTextBlockFormat(baseformat),h4format=QTextBlockFormat(baseformat),h5format=QTextBlockFormat(baseformat); // h1format.setProperty(QTextFormat::UserProperty,"H1"); // h1format.setProperty(QTextFormat::FontWeight,QFont::Bold); // h1format.setProperty(QTextFormat::FontSizeAdjustment,3); // h2format.setProperty(QTextFormat::UserProperty,"H2"); // h2format.setProperty(QTextFormat::FontWeight,QFont::Bold); // h2format.setProperty(QTextFormat::FontSizeAdjustment,2); // h3format.setProperty(QTextFormat::UserProperty,"H3"); // h3format.setProperty(QTextFormat::FontWeight,QFont::Bold); // h3format.setProperty(QTextFormat::FontSizeAdjustment,1); // h4format.setProperty(QTextFormat::UserProperty,"H4"); // h4format.setProperty(QTextFormat::FontWeight,QFont::Bold); // h4format.setProperty(QTextFormat::FontSizeAdjustment,0); // h5format.setProperty(QTextFormat::UserProperty,"H5"); // h5format.setProperty(QTextFormat::FontWeight,QFont::Bold); // h5format.setProperty(QTextFormat::FontSizeAdjustment,-1); // m_block_default_format.insert("H1",h1format); // m_block_default_format.insert("H2",h2format); // m_block_default_format.insert("H3",h3format); // m_block_default_format.insert("H4",h4format); // m_block_default_format.insert("H5",h5format); // QTextBlockFormat bqformat=QTextBlockFormat(baseformat); // bqformat.setProperty(QTextFormat::UserProperty,"BLOCKQUOTE"); // bqformat.setProperty(QTextFormat::FontItalic,true); // bqformat.setLeftMargin(50.0); // bqformat.setRightMargin(50.0); // m_block_default_format.insert("BLOCKQUOTE",bqformat); // QTextBlockFormat attformat=QTextBlockFormat(baseformat); // attformat.setAlignment(Qt::AlignRight); // attformat.setProperty(QTextFormat::UserProperty,"ATTRIBUTION"); // attformat.setProperty(QTextFormat::FontItalic,true); // attformat.setBottomMargin(15.0); // attformat.setLeftMargin(50.0); // attformat.setRightMargin(50.0); // attformat.setNonBreakableLines(true); // m_block_default_format.insert("ATTRIBUTION",attformat); // QTextBlockFormat preformat=QTextBlockFormat(); // preformat.setProperty(QTextFormat::UserProperty,"PRE"); // preformat.setNonBreakableLines(true); // m_block_default_format.insert("PRE",preformat); // QTextBlockFormat d1format=QTextBlockFormat(); // d1format.setProperty(QTextFormat::UserProperty,"DIVIDER1"); // m_block_default_format.insert("DIVIDER1",d1format); // QTextBlockFormat d2format=QTextBlockFormat(); // d2format.setProperty(QTextFormat::UserProperty,"DIVIDER2"); // d2format.setTopMargin(5); // d2format.setBottomMargin(5); // m_block_default_format.insert("DIVIDER2",d2format); // QTextBlockFormat d3format=QTextBlockFormat(); // d3format.setProperty(QTextFormat::UserProperty,"DIVIDER3"); // d3format.setTopMargin(5); // d3format.setBottomMargin(10); // d3format.setProperty(QTextFormat::BlockTrailingHorizontalRulerWidth,QTextLength(QTextLength::PercentageLength,20)); // m_block_default_format.insert("DIVIDER3",d3format); // QTextBlockFormat d4format=QTextBlockFormat(); // d4format.setProperty(QTextFormat::UserProperty,"DIVIDER4"); // d4format.setTopMargin(10); // d4format.setBottomMargin(15); // d4format.setProperty(QTextFormat::BlockTrailingHorizontalRulerWidth,QTextLength(QTextLength::PercentageLength,50)); // m_block_default_format.insert("DIVIDER4",d4format); // QTextBlockFormat d5format=QTextBlockFormat(); // d5format.setProperty(QTextFormat::UserProperty,"DIVIDER5"); // d5format.setTopMargin(15); // d5format.setBottomMargin(25); // d5format.setProperty(QTextFormat::BlockTrailingHorizontalRulerWidth,QTextLength(QTextLength::PercentageLength,100)); // m_block_default_format.insert("DIVIDER5",d5format); }
void HeatmapView::paintRow(QPainter& painter, HeatmapRowIterator* itr) { bool selection = m_selectionState ? m_selectionState->type != SelectionState::None : false; while (itr->next()) { double heat = itr->heat(); int width = itr->width(); int x = itr->step(); /* Gamma correction */ heat = qPow(heat, 1.0 / 2.0); if (width == 1) { /* Draw single line */ if (selection) { double selectedHeat = itr->selectedHeat(); if (selectedHeat >= 0.999) { heat = 255.0 - qBound(0.0, heat * 255.0, 255.0); if (itr->isGpu()) { painter.setPen(QColor(255, heat, heat)); } else { painter.setPen(QColor(heat, heat, 255)); } painter.drawLine(x, 0, x, m_rowHeight - 1); } else { heat = 255.0 - qBound(0.0, heat * 100.0, 100.0); painter.setPen(QColor(heat, heat, heat)); painter.drawLine(x, 0, x, m_rowHeight - 1); if (selectedHeat > 0.001) { selectedHeat = qPow(selectedHeat, 1.0 / 2.0); selectedHeat = qBound(0.0, selectedHeat * 255.0, 255.0); if (itr->isGpu()) { painter.setPen(QColor(255, 0, 0, selectedHeat)); } else { painter.setPen(QColor(0, 0, 255, selectedHeat)); } painter.drawLine(x, 0, x, m_rowHeight - 1); } } } else { heat = qBound(0.0, heat * 255.0, 255.0); if (itr->isGpu()) { painter.setPen(QColor(255, 255 - heat, 255 - heat)); } else { painter.setPen(QColor(255 - heat, 255 - heat, 255)); } painter.drawLine(x, 0, x, m_rowHeight - 1); } } else { double selectedHeat = itr->selectedHeat(); if (selection && selectedHeat < 0.9) { painter.fillRect(x, 0, width, m_rowHeight, QColor(255 - 100, 255 - 100, 255 - 100)); } else if (itr->isGpu()) { painter.fillRect(x, 0, width, m_rowHeight, QColor(255, 0, 0)); } else { painter.fillRect(x, 0, width, m_rowHeight, QColor(0, 0, 255)); } if (width > 6) { painter.setPen(Qt::white); QString elided = painter.fontMetrics().elidedText(itr->label(), Qt::ElideRight, width - 1); painter.drawText(x + 1, 0, width - 1, m_rowHeight - 1, Qt::AlignLeft | Qt::AlignVCenter, elided); } } } }
QRectF PanelPageSize::BoundingPageSumme(const int summe) { int summetotal = qBound(1,summe,MaximumPages); const qreal alto = summetotal * G_regt.height(); return QRectF(0,0,G_regt.width(),alto); }
void QGLFramebufferObjectPrivate::init(QGLFramebufferObject *q, const QSize &sz, QGLFramebufferObject::Attachment attachment, GLenum texture_target, GLenum internal_format, GLint samples, bool mipmap) { QGLContext *ctx = const_cast<QGLContext *>(QGLContext::currentContext()); fbo_guard.setContext(ctx); bool ext_detected = (QGLExtensions::glExtensions() & QGLExtensions::FramebufferObject); if (!ext_detected || (ext_detected && !qt_resolve_framebufferobject_extensions(ctx))) return; size = sz; target = texture_target; // texture dimensions QT_RESET_GLERROR(); // reset error state GLuint fbo = 0; glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER_EXT, fbo); fbo_guard.setId(fbo); glDevice.setFBO(q, attachment); QT_CHECK_GLERROR(); // init texture if (samples == 0) { glGenTextures(1, &texture); glBindTexture(target, texture); glTexImage2D(target, 0, internal_format, size.width(), size.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); if (mipmap) glGenerateMipmap(GL_TEXTURE_2D); #ifndef QT_OPENGL_ES glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #else glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #endif glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, target, texture, 0); QT_CHECK_GLERROR(); valid = checkFramebufferStatus(); glBindTexture(target, 0); color_buffer = 0; } else { mipmap = false; GLint maxSamples; glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples); samples = qBound(0, int(samples), int(maxSamples)); glGenRenderbuffers(1, &color_buffer); glBindRenderbuffer(GL_RENDERBUFFER_EXT, color_buffer); if (glRenderbufferStorageMultisampleEXT && samples > 0) { glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, internal_format, size.width(), size.height()); } else { samples = 0; glRenderbufferStorage(GL_RENDERBUFFER_EXT, internal_format, size.width(), size.height()); } glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, color_buffer); QT_CHECK_GLERROR(); valid = checkFramebufferStatus(); if (valid) glGetRenderbufferParameteriv(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_SAMPLES_EXT, &samples); } // In practice, a combined depth-stencil buffer is supported by all desktop platforms, while a // separate stencil buffer is not. On embedded devices however, a combined depth-stencil buffer // might not be supported while separate buffers are, according to QTBUG-12861. if (attachment == QGLFramebufferObject::CombinedDepthStencil && (QGLExtensions::glExtensions() & QGLExtensions::PackedDepthStencil)) { // depth and stencil buffer needs another extension glGenRenderbuffers(1, &depth_buffer); Q_ASSERT(!glIsRenderbuffer(depth_buffer)); glBindRenderbuffer(GL_RENDERBUFFER_EXT, depth_buffer); Q_ASSERT(glIsRenderbuffer(depth_buffer)); if (samples != 0 && glRenderbufferStorageMultisampleEXT) glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_DEPTH24_STENCIL8_EXT, size.width(), size.height()); else glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8_EXT, size.width(), size.height()); stencil_buffer = depth_buffer; glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_buffer); glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, stencil_buffer); valid = checkFramebufferStatus(); if (!valid) { glDeleteRenderbuffers(1, &depth_buffer); stencil_buffer = depth_buffer = 0; } } if (depth_buffer == 0 && (attachment == QGLFramebufferObject::CombinedDepthStencil || (attachment == QGLFramebufferObject::Depth))) { glGenRenderbuffers(1, &depth_buffer); Q_ASSERT(!glIsRenderbuffer(depth_buffer)); glBindRenderbuffer(GL_RENDERBUFFER_EXT, depth_buffer); Q_ASSERT(glIsRenderbuffer(depth_buffer)); if (samples != 0 && glRenderbufferStorageMultisampleEXT) { #ifdef QT_OPENGL_ES if (QGLExtensions::glExtensions() & QGLExtensions::Depth24) { glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_DEPTH_COMPONENT24_OES, size.width(), size.height()); } else { glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_DEPTH_COMPONENT16, size.width(), size.height()); } #else glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_DEPTH_COMPONENT, size.width(), size.height()); #endif } else { #ifdef QT_OPENGL_ES if (QGLExtensions::glExtensions() & QGLExtensions::Depth24) { glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24_OES, size.width(), size.height()); } else { glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT16, size.width(), size.height()); } #else glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, size.width(), size.height()); #endif } glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_buffer); valid = checkFramebufferStatus(); if (!valid) { glDeleteRenderbuffers(1, &depth_buffer); depth_buffer = 0; } } if (stencil_buffer == 0 && (attachment == QGLFramebufferObject::CombinedDepthStencil)) { glGenRenderbuffers(1, &stencil_buffer); Q_ASSERT(!glIsRenderbuffer(stencil_buffer)); glBindRenderbuffer(GL_RENDERBUFFER_EXT, stencil_buffer); Q_ASSERT(glIsRenderbuffer(stencil_buffer)); if (samples != 0 && glRenderbufferStorageMultisampleEXT) { #ifdef QT_OPENGL_ES glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_STENCIL_INDEX8_EXT, size.width(), size.height()); #else glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_STENCIL_INDEX, size.width(), size.height()); #endif } else { #ifdef QT_OPENGL_ES glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_STENCIL_INDEX8_EXT, size.width(), size.height()); #else glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_STENCIL_INDEX, size.width(), size.height()); #endif } glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, stencil_buffer); valid = checkFramebufferStatus(); if (!valid) { glDeleteRenderbuffers(1, &stencil_buffer); stencil_buffer = 0; } } // The FBO might have become valid after removing the depth or stencil buffer. valid = checkFramebufferStatus(); if (depth_buffer && stencil_buffer) { fbo_attachment = QGLFramebufferObject::CombinedDepthStencil; } else if (depth_buffer) { fbo_attachment = QGLFramebufferObject::Depth; } else { fbo_attachment = QGLFramebufferObject::NoAttachment; } glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); if (!valid) { if (color_buffer) glDeleteRenderbuffers(1, &color_buffer); else glDeleteTextures(1, &texture); if (depth_buffer) glDeleteRenderbuffers(1, &depth_buffer); if (stencil_buffer && depth_buffer != stencil_buffer) glDeleteRenderbuffers(1, &stencil_buffer); glDeleteFramebuffers(1, &fbo); fbo_guard.setId(0); } QT_CHECK_GLERROR(); format.setTextureTarget(target); format.setSamples(int(samples)); format.setAttachment(fbo_attachment); format.setInternalTextureFormat(internal_format); format.setMipmap(mipmap); }
void ModelTest::layoutAboutToBeChanged() { for (int i = 0; i < qBound(0, model->rowCount(), 100); ++i) changing.append(QPersistentModelIndex(model->index(i, 0))); }
QVector<bool> resizeBoolVecImage(const QVector<bool>& image, int w, int h, int newWidth, int newHeight, int* askUserResizeMasks, const QString& image_name, const QString& comment) { if (w==newWidth && h==newHeight) return image; if (image.size()<w*h) return QVector<bool>(); double ax=double(w)/double(h); double newax=double(newWidth)/double(newHeight); bool transform=false; if (askUserResizeMasks) { transform=((*askUserResizeMasks)>0); if ((*askUserResizeMasks)<0) { int res=QMessageBox::question(NULL, QObject::tr("resize %1").arg(image_name), QObject::tr("%2\nShould the %1 be resized?").arg(image_name).arg(comment), QMessageBox::Yes|QMessageBox::No, QMessageBox::Yes); if (res==QMessageBox::Yes) { *askUserResizeMasks=1; transform=true; } else if (res==QMessageBox::No) { *askUserResizeMasks=0; transform=false; } } } else { transform=true; } if (transform) { QVector<bool> r; if (w*h==newWidth*newHeight) { for (int i=0; i<newWidth*newHeight; i++) { r<<image[i]; } } else if (newWidth*newHeight>w*h) { for (int i=0; i<newWidth*newHeight; i++) { int x=i%w; int y=i/w; int x2=round(double(x)/double(newWidth)*double(w)); int y2=round(double(y)/double(newHeight)*double(h)); int i2=qBound(0, y2*w+x2, w*h); r<<image[i2]; } } else if (newWidth*newHeight<w*h) { QVector<int> rr; for (int i=0; i<newWidth*newHeight; i++) { r<<false; rr<<0; } int max=0; for (int i=0; i<w*h; i++) { int x=i%w; int y=i/h; int x2=round(double(x)/double(w)*double(newWidth)); int y2=round(double(y)/double(h)*double(newHeight)); int i2=y2*newWidth+x2; if (i2>=0 && i2<w*h && image[i]) { rr[i2]=rr[i2]+1; max=qMax(max, rr[i2]); } } for (int i=0; i<newWidth*newHeight; i++) { r[i]=(rr[i]>=max/2); } } return r; } return QVector<bool>(); }
//virtual QVariant AbstractGroupItem::itemChange(GraphicsItemChange change, const QVariant &value) { if (change == QGraphicsItem::ItemSelectedChange) { if (value.toBool()) setZValue(3); else setZValue(1); } CustomTrackScene *scene = NULL; if (change == ItemPositionChange && parentItem() == 0) { scene = projectScene(); } if (scene) { // calculate new position. if (scene->isZooming) { // For some reason, mouse wheel on selected itm sometimes triggered // a position change event corrupting timeline, so discard it return pos(); } // calculate new position. const int trackHeight = KdenliveSettings::trackheight(); QPointF start = sceneBoundingRect().topLeft(); QPointF newPos = value.toPointF(); int xpos = projectScene()->getSnapPointForPos((int)(start.x() + newPos.x() - pos().x()), KdenliveSettings::snaptopoints()); xpos = qMax(xpos, 0); ////qDebug()<<"GRP XPOS:"<<xpos<<", START:"<<start.x()<<",NEW:"<<newPos.x()<<"; SCENE:"<<scenePos().x()<<",POS:"<<pos().x(); newPos.setX((int)(pos().x() + xpos - (int) start.x())); QStringList lockedTracks = property("locked_tracks").toStringList(); int proposedTrack = trackForPos(property("y_absolute").toInt() + newPos.y()); // Check if top item is a clip or a transition int offset = 0; int topTrack = -1; QList<int> groupTracks; QList<QGraphicsItem *> children = childItems(); for (int i = 0; i < children.count(); ++i) { int currentTrack = 0; if (children.at(i)->type() == AVWidget || children.at(i)->type() == TransitionWidget) { currentTrack = static_cast <AbstractClipItem*> (children.at(i))->track(); if (!groupTracks.contains(currentTrack)) groupTracks.append(currentTrack); } else if (children.at(i)->type() == GroupWidget) { currentTrack = static_cast <AbstractGroupItem*> (children.at(i))->track(); } else continue; if (children.at(i)->type() == AVWidget) { if (topTrack == -1 || currentTrack >= topTrack) { offset = 0; topTrack = currentTrack; } } else if (children.at(i)->type() == TransitionWidget) { if (topTrack == -1 || currentTrack > topTrack) { offset = (int)(trackHeight / 3 * 2 - 1); topTrack = currentTrack; } } else if (children.at(i)->type() == GroupWidget) { QList<QGraphicsItem *> subchildren = children.at(i)->childItems(); bool clipGroup = false; for (int j = 0; j < subchildren.count(); ++j) { if (subchildren.at(j)->type() == AVWidget || subchildren.at(j)->type() == TransitionWidget) { int subTrack = static_cast <AbstractClipItem*> (subchildren.at(j))->track(); if (!groupTracks.contains(subTrack)) groupTracks.append(subTrack); clipGroup = true; } } if (clipGroup) { if (topTrack == -1 || currentTrack >= topTrack) { offset = 0; topTrack = currentTrack; } } else { if (topTrack == -1 || currentTrack > topTrack) { offset = (int)(trackHeight / 3 * 2 - 1); topTrack = currentTrack; } } } } // Check no clip in the group goes outside of existing tracks int maximumTrack = projectScene()->tracksCount(); int groupHeight = 0; for (int i = 0; i < groupTracks.count(); ++i) { int trackOffset = topTrack - groupTracks.at(i) + 1; if (trackOffset > groupHeight) groupHeight = trackOffset; } proposedTrack = qBound(groupHeight, proposedTrack, maximumTrack); int groupOffset = proposedTrack - topTrack; if (!lockedTracks.isEmpty()) { for (int i = 0; i < groupTracks.count(); ++i) { if (lockedTracks.contains(QString::number(groupTracks.at(i) + groupOffset))) { return pos(); } } } newPos.setY(posForTrack(proposedTrack) + offset); //if (newPos == start) return start; /*if (newPos.x() < 0) { // If group goes below 0, adjust position to 0 return QPointF(pos().x() - start.x(), pos().y()); }*/ QList<QGraphicsItem*> collidingItems; QPainterPath shape; if (projectScene()->editMode() == NormalEdit) { shape = clipGroupShape(newPos - pos()); collidingItems = scene->items(shape, Qt::IntersectsItemShape); collidingItems.removeAll(this); for (int i = 0; i < children.count(); ++i) { if (children.at(i)->type() == GroupWidget) { QList<QGraphicsItem *> subchildren = children.at(i)->childItems(); for (int j = 0; j < subchildren.count(); ++j) { collidingItems.removeAll(subchildren.at(j)); } } collidingItems.removeAll(children.at(i)); } } if (!collidingItems.isEmpty()) { bool forwardMove = xpos > start.x(); int offset = 0; for (int i = 0; i < collidingItems.count(); ++i) { QGraphicsItem *collision = collidingItems.at(i); if (collision->type() == AVWidget) { // Collision if (newPos.y() != pos().y()) { // Track change results in collision, restore original position return pos(); } AbstractClipItem *item = static_cast <AbstractClipItem *>(collision); // Determine best pos QPainterPath clipPath; clipPath.addRect(item->sceneBoundingRect()); QPainterPath res = shape.intersected(clipPath); offset = qMax(offset, (int)(res.boundingRect().width() + 0.5)); } } if (offset > 0) { if (forwardMove) { newPos.setX(newPos.x() - offset); } else { newPos.setX(newPos.x() + offset); } // If there is still a collision after our position adjust, restore original pos collidingItems = scene->items(clipGroupShape(newPos - pos()), Qt::IntersectsItemShape); collidingItems.removeAll(this); for (int i = 0; i < children.count(); ++i) { if (children.at(i)->type() == GroupWidget) { QList<QGraphicsItem *> subchildren = children.at(i)->childItems(); for (int j = 0; j < subchildren.count(); ++j) { collidingItems.removeAll(subchildren.at(j)); } } collidingItems.removeAll(children.at(i)); } for (int i = 0; i < collidingItems.count(); ++i) if (collidingItems.at(i)->type() == AVWidget) return pos(); } } if (projectScene()->editMode() == NormalEdit) { shape = transitionGroupShape(newPos - pos()); collidingItems = scene->items(shape, Qt::IntersectsItemShape); collidingItems.removeAll(this); for (int i = 0; i < children.count(); ++i) { if (children.at(i)->type() == GroupWidget) { QList<QGraphicsItem *> subchildren = children.at(i)->childItems(); for (int j = 0; j < subchildren.count(); ++j) { collidingItems.removeAll(subchildren.at(j)); } } collidingItems.removeAll(children.at(i)); } } if (collidingItems.isEmpty()) return newPos; else { bool forwardMove = xpos > start.x(); int offset = 0; for (int i = 0; i < collidingItems.count(); ++i) { QGraphicsItem *collision = collidingItems.at(i); if (collision->type() == TransitionWidget) { // Collision if (newPos.y() != pos().y()) { // Track change results in collision, restore original position return pos(); } AbstractClipItem *item = static_cast <AbstractClipItem *>(collision); // Determine best pos QPainterPath clipPath; clipPath.addRect(item->sceneBoundingRect()); QPainterPath res = shape.intersected(clipPath); offset = qMax(offset, (int)(res.boundingRect().width() + 0.5)); } } if (offset > 0) { if (forwardMove) { newPos.setX(newPos.x() - offset); } else { newPos.setX(newPos.x() + offset); } // If there is still a collision after our position adjust, restore original pos collidingItems = scene->items(transitionGroupShape(newPos - pos()), Qt::IntersectsItemShape); for (int i = 0; i < children.count(); ++i) { collidingItems.removeAll(children.at(i)); } for (int i = 0; i < collidingItems.count(); ++i) if (collidingItems.at(i)->type() == TransitionWidget) return pos(); } } return newPos; } return QGraphicsItemGroup::itemChange(change, value); }
void KNewPasswordWidget::setPasswordStrengthWarningLevel(int warningLevel) { d->passwordStrengthWarningLevel = qBound(0, warningLevel, 99); }
QColor CallgrindHelper::colorForCostRatio(qreal ratio) { ratio = qBound(qreal(0.0), ratio, qreal(1.0)); return QColor::fromHsv(120 - ratio * 120, 255, 255, (-((ratio-1) * (ratio-1))) * 120 + 120); }
void MeshGenerator::generateMesh(int nSlabs, QStringList volumeFiles, QString flnm, int depth, QGradientStops vstops, int fillValue, bool checkForMore, bool lookInside, Vec voxelScaling, QList<Vec> clipPos, QList<Vec> clipNormal, QList<CropObject> crops, QList<PathObject> paths, uchar *lut, int chan, bool avgColor) { bool saveIntermediate = false; int bpv = 1; if (m_voxelType > 0) bpv = 2; int nbytes = bpv*m_nY*m_nZ; // if (nSlabs > 1) // { // QStringList sl; // sl << "No"; // sl << "Yes"; // bool ok; // QString okstr = QInputDialog::getItem(0, "Save slab files", // "Save slab files in .ply format.\nFiles will not be collated together to create a unified mesh for the whole sample.", // sl, 0, false, &ok); // if (ok && okstr == "Yes") // saveIntermediate = true; // } QGradientStops lutstops; for(int i=0; i<255; i++) { QColor col(lut[4*i+0], lut[4*i+1], lut[4*i+2], lut[4*i+3]); lutstops << QGradientStop((float)i/(float)255.0f, col); } bool trim = (qRound(m_dataSize.x) < m_height || qRound(m_dataSize.y) < m_width || qRound(m_dataSize.z) < m_depth); bool clipPresent = (clipPos.count() > 0); m_cropPresent = false; m_tearPresent = false; m_blendPresent = false; for(int ci=0; ci<m_crops.count(); ci++) { if (crops[ci].cropType() < CropObject::Tear_Tear) m_cropPresent = true; else if (crops[ci].cropType() < CropObject::View_Tear) m_tearPresent = true; else if (m_crops[ci].cropType() > CropObject::Displace_Displace && m_crops[ci].cropType() < CropObject::Glow_Ball) m_blendPresent = true; } m_pathCropPresent = false; m_pathBlendPresent = false; for (int i=0; i<m_paths.count(); i++) { if (m_paths[i].blend()) m_pathBlendPresent = true; if (m_paths[i].crop()) m_pathCropPresent = true; } int nextra = depth; int blockStep = m_nX/nSlabs; //----------------------------- int nvols = volumeFiles.count(); //----------------------------- for (int volnum=0; volnum < nvols; volnum++) { //if (nvols > 1) { m_vfm->setBaseFilename(volumeFiles[volnum]); uchar *vslice = m_vfm->getSlice(0); } m_meshLog->moveCursor(QTextCursor::End); m_meshLog->insertPlainText(QString("\nProcessing file %1 of %2 : %3\n").\ arg(volnum+1).arg(nvols).arg(m_vfm->fileName())); for (int nb=0; nb<nSlabs; nb++) { m_meshLog->moveCursor(QTextCursor::End); m_meshLog->insertPlainText(QString(" Processing slab %1 of %2\n").arg(nb+1).arg(nSlabs)); int d0 = nb*blockStep; int d1 = qMin(m_nX-1, (nb+1)*blockStep); int dlen = d1-d0+1; int d0z = d0 + qRound(m_dataMin.z); int d1z = d1 + qRound(m_dataMin.z); uchar *extData; if (m_voxelType == 0) extData = new uchar[(dlen+2*nextra)*m_nY*m_nZ]; else extData = new uchar[2*(dlen+2*nextra)*m_nY*m_nZ]; // ushort uchar *cropped = new uchar[nbytes]; uchar *tmp = new uchar[nbytes]; int i0 = 0; for(int i=d0z-nextra; i<=d1z+nextra; i++) { m_meshProgress->setValue((int)(100.0*(float)(i0/(float)(dlen+2*nextra)))); qApp->processEvents(); int iv = qBound(0, i, m_depth-1); uchar *vslice = m_vfm->getSlice(iv); memset(cropped, 0, nbytes); if (!trim) memcpy(tmp, vslice, nbytes); else { int wmin = qRound(m_dataMin.y); int hmin = qRound(m_dataMin.x); if (m_voxelType == 0) { for(int w=0; w<m_nY; w++) for(int h=0; h<m_nZ; h++) tmp[w*m_nZ + h] = vslice[(wmin+w)*m_height + (hmin+h)]; } else { for(int w=0; w<m_nY; w++) for(int h=0; h<m_nZ; h++) ((ushort*)tmp)[w*m_nZ + h] = ((ushort*)vslice)[(wmin+w)*m_height + (hmin+h)]; } } int jk = 0; for(int j=0; j<m_nY; j++) for(int k=0; k<m_nZ; k++) { Vec po = Vec(m_dataMin.x+k, m_dataMin.y+j, iv); bool ok = true; // we don't want to scale before pruning // no mop pruning po *= m_samplingLevel; if (ok && clipPresent) ok = StaticFunctions::getClip(po, clipPos, clipNormal); if (ok && m_cropPresent) ok = checkCrop(po); if (ok && m_pathCropPresent) ok = checkPathCrop(po); if (ok && m_blendPresent) { ushort v; if (m_voxelType == 0) v = tmp[j*m_nZ + k]; else v = ((ushort*)tmp)[j*m_nZ + k]; ok = checkBlend(po, v, lut); } if (ok && m_pathBlendPresent) { ushort v; if (m_voxelType == 0) v = tmp[j*m_nZ + k]; else v = ((ushort*)tmp)[j*m_nZ + k]; ok = checkPathBlend(po, v, lut); } if (ok) //cropped[jk] = mop; // nop mop pruning cropped[jk] = 255; else cropped[jk] = 0; jk ++; } if (m_voxelType == 0) { for(int j=0; j<m_nY*m_nZ; j++) { if (cropped[j] == 0) tmp[j] = 0; } } else { for(int j=0; j<m_nY*m_nZ; j++) { if (cropped[j] == 0) ((ushort*)tmp)[j] = 0; } } // tmp now clipped and contains raw data memcpy(extData + bpv*i0*m_nY*m_nZ, tmp, nbytes); i0++; } delete [] tmp; delete [] cropped; m_meshProgress->setValue(100); qApp->processEvents(); //------------ if (m_tearPresent) { uchar *data0 = new uchar[(dlen+2*nextra)*m_nY*m_nZ]; uchar *data1 = extData; memcpy(data0, data1, (dlen+2*nextra)*m_nY*m_nZ); applyTear(d0, d1, nextra, data0, data1, true); delete [] data0; } //------------ //-------------------------------- // ---- set border voxels to fillValue if (fillValue >= 0) { uchar *v = extData; i0 = 0; for(int i=d0z-nextra; i<=d1z+nextra; i++) { int iv = qBound(0, i, m_depth-1); int i0dx = i0*m_nY*m_nZ; if (iv <= qRound(m_dataMin.z) || iv >= qRound(m_dataMax.z)) { if (m_voxelType == 0) memset(v + i0dx, fillValue, m_nY*m_nZ); else { for(int fi=0; fi<m_nY*m_nZ; fi++) ((ushort*)v)[i0*m_nY*m_nZ + fi] = fillValue; } } else { if (m_voxelType == 0) { for(int j=0; j<m_nY; j++) v[i0dx + j*m_nZ] = fillValue; for(int j=0; j<m_nY; j++) v[i0dx + j*m_nZ + m_nZ-1] = fillValue; for(int k=0; k<m_nZ; k++) v[i0dx + k] = fillValue; for(int k=0; k<m_nZ; k++) v[i0dx + (m_nY-1)*m_nZ + k] = fillValue; } else { for(int j=0; j<m_nY; j++) ((ushort*)v)[i0dx + j*m_nZ] = fillValue; for(int j=0; j<m_nY; j++) ((ushort*)v)[i0dx + j*m_nZ + m_nZ-1] = fillValue; for(int k=0; k<m_nZ; k++) ((ushort*)v)[i0dx + k] = fillValue; for(int k=0; k<m_nZ; k++) ((ushort*)v)[i0dx + (m_nY-1)*m_nZ + k] = fillValue; } } i0++; } } //-------------------------------- m_meshLog->moveCursor(QTextCursor::End); m_meshLog->insertPlainText(" Generating Color ...\n"); for(int ni=0; ni<m_nverts; ni++) { m_meshProgress->setValue((int)(100.0*(float)ni/(float)m_nverts)); qApp->processEvents(); float v[3]; v[0] = m_vlist[ni]->x/voxelScaling.x/m_scaleModel; v[1] = m_vlist[ni]->y/voxelScaling.y/m_scaleModel; v[2] = m_vlist[ni]->z/voxelScaling.z/m_scaleModel; if (v[2] > d0 && v[2] <= d1) { // QMessageBox::information(0, "", QString("%1 %2 %3\n%4 %5 %6\n%7 %8"). \ // arg(v[0]).arg(v[1]).arg(v[2]). \ // arg(m_vlist[ni]->x).arg(m_vlist[ni]->y).arg(m_vlist[ni]->z). \ // arg(d0).arg(d1)); uchar *volData = extData; QColor col; QVector3D pos, normal; pos = QVector3D(v[0], v[1], v[2]-d0 + nextra); normal = QVector3D(-m_vlist[ni]->nx, -m_vlist[ni]->ny, -m_vlist[ni]->nz); col = getVRLutColor(volData, dlen, depth, nextra, pos, normal, lut, lookInside, QVector3D(v[0], v[1], v[2])); if (col.alphaF() > 0) { float r = col.red()/255.0f; float g = col.green()/255.0f; float b = col.blue()/255.0f; float a = col.alphaF(); // tinge with lutcolor QColor col0 = vstops[255*(float)(volnum+1)/(float)nvols].second; float aa = col0.alphaF(); float tr = col0.red()/255.0f; float tg = col0.green()/255.0f; float tb = col0.blue()/255.0f; r = (1.0-aa)*r + aa*a*tr; g = (1.0-aa)*g + aa*a*tg; b = (1.0-aa)*b + aa*a*tb; vcolor[3*ni+0] = (1-a)*vcolor[3*ni+0] + r; vcolor[3*ni+1] = (1-a)*vcolor[3*ni+1] + g; vcolor[3*ni+2] = (1-a)*vcolor[3*ni+2] + b; } } } m_meshProgress->setValue(100); delete [] extData; } // loop over slabs // if (nvols > 1) // save intermediate files // { // QString plyflnm = flnm; // plyflnm.chop(3); // plyflnm += QString("%1.ply").arg((int)volnum, (int)nvols/10+2, 10, QChar('0')); // // for(int ni=0; ni<m_nverts; ni++) // { // m_vlist[ni]->r = 255*vcolor[3*ni+0]; // m_vlist[ni]->g = 255*vcolor[3*ni+1]; // m_vlist[ni]->b = 255*vcolor[3*ni+2]; // } // savePLY(plyflnm); // } }// loop over files for(int ni=0; ni<m_nverts; ni++) { m_vlist[ni]->r = 255*vcolor[3*ni+0]; m_vlist[ni]->g = 255*vcolor[3*ni+1]; m_vlist[ni]->b = 255*vcolor[3*ni+2]; } savePLY(flnm); m_meshLog->moveCursor(QTextCursor::End); m_meshLog->insertPlainText("Mesh saved in "+flnm); QMessageBox::information(0, "", QString("Mesh saved in "+flnm)); }
void KNewPasswordWidget::setReasonablePasswordLength(int reasonableLength) { d->reasonablePasswordLength = qBound(1, reasonableLength, maximumPasswordLength()); }
QColor MeshGenerator::getVRLutColor(uchar *volData, int dlen, int depth, int nextra, QVector3D pos, QVector3D normal, uchar *lut, bool lookInside, QVector3D globalPos) { // go a bit deeper and start QVector3D vpos = pos + normal; // -- find how far deep we can go int nd = 0; for(int n=0; n<=depth; n++) { int i = vpos.x(); int j = vpos.y(); int k = vpos.z(); if (i > m_nZ-1 || j > m_nY-1 || k > dlen+2*nextra-1 || i < 0 || j < 0 || k < 0) // gone out break; nd ++; vpos += normal; } // now start collecting the samples vpos = pos + normal; QVector3D gpos = globalPos + normal; Vec rgb = Vec(0,0,0); float tota = 0; for(int ns=0; ns<=nd; ns++) { int i = vpos.x(); int j = vpos.y(); int k = vpos.z(); i = qBound(0, i, m_nZ-1); j = qBound(0, j, m_nY-1); k = qBound(0, k, dlen+2*nextra-1); Vec po0 = Vec(m_dataMin.x+gpos.x(), m_dataMin.y+gpos.y(), gpos.z()); Vec po = po0*m_samplingLevel; bool ok=true; if (ok) { ushort v, gr; if (m_voxelType == 0) { v = volData[k*m_nY*m_nZ + j*m_nZ + i]; gr = 0; } else { v = ((ushort*)volData)[k*m_nY*m_nZ + j*m_nZ + i]; gr = v%256; v = v/256; } // QMessageBox::information(0, "", QString("vrlut : %1 %2 %3 : %4").\ // arg(i).arg(j).arg(k).arg(v)); float a = lut[4*(256*gr + v)+3]/255.0f; float r = lut[4*(256*gr + v)+0]*a; float g = lut[4*(256*gr + v)+1]*a; float b = lut[4*(256*gr + v)+2]*a; if (m_blendPresent) { for(int ci=0; ci<m_crops.count(); ci++) { if (m_crops[ci].cropType() > CropObject::Displace_Displace && m_crops[ci].cropType() < CropObject::Glow_Ball) { float viewMix = m_crops[ci].checkBlend(po); int tfSet = m_crops[ci].tfset(); tfSet *= 256*256*4; float a1 = lut[tfSet+4*(256*gr + v)+3]/255.0f; float r1 = lut[tfSet+4*(256*gr + v)+0]*a1; float g1 = lut[tfSet+4*(256*gr + v)+1]*a1; float b1 = lut[tfSet+4*(256*gr + v)+2]*a1; r = (1-viewMix)*r + viewMix*r1; g = (1-viewMix)*g + viewMix*g1; b = (1-viewMix)*b + viewMix*b1; a = (1-viewMix)*a + viewMix*a1; } } } if (m_pathBlendPresent) { for(int ci=0; ci<m_paths.count(); ci++) { if (m_paths[ci].blend()) { float viewMix = m_paths[ci].checkBlend(po); int tfSet = m_paths[ci].blendTF(); tfSet *= 256*256*4; float a1 = lut[tfSet+4*(256*gr + v)+3]/255.0f; float r1 = lut[tfSet+4*(256*gr + v)+0]*a1; float g1 = lut[tfSet+4*(256*gr + v)+1]*a1; float b1 = lut[tfSet+4*(256*gr + v)+2]*a1; r = (1-viewMix)*r + viewMix*r1; g = (1-viewMix)*g + viewMix*g1; b = (1-viewMix)*b + viewMix*b1; a = (1-viewMix)*a + viewMix*a1; } } } // apply tag colors if (m_useTagColors) { Vec pp = po0 - m_dataMin; int ppi = pp.x/m_pruneLod; int ppj = pp.y/m_pruneLod; int ppk = pp.z/m_pruneLod; ppi = qBound(0, ppi, m_pruneX-1); ppj = qBound(0, ppj, m_pruneY-1); ppk = qBound(0, ppk, m_pruneZ-1); int mopidx = ppk*m_pruneY*m_pruneX + ppj*m_pruneX + ppi; int tag = m_pruneData[3*mopidx + 2]; // channel 2 has tag information if (tag > 0) { Vec tc = Vec(m_tagColors[4*tag+0], m_tagColors[4*tag+1], m_tagColors[4*tag+2]); float tagOp = m_tagColors[4*tag+3]/255.0f; tc *= tagOp; r = (1-tagOp)*r + tagOp*tc.x; g = (1-tagOp)*g + tagOp*tc.y; b = (1-tagOp)*b + tagOp*tc.z; a = qMax(tagOp, a); } } rgb = (1-a)*rgb + Vec(r,g,b)/255.0f; tota = (1-a)*tota + a; //rgb += Vec(r,g,b)/255.0f; //tota += a; } vpos += normal; gpos += normal; } // if (tota < 0.01) tota = 1.0; // rgb /= tota; rgb *= 255; QColor col = QColor(rgb.x, rgb.y, rgb.z, 255*tota); return col; }
void PowerDevilRunner::match(Plasma::RunnerContext &context) { const QString term = context.query(); if (term.length() < m_shortestCommand) { return; } QList<Plasma::QueryMatch> matches; QString parameter; if (parseQuery(term, QList<QRegExp>() << QRegExp(i18nc("Note this is a KRunner keyword; %1 is a parameter", "power profile %1", "(.*)"), Qt::CaseInsensitive) << QRegExp(i18nc("Note this is a KRunner keyword", "power profile"), Qt::CaseInsensitive), parameter)) { for (StringStringMap::const_iterator i = m_availableProfiles.constBegin(); i != m_availableProfiles.constEnd(); ++i) { if (!parameter.isEmpty()) { if (!i.value().startsWith(parameter, Qt::CaseInsensitive)) { continue; } } Plasma::QueryMatch match(this); match.setType(Plasma::QueryMatch::ExactMatch); match.setIcon(KIcon(m_profileIcon[i.key()])); match.setText(i18n("Set Profile to '%1'", i.value())); match.setData(i.key()); match.setRelevance(1); match.setId("ProfileChange "+ i.key()); matches.append(match); } } else if (parseQuery(term, QList<QRegExp>() << QRegExp(i18nc("Note this is a KRunner keyword; %1 is a parameter", "screen brightness %1", "(.*)"), Qt::CaseInsensitive) << QRegExp(i18nc("Note this is a KRunner keyword", "screen brightness"), Qt::CaseInsensitive) << QRegExp(i18nc("Note this is a KRunner keyword; %1 is a parameter", "dim screen %1", "(.*)"), Qt::CaseInsensitive) << QRegExp(i18nc("Note this is a KRunner keyword", "dim screen"), Qt::CaseInsensitive), parameter)) { if (!parameter.isEmpty()) { bool test; int b = parameter.toInt(&test); if (test) { int brightness = qBound(0, b, 100); Plasma::QueryMatch match(this); match.setType(Plasma::QueryMatch::ExactMatch); match.setIcon(KIcon("preferences-system-power-management")); match.setText(i18n("Set Brightness to %1", brightness)); match.setData(brightness); match.setRelevance(1); match.setId("BrightnessChange"); matches.append(match); } } else { Plasma::QueryMatch match1(this); match1.setType(Plasma::QueryMatch::ExactMatch); match1.setIcon(KIcon("preferences-system-power-management")); match1.setText(i18n("Dim screen totally")); match1.setRelevance(1); match1.setId("DimTotal"); matches.append(match1); Plasma::QueryMatch match2(this); match2.setType(Plasma::QueryMatch::ExactMatch); match2.setIcon(KIcon("preferences-system-power-management")); match2.setText(i18n("Dim screen by half")); match2.setRelevance(1); match2.setId("DimHalf"); matches.append(match2); Plasma::QueryMatch match3(this); match3.setType(Plasma::QueryMatch::ExactMatch); match3.setIcon(KIcon("video-display")); match3.setText(i18n("Turn off screen")); match3.setRelevance(1); match3.setId("TurnOffScreen"); matches.append(match3); } } else if (term.compare(i18nc("Note this is a KRunner keyword", "suspend"), Qt::CaseInsensitive) == 0) { QSet< Solid::PowerManagement::SleepState > states = Solid::PowerManagement::supportedSleepStates(); if (states.contains(Solid::PowerManagement::SuspendState)) { addSuspendMatch(Solid::PowerManagement::SuspendState, matches); } if (states.contains(Solid::PowerManagement::HibernateState)) { addSuspendMatch(Solid::PowerManagement::HibernateState, matches); } } else if (term.compare(i18nc("Note this is a KRunner keyword", "sleep"), Qt::CaseInsensitive) == 0 || term.compare(i18nc("Note this is a KRunner keyword", "to ram"), Qt::CaseInsensitive) == 0) { addSuspendMatch(Solid::PowerManagement::SuspendState, matches); } else if (term.compare(i18nc("Note this is a KRunner keyword", "hibernate"), Qt::CaseInsensitive) == 0 || term.compare(i18nc("Note this is a KRunner keyword", "to disk"), Qt::CaseInsensitive) == 0) { addSuspendMatch(Solid::PowerManagement::HibernateState, matches); } if (!matches.isEmpty()) { context.addMatches(term, matches); } }
//----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tRepowerMotoringWidgetSimrad::PaintBars( QPainter& painter, QVector< float >& values, bool isLeft ) { if ( m_pEngineRPMGauge ) { painter.save(); QRect gaugeRect = m_pEngineRPMGauge->geometry(); const int barWidth( qRound( gaugeRect.height() * 0.05 ) ); const int offsetValue ( qRound( barWidth + ( barWidth * 0.5 ) ) ); const int cStep( offsetValue / 4 ) ; int totalOffset( int( offsetValue / 1.5 ) ); int count( 0 ); foreach( float value, values ) { QRect middleRect( gaugeRect ); tDigitalData data( DATA_TYPE_ENGINE_TEMP ); middleRect.adjust( -totalOffset, -totalOffset, totalOffset, totalOffset ); if ( true == isLeft ) { data = tDigitalData( DATA_TYPE_ENGINE_TRIM ); } qreal span( ( 45 - ( count * cStep ) ) ); count ++; int spanForArc( int( span * 16 ) ); qreal leftStartAngle( 180 * 16 ); qreal rightStartAngle( 360 * 16 ); // Red bit tNOSStyle* pStyle = qobject_cast< tNOSStyle* >( style() ); Assert( pStyle ); QColor redColour( Qt::red ); if ( pStyle ) { redColour = pStyle->GetColor( tNOSStyle::eNCR_Destructive ); } painter.setPen( QPen( redColour, barWidth ) ); if ( true == isLeft ) { painter.drawArc( middleRect, int( leftStartAngle - ( spanForArc / 2 ) ), spanForArc ); } else { painter.drawArc( middleRect, int( rightStartAngle - ( spanForArc / 2 ) ), spanForArc ); } // Black bit span -= cRedLineWidth; int blackSpan( int( span * 16 ) ); painter.setPen( QPen( palette().color( QPalette::Active, QPalette::Background ), barWidth ) ); if ( true == isLeft ) { painter.translate( QPoint( cRedLineWidth, 0 ) ); painter.drawArc( middleRect, int( leftStartAngle - ( blackSpan / 2 ) ), blackSpan ); } else { painter.translate( QPoint( -cRedLineWidth, 0 ) ); painter.drawArc( middleRect, int( rightStartAngle- ( blackSpan / 2 ) ), blackSpan ); } // Grey bit. span -= ( cBlackLineWidth / 3 ); int greyBarWidth( barWidth - ( cBlackLineWidth * 3 ) ); int greySpan( int( span * 16 ) ); QColor greyColour( palette().color( QPalette::Disabled, QPalette::Text ) ); greyColour.setAlpha( 100 ); painter.setPen( QPen( greyColour, greyBarWidth ) ); if ( true == isLeft ) { painter.translate( QPoint( cBlackLineWidth / 3, 0 ) ); painter.drawArc( middleRect, int( leftStartAngle - ( greySpan / 2 ) ), greySpan ); painter.translate( QPoint( -cBlackLineWidth / 3, 0 ) ); } else { painter.translate( QPoint( -cBlackLineWidth / 3, 0 ) ); painter.drawArc( middleRect, int( rightStartAngle - ( greySpan / 2 ) ), greySpan ); painter.translate( QPoint( cBlackLineWidth / 3, 0 ) ); } // White bit if ( value > 0 ) { painter.setPen( QPen( palette().color( QPalette::Active, QPalette::Text ), greyBarWidth ) ); float fillPercentage( qBound( 0.0f, ( 1 / data.Max() ) * value, 1.0f ) ); int fillSpan( int( span * fillPercentage * 16 ) ); // Adjust the value to take into account the line thickness. if ( fillSpan > greyBarWidth ) { fillSpan -= int( greyBarWidth ); } if ( true == isLeft ) { painter.drawArc( middleRect, int( ( leftStartAngle - ( greySpan / 2) ) ) + ( greySpan - fillSpan ), fillSpan ); } else { painter.drawArc( middleRect, int( rightStartAngle - ( greySpan / 2 ) ), fillSpan ); } } // Black lines qreal greyAreaHalfWidth( ( ( barWidth - cRedLineWidth - cBlackLineWidth ) / 2 ) ); qreal quarterRotation( span / 4 ); painter.setPen( QPen( Qt::black, cBlackLineWidth ) ); painter.save(); QPointF centrePoint( 0, middleRect.width() / 2 ); painter.translate( middleRect.center() ); painter.rotate( quarterRotation ); if ( true == isLeft ) { painter.drawLine( QPointF( - ( middleRect.width() / 2 ) - greyAreaHalfWidth, 0 ), QPointF( - ( middleRect.width() / 2 ) + greyAreaHalfWidth, 0 ) ); } else { painter.drawLine( QPointF( ( middleRect.width() / 2 ) - greyAreaHalfWidth, 0 ), QPointF( ( middleRect.width() / 2 ) + greyAreaHalfWidth, 0 ) ); } painter.translate( QPoint( 0, 0 ) ); painter.restore(); painter.save(); if ( true == isLeft ) { painter.drawLine( QPointF( middleRect.left() + greyAreaHalfWidth, middleRect.center().y() ), QPointF( middleRect.left() - greyAreaHalfWidth, middleRect.center().y() ) ); } else { painter.drawLine( QPointF( middleRect.right() + greyAreaHalfWidth, middleRect.center().y() ), QPointF( middleRect.right() - greyAreaHalfWidth, middleRect.center().y() ) ); } painter.restore(); painter.save(); centrePoint = QPointF( 0, middleRect.width() / 2 ); painter.translate( middleRect.center() ); painter.rotate( - ( quarterRotation ) ); if ( true == isLeft ) { painter.drawLine( QPointF( - ( middleRect.width() / 2 ) - greyAreaHalfWidth, 0 ), QPointF( - ( middleRect.width() / 2 ) + greyAreaHalfWidth, 0 ) ); } else { painter.drawLine( QPointF( ( middleRect.width() / 2 ) - greyAreaHalfWidth, 0 ), QPointF( ( middleRect.width() / 2 ) + greyAreaHalfWidth, 0 ) ); } painter.translate( QPoint( 0, 0 ) ); painter.restore(); totalOffset += offsetValue; } painter.restore(); }
/*! \internal effectiveSizeHint has a quirky behavior, one of the quirkinesses is when the hfw function is combined with user-specified min/max sizes. The input to hfw function (e.g width) must be within the min/max width constraint, and the output must be within the min/max height. This sets up a loose dependency between minimum width and maximum height (or minimum height, depending on the type of hfw function). Note that its only the concrete subclass that implements that hfw function that knows if this dependency means that the height will increase or decrease when the width is increased. The application should try to ensure that the user-defined sizes are within the range so that they don't conflict with the hfw function. Suppose, for instance that the hfw function is: height = 2000/width and the item has these user-defined sizes: min ( 5, 5) pref(100, 10) max (500,100) what is the return value if one calls item->effectiveSizeHint(Qt::MinimumSize, QSizeF(10, -1)); ? The sizeHint() function would return QSizeF(10, 200), but it would be bounded down to 100 due to the max value, so it would return (10, 100). This is not what the item expects, since it really wants that its hfw is respected. If this is a label with wrapped text, this would most likely lead to that some text is clipped. This is certainly not what the app developer wants. Now, it would be better if the user changed those constraints to match the hfw function: min ( 20, 5) pref(100, 10) max (500,100) here, it says that the width cannot be smaller than 20. This is because if it becomes smaller than 20 the result of the hfw function would violate the max height (100). However, there is a similar problem if the width passed to the hfw function reaches *max* width: the sizeHint() function would now return QSizeF(500, 4), but 4 is smaller than the minimum height (5), so effectiveSizeHint() would return (500, 5), which would leave too much space. In this case, setting the max width to 400 fixes the problem: min ( 20, 5) pref(100, 10) max (400,100) The implementor of a hfw widget must be aware of this when sizeHint() is reimplemented, so that the default min and max sizes works sensible. (unfortunately the implementor does not have the control over user-set values). */ QSizeF *QGraphicsLayoutItemPrivate::effectiveSizeHints(const QSizeF &constraint) const { Q_Q(const QGraphicsLayoutItem); QSizeF *sizeHintCache; const bool hasConstraint = constraint.width() >= 0 || constraint.height() >= 0; QSizeF adjustedConstraint = constraint; if (hasConstraint) { if (!sizeHintWithConstraintCacheDirty && constraint == cachedConstraint) return cachedSizeHintsWithConstraints; const QSizeF *hintsWithoutConstraint = effectiveSizeHints(QSizeF(-1,-1)); if (adjustedConstraint.width() >= 0) adjustedConstraint.setWidth( qBound( hintsWithoutConstraint[Qt::MinimumSize].width(), adjustedConstraint.width(), hintsWithoutConstraint[Qt::MaximumSize].width())); if (adjustedConstraint.height() >= 0) adjustedConstraint.setHeight( qBound( hintsWithoutConstraint[Qt::MinimumSize].height(), adjustedConstraint.height(), hintsWithoutConstraint[Qt::MaximumSize].height())); if (!sizeHintWithConstraintCacheDirty && adjustedConstraint == cachedConstraint) return cachedSizeHintsWithConstraints; sizeHintCache = cachedSizeHintsWithConstraints; } else { if (!sizeHintCacheDirty) return cachedSizeHints; sizeHintCache = cachedSizeHints; } for (int i = 0; i < Qt::NSizeHints; ++i) { sizeHintCache[i] = adjustedConstraint; if (userSizeHints) combineSize(sizeHintCache[i], userSizeHints[i]); } QSizeF &minS = sizeHintCache[Qt::MinimumSize]; QSizeF &prefS = sizeHintCache[Qt::PreferredSize]; QSizeF &maxS = sizeHintCache[Qt::MaximumSize]; QSizeF &descentS = sizeHintCache[Qt::MinimumDescent]; normalizeHints(minS.rwidth(), prefS.rwidth(), maxS.rwidth(), descentS.rwidth()); normalizeHints(minS.rheight(), prefS.rheight(), maxS.rheight(), descentS.rheight()); // if the minimum, preferred and maximum sizes contradict each other // (e.g. the minimum is larger than the maximum) we give priority to // the maximum size, then the minimum size and finally the preferred size COMBINE_SIZE(maxS, q->sizeHint(Qt::MaximumSize, maxS)); combineSize(maxS, QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); expandSize(maxS, prefS); expandSize(maxS, minS); boundSize(maxS, QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); COMBINE_SIZE(minS, q->sizeHint(Qt::MinimumSize, minS)); expandSize(minS, QSizeF(0, 0)); boundSize(minS, prefS); boundSize(minS, maxS); COMBINE_SIZE(prefS, q->sizeHint(Qt::PreferredSize, prefS)); expandSize(prefS, minS); boundSize(prefS, maxS); // Not supported yet // COMBINE_SIZE(descentS, q->sizeHint(Qt::MinimumDescent, constraint)); if (hasConstraint) { cachedConstraint = adjustedConstraint; sizeHintWithConstraintCacheDirty = false; } else { sizeHintCacheDirty = false; } return sizeHintCache; }
int setProgress(const int p) { const int old = _progress; _progress = qBound(0, p, 100); return old; }
void PropagateUploadFileNG::slotPutFinished() { PUTFileJob *job = qobject_cast<PUTFileJob *>(sender()); ASSERT(job); slotJobDestroyed(job); // remove it from the _jobs list propagator()->_activeJobList.removeOne(this); if (_finished) { // We have sent the finished signal already. We don't need to handle any remaining jobs return; } QNetworkReply::NetworkError err = job->reply()->error(); if (err != QNetworkReply::NoError) { _item->_httpErrorCode = job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); commonErrorHandling(job); return; } ENFORCE(_sent <= _item->_size, "can't send more than size"); // Adjust the chunk size for the time taken. // // Dynamic chunk sizing is enabled if the server configured a // target duration for each chunk upload. double targetDuration = propagator()->syncOptions()._targetChunkUploadDuration; if (targetDuration > 0) { double uploadTime = job->msSinceStart() + 1; // add one to avoid div-by-zero auto predictedGoodSize = static_cast<quint64>( _currentChunkSize / uploadTime * targetDuration); // The whole targeting is heuristic. The predictedGoodSize will fluctuate // quite a bit because of external factors (like available bandwidth) // and internal factors (like number of parallel uploads). // // We use an exponential moving average here as a cheap way of smoothing // the chunk sizes a bit. quint64 targetSize = (propagator()->_chunkSize + predictedGoodSize) / 2; // Adjust the dynamic chunk size _chunkSize used for sizing of the item's chunks to be send propagator()->_chunkSize = qBound( propagator()->syncOptions()._minChunkSize, targetSize, propagator()->syncOptions()._maxChunkSize); qCInfo(lcPropagateUpload) << "Chunked upload of" << _currentChunkSize << "bytes took" << uploadTime << "ms, desired is" << targetDuration << "ms, expected good chunk size is" << predictedGoodSize << "bytes and nudged next chunk size to " << propagator()->_chunkSize << "bytes"; } bool finished = _sent == _item->_size; // Check if the file still exists const QString fullFilePath(propagator()->getFilePath(_item->_file)); if (!FileSystem::fileExists(fullFilePath)) { if (!finished) { abortWithError(SyncFileItem::SoftError, tr("The local file was removed during sync.")); return; } else { propagator()->_anotherSyncNeeded = true; } } // Check whether the file changed since discovery. if (!FileSystem::verifyFileUnchanged(fullFilePath, _item->_size, _item->_modtime)) { propagator()->_anotherSyncNeeded = true; if (!finished) { abortWithError(SyncFileItem::SoftError, tr("Local file changed during sync.")); return; } } if (!finished) { // Deletes an existing blacklist entry on successful chunk upload if (_item->_hasBlacklistEntry) { propagator()->_journal->wipeErrorBlacklistEntry(_item->_file); _item->_hasBlacklistEntry = false; } // Reset the error count on successful chunk upload auto uploadInfo = propagator()->_journal->getUploadInfo(_item->_file); uploadInfo._errorCount = 0; propagator()->_journal->setUploadInfo(_item->_file, uploadInfo); propagator()->_journal->commit("Upload info"); } startNextChunk(); }
void X11EmbedContainer::ensureValidSize() { QSize s = QSize(qBound(minimumSize().width(), width(), maximumSize().width()), qBound(minimumSize().height(), height(), maximumSize().height())); resize(s); }
bool FHGAACEncoder::encode(const QString &sourceFile, const AudioFileModel_MetaInfo &metaInfo, const unsigned int duration, const unsigned int channels, const QString &outputFile, volatile bool *abortFlag) { QProcess process; QStringList args; int maxBitrate = 576; if(m_configRCMode == SettingsModel::CBRMode) { switch(m_configProfile) { case 1: args << L1S("--profile") << L1S("lc"); //Forces use of LC AAC profile break; case 2: maxBitrate = 128; args << L1S("--profile") << L1S("he"); //Forces use of HE AAC profile break; case 3: maxBitrate = 56; args << L1S("--profile") << L1S("hev2"); //Forces use of HEv2 AAC profile break; } } switch(m_configRCMode) { case SettingsModel::CBRMode: args << L1S("--cbr") << QString::number(qBound(8, index2bitrate(m_configBitrate), maxBitrate)); break; case SettingsModel::VBRMode: args << L1S("--vbr") << QString::number(qBound(1, m_configBitrate + 1, 6)); break; default: MUTILS_THROW("Bad rate-control mode!"); break; } //args << "--dll" << m_binary_dll; if(!m_configCustomParams.isEmpty()) args << m_configCustomParams.split(" ", QString::SkipEmptyParts); args << QDir::toNativeSeparators(sourceFile); args << QDir::toNativeSeparators(outputFile); if(!startProcess(process, m_binary_enc, args)) { return false; } bool bTimeout = false; bool bAborted = false; int prevProgress = -1; QRegExp regExp(L1S("Progress:\\s*(\\d+)%")); while(process.state() != QProcess::NotRunning) { if(*abortFlag) { process.kill(); bAborted = true; emit messageLogged(L1S("\nABORTED BY USER !!!")); break; } process.waitForReadyRead(m_processTimeoutInterval); if(!process.bytesAvailable() && process.state() == QProcess::Running) { process.kill(); qWarning("FhgAacEnc process timed out <-- killing!"); emit messageLogged(L1S("\nPROCESS TIMEOUT !!!")); bTimeout = true; break; } while(process.bytesAvailable() > 0) { QByteArray line = process.readLine(); QString text = QString::fromUtf8(line.constData()).simplified(); if(regExp.lastIndexIn(text) >= 0) { bool ok = false; int progress = regExp.cap(1).toInt(&ok); if(ok && (progress > prevProgress)) { emit statusUpdated(progress); prevProgress = qMin(progress + 2, 99); } } else if(!text.isEmpty()) { emit messageLogged(text); } } } process.waitForFinished(); if(process.state() != QProcess::NotRunning) { process.kill(); process.waitForFinished(-1); } emit statusUpdated(100); emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode())); if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS) { return false; } return true; }
// Hàm dùng lọc ảnh bằng các filter tương ứng QImage ExtraFiltersPlugin::filterImage(const QString &filter, const QImage &image, QWidget *parent) { // Chuyển đổi định dạng ảnh sang RGB 32-bit để các hàm làm việc như mong // đợi QImage original = image.convertToFormat(QImage::Format_RGB32); QImage result = original; if (filter == tr("Lật ngang")) { // Nếu filter là "Lật ngang" thì hoán đổi các pixel của ảnh theo chiều // ngang của ảnh for (int y = 0; y < original.height(); ++y) { for (int x = 0; x < original.width(); ++x) { int pixel = original.pixel(original.width() - x - 1, y); result.setPixel(x, y, pixel); } } } else if (filter == tr("Lật dọc")) { // Nếu filter là "Lật dọc" thì hoán đổi các pixel của ảnh theo chiều // dọc của ảnh for (int y = 0; y < original.height(); ++y) { for (int x = 0; x < original.width(); ++x) { int pixel = original.pixel(x, original.height() - y - 1); result.setPixel(x, y, pixel); } } } else if (filter == tr("Làm mờ")) { // Ta sẽ nhân từng điểm ảnh với ma trận tích chập để làm mờ // trừ các điểm ở biên. int kernel[5][5] = {{0, 0, 1, 0, 0}, {0, 1, 3, 1, 0}, {1, 3, 7, 3, 1}, {0, 1, 3, 1, 0}, {0, 0, 1, 0, 0} }; int kernelSize = 5; int sumKernel = 27; int r, g, b; int pixel; for (int x = kernelSize / 2; x < original.width() - (kernelSize / 2); ++x) { for (int y = kernelSize / 2; y < original.height() - (kernelSize / 2); ++y) { r = 0; g = 0; b = 0; // Tính tổng giá trị màu của điểm pixel và các điểm ảnh xung quanh for ( int i = -kernelSize / 2 ; i <= kernelSize / 2 ; ++i) { for ( int j = -kernelSize / 2 ; j <= kernelSize / 2 ; ++j) { pixel = original.pixel ( x + i , y + j ); r += qRed(pixel) * kernel[kernelSize / 2 + i][kernelSize / 2 + j] ; g += qGreen(pixel) * kernel[kernelSize / 2 + i][kernelSize / 2 + j]; b += qBlue(pixel) * kernel[kernelSize / 2 + i][kernelSize / 2 + j]; } } // Kiểm tra giá trị các màu trong khoảng giới hạn r = qBound ( 0 , r / sumKernel , 255 ); g = qBound ( 0 , g / sumKernel , 255 ); b = qBound ( 0 , b / sumKernel , 255 ); result.setPixel ( x, y, qRgba(r , g , b, qAlpha(pixel))); } } } else if (filter == tr("Ảnh nhị phân")) { // Nếu filter là "Ảnh nhị phân" thì bật QInputDialog lên cho người dùng // nhập vào giá trị ngưỡng, nằm trong khoảng 0 đến 255 bool ok; // Kiểm tra giá trị nhập int threshold = QInputDialog::getInt(parent, tr("Ảnh nhị phân"), tr("Nhập ngưỡng:"), 85, 0, 255, 1, &ok); // Đầu tiên ta chuyển ảnh về ảnh đa mức xám rồi so sánh từng pixel của // ảnh với giá trị ngưỡng. if (ok) { for (int y = 0; y < original.height(); ++y) { for (int x = 0; x < original.width(); ++x) { int pixel = original.pixel(x, y); int gray = qGray(pixel); gray = gray > threshold ? 255 : 0; pixel = qRgb(gray, gray, gray); result.setPixel(x, y, pixel); } } } } else if (filter == tr("Ảnh âm bản")) { // Dùng hàm invertPixels() để đảo ngược các pixel. result.invertPixels(); } else if (filter == tr("Đảo màu (RGB->BGR)")) { // Dùng hàm rgbSwapped() để chuyển kênh màu của ảnh từ RGB sang BGR result = result.rgbSwapped(); } else if (filter == tr("Đa mức xám")) { // for (int y = 0; y < result.height(); ++y) { for (int x = 0; x < result.width(); ++x) { int pixel = result.pixel(x, y); int gray = qGray(pixel); int alpha = qAlpha(pixel); result.setPixel(x, y, qRgba(gray, gray, gray, alpha)); } } } else if (filter == tr("Độ sáng")) { // Nếu filter là "Độ sáng" thì bật QInputDialog lên cho người dùng // nhập vào giá trị ngưỡng, giá trị này trong khoảng -255 đến 255 bool ok; // Kiểm tra giá trị nhập int brighness = QInputDialog::getInt(parent, tr("Độ sáng"), tr("Nhập độ sáng:"), 10, -255, 255, 1, &ok); // Ta tăng hoặc giảm giá trị các màu của từng pixel if (ok) { int r, g, b; for (int x = 0; x < original.width(); x++) { for (int y = 0; y < original.height(); y++) { int pixel = original.pixel(x, y); r = qRed(pixel) + brighness; g = qGreen(pixel) + brighness; b = qBlue(pixel) + brighness; //Ta kiểm tra các giá trị mới trong khoảng cho phép. r = qBound(0, r, 255); g = qBound(0, g, 255); b = qBound(0, b, 255); result.setPixel(x, y, qRgba(r, g, b, qAlpha(pixel))); } } } } else if (filter == tr("Làm ấm")) { // Nếu filter là "Làm ấm" thì bật QInputDialog lên cho người dùng // nhập vào giá trị, giá trị này trong khoảng 1 đến 255 bool ok; // Kiểm tra giá trị nhập int delta = QInputDialog::getInt(parent, tr("Lầm ấm"), tr("Nhập mức độ ấm:"), 10, 1, 255, 1, &ok); // Hình sẽ trong ấm hơn nếu ta tăng độ vàng của ảnh, và màu vàng được // tổng hợp từ màu đỏ và xanh lục trong kênh màu RGB if (ok) { int r, g, b; for (int x = 0; x < original.width(); x++) { for (int y = 0; y < original.height(); y++) { int pixel = original.pixel(x, y); r = qRed(pixel) + delta; g = qGreen(pixel) + delta; b = qBlue(pixel); //Ta kiểm tra các giá trị mới trong khoảng cho phép. r = qBound(0, r, 255); g = qBound(0, g, 255); result.setPixel(x, y, qRgba(r, g, b, qAlpha(pixel))); } } } } else if (filter == tr("Làm mát...")) { // Nếu filter là "Làm mát" thì bật QInputDialog lên cho người dùng // nhập vào giá trị, giá trị này trong khoảng 1 đến 255 bool ok; // Kiểm tra giá trị nhập int delta = QInputDialog::getInt(parent, tr("Lầm mát"), tr("Nhập mức độ mát:"), 10, 1, 256, 1, &ok); // Hình sẽ có cảm giác mát hơn khi ta tăng giá trị kênh màu xanh lam if (ok) { int r, g, b; for (int x = 0; x < original.width(); x++) { for (int y = 0; y < original.height(); y++) { int pixel = original.pixel(x, y); r = qRed(pixel); g = qGreen(pixel); b = qBlue(pixel) + delta; //Ta kiểm tra giá trị mới trong khoảng cho phép. b = qBound(0, b, 255); result.setPixel(x, y, qRgba(r, g, b, qAlpha(pixel))); } } } } else if (filter == tr("Độ bão hòa")) { // Nếu filter là "Độ bão hòa" thì bật QInputDialog lên cho người dùng // nhập vào giá trị, giá trị này trong khoảng -255 đến 255 bool ok; // Kiểm tra giá trị nhập vào int delta = QInputDialog::getInt(parent, tr("Độ bão hòa"), tr("Nhập độ bão hòa:"), 10, -255, 255, 1, &ok); QColor newClolor; QColor oldColor; int h, s, l; // Ta chuyển hình về kênh màu HSL rồi sau đó tăng hoặc giảm kênh // saturation để tăng hoặc giảm độ bão hòa sau đó lại chuyển ảnh về RGB if (ok) { for (int y = 0; y < original.height(); ++y) { for (int x = 0; x < original.width(); ++x) { oldColor = QColor(original.pixel(x, y)); newClolor = oldColor.toHsl(); h = newClolor.hue(); s = newClolor.saturation() + delta; l = newClolor.lightness(); // Ta kiểm tra giá trị mới trong khoảng cho phép s = qBound(0, s, 255); newClolor.setHsl(h, s, l); result.setPixel(x, y, qRgba(newClolor.red(), newClolor.green(), newClolor.blue(), newClolor.alpha())); } } } } return result; }
void MapView::setZoom(double value) { zoom = qBound(zoom_out_limit, value, zoom_in_limit); updateTransform(ZoomChange); }
void AbstractClipItem::updateKeyFramePos(int frame, const double y) { m_keyframeView.updateKeyFramePos(rect(), frame, qBound(0.0, y, rect().height())); }
ProgressInfo::Estimates ProgressInfo::totalProgress() const { Estimates file = _fileProgress.estimates(); if (_sizeProgress._total == 0) { return file; } Estimates size = _sizeProgress.estimates(); // Ideally the remaining time would be modeled as: // remaning_file_sizes / transfer_speed // + remaining_file_count * per_file_overhead // + remaining_chunked_file_sizes / chunked_reassembly_speed // with us estimating the three parameters in conjunction. // // But we currently only model the bandwidth and the files per // second independently, which leads to incorrect values. To slightly // mitigate this problem, we combine the two models depending on // which factor dominates (essentially big-file-upload vs. // many-small-files) // // If we have size information, we prefer an estimate based // on the upload speed. That's particularly relevant for large file // up/downloads, where files per second will be close to 0. // // However, when many *small* files are transfered, the estimate // can become very pessimistic as the transfered amount per second // drops significantly. // // So, if we detect a high rate of files per second or a very low // transfer rate (often drops hugely during a sequence of deletes, // for instance), we gradually prefer an optimistic estimate and // assume the remaining transfer will be done with the highest speed // we've seen. // This assumes files and transfers finish as quickly as possible // *but* note that maxPerSecond could be serious underestimates // (if we never got to fully excercise transfer or files/second) quint64 optimisticEta = _fileProgress.remaining() / _maxFilesPerSecond * 1000 + _sizeProgress.remaining() / _maxBytesPerSecond * 1000; // Compute a value that is 0 when fps is <=L*max and 1 when fps is >=U*max double fps = _fileProgress._progressPerSec; double fpsL = 0.5; double fpsU = 0.8; double nearMaxFps = qBound(0.0, (fps - fpsL * _maxFilesPerSecond) / ((fpsU - fpsL) * _maxFilesPerSecond), 1.0); // Compute a value that is 0 when transfer is >= U*max and // 1 when transfer is <= L*max double trans = _sizeProgress._progressPerSec; double transU = 0.1; double transL = 0.01; double slowTransfer = 1.0 - qBound(0.0, (trans - transL * _maxBytesPerSecond) / ((transU - transL) * _maxBytesPerSecond), 1.0); double beOptimistic = nearMaxFps * slowTransfer; size.estimatedEta = (1.0 - beOptimistic) * size.estimatedEta + beOptimistic * optimisticEta; return size; }
/*! \brief Specify the visible portion of the wheel. You may use this function for fine-tuning the appearance of the wheel. The default value is 175 degrees. The value is limited from 10 to 175 degrees. \param angle Visible angle in degrees \sa viewAngle(), setTotalAngle() */ void QwtWheel::setViewAngle( double angle ) { d_data->viewAngle = qBound( 10.0, angle, 175.0 ); update(); }
void OpenGL2Common::paintGL() { const bool frameIsEmpty = videoFrame.isEmpty(); if (updateTimer.isActive()) updateTimer.stop(); if (frameIsEmpty && !hasImage) return; const QSize winSize = widget()->size(); bool resetDone = false; if (!frameIsEmpty && hwAccellPossibleLock()) { const GLsizei widths[3] = { videoFrame.size.width, videoFrame.size.chromaWidth(), videoFrame.size.chromaWidth(), }; const GLsizei heights[3] = { videoFrame.size.height, videoFrame.size.chromaHeight(), videoFrame.size.chromaHeight() }; if (doReset) { if (hwAccellnterface) { /* Release HWAccell resources */ hwAccellnterface->clear(false); if (hwAccellnterface->canInitializeTextures()) { if (numPlanes == 2) { //NV12 for (int p = 0; p < 2; ++p) { glBindTexture(target, textures[p + 1]); glTexImage2D(target, 0, !p ? GL_R8 : GL_RG8, widths[p], heights[p], 0, !p ? GL_RED : GL_RG, GL_UNSIGNED_BYTE, nullptr); } } else if (numPlanes == 1) { //RGB32 glBindTexture(target, textures[1]); glTexImage2D(target, 0, GL_RGBA, widths[0], heights[0], 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); } } m_textureSize = QSize(widths[0], heights[0]); if (hqScaling) { // Must be set before "HWAccelInterface::init()" and must have "m_textureSize" maybeSetMipmaps(widget()->devicePixelRatioF()); } /* Prepare textures, register GL textures */ const bool hasHwAccelError = hwAccelError; hwAccelError = !hwAccellnterface->init(&textures[1]); if (hwAccelError && !hasHwAccelError) QMPlay2Core.logError("OpenGL 2 :: " + tr("Can't init textures for") + " " + hwAccellnterface->name()); /* Prepare texture coordinates */ texCoordYCbCr[2] = texCoordYCbCr[6] = 1.0f; } else { /* Check linesize */ const qint32 halfLinesize = (videoFrame.linesize[0] >> videoFrame.size.chromaShiftW); correctLinesize = ( (halfLinesize == videoFrame.linesize[1] && videoFrame.linesize[1] == videoFrame.linesize[2]) && (!sphericalView ? (videoFrame.linesize[1] == halfLinesize) : (videoFrame.linesize[0] == widths[0])) ); /* Prepare textures */ for (qint32 p = 0; p < 3; ++p) { const GLsizei w = correctLinesize ? videoFrame.linesize[p] : widths[p]; const GLsizei h = heights[p]; if (p == 0) m_textureSize = QSize(w, h); if (hasPbo) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo[p + 1]); glBufferData(GL_PIXEL_UNPACK_BUFFER, w * h, nullptr, GL_DYNAMIC_DRAW); } glBindTexture(GL_TEXTURE_2D, textures[p + 1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, w, h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, nullptr); } /* Prepare texture coordinates */ texCoordYCbCr[2] = texCoordYCbCr[6] = (videoFrame.linesize[0] == widths[0]) ? 1.0f : (widths[0] / (videoFrame.linesize[0] + 1.0f)); if (hqScaling) maybeSetMipmaps(widget()->devicePixelRatioF()); } resetDone = true; hasImage = false; } if (hwAccellnterface) { const HWAccelInterface::Field field = (HWAccelInterface::Field)Functions::getField(videoFrame, Deinterlace, HWAccelInterface::FullFrame, HWAccelInterface::TopField, HWAccelInterface::BottomField); bool imageReady = false; if (!hwAccelError) { const HWAccelInterface::CopyResult res = hwAccellnterface->copyFrame(videoFrame, field); if (res == HWAccelInterface::CopyOk) imageReady = true; else if (res == HWAccelInterface::CopyError) { QMPlay2Core.logError("OpenGL 2 :: " + hwAccellnterface->name() + " " + tr("texture copy error")); hwAccelError = true; } } hwAccellnterface->unlock(); if (!imageReady && !hasImage) return; for (int p = 0; p < numPlanes; ++p) { glActiveTexture(GL_TEXTURE0 + p); glBindTexture(target, textures[p + 1]); if (m_useMipmaps) glGenerateMipmap(target); } } else { /* Load textures */ for (qint32 p = 0; p < 3; ++p) { const quint8 *data = videoFrame.buffer[p].constData(); const GLsizei w = correctLinesize ? videoFrame.linesize[p] : widths[p]; const GLsizei h = heights[p]; if (hasPbo) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo[p + 1]); quint8 *dst; if (glMapBufferRange) dst = (quint8 *)glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, w * h, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); else dst = (quint8 *)glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY); if (!dst) glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); else { if (correctLinesize) memcpy(dst, data, w * h); else for (int y = 0; y < h; ++y) { memcpy(dst, data, w); data += videoFrame.linesize[p]; dst += w; } glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); data = nullptr; } } glActiveTexture(GL_TEXTURE0 + p); glBindTexture(GL_TEXTURE_2D, textures[p + 1]); if (hasPbo || correctLinesize) glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_LUMINANCE, GL_UNSIGNED_BYTE, data); else for (int y = 0; y < h; ++y) { glTexSubImage2D(GL_TEXTURE_2D, 0, 0, y, w, 1, GL_LUMINANCE, GL_UNSIGNED_BYTE, data); data += videoFrame.linesize[p]; } if (m_useMipmaps) glGenerateMipmap(GL_TEXTURE_2D); } if (hasPbo) glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } videoFrame.clear(); hasImage = true; } if (!sphericalView) { deleteSphereVbo(); shaderProgramVideo->setAttributeArray(positionYCbCrLoc, verticesYCbCr[verticesIdx], 2); shaderProgramVideo->setAttributeArray(texCoordYCbCrLoc, texCoordYCbCr, 2); } else { if (nIndices == 0) loadSphere(); glBindBuffer(GL_ARRAY_BUFFER, sphereVbo[0]); shaderProgramVideo->setAttributeBuffer(positionYCbCrLoc, GL_FLOAT, 0, 3); glBindBuffer(GL_ARRAY_BUFFER, sphereVbo[1]); shaderProgramVideo->setAttributeBuffer(texCoordYCbCrLoc, GL_FLOAT, 0, 2); glBindBuffer(GL_ARRAY_BUFFER, 0); } shaderProgramVideo->enableAttributeArray(positionYCbCrLoc); shaderProgramVideo->enableAttributeArray(texCoordYCbCrLoc); shaderProgramVideo->bind(); if (doReset) { const float brightness = videoAdjustment.brightness / 100.0f; const float contrast = (videoAdjustment.contrast + 100) / 100.0f; const float sharpness = videoAdjustment.sharpness / 50.0f; if (hwAccellnterface && numPlanes == 1) { hwAccellnterface->setVideAdjustment(videoAdjustment); const bool hasBrightness = videoAdjustmentKeys.contains("Brightness"); const bool hasContrast = videoAdjustmentKeys.contains("Contrast"); const bool hasSharpness = videoAdjustmentKeys.contains("Sharpness"); shaderProgramVideo->setUniformValue ( "uVideoAdj", hasBrightness ? 0.0f : brightness, hasContrast ? 1.0f : contrast, hasSharpness ? 0.0f : sharpness ); } else { const float saturation = (videoAdjustment.saturation + 100) / 100.0f; const float hue = videoAdjustment.hue / -31.831f; shaderProgramVideo->setUniformValue("uVideoEq", brightness, contrast, saturation, hue); shaderProgramVideo->setUniformValue("uSharpness", sharpness); } if (hqScaling) { const qreal dpr = widget()->devicePixelRatioF(); if (!resetDone) maybeSetMipmaps(dpr); const bool useBicubic = (W * dpr > m_textureSize.width() || H * dpr > m_textureSize.height()); shaderProgramVideo->setUniformValue("uBicubic", useBicubic ? 1 : 0); } shaderProgramVideo->setUniformValue("uTextureSize", m_textureSize); doReset = !resetDone; setMatrix = true; } if (setMatrix) { QMatrix4x4 matrix; if (!sphericalView) { matrix.scale(W / (qreal)winSize.width(), H / (qreal)winSize.height()); if (!videoOffset.isNull()) matrix.translate(-videoOffset.x(), videoOffset.y()); } else { const double z = qBound(-1.0, (zoom > 1.0 ? log10(zoom) : zoom - 1.0), 0.99); matrix.perspective(68.0, (qreal)winSize.width() / (qreal)winSize.height(), 0.001, 2.0); matrix.translate(0.0, 0.0, z); matrix.rotate(rot.x(), 1.0, 0.0, 0.0); matrix.rotate(rot.y(), 0.0, 0.0, 1.0); } shaderProgramVideo->setUniformValue("uMatrix", matrix); setMatrix = false; } if (!sphericalView) glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); else { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereVbo[2]); glDrawElements(GL_TRIANGLE_STRIP, nIndices, GL_UNSIGNED_SHORT, nullptr); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } shaderProgramVideo->release(); shaderProgramVideo->disableAttributeArray(texCoordYCbCrLoc); shaderProgramVideo->disableAttributeArray(positionYCbCrLoc); glActiveTexture(GL_TEXTURE3); /* OSD */ osdMutex.lock(); if (!osdList.isEmpty()) { glBindTexture(GL_TEXTURE_2D, textures[0]); QRect bounds; const qreal scaleW = (qreal)subsW / outW, scaleH = (qreal)subsH / outH; bool mustRepaint = Functions::mustRepaintOSD(osdList, osd_ids, &scaleW, &scaleH, &bounds); bool hasNewSize = false; if (!mustRepaint) mustRepaint = osdImg.size() != bounds.size(); if (mustRepaint) { if (osdImg.size() != bounds.size()) { osdImg = QImage(bounds.size(), QImage::Format_ARGB32); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bounds.width(), bounds.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); hasNewSize = true; } osdImg.fill(0); QPainter p(&osdImg); p.translate(-bounds.topLeft()); Functions::paintOSD(false, osdList, scaleW, scaleH, p, &osd_ids); const quint8 *data = osdImg.constBits(); if (hasPbo) { const GLsizeiptr dataSize = (osdImg.width() * osdImg.height()) << 2; glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo[0]); if (hasNewSize) glBufferData(GL_PIXEL_UNPACK_BUFFER, dataSize, nullptr, GL_DYNAMIC_DRAW); quint8 *dst; if (glMapBufferRange) dst = (quint8 *)glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, dataSize, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); else dst = (quint8 *)glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY); if (!dst) glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); else { memcpy(dst, data, dataSize); glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); data = nullptr; } } glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, bounds.width(), bounds.height(), GL_RGBA, GL_UNSIGNED_BYTE, data); if (hasPbo && !data) glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); } const QSizeF winSizeSubs = winSize * widget()->devicePixelRatioF(); const float left = (bounds.left() + subsX) * 2.0f / winSizeSubs.width() - osdOffset.x(); const float right = (bounds.right() + subsX + 1) * 2.0f / winSizeSubs.width() - osdOffset.x(); const float top = (bounds.top() + subsY) * 2.0f / winSizeSubs.height() - osdOffset.y(); const float bottom = (bounds.bottom() + subsY + 1) * 2.0f / winSizeSubs.height() - osdOffset.y(); const float verticesOSD[8] = { left - 1.0f, -bottom + 1.0f, right - 1.0f, -bottom + 1.0f, left - 1.0f, -top + 1.0f, right - 1.0f, -top + 1.0f, }; shaderProgramOSD->setAttributeArray(positionOSDLoc, verticesOSD, 2); shaderProgramOSD->setAttributeArray(texCoordOSDLoc, texCoordOSD, 2); shaderProgramOSD->enableAttributeArray(positionOSDLoc); shaderProgramOSD->enableAttributeArray(texCoordOSDLoc); glEnable(GL_BLEND); shaderProgramOSD->bind(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); shaderProgramOSD->release(); glDisable(GL_BLEND); shaderProgramOSD->disableAttributeArray(texCoordOSDLoc); shaderProgramOSD->disableAttributeArray(positionOSDLoc); } osdMutex.unlock(); glBindTexture(GL_TEXTURE_2D, 0); }
/*! \reimp */ void HbScrollBar::mousePressEvent( QGraphicsSceneMouseEvent *event ) { Q_D(HbScrollBar); QGraphicsWidget::mousePressEvent(event); if ( !d->mInteractive ) { return; } HbStyleOptionScrollBar opt; QRectF handleBounds = d->handleItem->boundingRect(); d->mPressPosition = mapToItem(d->handleItem, event->pos()); switch (orientation()) { case Qt::Horizontal: d->mThumbPressed = (event->pos().x() >= d->handleItem->pos().x() && event->pos().x() <= d->handleItem->pos().x() + handleBounds.width()); if (!d->mThumbPressed) { d->mGroovePressed = true; HbWidgetFeedback::triggered(this, Hb::InstantPressed); if (d->handleItem->pos().x() < event->pos().x()) { emit valueChangeRequested(qMin(value() + pageSize(), qreal(1.0)), orientation()); } else { emit valueChangeRequested(qMax(value() - pageSize(), qreal(0.0)), orientation()); } d->mPressedTargetValue = qBound(qreal(0.0), qreal((event->pos().x() - (handleBounds.width() / 2.0)) / (boundingRect().width() - handleBounds.width())), qreal(1.0)); d->repeatActionTimer.start(REPEATION_TIME, this); } else { HbWidgetFeedback::triggered(this, Hb::InstantPressed, Hb::ModifierSliderHandle); initStyleOption(&opt); style()->updatePrimitive(d->handleItem, HbStyle::P_ScrollBar_handle, &opt ); emit d->core.handlePressed(); } break; case Qt::Vertical: d->mThumbPressed = (event->pos().y() >= d->handleItem->pos().y() && event->pos().y() <= d->handleItem->pos().y() + handleBounds.height()); if (!d->mThumbPressed) { d->mGroovePressed = true; HbWidgetFeedback::triggered(this, Hb::InstantPressed); if (d->handleItem->pos().y() < event->pos().y()) { emit valueChangeRequested(qMin(value() + pageSize(), qreal(1.0)), orientation()); } else { emit valueChangeRequested(qMax(value() - pageSize(), qreal(0.0)), orientation()); } d->mPressedTargetValue = qBound(qreal(0.0), qreal((event->pos().y() - (handleBounds.height() / 2.0)) / (boundingRect().height() - handleBounds.height())), qreal(1.0)); d->repeatActionTimer.start(REPEATION_TIME, this); } else { HbWidgetFeedback::triggered(this, Hb::InstantPressed, Hb::ModifierSliderHandle); initStyleOption(&opt); style()->updatePrimitive(d->handleItem, HbStyle::P_ScrollBar_handle, &opt ); emit d->core.handlePressed(); } break; } event->accept(); }
static void _q_boundGeometryToSizeConstraints(const QRectF &startGeometry, QRectF *rect, Qt::WindowFrameSection section, const QSizeF &min, const QSizeF &max) { int height; int width; switch (section) { case Qt::LeftSection: width = qRound(qBound(min.width(), rect->width(), max.width())); rect->setRect(startGeometry.right() - width, startGeometry.top(), width, startGeometry.height()); break; case Qt::TopLeftSection: width = qRound(qBound(min.width(), rect->width(), max.width())); height = qRound(qBound(min.height(), rect->height(), max.height())); rect->setRect(startGeometry.right() - width, startGeometry.bottom() - height, width, height); break; case Qt::TopSection: height = qRound(qBound(min.height(), rect->height(), max.height())); rect->setRect(startGeometry.left(), startGeometry.bottom() - height, startGeometry.width(), height); break; case Qt::TopRightSection: height = qRound(qBound(min.height(), rect->height(), max.height())); rect->setTop(rect->bottom() - height); rect->setWidth(qBound(min.width(), rect->width(), max.width())); break; case Qt::RightSection: rect->setWidth(qBound(min.width(), rect->width(), max.width())); break; case Qt::BottomRightSection: rect->setWidth(qBound(min.width(), rect->width(), max.width())); rect->setHeight(qBound(min.height(), rect->height(), max.height())); break; case Qt::BottomSection: rect->setHeight(qBound(min.height(), rect->height(), max.height())); break; case Qt::BottomLeftSection: height = qRound(qBound(min.height(), rect->height(), max.height())); width = qRound(qBound(min.width(), rect->width(), max.width())); rect->setRect(startGeometry.right() - width, startGeometry.top(), width, height); break; default: break; } }
void VisibleTimeRange::setViewStartOffset(int secs) { secs = qBound(0, secs, maxVisibleSeconds() - visibleSeconds()); m_visibleRange = m_visibleRange.moveStart(m_range.start().addSecs(secs)).moveInto(m_range); }
void DocxReader::readStyles() { if (!m_xml.readNextStartElement()) { return; } // Read document defaults if (m_xml.qualifiedName() == "w:docDefaults") { while (m_xml.readNextStartElement()) { if (m_xml.qualifiedName() == "w:rPrDefault") { if (m_xml.readNextStartElement()) { if (m_xml.qualifiedName() == "w:rPr") { readRunProperties(m_current_style); } else { m_xml.skipCurrentElement(); } } } else if (m_xml.qualifiedName() == "w:pPrDefault") { if (m_xml.readNextStartElement()) { if (m_xml.qualifiedName() == "w:pPr") { readParagraphProperties(m_current_style); } else { m_xml.skipCurrentElement(); } } } else { m_xml.skipCurrentElement(); } } m_xml.skipCurrentElement(); } // Read styles QHash<Style::Type, QString> default_style; QHash<QString, QStringList> style_tree; do { if (m_xml.qualifiedName() == "w:style") { Style style; // Find style type QStringRef type = m_xml.attributes().value("w:type"); if (type == "paragraph") { style.type = Style::Paragraph; } else if (type == "character") { style.type = Style::Character; } else { m_xml.skipCurrentElement(); continue; } // Find style ID QString style_id = m_xml.attributes().value(QLatin1String("w:styleId")).toString(); if (m_styles.contains(style_id)) { m_xml.skipCurrentElement(); continue; } // Add style ID to tree if (!style_tree.contains(style_id)) { style_tree.insert(style_id, QStringList()); } // Determine if this is the default style if (m_xml.attributes().hasAttribute("w:default") && readBool(m_xml.attributes().value("w:default"))) { default_style[style.type] = style_id; } // Read style contents while (m_xml.readNextStartElement()) { if (m_xml.qualifiedName() == "w:name") { QString name = m_xml.attributes().value("w:val").toString(); if (name.startsWith("Head")) { int heading = qBound(1, name.at(name.length() - 1).digitValue(), 6); style.block_format.setProperty(QTextFormat::UserProperty, heading); } m_xml.skipCurrentElement(); } else if (m_xml.qualifiedName() == "w:basedOn") { QString parent_style_id = m_xml.attributes().value("w:val").toString(); if (m_styles.contains(parent_style_id) && (style.type == m_styles[parent_style_id].type)) { Style newstyle = m_styles[parent_style_id]; newstyle.block_format.merge(style.block_format); newstyle.char_format.merge(style.char_format); style = newstyle; } style_tree[parent_style_id] += style_id; m_xml.skipCurrentElement(); } else if ((style.type == Style::Paragraph) && (m_xml.qualifiedName() == "w:pPr")) { readParagraphProperties(style, false); } else if (m_xml.qualifiedName() == "w:rPr") { readRunProperties(style, false); } else { m_xml.skipCurrentElement(); } } // Add to style list m_styles.insert(style_id, style); // Recursively apply style to children QStringList children = style_tree.value(style_id); while (!children.isEmpty()) { QString child_id = children.takeFirst(); Style newstyle = style; Style& childstyle = m_styles[child_id]; newstyle.merge(childstyle); childstyle = newstyle; children.append(style_tree.value(child_id)); } } else if (m_xml.tokenType() != QXmlStreamReader::EndElement) { m_xml.skipCurrentElement(); } } while (m_xml.readNextStartElement()); // Apply default style m_current_style.block_format.merge(m_styles.value(default_style.value(Style::Paragraph)).block_format); m_current_style.char_format.merge(m_styles.value(default_style.value(Style::Character)).char_format); }
static inline QPointF boundPosition(const QPointF minPosition, const QPointF& position, const QPointF& maxPosition) { return QPointF(qBound(minPosition.x(), position.x(), maxPosition.x()), qBound(minPosition.y(), position.y(), maxPosition.y())); }