Exemple #1
0
QImage* LH_QImage::getPlaceholder()
{
    QImage* image = new QImage();
    image->loadFromData(_logo_blob_d.data, _logo_blob_d.len);
    return image;
}
void SeasidePhotoHandler::propertyProcessed(const QVersitDocument &, const QVersitProperty &property, const QContact &, bool *alreadyProcessed, QList<QContactDetail> * updatedDetails)
{
    // if the property is a PHOTO property, store the data to disk
    // and then create an avatar detail which points to it.
    if (property.name().toLower() != QLatin1String("photo"))
        return;

#ifndef QT_VERSION_5
    // The Qt4 / QtMobility version has QContactThumbnail support.
    // We need to remove any such thumbnail detail from the output,
    // as some backends (such as qtcontacts-sqlite) do not support
    // that detail type.
    for (int i = 0; i < updatedDetails->size(); ++i) {
        if (updatedDetails->at(i).definitionName() == QContactThumbnail::DefinitionName) {
            updatedDetails->removeAt(i);
            --i;
        }
    }
#endif

    // The data might be either a URL, a file path, or encoded image data
    // It's hard to tell what the content is, because versit removes the encoding
    // information in the process of decoding the data...

    // Try to interpret the data as a URL
    QString path(property.variantValue().toString());
    QUrl url(path);
    if (url.isValid()) {
        // Treat remote URL as a true URL, and reference it in the avatar
        if (!url.scheme().isEmpty() && !url.isLocalFile()) {
            QContactAvatar newAvatar;
            newAvatar.setImageUrl(url);
            updatedDetails->append(newAvatar);

            // we have successfully processed this PHOTO property.
            *alreadyProcessed = true;
            return;
        }
    }

    if (!url.isValid()) {
        // See if we can resolve the data as a local file path
        url = QUrl::fromLocalFile(path);
    }

    QByteArray photoData;

    if (url.isValid()) {
        // Try to read the data from the referenced file
        const QString filePath(url.path());
        if (QFile::exists(filePath)) {
            QFile file(filePath);
            if (!file.open(QIODevice::ReadOnly)) {
                qWarning() << "Unable to process photo data as file:" << path;
                return;
            } else {
                photoData = file.readAll();
            }
        }
    }

    if (photoData.isEmpty()) {
        // Try to interpret the encoded property data as the image
        photoData = property.variantValue().toByteArray();
        if (photoData.isEmpty()) {
            qWarning() << "Failed to extract avatar data from vCard PHOTO property";
            return;
        }
    }

    QImage img;
    bool loaded = img.loadFromData(photoData);
    if (!loaded) {
        qWarning() << "Failed to load avatar image from vCard PHOTO data";
        return;
    }

    // We will save the avatar image to disk in the system's data location
    // Since we're importing user data, it should not require privileged access
    const QString subdirectory(QString::fromLatin1(".local/share/system/Contacts/avatars"));
    const QString photoDirPath(QDir::home().filePath(subdirectory));

    // create the photo file dir if it doesn't exist.
    QDir photoDir;
    if (!photoDir.mkpath(photoDirPath)) {
        qWarning() << "Failed to create avatar image directory when loading avatar image from vCard PHOTO data";
        return;
    }

    // construct the filename of the new avatar image.
    QString photoFilePath = QString::fromLatin1(QCryptographicHash::hash(photoData, QCryptographicHash::Md5).toHex());
    photoFilePath = photoDirPath + QDir::separator() + photoFilePath + QString::fromLatin1(".jpg");

    // save the file to disk
    bool saved = img.save(photoFilePath);
    if (!saved) {
        qWarning() << "Failed to save avatar image from vCard PHOTO data to" << photoFilePath;
        return;
    }

    qWarning() << "Successfully saved avatar image from vCard PHOTO data to" << photoFilePath;

    // save the avatar detail - TODO: mark the avatar as "owned by the contact" (remove on delete)
    QContactAvatar newAvatar;
    newAvatar.setImageUrl(QUrl::fromLocalFile(photoFilePath));
    updatedDetails->append(newAvatar);

    // we have successfully processed this PHOTO property.
    *alreadyProcessed = true;
}
QVariant XmlQImageSerializator::loadValue()
{
    QImage img;
    img.loadFromData(QByteArray::fromHex(node()->text().toLatin1()),"PNG");
    return img;
}
Exemple #4
0
	QByteArray baFond;
	in >> baFond;

	QByteArray baAlpha;
	in>> baAlpha;

	bool ok;


	//////////////////
	// Manage Data to create the map.
	//////////////////

	QImage fondOriginal;
	ok = fondOriginal.loadFromData(baFondOriginal, "jpeg");
	if (!ok)
	{
        error(tr("Extract original background information Failed (readMapAndNpc - bipmapwindow.cpp)"),this);
		return false;
	}

	QImage fond;
	ok = fond.loadFromData(baFond, "jpeg");
	if (!ok)
	{
        error(tr("Extract background information Failed (readMapAndNpc - bipmapwindow.cpp)"),this);
		return false;
	}

	QImage alpha;
Exemple #5
0
void ThumbGenerator::loadFile(QImage& image, const QFileInfo& fi)
{
    static int sequence = 0;

    if (GalleryUtil::IsMovie(fi.filePath()))
    {
        bool thumbnailCreated = false;
        QDir tmpDir("/tmp/mythgallery");
        if (!tmpDir.exists())
        {
            if (!tmpDir.mkdir(tmpDir.absolutePath()))
            {
                LOG(VB_GENERAL, LOG_ERR,
                    "Unable to create temp dir for movie thumbnail creation: " +
                    tmpDir.absolutePath());
            }
        }

        if (tmpDir.exists())
        {
            QString thumbFile = QString("%1.png")
                .arg(++sequence,8,10,QChar('0'));

            QString cmd = "mythpreviewgen";
            QStringList args;
            args << logPropagateArgs.split(" ", QString::SkipEmptyParts);
            args << "--infile" << '"' + fi.absoluteFilePath() + '"';
            args << "--outfile" << '"' + tmpDir.filePath(thumbFile) + '"';

            MythSystem ms(cmd, args, kMSRunShell);
            ms.SetDirectory(tmpDir.absolutePath());
            ms.Run();
            if (ms.Wait() == GENERIC_EXIT_OK)
            {
                QFileInfo thumb(tmpDir.filePath(thumbFile));
                if (thumb.exists())
                {
                    QImage img(thumb.absoluteFilePath());
                    image = img;
                    thumbnailCreated = true;
                }
            }
        }

        if (!thumbnailCreated)
        {
            QImage *img = GetMythUI()->LoadScaleImage("gallery-moviethumb.png");
            if (img)
            {
                image = *img;
            }
        }
    }
    else
    {
#ifdef EXIF_SUPPORT
        // Try to get thumbnail from exif data
        ExifData *ed = exif_data_new_from_file(fi.absoluteFilePath()
                                               .toLocal8Bit().constData());
        if (ed && ed->data)
        {
            image.loadFromData(ed->data, ed->size);
        }

        if (ed)
            exif_data_free(ed);

        if (image.width() > m_width && image.height() > m_height)
            return;
#endif

#ifdef DCRAW_SUPPORT
        QString extension = fi.suffix();
        QSet<QString> dcrawFormats = DcrawFormats::getFormats();
        int rotateAngle;

        if (dcrawFormats.contains(extension) &&
            (rotateAngle = DcrawHandler::loadThumbnail(&image,
                                               fi.absoluteFilePath())) != -1 &&
            image.width() > m_width && image.height() > m_height)
        {
            if (rotateAngle != 0)
            {
                QMatrix matrix;
                matrix.rotate(rotateAngle);
                image = image.transformed(matrix);
            }

            return;
        }
#endif

        image.load(fi.absoluteFilePath());
    }
}
/*
 *  Constructs a CustomFaceManagerUI as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 */
CustomFaceManagerUI::CustomFaceManagerUI( QWidget* parent, const char* name, WFlags fl )
    : QWidget( parent, name, fl )
{
    QImage img;
    img.loadFromData( image0_data, sizeof( image0_data ), "PNG" );
    image0 = img;
    img.loadFromData( image1_data, sizeof( image1_data ), "PNG" );
    image1 = img;
    img.loadFromData( image2_data, sizeof( image2_data ), "PNG" );
    image2 = img;
    if ( !name )
	setName( "CustomFaceManagerUI" );
    CustomFaceManagerUILayout = new QGridLayout( this, 1, 1, 3, 0, "CustomFaceManagerUILayout"); 

    layout9 = new QVBoxLayout( 0, 0, 6, "layout9"); 

    frame7 = new QFrame( this, "frame7" );
    frame7->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)1, 0, 0, frame7->sizePolicy().hasHeightForWidth() ) );
    frame7->setFrameShape( QFrame::TabWidgetPanel );
    frame7->setFrameShadow( QFrame::Raised );
    frame7Layout = new QGridLayout( frame7, 1, 1, 2, 0, "frame7Layout"); 

    layout1 = new QHBoxLayout( 0, 0, 6, "layout1"); 

    tbtnImport = new QToolButton( frame7, "tbtnImport" );
    tbtnImport->setAutoRaise( TRUE );
    layout1->addWidget( tbtnImport );

    tbtnExport = new QToolButton( frame7, "tbtnExport" );
    tbtnExport->setAutoRaise( TRUE );
    layout1->addWidget( tbtnExport );

    tbtnAddGroup = new QToolButton( frame7, "tbtnAddGroup" );
    tbtnAddGroup->setIconSet( QIconSet( image0 ) );
    tbtnAddGroup->setUsesTextLabel( TRUE );
    tbtnAddGroup->setAutoRaise( TRUE );
    tbtnAddGroup->setTextPosition( QToolButton::BesideIcon );
    layout1->addWidget( tbtnAddGroup );

    tbtnEditGroup = new QToolButton( frame7, "tbtnEditGroup" );
    tbtnEditGroup->setIconSet( QIconSet( image1 ) );
    tbtnEditGroup->setUsesTextLabel( TRUE );
    tbtnEditGroup->setAutoRaise( TRUE );
    tbtnEditGroup->setTextPosition( QToolButton::BesideIcon );
    layout1->addWidget( tbtnEditGroup );

    tbtnRemoveGroup = new QToolButton( frame7, "tbtnRemoveGroup" );
    tbtnRemoveGroup->setIconSet( QIconSet( image2 ) );
    tbtnRemoveGroup->setUsesBigPixmap( TRUE );
    tbtnRemoveGroup->setUsesTextLabel( TRUE );
    tbtnRemoveGroup->setAutoRaise( TRUE );
    tbtnRemoveGroup->setTextPosition( QToolButton::BesideIcon );
    layout1->addWidget( tbtnRemoveGroup );

    frame7Layout->addLayout( layout1, 0, 0 );
    layout9->addWidget( frame7 );

    layout7 = new QHBoxLayout( 0, 0, 6, "layout7"); 

    frame6 = new QFrame( this, "frame6" );
    frame6->setPaletteForegroundColor( QColor( 0, 124, 206 ) );
    frame6->setFrameShape( QFrame::Box );
    frame6->setFrameShadow( QFrame::Plain );
    frame6Layout = new QGridLayout( frame6, 1, 1, 1, 0, "frame6Layout"); 

    lvGroups = new QListView( frame6, "lvGroups" );
    lvGroups->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)7, 0, 0, lvGroups->sizePolicy().hasHeightForWidth() ) );
    lvGroups->setMinimumSize( QSize( 100, 0 ) );
    lvGroups->setMaximumSize( QSize( 250, 32767 ) );
    lvGroups->setFrameShape( QListView::NoFrame );
    lvGroups->setFrameShadow( QListView::Plain );
    lvGroups->setLineWidth( 1 );
    lvGroups->setHScrollBarMode( QListView::AlwaysOff );
    lvGroups->setSorting( -1 ); // don't sort

    frame6Layout->addWidget( lvGroups, 0, 0 );
    layout7->addWidget( frame6 );

    frmMain = new QFrame( this, "frmMain" );
    frmMain->setPaletteForegroundColor( QColor( 0, 124, 206 ) );
    frmMain->setPaletteBackgroundColor( QColor( 255, 255, 255 ) );
    frmMain->setFrameShape( QFrame::Box );
    frmMain->setFrameShadow( QFrame::Plain );
    frmMainLayout = new QGridLayout( frmMain, 1, 1, 11, 6, "frmMainLayout"); 

    layout6 = new QHBoxLayout( 0, 0, 6, "layout6"); 

    tblFaceList = new QTable( frmMain, "tblFaceList" );
    tblFaceList->setNumCols( tblFaceList->numCols() + 1 );
    tblFaceList->horizontalHeader()->setLabel( tblFaceList->numCols() - 1, i18n("No." ) );
    tblFaceList->setNumCols( tblFaceList->numCols() + 1 );
    tblFaceList->horizontalHeader()->setLabel( tblFaceList->numCols() - 1, i18n("Smiley" ) );
    tblFaceList->setNumCols( tblFaceList->numCols() + 1 );
    tblFaceList->horizontalHeader()->setLabel( tblFaceList->numCols() - 1, i18n("Shortcut" ) );
    tblFaceList->setFrameShape( QTable::GroupBoxPanel );
    tblFaceList->setFrameShadow( QTable::Plain );
    tblFaceList->setHScrollBarMode( QTable::AlwaysOff );
    tblFaceList->setNumRows( 0 );
    tblFaceList->setNumCols( 3 );
    tblFaceList->setSelectionMode( QTable::MultiRow );
    tblFaceList->setFocusStyle( QTable::FollowStyle );
    layout6->addWidget( tblFaceList );

    layout5 = new QVBoxLayout( 0, 0, 6, "layout5"); 

    btnAdd = new QPushButton( frmMain, "btnAdd" );
    layout5->addWidget( btnAdd );

    btnRemove = new QPushButton( frmMain, "btnRemove" );
    layout5->addWidget( btnRemove );

    btnEdit = new QPushButton( frmMain, "btnEdit" );
    layout5->addWidget( btnEdit );

    btnUp = new QPushButton( frmMain, "btnUp" );
    layout5->addWidget( btnUp );

    btnDown = new QPushButton( frmMain, "btnDown" );
    layout5->addWidget( btnDown );

    btnMoveTo = new QPushButton( frmMain, "btnMoveTo" );
    layout5->addWidget( btnMoveTo );
    spacer1 = new QSpacerItem( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding );
    layout5->addItem( spacer1 );

    lblPreview = new QLabel( frmMain, "lblPreview" );
    lblPreview->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, 0, 0, lblPreview->sizePolicy().hasHeightForWidth() ) );
    lblPreview->setMinimumSize( QSize( 100, 85 ) );
    lblPreview->setMaximumSize( QSize( 100, 85 ) );
    lblPreview->setPaletteForegroundColor( QColor( 0, 124, 206 ) );
    lblPreview->setFrameShape( QLabel::Box );
    layout5->addWidget( lblPreview );
    layout6->addLayout( layout5 );

    frmMainLayout->addLayout( layout6, 0, 0 );
    layout7->addWidget( frmMain );
    layout9->addLayout( layout7 );

    layout8 = new QHBoxLayout( 0, 0, 6, "layout8"); 
    spacer2 = new QSpacerItem( 91, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
    layout8->addItem( spacer2 );

    btnOK = new QPushButton( this, "btnOK" );
    layout8->addWidget( btnOK );

    btnCancel = new QPushButton( this, "btnCancel" );
    layout8->addWidget( btnCancel );
    layout9->addLayout( layout8 );

    CustomFaceManagerUILayout->addLayout( layout9, 0, 0 );
    languageChange();
    resize( QSize(521, 382).expandedTo(minimumSizeHint()) );
    clearWState( WState_Polished );

    QRect scr = KApplication::desktop()->screenGeometry();
    move(scr.center()-rect().center());
}
Exemple #7
0
void LocalSong::setInfo(const QString &filePath)
{
    QFileInfo fileInfo(filePath);
    fileExtension = fileInfo.completeSuffix();
    QString singer="";
    QString sname="";
    QString album="";
    QImage covpic;
    if(fileExtension == "m4a")
    {

        TagLib::MP4::File *mp4File = new TagLib::MP4::File(
                    QFile::encodeName(filePath).constData());
        if(false==mp4File->isOpen())
            return;
        sname=QString(mp4File->tag()->title().toCString(true));
        singer=QString(mp4File->tag()->artist().toCString(true));
        album=QString(mp4File->tag()->album().toCString(true));
        TagLib::MP4::ItemListMap itemListMap = mp4File->tag()->itemListMap();
        TagLib::MP4::Item albumArtItem = itemListMap["covr"];
        TagLib::MP4::CoverArtList albumArtList = albumArtItem.toCoverArtList();
        TagLib::MP4::CoverArt albumArt = albumArtList.front();
        QImage cover;
        cover.loadFromData((const uchar *)
                           albumArt.data().data(),
                           albumArt.data().size());
        covpic = cover.scaled(
                    50,
                    50,
                    Qt::IgnoreAspectRatio,
                    Qt::SmoothTransformation);
        if(!covpic.isNull())
        {
            qDebug()<<"读取M4A封面信息成功";
        }else
        {
            covpic.load(":/image/image/playIcon.png");
            qDebug()<<"读取音乐封面信息失败";
        }
    }
    else if(fileExtension == "mp3")
    {
        TagLib::MPEG::File *mpegFile = new TagLib::MPEG::File(
                    QFile::encodeName(filePath).constData());
        if(false==mpegFile->isOpen())
            return;
        else
        {
            sname=QString(mpegFile->tag()->title().toCString(true));
            singer=QString(mpegFile->tag()->artist().toCString(true));
            album=QString(mpegFile->tag()->album().toCString(true));
            auto tag = mpegFile->ID3v2Tag(false);
            auto list = tag->frameListMap()["APIC"];
            if(!list.isEmpty()) {
                auto frame = list.front();
                auto pic = reinterpret_cast<TagLib::ID3v2::AttachedPictureFrame *>(frame);
                if(pic && !pic->picture().isNull())
                {
                    QImage cover;
                    if(cover.loadFromData(QByteArray::fromRawData(pic->picture().data(), pic->picture().size()))) {
                        covpic = cover.scaled(
                                    50,
                                    50,
                                    Qt::IgnoreAspectRatio,
                                    Qt::SmoothTransformation);
                        qDebug()<<"读取MP3封面信息成功";
                    }
                }
            }
            else
            {
                covpic.load(":/image/image/playIcon.png");
                qDebug()<<"读取音乐封面信息失败";
            }
        }
    }
    singerlist.append(singer);
    snamelist.append(sname);
    albumlist.append(album);
    covPiclist.append(covpic);
    int covCount=covPiclist.length();
    QString covpicpath=QDir::tempPath()+QString("/%1.png").arg(covCount);
    covpic.save(covpicpath);
    QUrl covpicUrl=QUrl::fromLocalFile(covpicpath);
    qDebug()<<"歌名为"<<sname;
    qDebug()<<"歌手为"<<singer;
    qDebug()<<"专辑为"<<album;
    qDebug()<<"URL为"<<covpicUrl;
    emit setSongInfo(singer,sname,album,covpicUrl);
    return;
}
Exemple #8
0
bool DjVuCreator::create(const QString &path, int width, int height, QImage &img)
{
  int output[2];
  QByteArray data(1024, 'k');
  bool ok = false;

  if (pipe(output) == -1)
    return false;
  
  const char* argv[8];
  QByteArray sizearg, fnamearg;
  sizearg = QByteArray::number(width) + 'x' + QByteArray::number(height);
  fnamearg = QFile::encodeName( path );
  argv[0] = "ddjvu";
  argv[1] = "-page";
  argv[2] = "1"; // krazy:exclude=doublequote_chars
  argv[3] = "-size";
  argv[4] = sizearg.data(); 
  argv[5] = fnamearg.data(); 
  argv[6] = 0;
  
  pid_t pid = fork(); 
  if (pid == 0)
    {
      close(output[0]);
      dup2(output[1], STDOUT_FILENO);	  
      execvp(argv[0], const_cast<char *const *>(argv));
      exit(1);
    }
  else if (pid >= 0)
    {
      close(output[1]);
      int offset = 0;
      while (!ok) {
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(output[0], &fds);
        struct timeval tv;
        tv.tv_sec = 20;
        tv.tv_usec = 0;
        if (select(output[0] + 1, &fds, 0, 0, &tv) <= 0) {
          if (errno == EINTR || errno == EAGAIN)
            continue;
          break; // error or timeout
        }
        if (FD_ISSET(output[0], &fds)) {
          int count = read(output[0], data.data() + offset, 1024);
          if (count == -1)
            break;
          if (count) // prepare for next block
            {
              offset += count;
              data.resize(offset + 1024);
            }
          else // got all data
            {
              data.resize(offset);
              ok = true;
            }
        }
      }
      if (!ok)
        kill(pid, SIGTERM);
      int status = 0;
      if (waitpid(pid, &status, 0) != pid || (status != 0  && status != 256) )
        ok = false;
    }
  else
    {
      close(output[1]);
    }
  
  close(output[0]);
  int l = img.loadFromData( data );
  return ok && l;
}
/*
 *  Constructs a MainWindow as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 *
 */
MainWindow::MainWindow( QWidget* parent, const char* name, WFlags fl )
    : QMainWindow( parent, name, fl )
{
    (void)statusBar();
    QImage img;
    img.loadFromData( image0_data, sizeof( image0_data ), "PNG" );
    image0 = img;
    img.loadFromData( image1_data, sizeof( image1_data ), "PNG" );
    image1 = img;
    img.loadFromData( image2_data, sizeof( image2_data ), "PNG" );
    image2 = img;
    img.loadFromData( image3_data, sizeof( image3_data ), "PNG" );
    image3 = img;
    img.loadFromData( image4_data, sizeof( image4_data ), "PNG" );
    image4 = img;
    img.loadFromData( image5_data, sizeof( image5_data ), "PNG" );
    image5 = img;
    img.loadFromData( image6_data, sizeof( image6_data ), "PNG" );
    image6 = img;
    img.loadFromData( image7_data, sizeof( image7_data ), "PNG" );
    image7 = img;
    img.loadFromData( image8_data, sizeof( image8_data ), "PNG" );
    image8 = img;
    img.loadFromData( image9_data, sizeof( image9_data ), "PNG" );
    image9 = img;
    if ( !name )
	setName( "MainWindow" );
    setCentralWidget( new QWidget( this, "qt_central_widget" ) );

    QWidget* privateLayoutWidget = new QWidget( centralWidget(), "layout8" );
    privateLayoutWidget->setGeometry( QRect( 1, 11, 340, 300 ) );
    layout8 = new QVBoxLayout( privateLayoutWidget, 11, 6, "layout8"); 

    BotonesLector = new QButtonGroup( privateLayoutWidget, "BotonesLector" );
    BotonesLector->setColumnLayout(0, Qt::Vertical );
    BotonesLector->layout()->setSpacing( 6 );
    BotonesLector->layout()->setMargin( 11 );
    BotonesLectorLayout = new QHBoxLayout( BotonesLector->layout() );
    BotonesLectorLayout->setAlignment( Qt::AlignTop );

    layout9 = new QHBoxLayout( 0, 0, 6, "layout9"); 

    pushButton1 = new QPushButton( BotonesLector, "pushButton1" );
    layout9->addWidget( pushButton1 );

    pushButton2 = new QPushButton( BotonesLector, "pushButton2" );
    layout9->addWidget( pushButton2 );
    BotonesLectorLayout->addLayout( layout9 );
    layout8->addWidget( BotonesLector );

    layout6 = new QHBoxLayout( 0, 0, 6, "layout6"); 

    layout5 = new QVBoxLayout( 0, 0, 6, "layout5"); 

    txtSldrTitleTemp = new QLabel( privateLayoutWidget, "txtSldrTitleTemp" );
    txtSldrTitleTemp->setFrameShape( QLabel::Box );
    txtSldrTitleTemp->setScaledContents( FALSE );
    layout5->addWidget( txtSldrTitleTemp );

    sldrTemp = new QSlider( privateLayoutWidget, "sldrTemp" );
    sldrTemp->setMaxValue( 4 );
    sldrTemp->setOrientation( QSlider::Vertical );
    layout5->addWidget( sldrTemp );

    txtTemp = new QLabel( privateLayoutWidget, "txtTemp" );
    QFont txtTemp_font(  txtTemp->font() );
    txtTemp_font.setPointSize( 8 );
    txtTemp->setFont( txtTemp_font ); 
    layout5->addWidget( txtTemp );
    layout6->addLayout( layout5 );

    Grupo1 = new QGroupBox( privateLayoutWidget, "Grupo1" );
    layout6->addWidget( Grupo1 );

    layout4 = new QVBoxLayout( 0, 0, 6, "layout4"); 

    txtSldrTitleVelocidad = new QLabel( privateLayoutWidget, "txtSldrTitleVelocidad" );
    txtSldrTitleVelocidad->setFrameShape( QLabel::Box );
    txtSldrTitleVelocidad->setScaledContents( FALSE );
    layout4->addWidget( txtSldrTitleVelocidad );

    sldrVelocidad = new QSlider( privateLayoutWidget, "sldrVelocidad" );
    sldrVelocidad->setOrientation( QSlider::Vertical );
    layout4->addWidget( sldrVelocidad );

    txtVelocidad = new QLabel( privateLayoutWidget, "txtVelocidad" );
    QFont txtVelocidad_font(  txtVelocidad->font() );
    txtVelocidad_font.setPointSize( 8 );
    txtVelocidad->setFont( txtVelocidad_font ); 
    layout4->addWidget( txtVelocidad );
    layout6->addLayout( layout4 );
    layout8->addLayout( layout6 );

    BotonActivar = new QButtonGroup( privateLayoutWidget, "BotonActivar" );
    BotonActivar->setColumnLayout(0, Qt::Vertical );
    BotonActivar->layout()->setSpacing( 6 );
    BotonActivar->layout()->setMargin( 11 );
    BotonActivarLayout = new QHBoxLayout( BotonActivar->layout() );
    BotonActivarLayout->setAlignment( Qt::AlignTop );

    btnIniciar = new QPushButton( BotonActivar, "btnIniciar" );
    btnIniciar->setToggleButton( TRUE );
    BotonActivarLayout->addWidget( btnIniciar );
    layout8->addWidget( BotonActivar );

    // actions
    fileNewAction = new QAction( this, "fileNewAction" );
    fileNewAction->setIconSet( QIconSet( image0 ) );
    fileOpenAction = new QAction( this, "fileOpenAction" );
    fileOpenAction->setIconSet( QIconSet( image1 ) );
    fileSaveAction = new QAction( this, "fileSaveAction" );
    fileSaveAction->setIconSet( QIconSet( image2 ) );
    fileSaveAsAction = new QAction( this, "fileSaveAsAction" );
    filePrintAction = new QAction( this, "filePrintAction" );
    filePrintAction->setIconSet( QIconSet( image3 ) );
    fileExitAction = new QAction( this, "fileExitAction" );
    editUndoAction = new QAction( this, "editUndoAction" );
    editUndoAction->setIconSet( QIconSet( image4 ) );
    editRedoAction = new QAction( this, "editRedoAction" );
    editRedoAction->setIconSet( QIconSet( image5 ) );
    editCutAction = new QAction( this, "editCutAction" );
    editCutAction->setIconSet( QIconSet( image6 ) );
    editCopyAction = new QAction( this, "editCopyAction" );
    editCopyAction->setIconSet( QIconSet( image7 ) );
    editPasteAction = new QAction( this, "editPasteAction" );
    editPasteAction->setIconSet( QIconSet( image8 ) );
    editFindAction = new QAction( this, "editFindAction" );
    editFindAction->setIconSet( QIconSet( image9 ) );
    helpContentsAction = new QAction( this, "helpContentsAction" );
    helpIndexAction = new QAction( this, "helpIndexAction" );
    helpAboutAction = new QAction( this, "helpAboutAction" );


    // toolbars


    // menubar
    menubar = new QMenuBar( this, "menubar" );


    fileMenu = new QPopupMenu( this );
    fileOpenAction->addTo( fileMenu );
    fileSaveAction->addTo( fileMenu );
    fileMenu->insertSeparator();
    fileMenu->insertSeparator();
    fileExitAction->addTo( fileMenu );
    menubar->insertItem( QString(""), fileMenu, 1 );

    helpMenu = new QPopupMenu( this );
    helpMenu->insertSeparator();
    helpAboutAction->addTo( helpMenu );
    menubar->insertItem( QString(""), helpMenu, 2 );

    languageChange();
    resize( QSize(351, 352).expandedTo(minimumSizeHint()) );
    clearWState( WState_Polished );

    // signals and slots connections
    connect( fileNewAction, SIGNAL( activated() ), this, SLOT( fileNew() ) );
    connect( fileOpenAction, SIGNAL( activated() ), this, SLOT( fileOpen() ) );
    connect( fileSaveAction, SIGNAL( activated() ), this, SLOT( fileSave() ) );
    connect( fileSaveAsAction, SIGNAL( activated() ), this, SLOT( fileSaveAs() ) );
    connect( filePrintAction, SIGNAL( activated() ), this, SLOT( filePrint() ) );
    connect( fileExitAction, SIGNAL( activated() ), this, SLOT( fileExit() ) );
    connect( editUndoAction, SIGNAL( activated() ), this, SLOT( editUndo() ) );
    connect( editRedoAction, SIGNAL( activated() ), this, SLOT( editRedo() ) );
    connect( editCutAction, SIGNAL( activated() ), this, SLOT( editCut() ) );
    connect( editCopyAction, SIGNAL( activated() ), this, SLOT( editCopy() ) );
    connect( editPasteAction, SIGNAL( activated() ), this, SLOT( editPaste() ) );
    connect( editFindAction, SIGNAL( activated() ), this, SLOT( editFind() ) );
    connect( helpIndexAction, SIGNAL( activated() ), this, SLOT( helpIndex() ) );
    connect( helpContentsAction, SIGNAL( activated() ), this, SLOT( helpContents() ) );
    connect( helpAboutAction, SIGNAL( activated() ), this, SLOT( helpAbout() ) );
    connect( sldrTemp, SIGNAL( valueChanged(int) ), txtTemp, SLOT( setNum(int) ) );
    connect( sldrVelocidad, SIGNAL( valueChanged(int) ), txtVelocidad, SLOT( setNum(int) ) );
    connect( BotonActivar, SIGNAL( toggled(bool) ), this, SLOT( Activar(bool) ) );
}
Exemple #10
0
int main(int argc, char* argv[])
{
    QCoreApplication app(argc, argv);

    qreal tolerance = 0;

    QStringList args = app.arguments();
    for (int i = 0; i < argc; ++i)
        if (args[i] == "-t" || args[i] == "--tolerance")
            tolerance = args[i + 1].toDouble();

    char buffer[2048];
    QImage actualImage;
    QImage baselineImage;

    while (fgets(buffer, sizeof(buffer), stdin)) {
        // remove the CR
        char* newLineCharacter = strchr(buffer, '\n');
        if (newLineCharacter)
            *newLineCharacter = '\0';

        if (!strncmp("Content-Length: ", buffer, 16)) {
            strtok(buffer, " ");
            int imageSize = strtol(strtok(0, " "), 0, 10);

            if (imageSize <= 0) {
                fputs("error, image size must be specified.\n", stdout);
            } else {
                unsigned char buffer[2048];
                QBuffer data;

                // Read all the incoming chunks
                data.open(QBuffer::WriteOnly);
                while (imageSize > 0) {
                    size_t bytesToRead = qMin(imageSize, 2048);
                    size_t bytesRead = fread(buffer, 1, bytesToRead, stdin);
                    data.write(reinterpret_cast<const char*>(buffer), bytesRead);
                    imageSize -= static_cast<int>(bytesRead);
                }

                // Convert into QImage
                QImage decodedImage;
                decodedImage.loadFromData(data.data(), "PNG");
                decodedImage.convertToFormat(QImage::Format_ARGB32);

                // Place it in the right place
                if (actualImage.isNull())
                    actualImage = decodedImage;
                else
                    baselineImage = decodedImage;
            }
        }

        if (!actualImage.isNull() && !baselineImage.isNull()) {

            if (actualImage.size() != baselineImage.size()) {
                fprintf(stderr, "error, test and reference image have different properties.\n");
                fflush(stderr);
            } else {

                int w = actualImage.width();
                int h = actualImage.height();
                QImage diffImage(w, h, QImage::Format_ARGB32);

                int count = 0;
                qreal sum = 0;
                qreal maxDistance = 0;

                for (int x = 0; x < w; ++x)
                    for (int y = 0; y < h; ++y) {
                        QRgb pixel = actualImage.pixel(x, y);
                        QRgb basePixel = baselineImage.pixel(x, y);
                        qreal red = (qRed(pixel) - qRed(basePixel)) / static_cast<float>(qMax(255 - qRed(basePixel), qRed(basePixel)));
                        qreal green = (qGreen(pixel) - qGreen(basePixel)) / static_cast<float>(qMax(255 - qGreen(basePixel), qGreen(basePixel)));
                        qreal blue = (qBlue(pixel) - qBlue(basePixel)) / static_cast<float>(qMax(255 - qBlue(basePixel), qBlue(basePixel)));
                        qreal alpha = (qAlpha(pixel) - qAlpha(basePixel)) / static_cast<float>(qMax(255 - qAlpha(basePixel), qAlpha(basePixel)));
                        qreal distance = qSqrt(red * red + green * green + blue * blue + alpha * alpha) / 2.0f;
                        int gray = distance * qreal(255);
                        diffImage.setPixel(x, y, qRgb(gray, gray, gray));
                        if (distance >= 1 / qreal(255)) {
                            count++;
                            sum += distance;
                            maxDistance = qMax(maxDistance, distance);
                        }
                }

                qreal difference = 0;
                if (count)
                    difference = 100 * sum / static_cast<qreal>(w * h);
                if (difference <= tolerance) {
                    difference = 0;
                } else {
                    difference = qRound(difference * 100) / 100;
                    difference = qMax(difference, qreal(0.01));
                }

                if (!count) {
                    fprintf(stdout, "diff: %01.2f%% passed\n", difference);
                } else {
                    QBuffer buffer;
                    buffer.open(QBuffer::WriteOnly);
                    diffImage.save(&buffer, "PNG");
                    buffer.close();
                    const QByteArray &data = buffer.data();
                    printf("Content-Length: %lu\n", static_cast<unsigned long>(data.length()));

                    // We have to use the return value of fwrite to avoid "ignoring return value" gcc warning
                    // See https://bugs.webkit.org/show_bug.cgi?id=45384 for details.
                    if (fwrite(data.constData(), 1, data.length(), stdout)) {}

                    fprintf(stdout, "diff: %01.2f%% failed\n", difference);
                }

                fflush(stdout);
            }
        }
    }

    return 0;
}
/*
 *  Constructs a PlotWindowUI as a child of 'parent', with the
 *  name 'name' and widget flags set to 'f'.
 */
PlotWindowUI::PlotWindowUI( QWidget* parent, const char* name, WFlags fl )
    : QWidget( parent, name, fl )
{
    QImage img;
    img.loadFromData( image0_data, sizeof( image0_data ), "PNG" );
    image0 = img;
    img.loadFromData( image1_data, sizeof( image1_data ), "PNG" );
    image1 = img;
    if ( !name )
	setName( "PlotWindowUI" );

    frame = new QFrame( this, "frame" );
    frame->setGeometry( QRect( 40, 30, 645, 74 ) );
    frame->setFrameShape( QFrame::NoFrame );
    frame->setFrameShadow( QFrame::Plain );
    frameLayout = new QHBoxLayout( frame, 11, 6, "frameLayout"); 

    layout1 = new QGridLayout( 0, 1, 1, 0, 6, "layout1"); 

    currentScaleLabel = new QLabel( frame, "currentScaleLabel" );
    QFont currentScaleLabel_font(  currentScaleLabel->font() );
    currentScaleLabel_font.setBold( TRUE );
    currentScaleLabel->setFont( currentScaleLabel_font ); 

    layout1->addWidget( currentScaleLabel, 1, 0 );

    currentScaleEdit = new QComboBox( FALSE, frame, "currentScaleEdit" );
    currentScaleEdit->setMaximumSize( QSize( 50, 32767 ) );
    QFont currentScaleEdit_font(  currentScaleEdit->font() );
    currentScaleEdit->setFont( currentScaleEdit_font ); 

    layout1->addWidget( currentScaleEdit, 1, 3 );

    currentY2Edit = new QSpinBox( frame, "currentY2Edit" );
    currentY2Edit->setMinimumSize( QSize( 70, 0 ) );
    currentY2Edit->setMaximumSize( QSize( 70, 32767 ) );
    currentY2Edit->setMaxValue( 999999999 );
    currentY2Edit->setMinValue( -999999999 );
    currentY2Edit->setValue( 20 );

    layout1->addWidget( currentY2Edit, 1, 2 );

    timeScaleEdit = new QComboBox( FALSE, frame, "timeScaleEdit" );
    timeScaleEdit->setMaximumSize( QSize( 50, 32767 ) );
    QFont timeScaleEdit_font(  timeScaleEdit->font() );
    timeScaleEdit->setFont( timeScaleEdit_font ); 

    layout1->addWidget( timeScaleEdit, 0, 3 );

    timeX2Edit = new QSpinBox( frame, "timeX2Edit" );
    timeX2Edit->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)0, 0, 0, timeX2Edit->sizePolicy().hasHeightForWidth() ) );
    timeX2Edit->setMinimumSize( QSize( 70, 0 ) );
    timeX2Edit->setMaximumSize( QSize( 70, 32767 ) );
    timeX2Edit->setMaxValue( 999999999 );
    timeX2Edit->setValue( 1000 );

    layout1->addWidget( timeX2Edit, 0, 2 );

    currentY1Edit = new QSpinBox( frame, "currentY1Edit" );
    currentY1Edit->setMinimumSize( QSize( 70, 0 ) );
    currentY1Edit->setMaximumSize( QSize( 70, 32767 ) );
    currentY1Edit->setMaxValue( 999999999 );
    currentY1Edit->setMinValue( -999999999 );
    currentY1Edit->setValue( -20 );

    layout1->addWidget( currentY1Edit, 1, 1 );

    timeScaleLabel = new QLabel( frame, "timeScaleLabel" );
    QFont timeScaleLabel_font(  timeScaleLabel->font() );
    timeScaleLabel_font.setBold( TRUE );
    timeScaleLabel->setFont( timeScaleLabel_font ); 

    layout1->addWidget( timeScaleLabel, 0, 0 );

    timeX1Edit = new QSpinBox( frame, "timeX1Edit" );
    timeX1Edit->setMinimumSize( QSize( 70, 0 ) );
    timeX1Edit->setMaximumSize( QSize( 70, 32767 ) );
    timeX1Edit->setMaxValue( 999999999 );

    layout1->addWidget( timeX1Edit, 0, 1 );
    frameLayout->addLayout( layout1 );

    setAxesButton = new QPushButton( frame, "setAxesButton" );
    setAxesButton->setEnabled( TRUE );
    setAxesButton->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, 0, 0, setAxesButton->sizePolicy().hasHeightForWidth() ) );
    setAxesButton->setMinimumSize( QSize( 40, 40 ) );
    setAxesButton->setMaximumSize( QSize( 40, 40 ) );
    QFont setAxesButton_font(  setAxesButton->font() );
    setAxesButton->setFont( setAxesButton_font ); 
    setAxesButton->setPixmap( image0 );
    setAxesButton->setToggleButton( FALSE );
    setAxesButton->setFlat( FALSE );
    frameLayout->addWidget( setAxesButton );

    layout2 = new QVBoxLayout( 0, 0, 6, "layout2"); 

    overlaySweepsCheckBox = new QCheckBox( frame, "overlaySweepsCheckBox" );
    overlaySweepsCheckBox->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)1, 0, 0, overlaySweepsCheckBox->sizePolicy().hasHeightForWidth() ) );
    QFont overlaySweepsCheckBox_font(  overlaySweepsCheckBox->font() );
    overlaySweepsCheckBox_font.setBold( TRUE );
    overlaySweepsCheckBox->setFont( overlaySweepsCheckBox_font ); 
    layout2->addWidget( overlaySweepsCheckBox );

    plotAfterCheckBox = new QCheckBox( frame, "plotAfterCheckBox" );
    plotAfterCheckBox->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)1, 0, 0, plotAfterCheckBox->sizePolicy().hasHeightForWidth() ) );
    QFont plotAfterCheckBox_font(  plotAfterCheckBox->font() );
    plotAfterCheckBox_font.setBold( TRUE );
    plotAfterCheckBox->setFont( plotAfterCheckBox_font ); 
    layout2->addWidget( plotAfterCheckBox );
    frameLayout->addLayout( layout2 );

    layout3 = new QVBoxLayout( 0, 0, 6, "layout3"); 

    textLabel1 = new QLabel( frame, "textLabel1" );
    QFont textLabel1_font(  textLabel1->font() );
    textLabel1_font.setBold( TRUE );
    textLabel1->setFont( textLabel1_font ); 
    layout3->addWidget( textLabel1 );

    colorByComboBox = new QComboBox( FALSE, frame, "colorByComboBox" );
    QFont colorByComboBox_font(  colorByComboBox->font() );
    colorByComboBox->setFont( colorByComboBox_font ); 
    layout3->addWidget( colorByComboBox );
    frameLayout->addLayout( layout3 );
    spacer = new QSpacerItem( 1, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
    frameLayout->addItem( spacer );

    clearButton = new QPushButton( frame, "clearButton" );
    clearButton->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, 0, 0, clearButton->sizePolicy().hasHeightForWidth() ) );
    clearButton->setMinimumSize( QSize( 40, 40 ) );
    clearButton->setMaximumSize( QSize( 40, 40 ) );
    QFont clearButton_font(  clearButton->font() );
    clearButton->setFont( clearButton_font ); 
    clearButton->setPixmap( image1 );
    clearButton->setToggleButton( FALSE );
    frameLayout->addWidget( clearButton );
    languageChange();
    resize( QSize(938, 215).expandedTo(minimumSizeHint()) );
    clearWState( WState_Polished );
}
Exemple #12
0
	bool Executer::startExecution(bool onlySelection)
	{
		Q_ASSERT(mScriptAgent);
		Q_ASSERT(mScriptEngine);
		
	#ifdef ACT_PROFILE
		Tools::HighResolutionTimer timer("Executer::startExecution");
	#endif

        Code::CodeTools::addClassToScriptEngine<CodeActiona>("Actiona", mScriptEngine);
        CodeActiona::setActExec(mIsActExec);
        CodeActiona::setActionaVersion(mActionaVersion);
        CodeActiona::setScriptVersion(mScriptVersion);
        Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::version, "version", mScriptEngine);
        Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::scriptVersion, "scriptVersion", mScriptEngine);
        Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::isActExec, "isActExec", mScriptEngine);
        Code::CodeTools::addClassGlobalFunctionToScriptEngine("Actiona", &CodeActiona::isActiona, "isActiona", mScriptEngine);
		
		mScriptAgent->setContext(ScriptAgent::ActionInit);
		CodeInitializer::initialize(mScriptEngine, mScriptAgent, mActionFactory);
		mScriptAgent->setContext(ScriptAgent::Parameters);
		
        QScriptValue script = mScriptEngine->newObject();
		mScriptEngine->globalObject().setProperty("Script", script, QScriptValue::ReadOnly);
        script.setProperty("nextLine", 1);
        script.setProperty("line", 1, QScriptValue::ReadOnly);
        QScriptValue callProcedureFun = mScriptEngine->newFunction(callProcedureFunction);
        callProcedureFun.setData(mScriptEngine->newQObject(this));
        script.setProperty("callProcedure", callProcedureFun);

		QScriptValue console = mScriptEngine->newObject();
		mScriptEngine->globalObject().setProperty("Console", console, QScriptValue::ReadOnly);

        QScriptValue function = mScriptEngine->newFunction(printFunction);
        function.setData(mScriptEngine->newQObject(this));
        console.setProperty("print", function);

        function = mScriptEngine->newFunction(printWarningFunction);
        function.setData(mScriptEngine->newQObject(this));
        console.setProperty("printWarning", function);

        function = mScriptEngine->newFunction(printErrorFunction);
        function.setData(mScriptEngine->newQObject(this));
        console.setProperty("printError", function);

        function = mScriptEngine->newFunction(clearConsoleFunction);
        function.setData(mScriptEngine->newQObject(this));
        console.setProperty("clear", function);

		mExecuteOnlySelection = onlySelection;
		mCurrentActionIndex = 0;
		mActiveActionsCount = 0;
		mExecutionPaused = false;

		bool initSucceeded = true;
		int lastBeginProcedure = -1;

		mScript->clearProcedures();
		mScript->clearCallStack();

        const QHash<QString, ActionTools::Resource> &resources = mScript->resources();
        for(const QString &key: resources.keys())
        {
            const ActionTools::Resource &resource = resources.value(key);
            QScriptValue value;

            switch(resource.type())
            {
            case ActionTools::Resource::BinaryType:
            case ActionTools::Resource::TypeCount:
                value = Code::RawData::constructor(resource.data(), mScriptEngine);
                break;
            case ActionTools::Resource::TextType:
                value = QString::fromUtf8(resource.data(), resource.data().size());
                break;
            case ActionTools::Resource::ImageType:
                {
                    QImage image;

                    if(!image.loadFromData(resource.data()))
                    {
                        mConsoleWidget->addResourceLine(tr("Invalid image resource"), key, ActionTools::ConsoleWidget::Error);

                        return false;
                    }

                    value = Code::Image::constructor(image, mScriptEngine);
                }
                break;
            }

            mScriptEngine->globalObject().setProperty(key, value, QScriptValue::ReadOnly | QScriptValue::Undeletable);
        }

		for(int actionIndex = 0; actionIndex < mScript->actionCount(); ++actionIndex)
		{
			ActionTools::ActionInstance *actionInstance = mScript->actionAt(actionIndex);
			actionInstance->reset();
			actionInstance->clearRuntimeParameters();
			actionInstance->setupExecution(mScriptEngine, mScript, actionIndex);
			mActionEnabled.append(true);

			qint64 currentActionRuntimeId = -1;
			if(actionInstance)
				currentActionRuntimeId = actionInstance->runtimeId();

			if(canExecuteAction(actionIndex) == CanExecute)
			{
				++mActiveActionsCount;

				if(actionInstance->definition()->id() == "ActionBeginProcedure")
				{
					if(lastBeginProcedure != -1)
					{
						mConsoleWidget->addActionLine(tr("Invalid Begin procedure action, you have to end the previous procedure before starting another one"), currentActionRuntimeId, QString(), QString(), -1, -1, ActionTools::ConsoleWidget::Error);

						return false;
					}

					lastBeginProcedure = actionIndex;

					const ActionTools::SubParameter &nameParameter = actionInstance->subParameter("name", "value");
					const QString &procedureName = nameParameter.value().toString();

					if(procedureName.isEmpty())
					{
						mConsoleWidget->addActionLine(tr("A procedure name cannot be empty"), currentActionRuntimeId, QString(), QString(), -1, -1, ActionTools::ConsoleWidget::Error);

						return false;
					}

					if(mScript->findProcedure(procedureName) != -1)
					{
						mConsoleWidget->addActionLine(tr("A procedure with the name \"%1\" has already been declared").arg(procedureName), currentActionRuntimeId, QString(), QString(), -1, -1, ActionTools::ConsoleWidget::Error);

						return false;
					}

					mScript->addProcedure(procedureName, actionIndex);
				}
				else if(actionInstance->definition()->id() == "ActionEndProcedure")
				{
					if(lastBeginProcedure == -1)
					{
						mConsoleWidget->addActionLine(tr("Invalid End procedure"), currentActionRuntimeId, QString(), QString(), -1, -1, ActionTools::ConsoleWidget::Error);

						return false;
					}

					ActionTools::ActionInstance *beginProcedureActionInstance = mScript->actionAt(lastBeginProcedure);

					actionInstance->setRuntimeParameter("procedureBeginLine", lastBeginProcedure);
					beginProcedureActionInstance->setRuntimeParameter("procedureEndLine", actionIndex);

					lastBeginProcedure = -1;
				}
			}
		}

		if(lastBeginProcedure != -1)
		{
			ActionTools::ActionInstance *actionInstance = mScript->actionAt(lastBeginProcedure);
			qint64 actionRuntimeId = -1;
			if(actionInstance)
				actionRuntimeId = actionInstance->runtimeId();

			mConsoleWidget->addActionLine(tr("Begin procedure action without end procedure"), actionRuntimeId, QString(), QString(), -1, -1, ActionTools::ConsoleWidget::Error);

			return false;
		}

		for(int parameterIndex = 0; parameterIndex < mScript->parameterCount(); ++parameterIndex)
		{
			mScriptAgent->setCurrentParameter(parameterIndex);

			const ActionTools::ScriptParameter &scriptParameter = mScript->parameter(parameterIndex);
			QRegExp nameRegExp("[a-z_][a-z0-9_]*", Qt::CaseInsensitive);

			if(!nameRegExp.exactMatch(scriptParameter.name()))
			{
				mConsoleWidget->addScriptParameterLine(tr("Incorrect parameter name: \"%1\"").arg(scriptParameter.name()),
													   parameterIndex,
													   -1,
													   -1,
													   ActionTools::ConsoleWidget::Error);
				initSucceeded = false;
				continue;
			}

			QString value;
			if(scriptParameter.isCode())
			{
				QScriptValue result = mScriptEngine->evaluate(scriptParameter.value());
				if(result.isError())
				{
					mConsoleWidget->addScriptParameterLine(tr("Error while evaluating parameter \"%1\", error message: \"%2\"")
														   .arg(scriptParameter.name())
														   .arg(result.toString()),
														   parameterIndex,
														   -1,
														   -1,
														   ActionTools::ConsoleWidget::Error);
					initSucceeded = false;
					continue;
				}
				else
					value = result.toString();
			}
			else
				value = scriptParameter.value();

			mScriptEngine->globalObject().setProperty(scriptParameter.name(), value, QScriptValue::ReadOnly | QScriptValue::Undeletable);
		}

		if(!initSucceeded || mScript->actionCount() == 0)
			return false;

		if(mShowExecutionWindow)
		{
			QRect screenRect = QApplication::desktop()->availableGeometry(mExecutionWindowScreen);
			QPoint position;

			if(mExecutionWindowPosition >= 0 && mExecutionWindowPosition <= 2)//Left
				position.setX(screenRect.left());
			else if(mExecutionWindowPosition >= 3 && mExecutionWindowPosition <= 5)//HCenter
				position.setX(screenRect.left() + screenRect.width() / 2 - mExecutionWindow->width() / 2);
			else if(mExecutionWindowPosition >= 6 && mExecutionWindowPosition <= 8)//Right
				position.setX(screenRect.left() + screenRect.width() - mExecutionWindow->width());

			if(mExecutionWindowPosition == 0 || mExecutionWindowPosition == 3 || mExecutionWindowPosition == 6)//Up
				position.setY(screenRect.top());
			else if(mExecutionWindowPosition == 1 || mExecutionWindowPosition == 4 || mExecutionWindowPosition == 7)//VCenter
				position.setY(screenRect.top() + screenRect.height() / 2 - mExecutionWindow->height() / 2);
			else if(mExecutionWindowPosition == 2 || mExecutionWindowPosition == 5 || mExecutionWindowPosition == 8)//Down
				position.setY(screenRect.top() + screenRect.height() - mExecutionWindow->height());

			mExecutionWindow->setPauseStatus(false);
			mExecutionWindow->move(position);
			mExecutionWindow->show();
		}

		if(mShowConsoleWindow)
		{
			QRect screenRect = QApplication::desktop()->availableGeometry(mConsoleWindowScreen);
			QPoint position;

			if(mConsoleWindowPosition >= 0 && mConsoleWindowPosition <= 2)//Left
				position.setX(screenRect.left());
			else if(mConsoleWindowPosition >= 3 && mConsoleWindowPosition <= 5)//HCenter
				position.setX(screenRect.left() + screenRect.width() / 2 - mConsoleWidget->width() / 2);
			else if(mConsoleWindowPosition >= 6 && mConsoleWindowPosition <= 8)//Right
				position.setX(screenRect.left() + screenRect.width() - mConsoleWidget->width());

			if(mConsoleWindowPosition == 0 || mConsoleWindowPosition == 3 || mConsoleWindowPosition == 6)//Up
				position.setY(screenRect.top());
			else if(mConsoleWindowPosition == 1 || mConsoleWindowPosition == 4 || mConsoleWindowPosition == 7)//VCenter
				position.setY(screenRect.top() + screenRect.height() / 2 - mConsoleWidget->height() / 2);
			else if(mConsoleWindowPosition == 2 || mConsoleWindowPosition == 5 || mConsoleWindowPosition == 8)//Down
				position.setY(screenRect.top() + screenRect.height() - mConsoleWidget->height());

			mConsoleWidget->move(position);
			mConsoleWidget->show();
		}

		mExecutionStarted = true;

		mScriptAgent->setContext(ScriptAgent::Actions);
		
		mHasExecuted = true;

		executeCurrentAction();

		return true;
	}
Exemple #13
0
bool RawIOHandler::read(QImage *image)
{
    if (!d->load(device())) return false;

    QSize finalSize = d->scaledSize.isValid() ?
        d->scaledSize : d->defaultSize;

    const libraw_data_t &imgdata = d->raw->imgdata;
    libraw_processed_image_t *output;
    if (finalSize.width() < imgdata.thumbnail.twidth ||
        finalSize.height() < imgdata.thumbnail.theight) {
        qDebug() << "Using thumbnail";
        d->raw->unpack_thumb();
        output = d->raw->dcraw_make_mem_thumb();
    } else {
        qDebug() << "Decoding raw data";
        d->raw->unpack();
        d->raw->dcraw_process();
        output = d->raw->dcraw_make_mem_image();
    }

    QImage unscaled;
    uchar *pixels = 0;
    if (output->type == LIBRAW_IMAGE_JPEG) {
        unscaled.loadFromData(output->data, output->data_size, "JPEG");
        if (imgdata.sizes.flip != 0) {
            QTransform rotation;
            int angle = 0;
            if (imgdata.sizes.flip == 3) angle = 180;
            else if (imgdata.sizes.flip == 5) angle = -90;
            else if (imgdata.sizes.flip == 6) angle = 90;
            if (angle != 0) {
                rotation.rotate(angle);
                unscaled = unscaled.transformed(rotation);
            }
        }
    } else {
        int numPixels = output->width * output->height;
        int colorSize = output->bits / 8;
        int pixelSize = output->colors * colorSize;
        pixels = new uchar[numPixels * 4];
        uchar *data = output->data;
        for (int i = 0; i < numPixels; i++, data += pixelSize) {
            if (output->colors == 3) {
                pixels[i * 4] = data[2 * colorSize];
                pixels[i * 4 + 1] = data[1 * colorSize];
                pixels[i * 4 + 2] = data[0];
            } else {
                pixels[i * 4] = data[0];
                pixels[i * 4 + 1] = data[0];
                pixels[i * 4 + 2] = data[0];
            }
        }
        unscaled = QImage(pixels,
                          output->width, output->height,
                          QImage::Format_RGB32);
    }

    if (unscaled.size() != finalSize) {
        // TODO: use quality parameter to decide transformation method
        *image = unscaled.scaled(finalSize, Qt::IgnoreAspectRatio,
                                 Qt::SmoothTransformation);
    } else {
        *image = unscaled;
        if (output->type == LIBRAW_IMAGE_BITMAP) {
            // make sure that the bits are copied
            uchar *b = image->bits();
            Q_UNUSED(b);
        }
    }
    d->raw->dcraw_clear_mem(output);
    delete pixels;

    return true;
}
Exemple #14
0
QFileInfo Content::GetAlbumArt( int nTrackId, int nWidth, int nHeight )
{
    // ----------------------------------------------------------------------
    // Read AlbumArt file path from database
    // ----------------------------------------------------------------------

    MusicMetadata *metadata = MusicMetadata::createFromID(nTrackId);

    if (!metadata)
        return QFileInfo();

    QString sFullFileName = metadata->getAlbumArtFile();
    LOG(VB_GENERAL, LOG_DEBUG, QString("GetAlbumArt: %1").arg(sFullFileName));

    delete metadata;

    if (!RemoteFile::Exists(sFullFileName))
        return QFileInfo();

    QString sNewFileName = QString( "/tmp/%1.%2x%3.jpg" )
                              .arg( QFileInfo(sFullFileName).fileName() )
                              .arg( nWidth    )
                              .arg( nHeight   );

    // ----------------------------------------------------------------------
    // check to see if albumart image is already created.
    // ----------------------------------------------------------------------

    if (QFile::exists( sNewFileName ))
        return QFileInfo( sNewFileName );

    // ----------------------------------------------------------------------
    // Must generate Albumart Image, Generate Image and save.
    // ----------------------------------------------------------------------


    QImage img;
    if (sFullFileName.startsWith("myth://"))
    {
        RemoteFile rf(sFullFileName, false, false, 0);
        QByteArray data;
        rf.SaveAs(data);

        img.loadFromData(data);
    }
    else
        img.load(sFullFileName);

    if (img.isNull())
        return QFileInfo();

    // We don't need to scale if no height and width were specified
    // but still need to save as jpg if it's in another format
    if ((nWidth == 0) && (nHeight == 0))
    {
        if (!sFullFileName.startsWith("myth://"))
        {
            QFileInfo fi(sFullFileName);
            if (fi.suffix().toLower() == "jpg")
                return fi;
        }
    }
    else if (nWidth > img.width() && nHeight > img.height())
    {
        // Requested dimensions are larger than the source image, so instead of
        // scaling up which will produce horrible results return the fullsize
        // image and the user can scale further if they want instead
        // NOTE: If this behaviour is changed, for example making it optional,
        //       then upnp code will need changing to compensate
    }
    else
    {
        float fAspect = 0.0;
        if (fAspect <= 0)
            fAspect = (float)(img.width()) / img.height();

        if ( nWidth == 0 || nWidth > img.width() )
            nWidth = (int)rint(nHeight * fAspect);

        if ( nHeight == 0 || nHeight > img.height() )
            nHeight = (int)rint(nWidth / fAspect);

        img = img.scaled( nWidth, nHeight, Qt::KeepAspectRatio,
                                           Qt::SmoothTransformation);
    }

    QString fname = sNewFileName.toLatin1().constData();
    // Use JPG not PNG for compatibility with the most uPnP devices and
    // faster loading (smaller file to send over network)
    if (!img.save( fname, "JPG" ))
        return QFileInfo();

    return QFileInfo( sNewFileName );
}
bool GSCreator::create(const QString &path, int width, int height, QImage &img)
{
// The code in the loop (when testing whether got_sig_term got set)
// should read some variation of:
// 		parentJob()->wasKilled()
//
// Unfortunatelly, that's currently impossible without breaking BIC.
// So we need to catch the signal ourselves.
// Otherwise, on certain funny PS files (for example
// http://www.tjhsst.edu/~Eedanaher/pslife/life.ps )
// gs would run forever after we were dead.
// #### Reconsider for KDE 4 ###
// (24/12/03 - luis_pedro)
//
  typedef void ( *sighandler_t )( int );
  // according to linux's "man signal" the above typedef is a gnu extension
  sighandler_t oldhandler = signal( SIGTERM, handle_sigterm );

  int input[2];
  int output[2];
  int dvipipe[2];

  QByteArray data(1024, '\0');

  bool ok = false;

  // Test if file is DVI
  bool no_dvi =!correctDVI(path);

  if (pipe(input) == -1) {
    return false;
  }
  if (pipe(output) == -1) {
    close(input[0]);
    close(input[1]);
    return false;
  }

  KDSC dsc;
  endComments = false;
  dsc.setCommentHandler(this);

  if (no_dvi)
  {
    FILE* fp = fopen(QFile::encodeName(path), "r");
    if (fp == 0) return false;

    char buf[4096];
    int count;
    while ((count = fread(buf, sizeof(char), 4096, fp)) != 0
           && !endComments) {
      dsc.scanData(buf, count);
    }
    fclose(fp);

    if (dsc.pjl() || dsc.ctrld()) {
      // this file is a mess.
      return false;
    }
  }

  const bool is_encapsulated = no_dvi &&
    (path.indexOf(QRegExp("\\.epsi?$", Qt::CaseInsensitive)) > 0) &&
    (dsc.bbox()->width() > 0) && (dsc.bbox()->height() > 0) &&
    (dsc.page_count() <= 1);

  char translation[64] = "";
  char pagesize[32] = "";
  char resopt[32] = "";
  std::auto_ptr<KDSCBBOX> bbox = dsc.bbox();
  if (is_encapsulated) {
    // GhostScript's rendering at the extremely low resolutions
    // required for thumbnails leaves something to be desired. To
    // get nicer images, we render to four times the required
    // resolution and let QImage scale the result.
    const int hres = (width * 72) / bbox->width();
    const int vres = (height * 72) / bbox->height();
    const int resolution = (hres > vres ? vres : hres) * 4;
    const int gswidth = ((bbox->urx() - bbox->llx()) * resolution) / 72;
    const int gsheight = ((bbox->ury() - bbox->lly()) * resolution) / 72;

    snprintf(pagesize, 31, "-g%ix%i", gswidth, gsheight);
    snprintf(resopt, 31, "-r%i", resolution);
    snprintf(translation, 63,
       " 0 %i sub 0 %i sub translate\n", bbox->llx(),
       bbox->lly());
  }

  const CDSC_PREVIEW_TYPE previewType =
    static_cast<CDSC_PREVIEW_TYPE>(dsc.preview());

  switch (previewType) {
  case CDSC_TIFF:
  case CDSC_WMF:
  case CDSC_PICT:
    // FIXME: these should take precedence, since they can hold
    // color previews, which EPSI can't (or can it?).
     break;
  case CDSC_EPSI:
    {
      const int xscale = bbox->width() / width;
      const int yscale = bbox->height() / height;
      const int scale = xscale < yscale ? xscale : yscale;
      if (getEPSIPreview(path,
                         dsc.beginpreview(),
                         dsc.endpreview(),
                         img,
                         bbox->width() / scale,
                         bbox->height() / scale))
        return true;
      // If the preview extraction routine fails, gs is used to
      // create a thumbnail.
    }
    break;
  case CDSC_NOPREVIEW:
  default:
    // need to run ghostscript in these cases
    break;
  }

  pid_t pid = fork();
  if (pid == 0) {
    // Child process (1)

    //    close(STDERR_FILENO);

    // find first zero entry in gsargs and put the filename
    // or - (stdin) there, if DVI
    const char **gsargs = gsargs_ps;
    const char **arg = gsargs;

    if (no_dvi && is_encapsulated) {
      gsargs = gsargs_eps;
      arg = gsargs;

      // find first zero entry and put page size there
      while (*arg) ++arg;
      *arg = pagesize;

      // find second zero entry and put resolution there
      while (*arg) ++arg;
      *arg = resopt;
    }

    // find next zero entry and put the filename there
    QByteArray fname = QFile::encodeName( path );
    while (*arg)
      ++arg;
    if( no_dvi )
      *arg = fname.data();
    else
      *arg = "-";

    // find first zero entry in dvipsargs and put the filename there
    arg = dvipsargs;
    while (*arg)
      ++arg;
    *arg = fname.data();

    if( !no_dvi ){
      pipe(dvipipe);
      pid_t pid_two = fork();
      if( pid_two == 0 ){
	// Child process (2), reopen stdout on the pipe "dvipipe" and exec dvips

	close(input[0]);
	close(input[1]);
	close(output[0]);
	close(output[1]);
	close(dvipipe[0]);

	dup2( dvipipe[1], STDOUT_FILENO);

	execvp(dvipsargs[0], const_cast<char *const *>(dvipsargs));
	exit(1);
      }
      else if(pid_two != -1){
	close(input[1]);
	close(output[0]);
	close(dvipipe[1]);

	dup2( dvipipe[0], STDIN_FILENO);
	dup2( output[1], STDOUT_FILENO);

	execvp(gsargs[0], const_cast<char *const *>(gsargs));
	exit(1);
      }
      else{
	// fork() (2) failed, close these
	close(dvipipe[0]);
	close(dvipipe[1]);
      }

    }
    else if( no_dvi ){
      // Reopen stdin/stdout on the pipes and exec gs
      close(input[1]);
      close(output[0]);

      dup2(input[0], STDIN_FILENO);
      dup2(output[1], STDOUT_FILENO);

      execvp(gsargs[0], const_cast<char *const *>(gsargs));
      exit(1);
    }
  }
  else if (pid != -1) {
    // Parent process, write first-page-only-hack (the hack is not
    // used if DVI) and read the png output
    close(input[0]);
    close(output[1]);
    const char *prolog;
    if (is_encapsulated)
      prolog = epsprolog;
    else
      prolog = psprolog;
    int count = write(input[1], prolog, strlen(prolog));
    if (is_encapsulated)
      write(input[1], translation, strlen(translation));

    close(input[1]);
    if (count == static_cast<int>(strlen(prolog))) {
      int offset = 0;
	while (!ok) {
	  fd_set fds;
	  FD_ZERO(&fds);
	  FD_SET(output[0], &fds);
	  struct timeval tv;
	  tv.tv_sec = 20;
	  tv.tv_usec = 0;

	  got_sig_term = false;
	  if (select(output[0] + 1, &fds, 0, 0, &tv) <= 0) {
            if ( ( errno == EINTR || errno == EAGAIN ) && !got_sig_term ) continue;
	    break; // error, timeout or master wants us to quit (SIGTERM)
          }
	  if (FD_ISSET(output[0], &fds)) {
	    count = read(output[0], data.data() + offset, 1024);
	    if (count == -1)
	      break;
	    else
	      if (count) // prepare for next block
		{
		  offset += count;
		  data.resize(offset + 1024);
		}
	      else // got all data
		{
		  data.resize(offset);
		  ok = true;
		}
	  }
	}
    }
    if (!ok) // error or timeout, gs probably didn't exit yet
    {
      kill(pid, SIGTERM);
    }

    int status = 0;
    int ret;
    do {
      ret = waitpid(pid, &status, 0);
    } while (ret == -1 && errno == EINTR);
    if (ret != pid || (status != 0  && status != 256) )
      ok = false;
  }
  else {
    // fork() (1) failed, close these
    close(input[0]);
    close(input[1]);
    close(output[1]);
  }
  close(output[0]);

  int l = img.loadFromData( data );

  if ( got_sig_term &&
	oldhandler != SIG_ERR &&
	oldhandler != SIG_DFL &&
	oldhandler != SIG_IGN ) {
	  oldhandler( SIGTERM ); // propagate the signal. Other things might rely on it
  }
  if ( oldhandler != SIG_ERR ) signal( SIGTERM, oldhandler );

  return ok && l;
}
Exemple #16
0
bool PixmapChannel::CacheChannelIcon(void)
{
    if (icon.isEmpty())
        return false;

    m_localIcon = icon;

    // Is icon local?
    if (QFile(icon).exists())
        return true;

    QString localDirStr = QString("%1/channels").arg(GetConfDir());
    QDir localDir(localDirStr);

    if (!localDir.exists() && !localDir.mkdir(localDirStr))
    {
        VERBOSE(VB_IMPORTANT, QString("Icons directory is missing and could "
                                      "not be created: %1").arg(localDirStr));
        icon.clear();
        return false;
    }

    // Has it been saved to the local cache?
    m_localIcon = QString("%1/%2").arg(localDirStr)
                                 .arg(QFileInfo(icon).fileName());
    if (QFile(m_localIcon).exists())
        return true;

    // Get address of master backed
    QString url = gCoreContext->GetMasterHostPrefix();
    if (url.length() < 1)
    {
        icon.clear();
        return false;
    }

    url.append(icon);

    QUrl qurl = url;
    if (qurl.host().isEmpty())
    {
        icon.clear();
        return false;
    }

    RemoteFile *rf = new RemoteFile(url, false, false, 0);

    QByteArray data;
    bool ret = rf->SaveAs(data);

    delete rf;

    if (ret && data.size())
    {
        QImage image;

        image.loadFromData(data);

        //if (image.loadFromData(data) && image.width() > 0

        if (image.save(m_localIcon))
        {
            VERBOSE(VB_GENERAL, QString("Caching channel icon %1").arg(m_localIcon));
            return true;
        }
        else
            VERBOSE(VB_GENERAL, QString("Failed to save to %1").arg(m_localIcon));
    }

    // if we get here then the icon is set in the db but couldn't be found
    // anywhere so maybe we should remove it from the DB?
    icon.clear();

    return false;
}
/*------------------------------------------------------------------*
 * MODIFICATIONS:                                                   *
 *  Date        Description                         Author          *
 *============  ==================================  =============== *
 *                                                                  *
 *------------------------------------------------------------------*/
void ZImageThread::run()
{
	ZRequestList::iterator	vIt;
	ZImageThreadEvent		*vEvt;
#ifdef ZULU_EXIF
	ExifData				*vEd;
#endif
	bool					vExifHasThumb;
	qDebug("%s::Thread started", __FILE__);
	for(;;)
	{
		qDebug("%s::Loop entered", __FILE__);
		/*
		 * Wait until we are notified to begin processing
		 */
		mThreadWait.wait();
		if (mShutdown)
			break;

		/*
		 * We've got data
		 */
		qDebug("%s::Data to process", __FILE__);
		vIt = mRequests.begin();
		QPixmap *vPix;
		while (vIt != mRequests.end())
		{
			vExifHasThumb = false;
			vPix = NULL;

#ifdef ZULU_EXIF
			/*
			 * try to obtain thumbnail from exif
			 */
			ExifLoader *vLoader = exif_loader_new();
			exif_loader_write_file(vLoader, (*vIt).GetURI().latin1());
			vEd = exif_loader_get_data(vLoader);
			exif_loader_unref(vLoader);
			if (vEd == NULL)
			{
				qDebug("%s::%s does not contain EXIF data!", __FILE__, (*vIt).GetURI().latin1());
			}
			else
			{
				qDebug("%s::%s has EXIF data!", __FILE__, (*vIt).GetURI().latin1());
				if (vEd->data != NULL)
				{
					QImage vTemp;
					if (vTemp.loadFromData(vEd->data, vEd->size) == false)
						qDebug("%s::Unable to load pixmap", __FILE__);
					else
					{
						vPix = new QPixmap(vTemp.smoothScale((*vIt).GetWidth(), (*vIt).GetHeight(), QImage::ScaleMin));
						if (vPix == NULL)
							qDebug("%s::Unable to create pixmap", __FILE__);
						else
							vExifHasThumb = true;
					}
				}
			}
#endif
			/*
			 * Create the thumbnail
			 */
			if (vExifHasThumb == false)
			{
				QString vURI = (*vIt).GetURI();
				qDebug("%s::Image format => [%s]", __FILE__, QImage::imageFormat(vURI));
				qDebug("%s::Loading image %s", __FILE__, (*vIt).GetURI().latin1());
				QImageIO vImgIO;
				vImgIO.setFileName(vURI);
				if (vImgIO.read() == false)
				{
					qDebug("%s::Unable to read image", __FILE__);
					continue;
				}

				vPix = new QPixmap(vImgIO.image().scale((*vIt).GetWidth() , (*vIt).GetHeight(), QImage::ScaleMin));
				if (vPix == NULL)
					qDebug("%s::Unable to create pixmap from image", __FILE__);
			}

			/*
			 * Create and send the notification event
			 */
			vEvt = new ZImageThreadEvent((*vIt).GetKey(), vPix);
			delete vPix;
			vPix = NULL;
			QApplication::postEvent(mParent, vEvt);

			/*
			 * Now remove this request from the queue
			 */
			mListLock.lock();
			vIt = mRequests.erase(vIt);
			mListLock.unlock();
		}
	}
	qDebug("%s::Thread exiting", __FILE__);
}
void loadFromXml( mlt_producer producer, QGraphicsScene *scene, const char *templateXml, const char *templateText )
{
	scene->clear();
	mlt_properties producer_props = MLT_PRODUCER_PROPERTIES( producer );
	QDomDocument doc;
	QString data = QString::fromUtf8(templateXml);
	QString replacementText = QString::fromUtf8(templateText);
	doc.setContent(data);
	QDomElement title = doc.documentElement();

	// Check for invalid title
	if ( title.isNull() || title.tagName() != "kdenlivetitle" ) return;
	
	// Check title locale
	if ( title.hasAttribute( "LC_NUMERIC" ) ) {
	    QString locale = title.attribute( "LC_NUMERIC" );
	    QLocale::setDefault( locale );
	}
	
        int originalWidth;
        int originalHeight;
	if ( title.hasAttribute("width") ) {
            originalWidth = title.attribute("width").toInt();
            originalHeight = title.attribute("height").toInt();
            scene->setSceneRect(0, 0, originalWidth, originalHeight);
        }
        else {
            originalWidth = scene->sceneRect().width();
            originalHeight = scene->sceneRect().height();
        }
        if ( title.hasAttribute( "out" ) ) {
            mlt_properties_set_position( producer_props, "_animation_out", title.attribute( "out" ).toDouble() );
        }
        else {
            mlt_properties_set_position( producer_props, "_animation_out", mlt_producer_get_out( producer ) );
        }
        
	mlt_properties_set_int( producer_props, "_original_width", originalWidth );
	mlt_properties_set_int( producer_props, "_original_height", originalHeight );

	QDomNode node;
	QDomNodeList items = title.elementsByTagName("item");
        for ( int i = 0; i < items.count(); i++ )
	{
		QGraphicsItem *gitem = NULL;
		node = items.item( i );
		QDomNamedNodeMap nodeAttributes = node.attributes();
		int zValue = nodeAttributes.namedItem( "z-index" ).nodeValue().toInt();
		if ( zValue > -1000 )
		{
			if ( nodeAttributes.namedItem( "type" ).nodeValue() == "QGraphicsTextItem" )
			{
				QDomNamedNodeMap txtProperties = node.namedItem( "content" ).attributes();
				QFont font( txtProperties.namedItem( "font" ).nodeValue() );
				QDomNode propsNode = txtProperties.namedItem( "font-bold" );
				if ( !propsNode.isNull() )
				{
					// Old: Bold/Not bold.
					font.setBold( propsNode.nodeValue().toInt() );
				}
				else
				{
					// New: Font weight (QFont::)
					font.setWeight( txtProperties.namedItem( "font-weight" ).nodeValue().toInt() );
				}
				font.setItalic( txtProperties.namedItem( "font-italic" ).nodeValue().toInt() );
				font.setUnderline( txtProperties.namedItem( "font-underline" ).nodeValue().toInt() );
				// Older Kdenlive version did not store pixel size but point size
				if ( txtProperties.namedItem( "font-pixel-size" ).isNull() )
				{
					QFont f2;
					f2.setPointSize( txtProperties.namedItem( "font-size" ).nodeValue().toInt() );
					font.setPixelSize( QFontInfo( f2 ).pixelSize() );
				}
				else
					font.setPixelSize( txtProperties.namedItem( "font-pixel-size" ).nodeValue().toInt() );
				QColor col( stringToColor( txtProperties.namedItem( "font-color" ).nodeValue() ) );
				QString text = node.namedItem( "content" ).firstChild().nodeValue();
				if ( !replacementText.isEmpty() )
				{
					text = text.replace( "%s", replacementText );
				}
				QGraphicsTextItem *txt = scene->addText(text, font);
				if (txtProperties.namedItem("font-outline").nodeValue().toDouble()>0.0){
					QTextDocument *doc = txt->document();
					// Make sure some that the text item does not request refresh by itself
					doc->blockSignals(true);
					QTextCursor cursor(doc);
					cursor.select(QTextCursor::Document);
					QTextCharFormat format;
					format.setTextOutline(
							QPen(QColor( stringToColor( txtProperties.namedItem( "font-outline-color" ).nodeValue() ) ),
							txtProperties.namedItem("font-outline").nodeValue().toDouble(),
							Qt::SolidLine,Qt::RoundCap,Qt::RoundJoin)
					);
					format.setForeground(QBrush(col));

					cursor.mergeCharFormat(format);
				} else {
					txt->setDefaultTextColor( col );
				}
				
				// Effects
				if (!txtProperties.namedItem( "typewriter" ).isNull()) {
					// typewriter effect
					mlt_properties_set_int( producer_props, "_animated", 1 );
					QStringList effetData = QStringList() << "typewriter" << text << txtProperties.namedItem( "typewriter" ).nodeValue();
					txt->setData(0, effetData);
					if ( !txtProperties.namedItem( "textwidth" ).isNull() )
						txt->setData( 1, txtProperties.namedItem( "textwidth" ).nodeValue() );
				}
				
				if ( txtProperties.namedItem( "alignment" ).isNull() == false )
				{
					txt->setTextWidth( txt->boundingRect().width() );
					QTextOption opt = txt->document()->defaultTextOption ();
					opt.setAlignment(( Qt::Alignment ) txtProperties.namedItem( "alignment" ).nodeValue().toInt() );
					txt->document()->setDefaultTextOption (opt);
				}
					if ( !txtProperties.namedItem( "kdenlive-axis-x-inverted" ).isNull() )
				{
					//txt->setData(OriginXLeft, txtProperties.namedItem("kdenlive-axis-x-inverted").nodeValue().toInt());
				}
				if ( !txtProperties.namedItem( "kdenlive-axis-y-inverted" ).isNull() )
				{
					//txt->setData(OriginYTop, txtProperties.namedItem("kdenlive-axis-y-inverted").nodeValue().toInt());
				}
					gitem = txt;
			}
			else if ( nodeAttributes.namedItem( "type" ).nodeValue() == "QGraphicsRectItem" )
			{
				QString rect = node.namedItem( "content" ).attributes().namedItem( "rect" ).nodeValue();
				QString br_str = node.namedItem( "content" ).attributes().namedItem( "brushcolor" ).nodeValue();
				QString pen_str = node.namedItem( "content" ).attributes().namedItem( "pencolor" ).nodeValue();
				double penwidth = node.namedItem( "content" ).attributes().namedItem( "penwidth") .nodeValue().toDouble();
				QGraphicsRectItem *rec = scene->addRect( stringToRect( rect ), QPen( QBrush( stringToColor( pen_str ) ), penwidth, Qt::SolidLine, Qt::SquareCap, Qt::RoundJoin ), QBrush( stringToColor( br_str ) ) );
				gitem = rec;
			}
			else if ( nodeAttributes.namedItem( "type" ).nodeValue() == "QGraphicsPixmapItem" )
			{
				const QString url = node.namedItem( "content" ).attributes().namedItem( "url" ).nodeValue();
				const QString base64 = items.item(i).namedItem("content").attributes().namedItem("base64").nodeValue();
				QImage img;
				if (base64.isEmpty()){
					img.load(url);
				}else{
					img.loadFromData(QByteArray::fromBase64(base64.toAscii()));
				}
				ImageItem *rec = new ImageItem(img);
				scene->addItem( rec );
				gitem = rec;
			}
			else if ( nodeAttributes.namedItem( "type" ).nodeValue() == "QGraphicsSvgItem" )
			{
				QString url = items.item(i).namedItem("content").attributes().namedItem("url").nodeValue();
				QString base64 = items.item(i).namedItem("content").attributes().namedItem("base64").nodeValue();
				QGraphicsSvgItem *rec = NULL;
				if (base64.isEmpty()){
					rec = new QGraphicsSvgItem(url);
				}else{
					rec = new QGraphicsSvgItem();
					QSvgRenderer *renderer= new QSvgRenderer(QByteArray::fromBase64(base64.toAscii()), rec );
					rec->setSharedRenderer(renderer);
				}
				if (rec){
					scene->addItem(rec);
					gitem = rec;
				}
			}
		}
		//pos and transform
		if ( gitem )
		{
			QPointF p( node.namedItem( "position" ).attributes().namedItem( "x" ).nodeValue().toDouble(),
			           node.namedItem( "position" ).attributes().namedItem( "y" ).nodeValue().toDouble() );
			gitem->setPos( p );
			gitem->setTransform( stringToTransform( node.namedItem( "position" ).firstChild().firstChild().nodeValue() ) );
			int zValue = nodeAttributes.namedItem( "z-index" ).nodeValue().toInt();
			gitem->setZValue( zValue );

#if QT_VERSION >= 0x040600
			// effects
			QDomNode eff = items.item(i).namedItem("effect");
			if (!eff.isNull()) {
				QDomElement e = eff.toElement();
				if (e.attribute("type") == "blur") {
					QGraphicsBlurEffect *blur = new QGraphicsBlurEffect();
					blur->setBlurRadius(e.attribute("blurradius").toInt());
					gitem->setGraphicsEffect(blur);
				}
				else if (e.attribute("type") == "shadow") {
					QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
					shadow->setBlurRadius(e.attribute("blurradius").toInt());
					shadow->setOffset(e.attribute("xoffset").toInt(), e.attribute("yoffset").toInt());
					gitem->setGraphicsEffect(shadow);
				}
			}
#endif
		}
	}

	QDomNode n = title.firstChildElement("background");
	if (!n.isNull()) {
		QColor color = QColor( stringToColor( n.attributes().namedItem( "color" ).nodeValue() ) );
                if (color.alpha() > 0) {
                        QGraphicsRectItem *rec = scene->addRect(0, 0, scene->width(), scene->height() , QPen( Qt::NoPen ), QBrush( color ) );
                        rec->setZValue(-1100);
                }
	  
	}

	QString startRect;
	n = title.firstChildElement( "startviewport" );
        // Check if node exists, if it has an x attribute, it is an old version title, don't use viewport
	if (!n.isNull() && !n.toElement().hasAttribute("x"))
	{
		startRect = n.attributes().namedItem( "rect" ).nodeValue();
	}
	n = title.firstChildElement( "endviewport" );
        // Check if node exists, if it has an x attribute, it is an old version title, don't use viewport
	if (!n.isNull() && !n.toElement().hasAttribute("x"))
	{
		QString rect = n.attributes().namedItem( "rect" ).nodeValue();
		if (startRect != rect)
			mlt_properties_set( producer_props, "_endrect", rect.toUtf8().data() );
	}
	if (!startRect.isEmpty()) {
	  	mlt_properties_set( producer_props, "_startrect", startRect.toUtf8().data() );
	}
	return;
}
Exemple #19
0
bool UserPlugin::onVCard(const VCardWrapper& vcardWrapper)
{
	const gloox::JID jid=vcardWrapper.jid();
	gloox::VCard vcard=gloox::VCard(vcardWrapper.vcard());

	qDebug() << "Got vcard: "+vcardWrapper.id();
	QString jidStr=QString::fromStdString(jid.full());
	QString reqId=QString("vcard_%1").arg(vcardWrapper.id());
	AsyncRequest* req=bot()->asyncRequests()->byStanzaId(reqId);
	if (req==0l)
	{
		return false;
	}
	if (vcardWrapper.isEmpty())
	{
		reply(req->stanza(), "No VCard found");
		bot()->asyncRequests()->removeAll(req);
		return true;
	}

	if (req->name()=="VCARD")
	{
		QString replyStr=vcardWrapper.vcardStr();
		if (replyStr.isEmpty())
		{
			reply(req->stanza(), "Empty VCard");
		}
		else
		{
			reply(req->stanza(), QString("VCard: %1").arg(replyStr));
		}
	}
	else if (req->name()=="PHOTO")
	{
		std::string photoContentStd=vcard.photo().binval;
		QByteArray photoContent=QByteArray(photoContentStd.data(),
				photoContentStd.size());
		//QFile file("/tmp/out.png");
		//file.open(QIODevice::WriteOnly);
		//file.write(photoContentStd.data(), photoContentStd.size());
		//file.close();
		QImage image;
		if (!image.loadFromData(photoContent))
		{
			reply(req->stanza(), "Can't load image");
			bot()->asyncRequests()->removeAll(req);
			return true;
		}

		MessageParser parser(req->stanza(), getMyNick(req->stanza()));
		parser.nextToken();
		QString cmd=parser.nextToken().toUpper();
		QString jid=parser.nextToken();
		QString widthStr=parser.nextToken();
		QString white=parser.nextToken();
		QString black=parser.nextToken();

		Image2Ascii img2ascii(image);

		if (!widthStr.isEmpty())
			img2ascii.setWidth(widthStr.toInt());
		if (!white.isEmpty() && white.length()<=5)
			img2ascii.setWhite(white);
		if (!black.isEmpty() && black.length()<=5)
			img2ascii.setBlack(black);

		QString ascii=img2ascii.ascii();
		if (ascii.isEmpty())
			reply(req->stanza(), "Can't convert image to ASCII");
		else
			reply(req->stanza(), QString("Photo:\n%1").arg(ascii));
	}
	bot()->asyncRequests()->removeAll(req);
	return true;
}
void KoListLevelProperties::loadOdf(KoShapeLoadingContext& scontext, const KoXmlElement& style)
{
    KoOdfLoadingContext &context = scontext.odfLoadingContext();

    // The text:level attribute specifies the level of the number list
    // style. It can be used on all list-level styles.
    const int level = qMax(1, style.attributeNS(KoXmlNS::text, "level", QString()).toInt());
    // The text:display-levels attribute specifies the number of
    // levels whose numbers are displayed at the current level.
    const QString displayLevel = style.attributeNS(KoXmlNS::text,
                                 "display-levels", QString());

    const QString styleName = style.attributeNS(KoXmlNS::text, "style-name", QString());
    KoCharacterStyle *cs = 0;
    if (!styleName.isEmpty()) {
//         kDebug(32500) << "Should use the style =>" << styleName << "<=";

        KoSharedLoadingData *sharedData = scontext.sharedData(KOTEXT_SHARED_LOADING_ID);
        KoTextSharedLoadingData *textSharedData = 0;
        if (sharedData) {
            textSharedData = dynamic_cast<KoTextSharedLoadingData *>(sharedData);
        }
        if (textSharedData) {
            cs = textSharedData->characterStyle(styleName, context.useStylesAutoStyles());
            if (!cs) {
               kWarning(32500) << "Missing KoCharacterStyle!";
            }
            else {
//                kDebug(32500) << "==> cs.name:" << cs->name();
//                kDebug(32500) << "==> cs.styleId:" << cs->styleId();
                setCharacterStyleId(cs->styleId());
            }
        }
    }

    if (style.localName() == "list-level-style-bullet") {   // list with bullets
        // special case bullets:
        //qDebug() << QChar(0x2202) << QChar(0x25CF) << QChar(0xF0B7) << QChar(0xE00C)
        //<< QChar(0xE00A) << QChar(0x27A2)<< QChar(0x2794) << QChar(0x2714) << QChar(0x2d) << QChar(0x2717);

        //1.6: KoParagCounter::loadOasisListStyle
        QString bulletChar = style.attributeNS(KoXmlNS::text, "bullet-char", QString());
//         kDebug(32500) << "style.localName()=" << style.localName() << "level=" << level << "displayLevel=" << displayLevel << "bulletChar=" << bulletChar;
        if (bulletChar.isEmpty()) {  // list without any visible bullets
            setStyle(KoListStyle::CustomCharItem);
            setBulletCharacter(QChar());
        } else { // try to determinate the bullet we should use
            switch (bulletChar[0].unicode()) {
            case 0x2022: // bullet, a small disc -> circle
                setStyle(KoListStyle::Bullet);
                break;
            case 0x25CF: // black circle, large disc -> disc
                setStyle(KoListStyle::BlackCircle);
                break;
            case 0x25CB:           //white circle, no fill
                setStyle(KoListStyle::CircleItem);
                break;
            case 0x25C6: // losange => rhombus
                setStyle(KoListStyle::RhombusItem);
                break;
            case 0x25A0: // square. Not in OASIS (reserved Unicode area!), but used in both OOo and kotext.
                setStyle(KoListStyle::SquareItem);
                break;
            case 0x27A2: // two-colors right-pointing triangle
                setStyle(KoListStyle::RightArrowHeadItem);
                break;
            case 0x2794: // arrow to right
                setStyle(KoListStyle::RightArrowItem);
                break;
            case 0x2714: // checkmark
                setStyle(KoListStyle::HeavyCheckMarkItem);
                break;
            case 0x2d: // minus
                setStyle(KoListStyle::CustomCharItem);
                break;
            case 0x2717: // cross
                setStyle(KoListStyle::BallotXItem);
                break;
            default:
                QChar customBulletChar = bulletChar[0];
                kDebug(32500) << "Unhandled bullet code 0x" << QString::number((uint)customBulletChar.unicode(), 16) << bulletChar;
                kDebug(32500) << "Should use the style =>" << style.attributeNS(KoXmlNS::text, "style-name", QString()) << "<=";
                setStyle(KoListStyle::CustomCharItem);
                /*
                QString customBulletFont;
                // often StarSymbol when it comes from OO; doesn't matter, Qt finds it in another font if needed.
                if ( listStyleProperties.hasAttributeNS( KoXmlNS::style, "font-name" ) )
                {
                    customBulletFont = listStyleProperties.attributeNS( KoXmlNS::style, "font-name", QString() );
                    kDebug(32500) <<"customBulletFont style:font-name =" << listStyleProperties.attributeNS( KoXmlNS::style,"font-name", QString() );
                }
                else if ( listStyleTextProperties.hasAttributeNS( KoXmlNS::fo, "font-family" ) )
                {
                    customBulletFont = listStyleTextProperties.attributeNS( KoXmlNS::fo, "font-family", QString() );
                    kDebug(32500) <<"customBulletFont fo:font-family =" << listStyleTextProperties.attributeNS( KoXmlNS::fo,"font-family", QString() );
                }
                // ## TODO in fact we're supposed to read it from the style pointed to by text:style-name
                */
//                     setStyle(KoListStyle::BoxItem); //fallback
                break;
            } // switch
            setBulletCharacter(bulletChar[0]);
        }
        QString size = style.attributeNS(KoXmlNS::text, "bullet-relative-size", QString());
        if (!size.isEmpty()) {
            setRelativeBulletSize(size.remove('%').toInt());
        }

    } else if (style.localName() == "list-level-style-number" || style.localName() == "outline-level-style") { // it's a numbered list

        if (style.localName() == "outline-level-style") {
            setOutlineList(true);
        }
        setRelativeBulletSize(100); //arbitrary value for numbered list

        KoOdfNumberDefinition numberDefinition;
        numberDefinition.loadOdf(style);

        switch(numberDefinition.formatSpecification()) {
        case KoOdfNumberDefinition::Empty:
            setStyle(KoListStyle::None);
            break;
        case KoOdfNumberDefinition::AlphabeticLowerCase:
            setStyle(KoListStyle::AlphaLowerItem);
            break;
        case KoOdfNumberDefinition::AlphabeticUpperCase:
            setStyle(KoListStyle::UpperAlphaItem);
            break;
        case KoOdfNumberDefinition::RomanLowerCase:
            setStyle(KoListStyle::RomanLowerItem);
            break;
        case KoOdfNumberDefinition::RomanUpperCase:
            setStyle(KoListStyle::UpperRomanItem);
            break;
        case KoOdfNumberDefinition::ArabicAlphabet:
                    setStyle(KoListStyle::ArabicAlphabet);
                    break;
        case KoOdfNumberDefinition::Thai:
            setStyle(KoListStyle::Thai);
            break;
        case KoOdfNumberDefinition::Abjad:
            setStyle(KoListStyle::Abjad);
            break;
        case KoOdfNumberDefinition::AbjadMinor:
            setStyle(KoListStyle::AbjadMinor);
            break;
        case KoOdfNumberDefinition::Tibetan:
            setStyle(KoListStyle::Tibetan);
            break;
        case KoOdfNumberDefinition::Telugu:
            setStyle(KoListStyle::Telugu);
            break;
        case KoOdfNumberDefinition::Tamil:
            setStyle(KoListStyle::Tamil);
            break;
        case KoOdfNumberDefinition::Oriya:
            setStyle(KoListStyle::Oriya);
            break;
        case KoOdfNumberDefinition::Malayalam:
            setStyle(KoListStyle::Malayalam);
            break;
        case KoOdfNumberDefinition::Kannada:
            setStyle(KoListStyle::Kannada);
            break;
        case KoOdfNumberDefinition::Gurumukhi:
            setStyle(KoListStyle::Gurumukhi);
            break;
        case KoOdfNumberDefinition::Gujarati:
            setStyle(KoListStyle::Gujarati);
            break;
        case KoOdfNumberDefinition::Bengali:
            setStyle(KoListStyle::Bengali);
            break;
        case KoOdfNumberDefinition::Numeric:
        default:
            setStyle(KoListStyle::DecimalItem);
        }

        if (!numberDefinition.prefix().isNull()) {
            setListItemPrefix(numberDefinition.prefix());
        }

        if (!numberDefinition.suffix().isNull()) {
            setListItemSuffix(numberDefinition.suffix());
        }
        const QString startValue = style.attributeNS(KoXmlNS::text, "start-value", QString("1"));
        setStartValue(startValue.toInt());
    }
    else if (style.localName() == "list-level-style-image") {   // list with image
        setStyle(KoListStyle::ImageItem);
        KoImageCollection *imageCollection = scontext.imageCollection();
        const QString href = style.attribute("href");
        if(imageCollection) {
            if (!href.isEmpty()) {
                KoStore *store = context.store();
                setBulletImage(imageCollection->createImageData(href, store));
            } else {
                // check if we have an office:binary data element containing the image data
                const KoXmlElement &binaryData(KoXml::namedItemNS(style, KoXmlNS::office, "binary-data"));
                if (!binaryData.isNull()) {
                    QImage image;
                    if (image.loadFromData(QByteArray::fromBase64(binaryData.text().toLatin1()))) {
                        setBulletImage(imageCollection->createImageData(image));
                    }
                }
            }
        }
    }
    else { // if not defined, we have do nothing
//         kDebug(32500) << "stylename else:" << style.localName() << "level=" << level << "displayLevel=" << displayLevel;
        setStyle(KoListStyle::DecimalItem);
        setListItemSuffix(".");
    }

    setLevel(level);
    if (!displayLevel.isEmpty())
        setDisplayLevel(displayLevel.toInt());

    KoXmlElement property;
    forEachElement(property, style) {
        if (property.namespaceURI() != KoXmlNS::style)
            continue;
        const QString localName = property.localName();
        if (localName == "list-level-properties") {
            QString mode(property.attributeNS(KoXmlNS::text, "list-level-position-and-space-mode"));
            if (mode == "label-alignment") {
                QString textAlign(property.attributeNS(KoXmlNS::fo, "text-align"));
                setAlignment(textAlign.isEmpty() ? Qt::AlignLeft : KoText::alignmentFromString(textAlign));

                KoXmlElement p;
                forEachElement(p, property) {
                     if (p.namespaceURI() == KoXmlNS::style && p.localName() == "list-level-label-alignment") {
                        // The <style:list-level-label-alignment> element and the fo:text-align attribute are used to define
                        // the position and spacing of the list label and the list item. The values of the attributes for
                        // text:space-before, text:min-label-width and text:min-label-distance are assumed to be 0.
                        setAlignmentMode(true);

                        QString textindent(p.attributeNS(KoXmlNS::fo, "text-indent"));
                        QString marginleft(p.attributeNS(KoXmlNS::fo, "margin-left"));
                        qreal ti = textindent.isEmpty() ? 0 : KoUnit::parseValue(textindent);
                        qreal ml = marginleft.isEmpty() ? 0 : KoUnit::parseValue(marginleft);
                        setTextIndent(ti);
                        setMargin(ml);

                        QString labelFollowedBy(p.attributeNS(KoXmlNS::text, "label-followed-by","space"));
                        if(labelFollowedBy.compare("listtab",Qt::CaseInsensitive)==0) {

                            setLabelFollowedBy(KoListStyle::ListTab);

                            // list tab position is evaluated only if label is followed by listtab
                            // the it is only evaluated if there is a list-tab-stop-position specified
                            // if not specified use the fo:margin-left:
                            QString tabStop(p.attributeNS(KoXmlNS::text, "list-tab-stop-position"));
                            if (!tabStop.isEmpty()) {
                                qreal tabStopPos = KoUnit::parseValue(tabStop);
                                setTabStopPosition(qMax<qreal>(0.0, tabStopPos));
                            }

                        }else if(labelFollowedBy.compare("nothing",Qt::CaseInsensitive)==0) {

                            setLabelFollowedBy(KoListStyle::Nothing);

                        }else {

                            setLabelFollowedBy(KoListStyle::Space);

                        }

                        setMinimumWidth(0);
                        setMinimumDistance(0);

                        //TODO support ODF 18.829 text:label-followed-by and 18.832 text:list-tab-stop-position
                     }
                }
            }

            if(alignmentMode()!=true ){ // default is mode == "label-width-and-position"
                // The text:space-before, text:min-label-width, text:minimum-label-distance and fo:text-align attributes
                // are used to define the position and spacing of the list label and the list item.

                setAlignmentMode(false);

                QString spaceBefore(property.attributeNS(KoXmlNS::text, "space-before"));
                if (!spaceBefore.isEmpty())
                    setIndent(KoUnit::parseValue(spaceBefore));

                QString minLableWidth(property.attributeNS(KoXmlNS::text, "min-label-width"));
                if (!minLableWidth.isEmpty())
                    setMinimumWidth(KoUnit::parseValue(minLableWidth));

                QString textAlign(property.attributeNS(KoXmlNS::fo, "text-align"));
                if (!textAlign.isEmpty())
                    setAlignment(KoText::alignmentFromString(textAlign));

                QString minLableDistance(property.attributeNS(KoXmlNS::text, "min-label-distance"));
                if (!minLableDistance.isEmpty())
                    setMinimumDistance(KoUnit::parseValue(minLableDistance));               
            }

            QString width(property.attributeNS(KoXmlNS::fo, "width"));
            if (!width.isEmpty())
                setWidth(KoUnit::parseValue(width));

            QString height(property.attributeNS(KoXmlNS::fo, "height"));
            if (!height.isEmpty())
                setHeight(KoUnit::parseValue(height));

        } else if (localName == "text-properties") {
Exemple #21
0
bool OpenDocument::traite_image(QTextCursor &curseur, QDomElement e, QString nom){
    ErrorManager instance_erreur;
    QString file = "";

    if(e.tagName() != "draw:image"){
        instance_erreur.Erreur_msg(tr("ODT : Mauvais paramètre envoyé : fonction de lecture d'image"), QMessageBox::Ignore);
        return false;
    }

    //On détecte si elle est en local ou en HTTP
    if(e.attribute("xlink:href").contains("http")){//Internet
        //On va piocher l'image sur Internet

        //On nettoye l'URL
        QString url_temp = e.attribute("xlink:href");
        if(url_temp.indexOf("?", 0) > 0){
            //Il y en a -> on vire tout ce qui est après
            int pos_depart = url_temp.indexOf("?", 0); int fin = url_temp.size();
            url_temp = url_temp.remove(pos_depart, fin);
        }
        QUrl url_image(url_temp);
        if(!url_image.isValid()){
            instance_erreur.Erreur_msg(tr("ODT : Erreur lors du téléchargement d'éléments distants"), QMessageBox::Ignore);
            return false;
        }

        QNetworkAccessManager nw_manager;
        QNetworkRequest request(url_image);
        QNetworkReply *reponse = nw_manager.get(request);
        QEventLoop eventLoop;
        QObject::connect(reponse, SIGNAL(finished()), &eventLoop, SLOT(quit()));
        eventLoop.exec();
        QImage image;
        image.loadFromData(reponse->readAll());
        QString ext = url_image.toString();
        ext = ext.remove(0, (ext.size()-4));
        qsrand(QDateTime::currentDateTime ().toTime_t ());
        file = QDir::tempPath()+QDir::separator()+QString::number(qrand())+".png";
        if(!image.isNull()){
            if(!image.save(file, "PNG")){
                //!sauvegarde
                instance_erreur.Erreur_msg(tr("ODT : Sauvegarde échouée de l'image téléchargée"), QMessageBox::Ignore);
                return false;
            }
        }
        else{
            //Image nulle
            instance_erreur.Erreur_msg(tr("ODT : Téléchargement échoué d'une image"), QMessageBox::Ignore);
            return false;
        }

        delete reponse;
    }
    else if(e.attribute("xlink:href").contains("Pictures")){//Local
        //On extrait le fichier
        QZipReader image(nom_odt, QIODevice::ReadOnly);
        Outils instance_outils;
        QString clean_fichier = e.attribute("xlink:href");
        clean_fichier = clean_fichier.split("/").last();
        image.extractOne(QDir::tempPath(), clean_fichier);
        image.close();

        //On sélectionne le fichier
        file = QDir::tempPath()+QDir::separator()+clean_fichier;

    }
    else{ //C'est pas normal ça : on se casse
        instance_erreur.Erreur_msg(tr("ODT : source d'image non trouvée"), QMessageBox::Ignore);
        return false;
    }


    //On affiche l'image
    QTextImageFormat format_image;
    format_image = cree_image_format(nom);
    format_image.setName(file);
    //On récupère d'éventuelles spécifications de taille
    QDomNode enfants = e.parentNode();
    e = enfants.toElement();
    //Width de l'image
    if(e.hasAttribute("svg:width")){
        QString width = e.attribute("svg:width");
        double value = width.left(width.length() - 2).toDouble();
        format_image.setWidth(value*28.3465058);
    }
    //Height de l'image
    if(e.hasAttribute("svg:height")){
        QString height = e.attribute("svg:height");
        double value = height.left(height.length() - 2).toDouble();
        format_image.setHeight(value*28.34650058);
    }

    QTextBlockFormat format_block_image;
    format_block_image = cree_bloc_format2(nom);
    curseur.insertBlock();
    curseur.movePosition(QTextCursor::PreviousBlock);
    curseur.setBlockFormat(format_block_image);
    curseur.insertImage(format_image);
    curseur.movePosition(QTextCursor::End);

    return true;
}
bool readPixmapNode( const QDomElement& element, QPixmap& pixmap )
{
    bool ok = true;
    ulong tempLength = 0;
    QString tempData;
    QDomNode node = element.firstChild();
    while( !node.isNull() ) {
        QDomElement element = node.toElement();
        if( !element.isNull() ) { // was really an element
            QString tagName = element.tagName();
            if( tagName == "Format" ) {
                QString formatName;
                ok = ok & readStringNode( element, formatName );
#ifndef NDEBUG
                if( formatName != "XPM.GZ" )
                    qDebug( "Unsupported pixmap format in XML file" );
#endif
            } else if( tagName == "Length" ) {
		int tempInt;
                ok = ok & readIntNode( element, tempInt );
	        tempLength = tempInt;
            } else if( tagName == "Data" ) {
                ok = ok & readStringNode( element, tempData );
            } else {
                qDebug( "Unknown tag in Pixmap" );
            }
        }
        node = node.nextSibling();
    }

    if( ok ) {
	if( 0 < tempLength ) {
            // Decode the image file format in the same way Qt Designer does.
            char *ba = new char[ tempData.length() / 2 ];
            for ( int i = 0; i < (int)tempData.length() / 2; ++i ) {
                char h = tempData[ 2 * i ].toLatin1();
                char l = tempData[ 2 * i  + 1 ].toLatin1();
                uchar r = 0;
                if ( h <= '9' )
                    r += h - '0';
                else
                    r += h - 'a' + 10;
                r = r << 4;
                if ( l <= '9' )
                    r += l - '0';
                else
                    r += l - 'a' + 10;
                ba[ i ] = r;
            }

            if( tempLength < tempData.length() * 5UL )
                tempLength = tempData.length() * 5;
            QByteArray baunzip( tempLength, '\0' );
            ::uncompress( (uchar*) baunzip.data(), &tempLength,
                          (uchar*) ba, tempData.length()/2 );
            QImage image;
            image.loadFromData( (const uchar*)baunzip.data(), tempLength, "XPM" );

            if( image.isNull() )
                pixmap = QPixmap( ); // This is _not_ an error, we just read a NULL pixmap!
            else {
                pixmap = QPixmap::fromImage( image );
		ok = ok & !pixmap.isNull();
	    }
        } else
            pixmap = QPixmap(); // This is _not_ an error, we just read a empty pixmap!
    }

    return ok;
}
QImage QImageHelper::createImageByByteArray(const QByteArray &bytes, ImageTypes::ImageTypesEnum imageType)
{
    QImage img;
    img.loadFromData(bytes);
    return img;
}
Exemple #24
0
int main( int argc, char **argv )
{
    if ( argc < 2 ) {
	qWarning( "Usage:\n\t%s [--images] files", argv[0] );
	return 1;
    }

    QFile output;
    bool  images = FALSE;
    output.open( IO_WriteOnly, stdout );
    QTextStream out( &output );

    EmbedImageList list_image;
    QList<Embed> list;
    list.setAutoDelete( TRUE );
    list_image.setAutoDelete( TRUE );

  // Embed data for all input files

    out << "/* Generated by qembed */\n";
    srand( time(0) );
    long l = rand();
    out << "#ifndef _" << l << endl;
    out << "#define _" << l << endl;

    for ( int i=1; i<argc; i++ ) {
	QString arg = argv[i];
	if ( arg == "--images" ) {
	    if ( !images ) {
		out << "#include <qimage.h>\n";
		out << "#include <stdlib.h>\n";
		images = TRUE;
	    }
	} else {
	    QFile f( argv[i] );
	    if ( !f.open(IO_ReadOnly) ) {
		qWarning( "Cannot open file %s, ignoring it", argv[i] );
		continue;
	    }
	    QByteArray a( f.size() );
	    if ( f.readBlock(a.data(), f.size()) != (int)f.size() ) {
		qWarning( "Cannot read file %s, ignoring it", argv[i] );
		f.close();
		continue;
	    }
	    if ( images ) {
		QImage img;
		if ( !img.loadFromData(a) ) {
		    qWarning( "Cannot read image from file %s, ignoring it", argv[i] );
		    f.close();
		    continue;
		}
		EmbedImage *e = new EmbedImage;
		e->width = img.width();
		e->height = img.height();
		e->depth = img.depth();
		e->numColors = img.numColors();
		e->colorTable = new QRgb[e->numColors];
		e->alpha = img.hasAlphaBuffer();
		memcpy(e->colorTable, img.colorTable(), e->numColors*sizeof(QRgb));
		QFileInfo fi(argv[i]);
		e->name = fi.baseName();
		e->cname = convertFileNameToCIdentifier( e->name.latin1() );
		list_image.append( e );
		QString s;
		if ( e->depth == 32 ) {
		    out << s.sprintf( "static const QRgb %s_data[] = {",
				   (const char *)e->cname );
		    embedData( (QRgb*)img.bits(), e->width*e->height, &output );
		} else {
		    if ( e->depth == 1 )
			img = img.convertBitOrder(QImage::BigEndian);
		    out << s.sprintf( "static const unsigned char %s_data[] = {",
				   (const char *)e->cname );
		    embedData( img.bits(), img.numBytes(), &output );
		}
		out << "\n};\n\n";
		if ( e->numColors ) {
		    out << s.sprintf( "static const QRgb %s_ctable[] = {",
				   (const char *)e->cname );
		    embedData( e->colorTable, e->numColors, &output );
		    out << "\n};\n\n";
		}
	    } else {
		Embed *e = new Embed;
		e->size = f.size();
		e->name = argv[i];
		e->cname = convertFileNameToCIdentifier( argv[i] );
		list.append( e );
		QString s;
		out << s.sprintf( "static const unsigned int  %s_len = %d;\n",
			       (const char *)e->cname, e->size );
		out << s.sprintf( "static const unsigned char %s_data[] = {",
			       (const char *)e->cname );
		embedData( a, &output );
		out << "\n};\n\n";
	    }

	    f.close();
	}
    }

  // Generate summery

    if ( list.count() > 0 ) {
	out << "#include <qcstring.h>\n";
	if ( !images )
	    out << "#include <qdict.h>\n";

	out << "static struct Embed {\n"
	       "    unsigned int         size;\n"
	       "    const unsigned char *data;\n"
	       "    const char          *name;\n"
	       "} embed_vec[] = {\n";
	Embed *e = list.first();
	while ( e ) {
	    out << "    { " << e->size << ", " << e->cname << "_data, "
		 << "\"" << e->name << "\" },\n";
	    e = list.next();
	}
	out << "    { 0, 0, 0 }\n};\n";

	out << "\n"
	    "inline const QByteArray& qembed_findData(const char* name)\n"
	    "{\n"
	    "    static QDict<QByteArray> dict;\n"
	    "    QByteArray* ba = dict.find(name);\n"
	    "    if ( !ba ) {\n"
	    "        for (int i=0; embed_vec[i].data; i++) {\n"
	    "    	if ( 0==strcmp(embed_vec[i].name, name) ) {\n"
	    "    	    ba = new QByteArray;\n"
	    "    	    ba->setRawData( (char*)embed_vec[i].data,\n"
	    "    			    embed_vec[i].size );\n"
	    "    	    break;\n"
	    "    	}\n"
	    "        }\n"
	    "        if ( !ba ) {\n"
	    "            static QByteArray dummy;\n"
	    "            return dummy;\n"
	    "        }\n"
	    "    }\n"
	    "    return *ba;\n"
	    "}\n\n";
    }

    if ( list_image.count() > 0 ) {
	out << "static struct EmbedImage {\n"
	       "    int width, height, depth;\n"
	       "    const unsigned char *data;\n"
	       "    int numColors;\n"
	       "    const QRgb *colorTable;\n"
	       "    bool alpha;\n"
	       "    const char *name;\n"
	       "} embed_image_vec[] = {\n";
	list_image.sort();
	EmbedImage *e = list_image.first();
	while ( e ) {
	    out << "    { "
		<< e->width << ", "
		<< e->height << ", "
		<< e->depth << ", "
		<< "(const unsigned char*)" << e->cname << "_data, "
		<< e->numColors << ", ";
	    if ( e->numColors )
		out << e->cname << "_ctable, ";
	    else
		out << "0, ";
	    if ( e->alpha )
		out << "TRUE, ";
	    else
		out << "FALSE, ";
	    out << "\"" << e->name << "\" },\n";
	    e = list_image.next();
	}
	out << "};\n";

	out << "\n"
	    "static int cmpEmbedImage(const void *a, const void *b)\n"
	    "{\n"
	    "    const EmbedImage* ea = (const EmbedImage*)a;\n"
	    "    const EmbedImage* eb = (const EmbedImage*)b;\n"
	    "    return strcmp(ea->name,eb->name);\n"
	    "}\n"
	    "inline const QImage& qembed_findImage(const char* name)\n"
	    "{\n"
	    "    EmbedImage key; key.name = name;\n"
	    "    EmbedImage* r = (EmbedImage*)bsearch( &key, embed_image_vec,\n"
	    "        sizeof(embed_image_vec)/sizeof(EmbedImage), sizeof(EmbedImage), cmpEmbedImage );\n"
	    "    QImage* img;\n"
	    "    if ( r ) {\n"
	    "        img = new QImage((uchar*)r->data,\n"
	    "                            r->width,\n"
	    "                            r->height,\n"
	    "                            r->depth,\n"
	    "                            (QRgb*)r->colorTable,\n"
	    "                            r->numColors,\n"
	    "                            QImage::BigEndian\n"
	    "                    );\n"
	    "        if ( r->alpha )\n"
	    "            img->setAlphaBuffer(TRUE);\n"
	    "    } else {\n"
	    "        static QImage dummy;\n"
	    "        img = &dummy;\n"
	    "    }\n"
	    "    return *img;\n"
	    "}\n\n";
    }

    out << "#endif" << endl;

    return 0;
}
Exemple #25
0
void* Bridge::processMessage(GUIMSG type, void* param1, void* param2)
{
    if(dbgStopped) //there can be no more messages if the debugger stopped = BUG
        __debugbreak();
    switch(type)
    {
    case GUI_DISASSEMBLE_AT:
        emit disassembleAt((int_t)param1, (int_t)param2);
        break;

    case GUI_SET_DEBUG_STATE:
        emit dbgStateChanged((DBGSTATE)(int_t)param1);
        break;

    case GUI_ADD_MSG_TO_LOG:
        emit addMsgToLog(QString((const char*)param1));
        break;

    case GUI_CLEAR_LOG:
        emit clearLog();
        break;

    case GUI_UPDATE_REGISTER_VIEW:
        emit updateRegisters();
        break;

    case GUI_UPDATE_DISASSEMBLY_VIEW:
        emit repaintGui();
        break;

    case GUI_UPDATE_BREAKPOINTS_VIEW:
        emit updateBreakpoints();
        break;

    case GUI_UPDATE_WINDOW_TITLE:
        emit updateWindowTitle(QString((const char*)param1));
        break;

    case GUI_GET_WINDOW_HANDLE:
        return winId;

    case GUI_DUMP_AT:
        emit dumpAt((int_t)param1);
        break;

    case GUI_SCRIPT_ADD:
    {
        BridgeResult result;
        emit scriptAdd((int)param1, (const char**)param2);
        result.Wait();
    }
    break;

    case GUI_SCRIPT_CLEAR:
        emit scriptClear();
        break;

    case GUI_SCRIPT_SETIP:
        emit scriptSetIp((int)param1);
        break;

    case GUI_SCRIPT_ERROR:
    {
        BridgeResult result;
        emit scriptError((int)param1, QString((const char*)param2));
        result.Wait();
    }
    break;

    case GUI_SCRIPT_SETTITLE:
        emit scriptSetTitle(QString((const char*)param1));
        break;

    case GUI_SCRIPT_SETINFOLINE:
        emit scriptSetInfoLine((int)param1, QString((const char*)param2));
        break;

    case GUI_SCRIPT_MESSAGE:
    {
        BridgeResult result;
        emit scriptMessage(QString((const char*)param1));
        result.Wait();
    }
    break;

    case GUI_SCRIPT_MSGYN:
    {
        BridgeResult result;
        emit scriptQuestion(QString((const char*)param1));
        return (void*)result.Wait();
    }
    break;

    case GUI_SCRIPT_ENABLEHIGHLIGHTING:
        emit scriptEnableHighlighting((bool)param1);
        break;

    case GUI_SYMBOL_UPDATE_MODULE_LIST:
        emit updateSymbolList((int)param1, (SYMBOLMODULEINFO*)param2);
        break;

    case GUI_SYMBOL_LOG_ADD:
        emit addMsgToSymbolLog(QString((const char*)param1));
        break;

    case GUI_SYMBOL_LOG_CLEAR:
        emit clearSymbolLog();
        break;

    case GUI_SYMBOL_SET_PROGRESS:
        emit setSymbolProgress((int)param1);
        break;

    case GUI_REF_ADDCOLUMN:
        emit referenceAddColumnAt((int)param1, QString((const char*)param2));
        break;

    case GUI_REF_SETROWCOUNT:
        emit referenceSetRowCount((int_t)param1);
        break;

    case GUI_REF_GETROWCOUNT:
        return (void*)referenceManager->currentReferenceView()->mList->getRowCount();

    case GUI_REF_DELETEALLCOLUMNS:
        GuiReferenceInitialize("References");
        break;

    case GUI_REF_SETCELLCONTENT:
    {
        CELLINFO* info = (CELLINFO*)param1;
        emit referenceSetCellContent(info->row, info->col, QString(info->str));
    }
    break;

    case GUI_REF_GETCELLCONTENT:
        return (void*)referenceManager->currentReferenceView()->mList->getCellContent((int)param1, (int)param2).toUtf8().constData();

    case GUI_REF_RELOADDATA:
        emit referenceReloadData();
        break;

    case GUI_REF_SETSINGLESELECTION:
        emit referenceSetSingleSelection((int)param1, (bool)param2);
        break;

    case GUI_REF_SETPROGRESS:
        emit referenceSetProgress((int)param1);
        break;

    case GUI_REF_SETSEARCHSTARTCOL:
        emit referenceSetSearchStartCol((int)param1);
        break;

    case GUI_REF_INITIALIZE:
    {
        BridgeResult result;
        emit referenceInitialize(QString((const char*)param1));
        result.Wait();
    }
    break;

    case GUI_STACK_DUMP_AT:
        emit stackDumpAt((uint_t)param1, (uint_t)param2);
        break;

    case GUI_UPDATE_DUMP_VIEW:
        emit updateDump();
        break;

    case GUI_UPDATE_THREAD_VIEW:
        emit updateThreads();
        break;

    case GUI_UPDATE_MEMORY_VIEW:
        emit updateMemory();
        break;

    case GUI_ADD_RECENT_FILE:
        emit addRecentFile(QString((const char*)param1));
        break;

    case GUI_SET_LAST_EXCEPTION:
        emit setLastException((unsigned int)param1);
        break;

    case GUI_GET_DISASSEMBLY:
    {
        uint_t parVA = (uint_t)param1;
        char* text = (char*)param2;
        if(!text || !parVA || !DbgIsDebugging())
            return 0;
        byte_t wBuffer[16];
        if(!DbgMemRead(parVA, wBuffer, 16))
            return 0;
        QBeaEngine disasm(-1);
        Instruction_t instr = disasm.DisassembleAt(wBuffer, 16, 0, 0, parVA);
        QList<RichTextPainter::CustomRichText_t> richText;
        CapstoneTokenizer::TokenToRichText(instr.tokens, richText, 0);
        QString finalInstruction = "";
        for(int i = 0; i < richText.size(); i++)
            finalInstruction += richText.at(i).text;
        strcpy_s(text, GUI_MAX_DISASSEMBLY_SIZE, finalInstruction.toUtf8().constData());
        return (void*)1;
    }
    break;

    case GUI_MENU_ADD:
    {
        BridgeResult result;
        emit menuAddMenu((int)param1, QString((const char*)param2));
        return (void*)result.Wait();
    }
    break;

    case GUI_MENU_ADD_ENTRY:
    {
        BridgeResult result;
        emit menuAddMenuEntry((int)param1, QString((const char*)param2));
        return (void*)result.Wait();
    }
    break;

    case GUI_MENU_ADD_SEPARATOR:
    {
        BridgeResult result;
        emit menuAddSeparator((int)param1);
        result.Wait();
    }
    break;

    case GUI_MENU_CLEAR:
    {
        BridgeResult result;
        emit menuClearMenu((int)param1);
        result.Wait();
    }
    break;

    case GUI_SELECTION_GET:
    {
        int hWindow = (int)param1;
        SELECTIONDATA* selection = (SELECTIONDATA*)param2;
        if(!DbgIsDebugging())
            return (void*)false;
        BridgeResult result;
        switch(hWindow)
        {
        case GUI_DISASSEMBLY:
            emit selectionDisasmGet(selection);
            break;
        case GUI_DUMP:
            emit selectionDumpGet(selection);
            break;
        case GUI_STACK:
            emit selectionStackGet(selection);
            break;
        default:
            return (void*)false;
        }
        result.Wait();
        if(selection->start > selection->end) //swap start and end
        {
            int_t temp = selection->end;
            selection->end = selection->start;
            selection->start = temp;
        }
        return (void*)true;
    }
    break;

    case GUI_SELECTION_SET:
    {
        int hWindow = (int)param1;
        const SELECTIONDATA* selection = (const SELECTIONDATA*)param2;
        if(!DbgIsDebugging())
            return (void*)false;
        BridgeResult result;
        switch(hWindow)
        {
        case GUI_DISASSEMBLY:
            emit selectionDisasmSet(selection);
            break;
        case GUI_DUMP:
            emit selectionDumpSet(selection);
            break;
        case GUI_STACK:
            emit selectionStackSet(selection);
            break;
        default:
            return (void*)false;
        }
        return (void*)result.Wait();
    }
    break;

    case GUI_GETLINE_WINDOW:
    {
        QString text = "";
        BridgeResult result;
        emit getStrWindow(QString((const char*)param1), &text);
        if(result.Wait())
        {
            strcpy_s((char*)param2, GUI_MAX_LINE_SIZE, text.toUtf8().constData());
            return (void*)true;
        }
        return (void*)false; //cancel/escape
    }
    break;

    case GUI_AUTOCOMPLETE_ADDCMD:
        emit autoCompleteAddCmd(QString((const char*)param1));
        break;

    case GUI_AUTOCOMPLETE_DELCMD:
        emit autoCompleteDelCmd(QString((const char*)param1));
        break;

    case GUI_AUTOCOMPLETE_CLEARALL:
        emit autoCompleteClearAll();
        break;

    case GUI_ADD_MSG_TO_STATUSBAR:
        emit addMsgToStatusBar(QString((const char*)param1));
        break;

    case GUI_UPDATE_SIDEBAR:
        emit updateSideBar();
        break;

    case GUI_REPAINT_TABLE_VIEW:
        emit repaintTableView();
        break;

    case GUI_UPDATE_PATCHES:
        emit updatePatches();
        break;

    case GUI_UPDATE_CALLSTACK:
        emit updateCallStack();
        break;

    case GUI_SYMBOL_REFRESH_CURRENT:
        emit symbolRefreshCurrent();
        break;

    case GUI_LOAD_SOURCE_FILE:
        emitLoadSourceFile(QString((const char*)param1), (int)param2);
        break;

    case GUI_MENU_SET_ICON:
    {
        int hMenu = (int)param1;
        const ICONDATA* icon = (const ICONDATA*)param2;
        BridgeResult result;
        if(!icon)
            emit setIconMenu(hMenu, QIcon());
        else
        {
            QImage img;
            img.loadFromData((uchar*)icon->data, icon->size);
            QIcon qIcon(QPixmap::fromImage(img));
            emit setIconMenu(hMenu, qIcon);
        }
        result.Wait();
    }
    break;

    case GUI_MENU_SET_ENTRY_ICON:
    {
        int hEntry = (int)param1;
        const ICONDATA* icon = (const ICONDATA*)param2;
        BridgeResult result;
        if(!icon)
            emit setIconMenuEntry(hEntry, QIcon());
        else
        {
            QImage img;
            img.loadFromData((uchar*)icon->data, icon->size);
            QIcon qIcon(QPixmap::fromImage(img));
            emit setIconMenuEntry(hEntry, qIcon);
        }
        result.Wait();
    }
    break;

    case GUI_SHOW_CPU:
        emit showCpu();
        break;

    case GUI_ADD_QWIDGET_TAB:
        emit addQWidgetTab((QWidget*)param1);
        break;

    case GUI_SHOW_QWIDGET_TAB:
        emit showQWidgetTab((QWidget*)param1);
        break;

    case GUI_CLOSE_QWIDGET_TAB:
        emit closeQWidgetTab((QWidget*)param1);
        break;

    case GUI_EXECUTE_ON_GUI_THREAD:
        GuiAddLogMessage(QString().sprintf("thread id (bridge) %X\n", GetCurrentThreadId()).toUtf8().constData());
        emit executeOnGuiThread(param1);
        break;

    case GUI_UPDATE_TIME_WASTED_COUNTER:
        emit updateTimeWastedCounter();
        break;

    case GUI_SET_GLOBAL_NOTES:
    {
        QString text = QString((const char*)param1);
        emit setGlobalNotes(text);
    }
    break;

    case GUI_GET_GLOBAL_NOTES:
    {
        BridgeResult result;
        emit getGlobalNotes(param1);
        result.Wait();
    }
    break;

    case GUI_SET_DEBUGGEE_NOTES:
    {
        QString text = QString((const char*)param1);
        emit setDebuggeeNotes(text);
    }
    break;

    case GUI_GET_DEBUGGEE_NOTES:
    {
        BridgeResult result;
        emit getDebuggeeNotes(param1);
        result.Wait();
    }
    break;
    }
    return nullptr;
}
void KoListLevelProperties::loadOdf(KoShapeLoadingContext& scontext, const KoXmlElement& style)
{
    KoOdfLoadingContext &context = scontext.odfLoadingContext();

    // The text:level attribute specifies the level of the number list
    // style. It can be used on all list-level styles.
    const int level = qMax(1, style.attributeNS(KoXmlNS::text, "level", QString()).toInt());
    // The text:display-levels attribute specifies the number of
    // levels whose numbers are displayed at the current level.
    const QString displayLevel = style.attributeNS(KoXmlNS::text,
                                 "display-levels", QString());

    if (style.localName() == "list-level-style-bullet") {   // list with bullets

        //1.6: KoParagCounter::loadOasisListStyle
        QString bulletChar = style.isNull() ? QString() : style.attributeNS(KoXmlNS::text, "bullet-char", QString());
        kDebug(32500) << "style.localName()=" << style.localName() << "level=" << level << "displayLevel=" << displayLevel << "bulletChar=" << bulletChar;
        if (bulletChar.isEmpty()) {  // list without any visible bullets
            setStyle(KoListStyle::CustomCharItem);
            setBulletCharacter(QChar());
        } else { // try to determinate the bullet we should use
            switch (bulletChar[0].unicode()) {
            case 0x2022: // bullet, a small disc -> circle
                //TODO use BulletSize to differ between small and large discs
                setStyle(KoListStyle::DiscItem);
                break;
            case 0x25CF: // black circle, large disc -> disc
            case 0xF0B7: // #113361
                setStyle(KoListStyle::DiscItem);
                break;
            case 0xE00C: // losange => rhombus
                setStyle(KoListStyle::RhombusItem);
                break;
            case 0xE00A: // square. Not in OASIS (reserved Unicode area!), but used in both OOo and kotext.
                setStyle(KoListStyle::SquareItem);
                break;
            case 0x27A2: // two-colors right-pointing triangle
                setStyle(KoListStyle::RightArrowHeadItem);
                break;
            case 0x2794: // arrow to right
                setStyle(KoListStyle::RightArrowItem);
                break;
            case 0x2714: // checkmark
                setStyle(KoListStyle::HeavyCheckMarkItem);
                break;
            case 0x2d: // minus
                setStyle(KoListStyle::CustomCharItem);
                break;
            case 0x2717: // cross
                setStyle(KoListStyle::BallotXItem);
                break;
            default:
                QChar customBulletChar = bulletChar[0];
                kDebug(32500) << "Unhandled bullet code 0x" << QString::number((uint)customBulletChar.unicode(), 16);
                kDebug(32500) << "Should use the style =>" << style.attributeNS(KoXmlNS::text, "style-name", QString()) << "<=";
                setStyle(KoListStyle::CustomCharItem);
                /*
                QString customBulletFont;
                // often StarSymbol when it comes from OO; doesn't matter, Qt finds it in another font if needed.
                if ( listStyleProperties.hasAttributeNS( KoXmlNS::style, "font-name" ) )
                {
                    customBulletFont = listStyleProperties.attributeNS( KoXmlNS::style, "font-name", QString::null );
                    kDebug(32500) <<"customBulletFont style:font-name =" << listStyleProperties.attributeNS( KoXmlNS::style,"font-name", QString::null );
                }
                else if ( listStyleTextProperties.hasAttributeNS( KoXmlNS::fo, "font-family" ) )
                {
                    customBulletFont = listStyleTextProperties.attributeNS( KoXmlNS::fo, "font-family", QString::null );
                    kDebug(32500) <<"customBulletFont fo:font-family =" << listStyleTextProperties.attributeNS( KoXmlNS::fo,"font-family", QString::null );
                }
                // ## TODO in fact we're supposed to read it from the style pointed to by text:style-name
                */
//                     setStyle(KoListStyle::BoxItem); //fallback
                break;
            } // switch
            setBulletCharacter(bulletChar[0]);
        }

    } else if (style.localName() == "list-level-style-number" || style.localName() == "outline-level-style") { // it's a numbered list

        KoOdfNumberDefinition numberDefinition;
        numberDefinition.loadOdf(style);

        switch(numberDefinition.formatSpecification()) {
        case KoOdfNumberDefinition::Empty:
            setStyle(KoListStyle::CustomCharItem);
            setBulletCharacter(QChar());
            break;
        case KoOdfNumberDefinition::AlphabeticLowerCase:
            setStyle(KoListStyle::AlphaLowerItem);
            break;
        case KoOdfNumberDefinition::AlphabeticUpperCase:
            setStyle(KoListStyle::UpperAlphaItem);
            break;
        case KoOdfNumberDefinition::RomanLowerCase:
            setStyle(KoListStyle::RomanLowerItem);
            break;
        case KoOdfNumberDefinition::RomanUpperCase:
            setStyle(KoListStyle::UpperRomanItem);
            break;
        case KoOdfNumberDefinition::Numeric:
        default:
            setStyle(KoListStyle::DecimalItem);
        }

        if (!numberDefinition.prefix().isNull()) {
            setListItemPrefix(numberDefinition.prefix());
        }

        if (!numberDefinition.suffix().isNull()) {
            setListItemSuffix(numberDefinition.suffix());
        }
        const QString startValue = style.attributeNS(KoXmlNS::text, "start-value", QString("1"));
        setStartValue(startValue.toInt());
    }
    else if (style.localName() == "list-level-style-image") {   // list with image
        setStyle(KoListStyle::ImageItem);
        KoImageCollection *imageCollection = scontext.imageCollection();
        const QString href = style.attribute("href");
        if(imageCollection) {
            if (!href.isEmpty()) {
                KoStore *store = context.store();
                setBulletImage(imageCollection->createImageData(href, store));
            } else {
                // check if we have an office:binary data element containing the image data
                const KoXmlElement &binaryData(KoXml::namedItemNS(style, KoXmlNS::office, "binary-data"));
                if (!binaryData.isNull()) {
                    QImage image;
                    if (image.loadFromData(QByteArray::fromBase64(binaryData.text().toLatin1()))) {
                        setBulletImage(imageCollection->createImageData(image));
                    }
                }
            }
        }
    }
    else { // if not defined, we have do nothing
        kDebug(32500) << "stylename else:" << style.localName() << "level=" << level << "displayLevel=" << displayLevel;
        setStyle(KoListStyle::DecimalItem);
        setListItemSuffix(".");
    }

    setLevel(level);
    if (!displayLevel.isEmpty())
        setDisplayLevel(displayLevel.toInt());

    KoXmlElement property;
    forEachElement(property, style) {
        if (property.namespaceURI() != KoXmlNS::style)
            continue;
        const QString localName = property.localName();
        if (localName == "list-level-properties") {
            QString mode(property.attributeNS(KoXmlNS::text, "list-level-position-and-space-mode"));
            if (mode == "label-alignment") {
                KoXmlElement p;
                forEachElement(p, property) {
                     if (p.namespaceURI() == KoXmlNS::style && p.localName() == "list-level-label-alignment") {
                        // The <style:list-level-label-alignment> element and the fo:text-align attribute are used to define
                        // the position and spacing of the list label and the list item. The values of the attributes for
                        // text:space-before, text:min-label-width and text:min-label-distance are assumed to be 0.

                        QString textAlign(p.attributeNS(KoXmlNS::fo, "text-align"));
                        setAlignment(textAlign.isEmpty() ? Qt::AlignLeft : KoText::alignmentFromString(textAlign));

                        QString textindent(p.attributeNS(KoXmlNS::fo, "text-indent"));
                        QString marginleft(p.attributeNS(KoXmlNS::fo, "margin-left"));
                        qreal ti = textindent.isEmpty() ? 0 : KoUnit::parseValue(textindent);
                        qreal ml = marginleft.isEmpty() ? 0 : KoUnit::parseValue(marginleft);
                        setIndent(qMax(0.0, ti + ml));
                
                        setMinimumWidth(0);
                        setMinimumDistance(0);
                        
                        //TODO support ODF 18.829 text:label-followed-by and 18.832 text:list-tab-stop-position
                     }   
                }
            } else { // default is mode == "label-width-and-position"
Exemple #27
0
int LoadImage::writeToDB(const QByteArray &pdata, const QString pkgname, QString &errMsg)
{
  if (pdata.isEmpty())
  {
    errMsg = TR("<font color=orange>The image %1 is empty.</font>")
                         .arg(_name);
    return -2;
  }

  QByteArray encodeddata;
  if (DEBUG)
    qDebug("LoadImage::writeToDB(): image starts with %s",
           pdata.left(10).data());
  if (QString(pdata.left(pdata.indexOf("\n"))).contains(QRegExp("^\\s*begin \\d+ \\S+")))
  {
    if (DEBUG) qDebug("LoadImage::writeToDB() image is already uuencoded");
    encodeddata = pdata;
  }
  else
  {
    // there's just GOT to be a better way to do this
    QImageWriter imageIo;
    QBuffer      imageBuffer;

    imageBuffer.open(QIODevice::ReadWrite);
    imageIo.setDevice(&imageBuffer);
    imageIo.setFormat(_filename.right(_filename.size() -
                                      _filename.lastIndexOf(".") - 1).toAscii());
    if (DEBUG)
      qDebug("LoadImage::writeToDB() image has format %s",
             imageIo.format().data());
    QImage image;
    image.loadFromData(pdata);
    if (!imageIo.write(image))
    {
      errMsg = TR("<font color=orange>Error processing image %1: "
                           "<br>%2</font>")
                .arg(_name).arg(imageIo.errorString());
      return -3;
    }

    imageBuffer.close();
    encodeddata = QUUEncode(imageBuffer).toAscii();
    if (DEBUG) qDebug("LoadImage::writeToDB() image was uuencoded: %s",
                      encodeddata.left(160).data());
  }

  _selectMql = new MetaSQLQuery("SELECT image_id, -1, -1"
                      "  FROM <? literal(\"tablename\") ?> "
                      " WHERE (image_name=<? value(\"name\") ?>);");

  _updateMql = new MetaSQLQuery("UPDATE <? literal(\"tablename\") ?> "
                      "   SET image_data=<? value(\"source\") ?>,"
                      "       image_descrip=<? value(\"notes\") ?> "
                      " WHERE (image_id=<? value(\"id\") ?>) "
                      "RETURNING image_id AS id;");

  _insertMql = new MetaSQLQuery("INSERT INTO <? literal(\"tablename\") ?> ("
                      "   image_id, image_name, image_data, image_descrip"
                      ") VALUES ("
                      "  DEFAULT, <? value(\"name\") ?>,"
                      "  <? value(\"source\") ?>, <? value(\"notes\") ?>) "
                      "RETURNING image_id AS id;");

  ParameterList params;
  params.append("tablename", "image");

  return Loadable::writeToDB(encodeddata, pkgname, errMsg, params);
}
bool fb2Creator::create(const QString& path, int width, int height, QImage& img)
{
    QFile file(path);
    
    KZip zip(path);
    QIODevice *device;
    const KArchiveDirectory *dir;
    const KZipFileEntry *fb2File;
    
    QXmlStreamReader qxml;
    
    QString fileExt = QFileInfo(path).suffix().toLower();
    if (fileExt == "fb2")
    {
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            qDebug() << "[fb2 thumbnailer]" << "Couldn't open" << path;
            return false;
        }
        else
        {
            qDebug() << "[fb2 thumbnailer]" << "Reading" << path;
            qxml.setDevice(&file);
        }
    }
    else //if *.fb2.zip
    {
        if (!zip.open(QIODevice::ReadOnly))
        {
            qDebug() << "[fb2 thumbnailer]" << "Couldn't open" << path;
            return false;
        }
        else
        {
            qDebug() << "[fb2 thumbnailer]" << "Reading" << path;

            dir = zip.directory();

            QStringList fileList = dir->entries();

            for (int i=0; i < fileList.count(); i++)
            {
                if (fileList.at(i).endsWith(".fb2"))
                {
                    fb2File = static_cast<const KZipFileEntry*>(dir->entry(fileList.at(i)));
                    device = fb2File->createDevice();
                    qxml.setDevice(device);

                    break;
                }
            }
        }
    }
    
    //----

    bool inCoverpage = false;
    QString coverId = "";
    QByteArray coverBase64;
    
    while(!qxml.atEnd() && !qxml.hasError())
    {
        qxml.readNext();

        if (qxml.name() == "coverpage")
        {
            if (qxml.isStartElement())
                inCoverpage = true;
            else
                inCoverpage = false;
        }

        if (qxml.name() == "image" && qxml.isStartElement() && inCoverpage == true)
        {
            //various namespaces: xlink, l, NS2
            QXmlStreamAttributes qxmlAttributes = qxml.attributes();

            for (int pos = 0; pos < qxmlAttributes.size(); pos++)
            {
                if (qxmlAttributes.at(pos).name() == "href")
                {
                    coverId = qxmlAttributes.at(pos).value().toString();
                    break;
                }
            }

            if (coverId != "")
            {
                coverId.remove("#");
                qDebug() << "[fb2 thumbnailer]" << "Found cover id:" << coverId;
            }
        }

        if (qxml.name() == "binary" && qxml.isStartElement())
        {
            if (coverId != "")
            {
                if (qxml.attributes().value("id") == coverId)
                {
                    qDebug() << "[fb2 thumbnailer]" << "Found cover data";

                    coverBase64 = qxml.readElementText().toAscii();

                    QImage coverImage;
                    coverImage.loadFromData(QByteArray::fromBase64(coverBase64));
                    
                    img = coverImage.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);

                    break;
                }
            }
            else //if coverId not found then the file doesn't follow the specification, try a workaround
            {
                qDebug() << "[fb2 thumbnailer]" << "Cover id not found";
                qDebug() << "[fb2 thumbnailer]" << "Using first image as cover";

                coverBase64 = qxml.readElementText().toAscii();

                QImage coverImage;
                coverImage.loadFromData(QByteArray::fromBase64(coverBase64));

                img = coverImage.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);

                break;
            }
        }
    }

    if (coverBase64.isEmpty())
        qDebug() << "[fb2 thumbnailer]" << "Cover data not found";

    if (qxml.hasError())
        qDebug() << "[fb2 thumbnailer]" << "Parsing error:" << qxml.errorString();

    qxml.clear();

    if (fileExt == "fb2")
        file.close();
    else
    {
        device->close();
        delete device;
        //delete fb2File;
        //delete dir;
    }

    return !img.isNull();
}
// Loads data from a cell into the Edit Cell window
void EditDialog::loadData(const QByteArray& data)
{
    QImage img;
    QString textData;

    // Clear previously removed BOM
    removedBom.clear();

    // Determine the data type, saving that info in the class variable
    dataType = checkDataType(data);

    // Get the current editor mode (eg text, hex, image, json or xml mode)
    int editMode = ui->comboMode->currentIndex();

    // Data type specific handling
    switch (dataType) {
    case Null:
        // Set enabled any of the text widgets
        ui->editorText->setEnabled(true);
        sciEdit->setEnabled(true);
        switch (editMode) {
        case TextEditor:
            // The text widget buffer is now the main data source
            dataSource = TextBuffer;

            // Empty the text editor contents, then enable text editing
            ui->editorText->clear();

            break;

        case JsonEditor:
        case XmlEditor:

            // The JSON widget buffer is now the main data source
            dataSource = SciBuffer;

            // Empty the text editor contents, then enable text editing
            sciEdit->clear();

            break;

        case HexEditor:
            // The hex widget buffer is now the main data source
            dataSource = HexBuffer;

            // Load the Null into the hex editor
            hexEdit->setData(data);

            break;

        case ImageViewer:
            // The hex widget buffer is now the main data source
            dataSource = HexBuffer;

            // Clear any image from the image viewing widget
            ui->editorImage->setPixmap(QPixmap(0,0));

            // Load the Null into the hex editor
            hexEdit->setData(data);

            break;
        }
        break;

    case Text:
    case JSON:
        // Can be stored in any widget, except the ImageViewer

        switch (editMode) {
        case TextEditor:
            setDataInBuffer(data, TextBuffer);
            break;
        case JsonEditor:
        case XmlEditor:
            setDataInBuffer(data, SciBuffer);
            break;
        case HexEditor:
            setDataInBuffer(data, HexBuffer);
            break;
        case ImageViewer:
            // The image viewer cannot hold data nor display text.

            // Clear any image from the image viewing widget
            ui->editorImage->setPixmap(QPixmap(0,0));

            // Load the text into the text editor
            setDataInBuffer(data, TextBuffer);

            break;
        }
        break;

    case Image:
        // Image data is kept in the hex widget, mainly for safety.  If we
        // stored it in the editorImage widget instead, it would be a pixmap
        // and there's no good way to restore that back to the original
        // (pristine) image data.  eg image metadata would be lost
        setDataInBuffer(data, HexBuffer);

        // Update the display if in text edit or image viewer mode
        switch (editMode) {
        case TextEditor:
            // Disable text editing, and use a warning message as the contents
            ui->editorText->setText(QString("<i>" %
                    tr("Image data can't be viewed in this mode.") % "<br/>" %
                    tr("Try switching to Image or Binary mode.") %
                    "</i>"));
            ui->editorText->setEnabled(false);
            break;

        case XmlEditor:
        case JsonEditor:
            // Disable text editing, and use a warning message as the contents
            sciEdit->setText(tr("Image data can't be viewed in this mode.") % '\n' %
                             tr("Try switching to Image or Binary mode."));
            sciEdit->setEnabled(false);

            break;

        case ImageViewer:
            // Load the image into the image viewing widget
            if (img.loadFromData(data)) {
                ui->editorImage->setPixmap(QPixmap::fromImage(img));
            }
            break;
        }
        break;
    case SVG:
        // Set the XML data in any buffer or update image in image viewer mode
        switch (editMode) {
        case TextEditor:
            setDataInBuffer(data, TextBuffer);
            break;

        case JsonEditor:
        case XmlEditor:

            setDataInBuffer(data, SciBuffer);
            break;

        case HexEditor:

            setDataInBuffer(data, HexBuffer);
            break;

        case ImageViewer:
            // Set data in the XML (Sci) Buffer and load the SVG Image
            setDataInBuffer(data, SciBuffer);
            sciEdit->setLanguage(DockTextEdit::XML);

            // Load the image into the image viewing widget
            if (img.loadFromData(data)) {
                ui->editorImage->setPixmap(QPixmap::fromImage(img));
            }
            break;
        }
        break;

    default:

        // The data seems to be general binary data, which is always loaded
        // into the hex widget (the only safe place for it)

        // Load the data into the hex buffer
        setDataInBuffer(data, HexBuffer);

        switch (editMode) {
        case TextEditor:
            // Disable text editing, and use a warning message as the contents
            ui->editorText->setText(QString("<i>" %
                    tr("Binary data can't be viewed in this mode.") % "<br/>" %
                    tr("Try switching to Binary mode.") %
                    "</i>"));
            ui->editorText->setEnabled(false);
            break;

         case JsonEditor:
         case XmlEditor:
            // Disable text editing, and use a warning message as the contents
             sciEdit->setText(QString(tr("Binary data can't be viewed in this mode.") % '\n' %
                                      tr("Try switching to Binary mode.")));
             sciEdit->setEnabled(false);
            break;

        case ImageViewer:
            // Clear any image from the image viewing widget
            ui->editorImage->setPixmap(QPixmap(0,0));
            break;
        }
    }
}
QImage ImageProviderThumbnail::getThumbnailImage(QByteArray filename) {

    QString typeCache = (settings->thumbnailCacheFile ? "files" : "db");
    bool cacheEnabled = settings->thumbnailCache;

    if(settings->thumbnailCache && !settings->thumbnailCacheFile)
        setupDbWhenNotYetDone();

    // Create the md5 hash for the thumbnail file
    QByteArray path = "file://" + filename;
    QByteArray md5 = QCryptographicHash::hash(path,QCryptographicHash::Md5).toHex();

    // Prepare the return QImage
    QImage p;

    // We always opt for the 256px resolution for the thumbnails,
    // as then we don't have to re-create thumbnails depending on change in settings
    int ts = 256;

    // If files in XDG_CACHE_HOME/thumbnails/ shall be used, then do use them
    if(typeCache == "files" && cacheEnabled) {

        // If there exists a thumbnail of the current file already
        if(QFile(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails/large/" + md5 + ".png").exists()) {

            if(qgetenv("PHOTOQT_DEBUG") == "yes")
                LOG << CURDATE << "ImageProviderThumbnail: Found cached thumbnail (file cache): " <<
                       QFileInfo(filename).fileName().toStdString() << NL;

            p.load(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails/large/" + md5 + ".png");
            uint mtime = p.text("Thumb::MTime").trimmed().toInt();

            // Use image if it's up-to-date
            if(QFileInfo(filename).lastModified().toTime_t() == mtime)
                return p;
            else if(qgetenv("PHOTOQT_DEBUG") == "yes")
                LOG << CURDATE << "ImageProviderThumbnail: Image was modified since thumbnail creation, not using cached thumbnail: " <<
                       QFileInfo(filename).fileName().toStdString() << NL;

        }

    // otherwise use the database
    } else if(cacheEnabled) {

        needToReCreatedDbThumbnail = false;

        // Query database
        QSqlQuery query(db);
        query.prepare("SELECT thumbnail,filelastmod FROM Thumbnails WHERE filepath=:fpath");
        query.bindValue(":fpath",filename);
        query.exec();

        // Check for found value
        if(query.next()) {

            if(qgetenv("PHOTOQT_DEBUG") == "yes")
                LOG << CURDATE << "ImageProviderThumbnail: Found cached thumbnail (db cache): " << QFileInfo(filename).fileName().toStdString() << NL;

            // Check if updated
            if(query.value(query.record().indexOf("filelastmod")).toUInt() == QFileInfo(filename).lastModified().toTime_t()) {

                // If current thumbnail -> load it
                QByteArray b;
                b = query.value(query.record().indexOf("thumbnail")).toByteArray();
                p.loadFromData(b);

                // Cleaning up
                query.clear();

                // Return image
                return p;

            // The original image has been changed -> need to recreate thumbnail image
            } else {
                if(qgetenv("PHOTOQT_DEBUG") == "yes")
                    LOG << CURDATE << "ImageProviderThumbnail: Image was modified since thumbnail creation, not using cached thumbnail: " <<
                           QFileInfo(filename).fileName().toStdString() << NL;
                needToReCreatedDbThumbnail = true;
            }


        }

        // Cleaning up
        query.clear();

    }

    // If file wasn't loaded from file or database, then it doesn't exist yet (or isn't up-to-date anymore) and we have to create it

    // We create a temporary pointer, so that we can delete it properly afterwards
    QSize *tmp = new QSize(ts,ts);
    p = imageproviderfull->requestImage(filename.toPercentEncoding(),tmp,QSize(ts,ts));
    delete tmp;

    // Only if the image itself is smaller than the requested thumbnail size are both dimensions less than (strictly) than ts -> no caching
    if((p.width() < ts && p.height() < ts) || p.text("error") == "error") {
        if(qgetenv("PHOTOQT_DEBUG") == "yes")
            LOG << CURDATE << "ImageProviderThumbnail: Image is smaller than potential thumbnail, no need to cache: " <<
                   QFileInfo(filename).fileName().toStdString() << NL;
        return p;
    }

    // Create file cache thumbnail
    if(typeCache == "files" && cacheEnabled) {

        // If the file itself wasn't read from the thumbnails folder, is not a temporary file, and if the original file isn't at thumbnail size itself
        if(!filename.startsWith(QString(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails").toUtf8())
                && !filename.startsWith(QDir::tempPath().toUtf8())) {

            // Set some required (and additional) meta information
            p.setText("Thumb::URI", QString("file://%1").arg(QString(filename)));
            p.setText("Thumb::MTime", QString("%1").arg(QFileInfo(filename).lastModified().toTime_t()));
            QString mime = mimedb.mimeTypeForFile(filename, QMimeDatabase::MatchContent).name();
            // this is the default mime type if no mime type is available or file cannot be found
            if(mime != "application/octet-stream")
                p.setText("Thumb::Mimetype", mime);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
            p.setText("Thumb::Size", QString("%1").arg(p.sizeInBytes()));
#else
            QFileInfo info(filename);
            p.setText("Thumb::Size", QString("%1").arg(info.size()));
#endif

            // If the file does already exist, then the image has likely been updated -> delete old thumbnail image
            if(QFile(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails/large/" + md5 + ".png").exists())
                QFile(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails/large/" + md5 + ".png").remove();

            // And save new thumbnail image
            if(!p.save(ConfigFiles::GENERIC_CACHE_DIR() + "/thumbnails/large/" + md5 + ".png"))
                LOG << CURDATE << "ImageProviderThumbnail: ERROR creating new thumbnail file: " <<
                       QFileInfo(filename).fileName().toStdString() << NL;
            else if(qgetenv("PHOTOQT_DEBUG") == "yes")
                LOG << CURDATE << "ImageProviderThumbnail: Successfully cached thumbnail (file cache): " <<
                       QFileInfo(filename).fileName().toStdString() << NL;

        }

    // if not file caching -> db caching
    } else if(cacheEnabled) {

        // make sure transaction is started
        if(!dbTransactionStarted) {
            if(!db.transaction())
                LOG << CURDATE << "ImageProviderThumbnail: ERROR: Cannot start db transaction" << NL;
            dbTransactionStarted = true;
        }

        QSqlQuery query2(db);

        // convert image to bytearray
        QByteArray b;
        QBuffer buf(&b);
        buf.open(QIODevice::WriteOnly);

        // Always use png format
        p.save(&buf,"PNG");

        // If it was once created, i.e. if the file changed (i.e. if last mod date changed), then we have to update it
        if(needToReCreatedDbThumbnail)
            query2.prepare("UPDATE Thumbnails SET filepath=:path,thumbnail=:thb,filelastmod=:mod,thumbcreated=:crt WHERE filepath=:path");
        else
            query2.prepare("INSERT INTO Thumbnails(filepath,thumbnail,filelastmod,thumbcreated) VALUES(:path,:thb,:mod,:crt)");

        // bind the thumbnail properties
        query2.bindValue(":path",filename);
        query2.bindValue(":thb",b);
        query2.bindValue(":mod",QFileInfo(filename).lastModified().toTime_t());
        query2.bindValue(":crt",QDateTime::currentMSecsSinceEpoch());
        query2.exec();

        if(query2.lastError().text().trimmed().length())
            LOG << CURDATE << "ImageProviderThumbnail: ERROR [" << QString(filename).toStdString() << "]: " <<
                   query2.lastError().text().trimmed().toStdString() << NL;
        else if(qgetenv("PHOTOQT_DEBUG") == "yes")
            LOG << CURDATE << "ImageProviderThumbnail: Successfully cached thumbnail (db cache): " <<
                   QFileInfo(filename).fileName().toStdString() << NL;

        // cleaning up
        query2.clear();

    }

    // aaaaand done!
    return p;

}