void MButtonGroupPrivate::buttonToggle(bool checked)
{
    Q_Q(MButtonGroup);

    MButton *button = static_cast<MButton *>(this->sender());
    if (!button) {
        mWarning("MButtonGroup") << "buttonToggle(): slot unexpectedly called by someone else than MButton";
        return;
    }

    if (!button->isCheckable()) {
        mWarning("MButtonGroup") << "buttonToggle(): Cannot check non-checkable button.";
        return;
    }

    if (checked && q->exclusive() && checkedButton) {
        exclusive = false;
        checkedButton->setChecked(false);
        exclusive = true;
    }

    if (checked) {
        checkedButton = button;
    } else if (checkedButton == button) {
        /* If a button is unchecked and its same as checkedButton, then
           checkedButton should be reset as well */
        checkedButton = 0;
    }
}
MApplicationExtensionInterface *MApplicationExtensionLoader::loadExtension(const MApplicationExtensionMetaData &metadata)
{
    QPluginLoader loader(metadata.extensionBinary());
    loader.setLoadHints(QLibrary::ResolveAllSymbolsHint | QLibrary::ExportExternalSymbolsHint);
    QObject *object = loader.instance();

    if (object != NULL) {
        if (object->inherits(metadata.interface().toUtf8().constData())) {
            MApplicationExtensionInterface *extension = qobject_cast<MApplicationExtensionInterface *>(object);
            if (extension != NULL) {
                if (extension->initialize(metadata.interface())) {
                    return extension;
                } else {
                    mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be initialized.";
                }
            } else {
                mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be instantiated. The extension does not implement MApplicationExtensionInterface.";
            }
        } else {
            mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be instantiated. The extension does not inherit" << metadata.interface();
        }
        delete object;
    } else {
        mWarning("MApplicationExtensionLoader") << "Application extension" << metadata.fileName() << "could not be loaded." << loader.errorString();
    }

    return false;
}
Пример #3
0
DataFrame&DataStream::get_frame(int id){
    // CHECK_BOUNDS(id, frames.size()); 
    if(id < 0){
        mWarning() << "frame_id out of bounds";
        return *(frames.at(0));
    }
    if(id >= frames.size()){
        mWarning() << "frame_id out of bounds";        
        return *(frames.at(frames.size()-1));
    }
    return *(frames.at(id)); 
}
void MButtonGroup::setId(MButton *button, int id)
{
    Q_D(MButtonGroup);
    if (d->buttonList.contains(button)) {
        if (id == -1)
            mWarning("MButtonGroup") << "setId(): Ignoring invalid id.";
        else
            d->buttonIdMap[button] = id;
    } else {
        mWarning("MButtonGroup") << "setId(): button(" << (void *)button << ") is not in the group.";
    }
}
MGLES2Renderer *MGLES2Renderer::instance()
{
    if (!MGLES2RendererPrivate::activeRenderer)
        mWarning("MGLES2Renderer::instance()") << "No active renderer.";

    return MGLES2RendererPrivate::activeRenderer;
}
void MIcuBreakIteratorPrivate::init(const MLocale &locale, const QString &text,
                                      MBreakIterator::Type type)
{
    UErrorCode status = U_ZERO_ERROR;

    icu::Locale msgLocale
    = locale.d_ptr->getCategoryLocale(MLocale::MLcMessages);

    switch (type) {
    case MBreakIterator::LineIterator:
        icuIterator = icu::BreakIterator::createLineInstance(msgLocale, status);
        break;
    case MBreakIterator::WordIterator:
        icuIterator = icu::BreakIterator::createWordInstance(msgLocale, status);
        break;
    case MBreakIterator::CharacterIterator:
        icuIterator = icu::BreakIterator::createCharacterInstance(msgLocale, status);
        break;
    case MBreakIterator::SentenceIterator:
        icuIterator = icu::BreakIterator::createSentenceInstance(msgLocale, status);
        break;
    case MBreakIterator::TitleIterator:
        icuIterator = icu::BreakIterator::createTitleInstance(msgLocale, status);
        break;
    }

    if (U_FAILURE(status)) {
        mWarning("MIcuBreakIteratorPrivate") << "failed creating iterator:" << u_errorName(status);
        return;
    }

    UCharCharacterIterator *it = new UCharCharacterIterator(text.utf16(), text.length());
    icuIterator->adoptText(it);
}
void ScreenShotPage::takeScreenshot()
{
    QPixmap screenshot;

    screenshot = QPixmap::grabWindow(scene()->views().at(0)->effectiveWinId());

    QString path;

    if (QDir(ImagesPath).exists())
        path = ImagesPath;
    else
        path = QDir::homePath();

    QString fileFormat(QString("%1/%2-%3.png").arg(path).arg(QDate::currentDate().toString("yyyyMMdd")).arg(QTime::currentTime().toString("hhmmss")));

    if (!screenshot.save(fileFormat))
        mWarning("MWindow") << "Could not save screenshot to" << path;

    playScreenshotEffect();

    MBanner * bannerPath = new MBanner();
    bannerPath->setObjectName("pathBanner");
    bannerPath->setStyleName("InformationBanner");
    bannerPath->setTitle("Screenshot has been saved in: " + fileFormat);
    bannerPath->appear(scene(), MSceneWindow::DestroyWhenDone);
}
Пример #8
0
bool MAssemblyPrivate::loadViewConfiguration(const QStringList &themeInheritance)
{
    viewConfiguration.clear();
    // load all view configuration files in inheritance order
    foreach(const QString & themePath, themeInheritance) {
        // resolve filename for configuration file
        QString filename = themePath + "meegotouch" + QDir::separator() + name + QDir::separator() + name + ".conf";

        // check that we have such file
        if (!QFile::exists(filename))
            continue;

        // load it
        QSettings config(filename, QSettings::IniFormat);
        if (config.status() != QSettings::NoError) {
            mWarning("MAssembly") << "Invalid view configuration file:" << filename;
            return false;
        }

        // copy all the loaded keys to our configuration table
        const QStringList keys(config.allKeys());
        foreach(const QString & key, keys) {
            QVariant value = config.value(key);
            if (!viewConfiguration.contains(key))
                viewConfiguration.insert(key, value.toString());
        }
void MGLES2Renderer::destroyAll()
{
    if (!MGLES2RendererPrivate::glRenderers.empty()) {
        mWarning("MGLES2Renderer::destroyAll()") << "Renderers still existing.";
        MGLES2Renderer::activate((QGLContext*)NULL);
        qDeleteAll(MGLES2RendererPrivate::glRenderers);
        MGLES2RendererPrivate::glRenderers.clear();
    }
}
QGLShaderProgram *MGLES2Renderer::compileShaderProgram(const QString &frag, const QString &vert)
{
    const QString fragFilename = (frag.isEmpty()) ? defaultFragmentShader() : frag;
    QGLShader fragShader(QGLShader::Fragment, d_ptr->m_glContext);
    if (!fragShader.compileSourceFile(fragFilename)) {
        mWarning("MGLES2Renderer") << "failed to compile fragment shader" << fragFilename
                                       << '\n' << fragShader.log();
        return 0;
    }
    const QString vertFilename = (vert.isEmpty()) ? defaultVertexShader() : vert;
    QGLShader vertShader(QGLShader::Vertex, d_ptr->m_glContext);
    if (!vertShader.compileSourceFile(vertFilename)) {
        mWarning("MGLES2Renderer") << "failed to compile vertex shader" << vertFilename
                                       << '\n' << vertShader.log();
        return 0;
    }
    QGLShaderProgram *const program = new QGLShaderProgram(d_ptr->m_glContext);

    if (program->addShader(&fragShader) && program->addShader(&vertShader)) {
        // bind needed attribute arrays to specific indices -- TODO: What's this for exactly?
        program->bindAttributeLocation("vertex", M_ATTR_VERTEX);
        program->bindAttributeLocation("texCoord", M_ATTR_TCOORD);
        program->bindAttributeLocation("color", M_ATTR_VCOLOR);

        // TODO: default context implicit here, but not above?
        if (program->link() && program->bind()) {
            // Setup default texturing uniforms here so we dont need setup them in runtime
            const QByteArray prefix("texture");
            GLint maxTexUnits = 0;
            glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTexUnits);

            for (int i = 0; i < maxTexUnits; ++i) {
                const int loc = program->uniformLocation(prefix + QByteArray::number(i));
                if (loc >= 0)
                    program->setUniformValue(loc, GLuint(i));
            }
        }
        return program;
    }
    mWarning("MGLES2Renderer") << "failed to link shader program"
                                   << (fragFilename + ':' + vertFilename);
    delete program;
    return 0;
}
Пример #11
0
int LocalPackage::fill_filelist(PACKAGE *package, bool)
{
	if (!package) package=&data;
	//mDebug("fill_filelist start");
	// Retrieving regular files
	// For setup mode, we can try to enable cached filelists
	vector<string> file_names;
	string fname;
	bool fname_temp = false;
	if (setupMode && FileExists(getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/flist")) {
		fname = getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/flist";
	}
	else {
		fname = get_tmp_file();
		fname_temp = true;
		system("tar tf "+filename+" --exclude install " +" > "+fname + " 2>/dev/null");
	}
	// Parsing file list
	file_names=ReadFileStrings(fname);
	if (fname_temp) unlink(fname.c_str());
	if (file_names.size()>2) file_names.erase(file_names.begin(), file_names.begin()+2);
	else {
		mWarning("Empty file list in package " + package->get_name());
		file_names.clear();
	}
	package->set_files(file_names);
	// Retrieving symlinks (from doinst.sh).
	string dt;
	bool dt_temp=false;
	// Extracting file to the temp dir
	if (setupMode && FileExists(getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/doinst.sh")) {
		dt = getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/doinst.sh";
	}
	else if (!setupMode || !FileExists(getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/flist")) { // Assuming that doinst.sh isn't present if flist is cached
		dt = get_tmp_file();
		extractFromTgz(filename, "install/doinst.sh", dt);
		dt_temp = true;
	}

	
	if (!dt.empty() && FileExists(dt)) {
		string lnfname=get_tmp_file();
		string sed_cmd = "sed -n 's,^( *cd \\([^ ;][^ ;]*\\) *; *rm -rf \\([^ )][^ )]*\\) *) *$,\\1/\\2,p' < ";
		sed_cmd += dt + " > " + lnfname;
		system(sed_cmd);
		vector<string>link_names=ReadFileStrings(lnfname);
		for (size_t i=0; i<link_names.size(); ++i) {
			if (!link_names[i].empty()) package->get_files_ptr()->push_back(link_names[i]);
		}
		if (dt_temp) unlink(dt.c_str());
		unlink(lnfname.c_str());
	}

	delete_tmp_files();
	return 0;
}
void MGLES2Renderer::activateProgram(QGLShaderProgram *program)
{
    if (program) {
        d_ptr->m_activeProgram = program;
        d_ptr->m_activeProgram->bind();
        d_ptr->m_activeProgram->setUniformValue("matProj", d_ptr->m_matProj);
    } else {
        mWarning("MGLES2Renderer") << "activateProgram() Invalid program.";
    }
}
void MGLES2Renderer::destroy(QGLContext *glContext)
{
    if (MGLES2Renderer *const renderer = MGLES2RendererPrivate::glRenderers.take(glContext)) {

        if (renderer == MGLES2RendererPrivate::activeRenderer) {
            mWarning("MGLES2Renderer::destroy()") << "Destroying active renderer.";
            MGLES2Renderer::activate((QGLContext*)NULL);
        }
        delete renderer;
    }
}
void MButtonGroup::addButton(MButton *button, int id)
{
    Q_D(MButtonGroup);

    if (id == -1)
        mWarning("MButtonGroup") << "addButton(): Ignoring invalid id.";
    else
        d->buttonIdMap.insert(button, id);

    addButton(button);
}
void MScalableImage::draw(qreal x, qreal y, qreal w, qreal h, QPainter *painter) const
{
    Q_D(const MScalableImage);

    if (!d->m_image) {
        mWarning("MScalableImage") << "MScalableImage::draw() scalable image: " << d->pixmapId << " not properly initialized yet";
        painter->fillRect(QRect(x, y, w, h), QColor(255, 0, 0));
        return;
    }

    switch (d->m_imageType) {
    case MScalableImagePrivate::MScalable1:
        d->drawScalable1(x, y, w, h, painter);
        break;
    case MScalableImagePrivate::MScalable9:
        d->drawScalable9(x, y, w, h, painter);
        break;
    default:
        mWarning("MScalableImage") << d->pixmapId << " draw() unsupported type " << d->m_imageType;
    }
}
void MScalableImagePrivate::validateSize() const
{
    if (!m_image) {
        return;
    }

    int w = m_image->width();
    int h = m_image->height();

    int cornerWidth = 0;
    int cornerHeight = 0;
    if (m_imageType == MScalable9) {
        cornerWidth =  m_preferredMargins.left() + m_preferredMargins.right();
        cornerHeight = m_preferredMargins.top() + m_preferredMargins.bottom();
    }

    if ((w <= cornerWidth || h <= cornerHeight) && !(w == 1 && h == 1)) //1x1 means a temporary pixmap
        mWarning("MScalableImage") << QString("The size of the image '%1', %2x%3, is smaller or equal than combined corner size %4x%5. This might cause rendering artifacts.").arg(pixmapId).arg(w).arg(h).arg(cornerWidth).arg(cornerHeight);
}
Пример #17
0
void DataStream::save(QString path){
    if(frames.size()==0){
        mWarning() << "WARNING: not saving an empty stream";
        return;
    }
    
    QFile file(path);
    file.open(QIODevice::WriteOnly);
    QDataStream out(&file);
    
    /// Header (#frames, image size)
    int num_frames = frames.size();
    int color_frame_size = frames[0]->color.total()*3; ///< was 3 because RGB=3xUCHAR?
    int depth_frame_size = frames[0]->depth.total()*2; ///< was 2 because USHORT=2xUCHAR?
    out << num_frames;
    out << color_frame_size;
    out << depth_frame_size;
    
    /// Data
    foreach(const DataFrame* frame, frames){
        out << QByteArray::fromRawData((const char*) frame->color.data, color_frame_size);
        out << QByteArray::fromRawData((const char*) frame->depth.data, depth_frame_size);
        // break; /// @REMOVE ME
    }
Пример #18
0
void MScenePrivate::logFpsCounter(const QTime *timeStamp, float fps)
{
    /* Open fps log-file, if needed */
    if (!fpsLog.output.isOpen()) {
        QFileInfo fi(qApp->arguments().at(0));
        QString appName = fi.baseName();
        QString pid("0");
#ifdef Q_OS_UNIX
        pid = QString().setNum(getpid());
#endif //Q_OS_UNIX

        QString fileName = QString("%1-%2.fps").arg(appName, pid);
        fpsLog.output.setFileName(fileName);
        if (!fpsLog.output.open(QIODevice::WriteOnly | QIODevice::Text)) {
            mWarning("MScene::logFpsCounter") << "Could not open fps log file " << fileName;
            MApplication::setLogFps(false);
            return;
        } else {
            fpsLog.stream.setDevice(&fpsLog.output);
        }
    }
    fpsLog.stream << timeStamp->toString();
    fpsLog.stream << " " << QString("%1").arg(fps, 0, 'f', 1) << endl;
}
Пример #19
0
void generateDeps(string tgz_filename, bool updateOnly)
{
	if (mConfig.getValue("add_deps_in_build")=="yes") updateOnly=false;
	if (tgz_filename.empty()) {
		mError("No filename specified");
		return;
	}
	say("Generating dependencies for %s\n",tgz_filename.c_str());
	string current_dir = (string) get_current_dir_name();
	// Create a temporary directory
	string tmpdir = get_tmp_file();
	string dep_out = get_tmp_file();
	unlink(tmpdir.c_str());
	system("mkdir -p " + tmpdir);
	say("Extracting\n");
	system("tar zxf " + tgz_filename + " -C " + tmpdir);
	PackageConfig *p = new PackageConfig(tmpdir+"/install/data.xml");
	PACKAGE pkg;
	if (p->parseOk) xml2package(p->getXMLNode(), &pkg);
	delete p;
	say("Building dependencies\n");
	
	system("env LC_ALL=C requiredbuilder -n -v " + tgz_filename + " > "+ dep_out);
	vector<string> data = ReadFileStrings(dep_out);
	
	string tmp;
	string tail;
	DEPENDENCY d;
	//pkg.get_dependencies()->clear();
	string condptr;
	for (unsigned int i=0; i<data.size(); i++)
	{
		tmp = data[i].substr(0,data[i].find_first_of(" "));
		tail = data[i].substr(tmp.length()+1);
		d.set_package_name(&tmp);

		tmp = tail.substr(0, tail.find_first_of(" "));
		tail = tail.substr(tmp.length()+1);
		condptr=IntToStr(condition2int(hcondition2xml(tmp)));
		d.set_condition(&condptr);

		tmp = tail.substr(0,tail.find_first_of("-"));
		d.set_package_version(&tmp);
		if (*d.get_package_name()!=*pkg.get_name()) {
			// Checking existing dependencies
			bool added=false;
			for (unsigned int t=0; t<pkg.get_dependencies()->size(); t++) {
				if (*d.get_package_name()==*pkg.get_dependencies()->at(t).get_package_name()) {
					pkg.get_dependencies()->at(t) = d;
					added=true;
				}
			}
			if (!added) {
				if (updateOnly) mWarning("Found (possible) missing dependencies: " + d.getDepInfo());
				else pkg.get_dependencies()->push_back(d);
			}
		}
	}
	say(_("Got %d dependencies\n"), pkg.get_dependencies()->size());
	p = new PackageConfig(tmpdir+"/install/data.xml");
	dumpPackage(&pkg, p, tmpdir+"/install/data.xml");
	delete p;
	if (tgz_filename[0]!='/') tgz_filename = current_dir + "/"+getDirectory(tgz_filename);
	system ("cd " + tmpdir + "; buildpkg " + tgz_filename );
	system("rm -rf " + tmpdir);
	delete_tmp_files();
}
void MScalableImagePrivate::drawScalable9(qreal x, qreal y, qreal w, qreal h, QPainter *painter) const
{
    QMargins margins = m_preferredMargins;

    if (w == -1 )
        w = m_image->width();
    if (h == -1 )
        h = m_image->height();

    int cornerWidth = 0;
    int cornerHeight = 0;
    if (m_imageType == MScalable9 ) {
        cornerWidth = margins.left() + margins.right();
        cornerHeight = margins.top() + margins.bottom();
    }

    //Make sure that the size of the drawn image is
    //bigger than the 4 corner blocks. If necessary,
    //use smaller border values than those set with setBorders API
    //call.
    if (w <= cornerWidth) {
        margins.setLeft(qMax((qreal)0.0, margins.left() - (cornerWidth - w + 1) / 2));
        margins.setRight(qMax((qreal)0.0, margins.right() - (cornerWidth - w + 1) / 2));
    }
    if (h <= cornerHeight) {
        margins.setTop(qMax((qreal)0.0, margins.top() - (cornerHeight - h + 1) / 2));
        margins.setBottom(qMax((qreal)0.0, margins.bottom() - (cornerHeight - h + 1) / 2));
    }

    if (w <= 0 || h <= 0) {
        // this should really not happen
        mWarning("MScalableImage") <<
                                   "Received request to draw pixmap of invalid size" << w << "x" << h;
        return;
    }

    //the image is used in its native size
    //no need to scale just draw it
    QSize requiredSize(w, h);
    if (m_image->size() == requiredSize) {
        painter->drawPixmap(x, y, *m_image);
        return;
    }
    else {
#if QT_VERSION < QT_VERSION_CHECK(4,8,0)
        //There is a known bug in Qt 4.7 qDrawBorderPixmap/QPainter which
        //can cause graphical glitches if the chosen borders result in
        //zero-sized blocks on the image, so as a workaround the borders
        //must be altered to prevent that in cases where rendering is done
        //using qDrawBorderPixmap.
        if (margins.top() == 0)
            margins.setTop(1);
        if (margins.left() == 0)
            margins.setLeft(1);

        if (margins.bottom() == 0)
            margins.setBottom(1);
        if (margins.right() == 0)
            margins.setRight(1);
#endif

#ifdef __arm__
        if (!downscaleWarningPrinted && (w < m_image->size().width() || h < m_image->size().height()))
            outputDownscaleWarning("MScalableImage9", w, h);
        else if(!nearscaleWarningPrinted && qAbs(m_image->size().width()/w-1.0) < SCALE_WARN_LIMIT && qAbs(m_image->size().height()/h-1.0) < SCALE_WARN_LIMIT)
            outputNearscaleWarning("MScalableImage9", w, h);
        qDrawBorderPixmap(painter, QRect(x, y, w, h), margins, *m_image, m_image->rect(), margins, tileRules);
#else
        //the image doesn't fit directly into the required size.
        //check whether or not we're allowed to cache
        bool docache = painter->paintEngine()->type() != QPaintEngine::OpenGL
                       && painter->paintEngine()->type() != QPaintEngine::OpenGL2;

        if (docache) {
            //software rendering is not fast when scaling pixmaps, so we use the
            //global pixmap cache to avoid rescaling more than needed.
            //
            //TODO: this cache gets thrashed a bit with widgetsgallery, may want to look into possibly
            //increasing the size of QPixmapCache.
            QString key = QString("msi-%1-%2,%3").arg((*m_image).cacheKey()).arg(w).arg(h);
            QPixmap scaled;
            if (QPixmapCache::find(key, &scaled)) {
                //cached! draw and we're done
                painter->drawPixmap(x, y, scaled);
                return;
            }

            // draw into cache
            scaled = QPixmap(requiredSize);
            scaled.fill(Qt::transparent);
            QPainter p;
            if (p.begin(&scaled)) {
                p.setRenderHint(QPainter::SmoothPixmapTransform);
                qDrawBorderPixmap(&p, QRect(0, 0, w, h), margins, *m_image, m_image->rect(), margins, tileRules);
                p.end();
            }

            // draw to screen
            painter->drawPixmap(x, y, scaled);
            QPixmapCache::insert(key, scaled);

            // remember the key so that the entry can be removed on-demand
            const_cast<MScalableImagePrivate*>(this)->cachedImageKey = key;
        } else {
            if (!downscaleWarningPrinted && (w < m_image->size().width() || h < m_image->size().height()))
                outputDownscaleWarning("MScalableImage9", w, h);
            else if(!nearscaleWarningPrinted && qAbs(m_image->size().width()/w-1.0) < SCALE_WARN_LIMIT && qAbs(m_image->size().height()/h-1.0) < SCALE_WARN_LIMIT)
                outputNearscaleWarning("MScalableImage9", w, h);
            // caching isn't permitted for this case; scale and render direct to screen.
            qDrawBorderPixmap(painter, QRect(x, y, w, h), margins, *m_image, m_image->rect(), margins, tileRules);

            if (!cachedImageKey.isEmpty()) {
                QPixmapCache::remove(cachedImageKey);
                const_cast<MScalableImagePrivate*>(this)->cachedImageKey.clear();
            }
        }
#endif // __arm__
    }
}
quint32 MGLES2Renderer::bindX11Pixmap(Qt::HANDLE /*pixmap*/)
{
    mWarning("MGLES2Renderer") << Q_FUNC_INFO << "is deprecated.";
    return 0;
}
void MGLES2Renderer::updateX11Pixmap(Qt::HANDLE /*pixmap*/)
{
    mWarning("MGLES2Renderer") << Q_FUNC_INFO << "is deprecated.";
}
void MPositionIndicatorView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
    Q_UNUSED(option);
    Q_D(const MPositionIndicatorView);

    if (d->isInSwitcher()) {
        return;
    }

    QSizeF  vpSize = model()->viewportSize();
    QRectF  pRange = model()->range().adjusted(0, 0, vpSize.width(), vpSize.height());
    QPointF pPos   = model()->position();

    if ((int)pRange.height() > (int)vpSize.height()) {
        const MScalableImage *indicator = style()->indicatorImage();
        if (!indicator) {
            mWarning("MPositionIndicatorView") << "could not get \"indicator-image\"";
            return;
        }

        qreal distanceK = pPos.y() / pRange.height();
        qreal sizeK = vpSize.height() / pRange.height();
        qreal railHeight = size().height();

        const MScalableImage *rail = style()->backgroundImage();

        int indicatorPixmapSizeX = indicator->pixmap()->width();

        int indicatorHeight = sizeK * railHeight;
        if (style()->minIndicatorSize() > indicatorHeight) {
            railHeight -= (style()->minIndicatorSize() - indicatorHeight);
            indicatorHeight = style()->minIndicatorSize();
        }

        int indicatorPositionY = distanceK * railHeight;

        if (indicatorPositionY + indicatorHeight >= int(size().height())) {
            indicatorHeight = size().height() - indicatorPositionY;
            indicatorPositionY -= 1;
        }

        if (indicatorPositionY < 0) {
            indicatorHeight += indicatorPositionY;
            indicatorPositionY = 0;
        }

        if (rail) {
            int railPixmapSizeX = rail->pixmap()->width();
            int railPositionX = (qApp->layoutDirection() == Qt::RightToLeft ? 0 : size().width() - railPixmapSizeX);

            rail->draw((qreal)railPositionX,
                        0.0,
                        (qreal)railPixmapSizeX,
                        size().height(),
                        painter);
        }

        int indicatorPositionX = (qApp->layoutDirection() == Qt::RightToLeft ? 0 : size().width() - indicatorPixmapSizeX);

        indicator->draw(indicatorPositionX,
                        indicatorPositionY,
                        indicatorPixmapSizeX,
                        indicatorHeight,
                        painter);
    }

    if ((int)pRange.width() > (int)vpSize.width()) {
        const MScalableImage *indicator = style()->indicatorImageHorizontal();
        if (!indicator) {
            mWarning("MPositionIndicatorView") << "could not get \"indicator-image-horizontal\"";
            return;
        }

        const MScalableImage *rail = style()->backgroundImageHorizontal();

        int indicatorPixmapSizeY = indicator->pixmap()->height();
        int indicatorWidth = qMax(style()->minIndicatorSize(), int((vpSize.width()/pRange.width())*size().width()));
        int indicatorPositionX = (pPos.x()/pRange.width())*size().width();

        if (indicatorPositionX + indicatorWidth > size().width()) {
            indicatorWidth = size().width() - indicatorPositionX;
        }

        if (indicatorPositionX < 0) {
            indicatorWidth += indicatorPositionX;
            indicatorPositionX = 0;
        }

        if (rail) {
            int railPixmapSizeY = rail->pixmap()->height();

            rail->draw( 0.0,
                        size().height() - railPixmapSizeY,
                        size().width(),
                        (qreal)railPixmapSizeY,
                        painter);
        }

        indicator->draw((qreal)indicatorPositionX,
                        size().height() - indicatorPixmapSizeY,
                        (qreal)indicatorWidth,
                        (qreal)indicatorPixmapSizeY,
                        painter);
    }
}
QString MAbstractLayoutPolicy::objectName() const
{
    mWarning("MAbstractLayoutPolicy") << Q_FUNC_INFO << "is deprecated. Use styleName() instead.";
    return styleName();
}
void MAbstractLayoutPolicy::setObjectName(const QString &name)
{
    mWarning("MAbstractLayoutPolicy") << Q_FUNC_INFO << "is deprecated. Use setStyleName() instead.";
    setStyleName(name);
}
bool MLogicalValuesPrivate::parse(const QFileInfo &fileInfo, Groups &groups)
{
    QFile file(fileInfo.filePath());
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    QByteArray group = "General";
    groups.insert("General", Values());

    while (!file.atEnd()) {
        QByteArray line = file.readLine().trimmed();
        // skip comments
        if (line.startsWith("[")) {
            // parse group header
            int index = line.indexOf("]", 1);
            if (index == -1) {
                mWarning("MLogicalValues") << "Error occurred when parsing .ini file:" << line;
                file.close();
                return false;
            }
            // this will be the currently active group
            group = line.mid(1, index - 1);
        } else {

            // key/value pair
            QByteArray key, value;
            QByteArray *target = &key;

            // stores the last 'good' character
            int truncation = 0;
            // go through whole line
            for (int i = 0; i < line.length(); i++) {
                QChar character = line.at(i);
                if (character == ';') {
                    break;
                } else if (character == '=') {
                    // remove trailing whitespaces
                    target->truncate(truncation);
                    // start to parse value
                    target = &value;
                    truncation = 0;
                } else {
                    if (target->isEmpty() && character.isSpace()) {
                        // do not add whitespaces at the beginning
                    } else {
                        (*target) += character;
                        if (!character.isSpace())
                            truncation = target->length();
                    }
                }
            }
            // remove trailing whitespaces
            target->truncate(truncation);

            // consistency check
            if (!line.startsWith(';') && line.length() > 0) {
                if (key.isEmpty() || value.isEmpty()) {
                    mWarning("MLogicalValues") << "Error occurred when parsing .ini file:" << line;
                    file.close();
                    return false;
                }
                // store
                Values &values = groups[group];

                if (!values.contains(key)) {
                    values.insert(key, value);
                }
            }
        }
    }

    saveToBinaryCache(fileInfo, groups);
    file.close();
    return true;
}
Пример #27
0
// New, very very fast function. The only one who should be used, if fact
int mpkgSys::requestInstall(vector<string> package_name, vector<string> package_version, vector<string> package_build, mpkgDatabase *db, DependencyTracker *DepTracker, vector<string> *eList) {
	
	// First of all, check for local packages
	
	vector<int> localPackages;
	vector<bool> isLocal(package_name.size(), false);
	LocalPackage *_p;
	string pkgType;
	for (size_t i=0; i<package_name.size(); i++) {
		pkgType=getExtension(package_name[i]);
		if (pkgType=="txz" || pkgType == "tbz" || pkgType == "tlz" || pkgType=="tgz" || pkgType == "spkg") {
		       if (FileExists(package_name[i])) {
				_p = new LocalPackage(package_name[i]);
				_p->injectFile();
				db->emerge_to_db(&_p->data);
				package_name[i] = _p->data.get_name();
				package_version[i] = _p->data.get_version();
				package_build[i] = _p->data.get_build();
				isLocal[i]=true;
				//printf("\nDetected local package\nFilename: %s\nName:%s\nVersion:%s\n", _p->data.get_filename().c_str(), _p->data.get_name().c_str(), _p->data.get_version().c_str());
				localPackages.push_back(_p->data.get_id());
				delete _p;
			}
		}
	}
	vector<string> errorList;
	//printf("using error list\n");
	// Creating DB cache
	// 1. Creating a request for all packages which are in package_name vector.
	SQLRecord sqlSearch;
	sqlSearch.setSearchMode(SEARCH_IN);
	for (size_t i=0; i<package_name.size(); i++) {
		if (isLocal[i]) {
			continue;
		}
		sqlSearch.addField("package_name", package_name[i]);
	}
	// 2. Requesting database by search array
	PACKAGE_LIST pCache;
	//printf("SLOW GET_PACKAGELIST CALL: %s %d\n", __func__, __LINE__);
	int query_ret = db->get_packagelist(sqlSearch, &pCache, true, false);
	if (query_ret != 0) {
		errorList.push_back(mError("Error querying database"));
		if (eList) *eList = errorList;
		return MPKGERROR_SQLQUERYERROR;
	}
	// 3. Temporary matrix, temporary list (for each package), and result list
	vector<PACKAGE_LIST> tmpMatrix;
	PACKAGE_LIST *tmpList=new PACKAGE_LIST;
	PACKAGE_LIST resultList;
	PACKAGE_LIST uninstallList;
	// 4. Search by cache for installed ones, check for availability and select the appropriate versions
	// 4.1 Building matrix: one vector per list of packages with same name
	for (size_t i=0; i<package_name.size(); i++) {
		delete tmpList;
		tmpList = new PACKAGE_LIST;
		for (size_t t=0; t<pCache.size(); t++) {
			if (pCache.at(t).get_name() == package_name[i]) {
				if (isLocal[i] && pCache[t].get_id()!=localPackages[i]) continue;
				tmpList->add(pCache.at(t));
			}
		}
		tmpMatrix.push_back(*tmpList);
	}
	//printf("tmpMatrix[0] size = %d\n", tmpMatrix[0].size());
	// So, the matrix has been created.
	// In case of any error, collect all of them, and return MPKGERROR_IMPOSSIBLE
	
	// Sizes of tmpMatrix and input vectors are the same, so we can use any of them
	PACKAGE *outPackage = NULL, *installedOne = NULL;
	for (size_t i=0; i<tmpMatrix.size(); i++) {
		delete tmpList;
		tmpList = new PACKAGE_LIST;
		for (size_t t=0; t<tmpMatrix[i].size(); t++) {
			// Filling the tmpList with reachable (=installed or available) ones for each package
			if (tmpMatrix[i].at(t).available(true) || tmpMatrix[i].at(t).installed()) {
				if (package_version[i].empty() || tmpMatrix[i].at(t).get_version() == package_version[i]) {
					if (package_build[i].empty() || package_build[i]==tmpMatrix[i].at(t).get_build()) tmpList->add(tmpMatrix[i][t]);
				}
			}
		}
		// Now, we have a list of all good candidates. We will filter already installed ones separately for better UI output.
		tmpList->initVersioning();
		outPackage = tmpList->getMaxVersion();
		//if (outPackage) printf("outPackage VERSION: %s\n", outPackage->get_fullversion().c_str());
		installedOne = (PACKAGE *) tmpMatrix[i].getInstalledOne();
		if (outPackage == NULL) {
			string errorText = _("Requested package ") + package_name[i];
		       	if (!package_version[i].empty()) errorText += "-" + package_version[i];
			if (!package_build[i].empty()) errorText += "-" + package_build[i];
			if (!installedOne) errorList.push_back(mError(errorText + _(" cannot be found")));
			else errorList.push_back(mError(errorText + _(" is already installed")));
		}
		else {
			//printf("____________________________CHECK FOR UPDATE, installedOne: %p_____________________________\n", installedOne);
			// Check for update
			if (installedOne && outPackage->get_id() != installedOne->get_id()) {
				// This is update
				//printf("added to uninstall: %d\n", installedOne->get_id());
				uninstallList.add(*installedOne);
			}
			resultList.add(*outPackage);
		}
	}
	delete tmpList;
	// Special addition for local packages installed using -z key: check for installed one
	for (size_t i=0; i<isLocal.size(); ++i) {
		if (!isLocal[i]) continue;
		for (size_t t=0; t<pCache.size(); ++t) {
			if (pCache[t].installed() && pCache[t].get_id()!=localPackages[i] && pCache[t].get_name()==package_name[i]) {
				requestUninstall(pCache.get_package_ptr(t), db, DepTracker);
			}
		}
	}
	// Now, check resultList for installed ones and unavailable ones
	for (size_t i=0; i<resultList.size(); i++) {
		if (resultList[i].installed()) {
			mWarning(_("Package ") + resultList[i].get_name() + "-" + resultList[i].get_fullversion() + _(" is already installed"));
		} 
		else {
			if (!resultList[i].available(true)) {
				errorList.push_back(mError(_("Package ") + resultList[i].get_name() + "-" + resultList[i].get_fullversion() + _(" is unavailable")));
			}
		}
	}
	// NEW: ignore already installed packages
	tmpList = new PACKAGE_LIST;
	for (size_t i=0; i<resultList.size(); ++i) {
		if (!resultList[i].installed()) {
			tmpList->add(resultList[i]);
		}
	}
	resultList = *tmpList;
	delete tmpList;
	

	//printf("resultList size = %d\n", resultList.size());
	if (errorList.empty())	{
		// Push to database
		__requestInstallPkgList(&resultList, db, DepTracker);
		for (size_t i=0; i<uninstallList.size(); i++) requestUninstall(uninstallList.get_package_ptr(i), db, DepTracker);

	}
	else {
		mError(_("Errors detected, cannot continue"));
		if (eList) *eList = errorList;
		return MPKGERROR_IMPOSSIBLE;
	}

	if (eList) *eList = errorList;
	return 0;
}