void QXmppVCard::toXmlElementFromChild(QXmlStreamWriter *writer) const { writer->writeStartElement("vCard"); helperToXmlAddAttribute(writer,"xmlns", ns_vcard); if (!m_fullName.isEmpty()) helperToXmlAddTextElement(writer, "FN", m_fullName); if(!m_nickName.isEmpty()) helperToXmlAddTextElement(writer, "NICKNAME", m_nickName); if (!m_firstName.isEmpty() || !m_lastName.isEmpty() || !m_middleName.isEmpty()) { writer->writeStartElement("N"); if (!m_firstName.isEmpty()) helperToXmlAddTextElement(writer, "GIVEN", m_firstName); if (!m_lastName.isEmpty()) helperToXmlAddTextElement(writer, "FAMILY", m_lastName); if (!m_middleName.isEmpty()) helperToXmlAddTextElement(writer, "MIDDLE", m_middleName); writer->writeEndElement(); } if (!m_url.isEmpty()) helperToXmlAddTextElement(writer, "URL", m_url); if(!photo().isEmpty()) { writer->writeStartElement("PHOTO"); helperToXmlAddTextElement(writer, "TYPE", getImageType(photo())); helperToXmlAddTextElement(writer, "BINVAL", photo().toBase64()); writer->writeEndElement(); } writer->writeEndElement(); }
bool UserProfile::save() const { QDomDocument domDoc; QDomElement rootElement = createElement(this, source(), parentElement(), domDoc); if (!rootElement.isNull()) { //Пересоздадим основной элемент QDomElement oldRootElement = rootElement; rootElement = domDoc.createElement(rootElement.tagName()); oldRootElement.parentNode().appendChild(rootElement); oldRootElement.parentNode().removeChild(oldRootElement); QDomElement idElement = domDoc.createElement("id"); rootElement.appendChild(idElement); QDomText idText = domDoc.createTextNode(QString::number(id())); idElement.appendChild(idText); QDomElement nameElement = domDoc.createElement("name"); rootElement.appendChild(nameElement); QDomText nameText = domDoc.createTextNode(name()); nameElement.appendChild(nameText); QDomElement photoElement = domDoc.createElement("photo"); rootElement.appendChild(photoElement); QByteArray ba; QBuffer buffer(&ba); if (!photo().isNull()) { buffer.open(QIODevice::WriteOnly); //Смаштабируем фото if (photo().width() > m_preferredSize.width() || photo().height() > m_preferredSize.height()) { QImage scaledPhoto = photo().scaled(m_preferredSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); scaledPhoto.save(&buffer, "PNG"); } else { photo().save(&buffer, "PNG"); } } QDomText photoText = domDoc.createTextNode(ba.toBase64()); photoElement.appendChild(photoText); QDomElement statusesElement = domDoc.createElement("statuses"); rootElement.appendChild(statusesElement); m_stateModel->appendItemsToDomElement(statusesElement, domDoc); QFile file (source().toLocalFile()); if(file.open(QFile::WriteOnly)) { QTextStream ts(&file); ts.setCodec("UTF-8"); ts << domDoc.toString(); file.close(); return true; } } return false; }
IO::Flow ScanPhotoDirectory::onFile(const String& completePath, const String& /*folder*/, const String& /*name*/, uint64 /*size*/) { if (!pIsValidFolder) return IO::flowContinue; if (!ExtendedPhoto::isExtensionManaged(completePath)) return IO::flowContinue; if (pMode == ReadDate::safe) { // We load the photo to check the date. We could imagine later to // provide a fast option which prevent this step (which shouldn't // modify anything in case folder actually support most of the date // information and photo directory was generated with PictStock; // however if not the case this step is really required) ExtendedPhoto::ExtendedPhoto photo(logs, pCameras, completePath); auto ptr = photo.informations(); assert(!(!ptr)); ExtendedPhoto::Date photoDate = ptr->date(); if (photoDate < pBeginDate || photoDate > pEndDate) return IO::flowContinue; } pValidPhotos.push_back(completePath); return IO::flowContinue; }
SmartPtr CreateSamplePhotoInfo() { SmartPtr photo(new PhotoInfoJPEG()); photo->SetFileSize(1024 * 500); photo->SetSize(1024, 768); SYSTEMTIME tm; ::GetLocalTime(&tm); photo->SetDateTime(SytemTimeToDateTime(tm)); photo->SetPhysicalPath(_T("C:\\DSC0001.JPG")); photo->SetPhotoName(_T("DSC0001")); photo->SetExposureTime(Rational(1, 250)); photo->SetFStop(Rational(4, 1)); photo->SetExposureProgram(0); //SRational exposure_bias_; //uint16 orientation_; //uint16 metering_mode_; //uint16 light_source_; //uint16 flash_; photo->SetFocalLength(Rational(50, 1)); //Rational aperture_value_; //SRational shutter_speed_value_; photo->SetMake(_T("DigiCam")); photo->SetModel(_T("TestCamera")); photo->SetExifDescription(L"Image description"); //uint16 thumbnail_orientation_; photo->SetSubjectDistance(Rational(100, 1)); XmpData xmp; xmp.Author = _T("MK"); photo->SetMetadata(xmp); PostProcessTime(photo.get()); return photo; }
void CreateGroupWindow::createProfilePictureWindow() { QImage photo(photoFileName); if (photo.width() < PREVIEW_WIDTH || photo.height() < PREVIEW_HEIGHT) { QMaemo5InformationBox::information(this,"The image is too small. "\ "Please select a photo with height and width of at least " + QString::number(PREVIEW_WIDTH) + " pixels", QMaemo5InformationBox::NoTimeout); } else { ProfilePictureWindow *window = new ProfilePictureWindow(photo,this); connect(window,SIGNAL(finished(QImage)), this,SLOT(finishedPhotoSelection(QImage))); window->setAttribute(Qt::WA_Maemo5StackedWindow); window->setAttribute(Qt::WA_DeleteOnClose); window->setWindowFlags(window->windowFlags() | Qt::Window); window->showFullScreen(); } }
void Application::uploadProfilePhoto(const QImage &tosend, const PeerId &peerId) { PreparedPhotoThumbs photoThumbs; QVector<MTPPhotoSize> photoSizes; QPixmap thumb = QPixmap::fromImage(tosend.scaled(160, 160, Qt::KeepAspectRatio, Qt::SmoothTransformation)); photoThumbs.insert('a', thumb); photoSizes.push_back(MTP_photoSize(MTP_string("a"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0))); QPixmap full = QPixmap::fromImage(tosend); photoThumbs.insert('c', full); photoSizes.push_back(MTP_photoSize(MTP_string("c"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0))); QByteArray jpeg; QBuffer jpegBuffer(&jpeg); full.save(&jpegBuffer, "JPG", 87); PhotoId id = MTP::nonce<PhotoId>(); MTPPhoto photo(MTP_photo(MTP_long(id), MTP_long(0), MTP_int(MTP::authedId()), MTP_int(unixtime()), MTP_string(""), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes))); QString file, filename; int32 filesize = 0; QByteArray data; ReadyLocalMedia ready(ToPreparePhoto, file, filename, filesize, data, id, id, peerId, photo, photoThumbs, MTP_documentEmpty(MTP_long(0)), jpeg); connect(App::uploader(), SIGNAL(photoReady(MsgId, const MTPInputFile &)), App::app(), SLOT(photoUpdated(MsgId, const MTPInputFile &)), Qt::UniqueConnection); MsgId newId = clientMsgId(); App::app()->regPhotoUpdate(peerId, newId); App::uploader()->uploadMedia(newId, ready); }
static void set_participant_images(ChatView* self) { ChatViewPrivate *priv = CHAT_VIEW_GET_PRIVATE(self); webkit_chat_container_clear_sender_images( WEBKIT_CHAT_CONTAINER(priv->webkit_chat_container) ); /* Set the sender image for the peer */ ContactMethod* sender_contact_method_peer; QVariant photo_variant_peer; if (priv->person) { photo_variant_peer = priv->person->photo(); sender_contact_method_peer = get_active_contactmethod(self); } else { if (priv->cm) { sender_contact_method_peer = priv->cm; } else { sender_contact_method_peer = priv->call->peerContactMethod(); } photo_variant_peer = sender_contact_method_peer->roleData((int) Call::Role::Photo); } if (photo_variant_peer.isValid()) { webkit_chat_container_set_sender_image( WEBKIT_CHAT_CONTAINER(priv->webkit_chat_container), sender_contact_method_peer, photo_variant_peer ); } /* set sender image for "ME" */ auto profile = ProfileModel::instance().selectedProfile(); if (profile) { auto person = profile->person(); if (person) { auto photo_variant_me = person->photo(); if (photo_variant_me.isValid()) { webkit_chat_container_set_sender_image( WEBKIT_CHAT_CONTAINER(priv->webkit_chat_container), nullptr, photo_variant_me ); } } } }
void AddresseeTest::assignmentTest() { KContacts::Addressee addressee1, addressee2; KContacts::Picture logo(QStringLiteral("http://scottlandyard.info/pics/logo.png")); KContacts::Picture photo(QStringLiteral("http://scottlandyard.info/~sinclair/photo.png")); KContacts::Sound sound(QStringLiteral("http://scottlandyard.info/~sinclair/sound.wav")); QStringList emails; emails << QStringLiteral("*****@*****.**") << QStringLiteral("*****@*****.**"); KContacts::Key::List keys; keys << KContacts::Key(QStringLiteral("SecretKey")); QStringList categories; categories << QStringLiteral("Helper") << QStringLiteral("Friend"); QStringList customs; customs << QStringLiteral("X-Danger: high"); addressee1.setUid(QStringLiteral("My uid")); addressee1.setName(QStringLiteral("John Sinclair")); addressee1.setFormattedName(QStringLiteral("Sinclair, John")); addressee1.setFamilyName(QStringLiteral("Sinclair")); addressee1.setGivenName(QStringLiteral("John")); addressee1.setAdditionalName(QStringLiteral("Bob")); addressee1.setPrefix(QStringLiteral("Sir")); addressee1.setSuffix(QStringLiteral("II")); addressee1.setNickName(QStringLiteral("ghosthunter")); addressee1.setBirthday(QDateTime(QDate(1982, 7, 19))); addressee1.setMailer(QStringLiteral("mutt")); addressee1.setTimeZone(KContacts::TimeZone(2)); addressee1.setGeo(KContacts::Geo(42, 23)); addressee1.setTitle(QStringLiteral("Ghost Hunter")); addressee1.setRole(QStringLiteral("Leader")); addressee1.setOrganization(QStringLiteral("Scottland Yard")); addressee1.setNote(QStringLiteral("Don't cross black deads way...")); addressee1.setProductId(QStringLiteral("ProductId45")); addressee1.setRevision(QDateTime(QDate(1982, 9, 15))); addressee1.setSortString(QStringLiteral("Name")); KContacts::ResourceLocatorUrl url; url.setUrl(QUrl(QStringLiteral("www.scottlandyard.info"))); addressee1.setUrl(url); addressee1.setSecrecy(KContacts::Secrecy(KContacts::Secrecy::Public)); addressee1.setLogo(logo); addressee1.setPhoto(photo); addressee1.setSound(sound); addressee1.setEmails(emails); addressee1.setKeys(keys); addressee1.setCategories(categories); addressee1.setCustoms(customs); addressee1.setChanged(false); addressee2 = addressee1; QVERIFY(addressee1 == addressee2); }
void PhotoCancelClickHandler::onClickImpl() const { auto data = photo(); if (!data->date) return; if (data->uploading()) { if (const auto item = App::histItemById(context())) { App::main()->cancelUploadLayer(item); } } else { data->cancel(); } }
bool TimeseriesGraph::init(const unsigned int numDimensions,const unsigned int graphWidth){ connect(ui->snapShotButton, SIGNAL(clicked()), this, SLOT(photo())); initialized = true; this->numDimensions = numDimensions; this->graphWidth = graphWidth; data.resize( graphWidth, GRT::VectorDouble(numDimensions,0) ); if( !lockRanges ){ minRange = 99e+99; maxRange = -minRange; } return true; }
void QXmppVCardIq::toXmlElementFromChild(QXmlStreamWriter *writer) const { writer->writeStartElement("vCard"); writer->writeAttribute("xmlns", ns_vcard); foreach (const QXmppVCardAddress &address, d->addresses) address.toXml(writer); if (d->birthday.isValid()) helperToXmlAddTextElement(writer, "BDAY", d->birthday.toString("yyyy-MM-dd")); if (!d->description.isEmpty()) helperToXmlAddTextElement(writer, "DESC", d->description); foreach (const QXmppVCardEmail &email, d->emails) email.toXml(writer); if (!d->fullName.isEmpty()) helperToXmlAddTextElement(writer, "FN", d->fullName); if(!d->nickName.isEmpty()) helperToXmlAddTextElement(writer, "NICKNAME", d->nickName); if (!d->firstName.isEmpty() || !d->lastName.isEmpty() || !d->middleName.isEmpty()) { writer->writeStartElement("N"); if (!d->firstName.isEmpty()) helperToXmlAddTextElement(writer, "GIVEN", d->firstName); if (!d->lastName.isEmpty()) helperToXmlAddTextElement(writer, "FAMILY", d->lastName); if (!d->middleName.isEmpty()) helperToXmlAddTextElement(writer, "MIDDLE", d->middleName); writer->writeEndElement(); } foreach (const QXmppVCardPhone &phone, d->phones) phone.toXml(writer); if(!photo().isEmpty()) { writer->writeStartElement("PHOTO"); QString photoType = d->photoType; if (photoType.isEmpty()) photoType = getImageType(d->photo); helperToXmlAddTextElement(writer, "TYPE", photoType); helperToXmlAddTextElement(writer, "BINVAL", d->photo.toBase64()); writer->writeEndElement(); } if (!d->url.isEmpty()) helperToXmlAddTextElement(writer, "URL", d->url); d->organization.toXml(writer); writer->writeEndElement(); }
QList<Photo> Picasa::getPhotosByAlbum(Album *album){ QList<Photo> photos; if(album->getId().isEmpty() || album->getOwnerId().isEmpty()) return photos; QUrl url = QUrl("https://picasaweb.google.com/data/feed/api/user/" + album->getOwnerId() + "/albumid/" + album->getId() + "?alt=json&access_token="+this->access_token); QJsonDocument document = getJsonDocument(url); QJsonObject feed = document.object().take("feed").toObject(); QJsonArray array = feed.take("entry").toArray(); foreach(QJsonValue photo_, array){ Photo photo(photo_.toObject()); photo.setAlbum(album->getTitle()); photos.append(photo); }
QFuture<QImage> EntryBase::RefreshAvatar (Size) { const auto maybeVCard = Account_->GetParentProtocol ()-> GetVCardStorage ()->GetVCard (GetHumanReadableID ()); if (maybeVCard && VCardPhotoHash_ == ComputeVCardPhotoHash (*maybeVCard)) return Util::MakeReadyFuture (QImage::fromData (maybeVCard->photo ())); QFutureInterface<QImage> iface; iface.reportStarted (); Account_->GetClientConnection ()->FetchVCard (GetJID (), [iface] (const QXmppVCardIq& iq) mutable { const auto& photo = iq.photo (); const auto image = photo.isEmpty () ? QImage {} : QImage::fromData (photo); iface.reportFinished (&image); }); return iface.future (); }
void LocalImageLoaderPrivate::prepareImages() { QString file, filename, mime; int32 filesize = 0; QImage img; QByteArray data; PeerId peer; uint64 id, jpeg_id = 0; ToPrepareMediaType type; { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); if (list.isEmpty()) return; file = list.front().file; img = list.front().img; data = list.front().data; peer = list.front().peer; id = list.front().id; type = list.front().type; } if (img.isNull()) { if (!file.isEmpty()) { QFileInfo info(file); if (type == ToPrepareAuto) { QString lower(file.toLower()); const QStringList &photoExtensions(cPhotoExtensions()); for (QStringList::const_iterator i = photoExtensions.cbegin(), e = photoExtensions.cend(); i != e; ++i) { if (lower.lastIndexOf(*i) == lower.size() - i->size()) { if (info.size() < MaxUploadPhotoSize) { type = ToPreparePhoto; break; } } } if (type == ToPrepareAuto && info.size() < MaxUploadDocumentSize) { type = ToPrepareDocument; } } if (type != ToPrepareAuto && info.size() < MaxUploadPhotoSize) { img = App::readImage(file); } if (type == ToPrepareDocument) { mime = QMimeDatabase().mimeTypeForFile(info).name(); } filename = info.fileName(); filesize = info.size(); } else if (!data.isEmpty()) { img = App::readImage(data); if (type == ToPrepareAuto) { if (!img.isNull() && data.size() < MaxUploadPhotoSize) { type = ToPreparePhoto; } else if (data.size() < MaxUploadDocumentSize) { type = ToPrepareDocument; } else { img = QImage(); } } QMimeType mimeType = QMimeDatabase().mimeTypeForData(data); if (type == ToPrepareDocument) { mime = mimeType.name(); } filename = qsl("Document"); QStringList patterns = mimeType.globPatterns(); if (!patterns.isEmpty()) { filename = patterns.front().replace('*', filename); } filesize = data.size(); } } else { if (type == ToPrepareDocument) { filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true); QMimeType mimeType = QMimeDatabase().mimeTypeForName("image/png"); data = QByteArray(); { QBuffer b(&data); img.save(&b, "PNG"); } filesize = data.size(); } else { type = ToPreparePhoto; // only photo from QImage filename = qsl("Untitled.jpg"); filesize = 0; } } if ((img.isNull() && (type != ToPrepareDocument || !filesize)) || type == ToPrepareAuto || (img.isNull() && file.isEmpty() && data.isEmpty())) { // if could not decide what type { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); list.pop_front(); } QTimer::singleShot(1, this, SLOT(prepareImages())); emit imageFailed(id); } else { PreparedPhotoThumbs photoThumbs; QVector<MTPPhotoSize> photoSizes; MTPPhotoSize thumb(MTP_photoSizeEmpty(MTP_string(""))); MTPPhoto photo(MTP_photoEmpty(MTP_long(0))); MTPDocument document(MTP_documentEmpty(MTP_long(0))); QByteArray jpeg; if (type == ToPreparePhoto) { int32 w = img.width(), h = img.height(); QPixmap thumb = (w > 100 || h > 100) ? QPixmap::fromImage(img.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); photoThumbs.insert('s', thumb); photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0))); QPixmap medium = (w > 320 || h > 320) ? QPixmap::fromImage(img.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); photoThumbs.insert('m', medium); photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0))); QPixmap full = (w > 800 || h > 800) ? QPixmap::fromImage(img.scaled(800, 800, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); photoThumbs.insert('x', full); photoSizes.push_back(MTP_photoSize(MTP_string("x"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0))); { QBuffer jpegBuffer(&jpeg); full.save(&jpegBuffer, "JPG", 87); } if (!filesize) filesize = jpeg.size(); photo = MTP_photo(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_string(""), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes)); jpeg_id = id; } else if ((type == ToPrepareVideo || type == ToPrepareDocument) && !img.isNull()) { int32 w = img.width(), h = img.height(); QPixmap full = (w > 90 || h > 90) ? QPixmap::fromImage(img.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); { QBuffer jpegBuffer(&jpeg); full.save(&jpegBuffer, "JPG", 87); } photoThumbs.insert('0', full); thumb = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); jpeg_id = MTP::nonce<uint64>(); } if (type == ToPrepareDocument) { document = MTP_document(MTP_long(id), MTP_long(0), MTP_int(MTP::authedId()), MTP_int(unixtime()), MTP_string(filename), MTP_string(mime), MTP_int(filesize), thumb, MTP_int(MTP::maindc())); } { QMutexLocker lock(loader->readyMutex()); loader->readyList().push_back(ReadyLocalMedia(type, file, filename, filesize, data, id, jpeg_id, peer, photo, photoThumbs, document, jpeg)); } { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); list.pop_front(); } QTimer::singleShot(1, this, SLOT(prepareImages())); emit imageReady(); } }
bool CatalogScanner::Scan(bool visitSubDirs, uint32& dirVisited, PhotoInfoStorage& store, boost::shared_ptr<::Database> db, CatalogHeader::DirPtr dir) { if (dir == 0) { ASSERT(false); return false; } //###### lousy hack ####### if (dirVisited < 0x40000000) dirVisited = 0x40000000; //######################### int start_id= dirVisited++; if (visitSubDirs) { const size_t count= dir->subdirs_.size(); for (size_t i= 0; i < count; ++i) { bool ret= Scan(visitSubDirs, dirVisited, store, db, dir->subdirs_[i]); if (!ret) return false; } } if (dir->records_.empty()) return true; const size_t max_count= dir->records_.size(); for (size_t i= 0; i < max_count; ++i) { uint64 offset= dir->records_[i]; if (offset == 0) // no more images here? break; CatalogImgRecord img; catalog_->ReadRecord(offset, img); SmartPhotoPtr photo(new PhotoInfoCatalog(img, db, offset)); photo->SetVisitedDirId(start_id); // maintain unique directory ids // if (photo->dir_visited_ >= dirVisited) // dirVisited = photo->dir_visited_ + 1; SetAutoRotationFlag(photo.get()); PostProcessTime(photo.get()); store.Append(photo); if (break_) // scan interrupted? return false; // refresh Notify(); } return true; /* // try { // CatalogFile cat(path); // this is db object shared by catalog photos; they will use it to read exif block // on request (in CompleteInfo method) // boost::shared_ptr<Database> db(new Database(false)); // VERIFY(db->Open(path_, catalog_->GetSupportedVersion(), true)); if (break_) // scan interrupted? return false; int start_id= dirVisited; uint64 offset= 0; while (catalog_->NextRecord(offset)) { const CatalogImgRecord& img= catalog_->Image(); AutoPtr<PhotoInfo> photo= new PhotoInfoCatalog(img, db, offset); photo->dir_visited_ += start_id; // maintain unique directory ids if (photo->dir_visited_ >= dirVisited) dirVisited = photo->dir_visited_ + 1; SetAutoRotationFlag(photo.get()); PostProcessTime(photo.get()); store.Append(photo); if (break_) // scan interrupted? return false; // refresh Notify(); } } // CATCH_ALL return true; */ }
void CatalogImages::Impl::ProcessFiles(int img_size, int jpeg_compression_level) { const size_t count= files_.size(); counter_ = 0; for (size_t i= 0; i < count; ++i) { if (parentWnd_) ::PostMessage(parentWnd_, MESSAGE, i, IMG_PROCESSING); if (break_) return; const Path& path= files_[i].first; PhotoFactory::CreateFn fn= 0; int id= 0; if (!GetPhotoFactory().MatchPhotoType(path.GetExtension(), fn, id)) { ASSERT(false); continue; } SmartPhotoPtr photo(fn()); try { CatalogImgRecord img; // ExifBlock exif; // exif.clear(); bool has_exif= photo->Scan(path.c_str(), img.exif_, false, nullptr); // scan image to find EXIF data if (!has_exif && readOnlyPhotosWithEXIF_) continue; if (!has_exif || photo->GetDateTime().is_not_a_date_time()) ReadFileTimeStamp(*photo, path); uint64 fileLength= 0; // write to db img.type_ = id; // get file length and last write time { WIN32_FIND_DATA findFileData; HANDLE find= ::FindFirstFile(path.c_str(), &findFileData); if (find != INVALID_HANDLE_VALUE) { VERIFY(::FindClose(find)); fileLength = uint64(findFileData.nFileSizeLow) + (uint64(findFileData.nFileSizeHigh) << 32); img.time_stamp_ = findFileData.ftLastWriteTime; img.access_time_ = findFileData.ftLastAccessTime; img.creation_time_ = findFileData.ftCreationTime; img.file_attribs_ = findFileData.dwFileAttributes; } } // uint64 fileLength= path.GetFileLength(); //photo->dir_visited_ = static_cast<uint32>(dir_visited); photo->SetFileSize(fileLength); photo->SetPhotoName(path.GetFileName()); photo->SetPhysicalPath(path); photo->exif_data_present_ = has_exif; // SetAutoRotationFlag(photo.get()); img.path_ = String2WStr(path); img.make_ = String2WStr(photo->GetMake()); img.model_ = String2WStr(photo->GetModel()); img.orientation_ = photo->OrientationField(); img.file_size_ = fileLength; // find.GetLastWriteTime(&img.time_stamp_); //photo->index_.Serialize(img.buf_index_); // verify this: =========== // img.jpeg_offset_ = photo->jpeg_offset_; // HACK: this is orientation extracted from CRW file; when reading info from // cache CRW is not scanned, so orientation cannot be set img.exif_orientation_ = has_exif ? 0u : photo->OrientationField(); // ========================= // EXIF block img.has_exif_ = has_exif; // img.exif_ifd_offset_ = static_cast<int32>(exif.ifd0Start); // if (exif.is_raw) // img.exif_type_ = exif.bigEndianByteOrder ? // CatalogImgRecord::RAW_MM_EXIF_BLOCK : CatalogImgRecord::RAW_II_EXIF_BLOCK; // else // img.exif_type_ = CatalogImgRecord::JPEG_EXIF_BLOCK; // img.exif_.swap(exif.exif_buffer); // prepare preview Dib bmp; CSize thumbnail_size(img_size, img_size); CImageDecoderPtr decoder= photo->GetDecoder(); bool ycbcr_image= true; ImageStat stat= decoder->DecodeImgToYCbCr(bmp, thumbnail_size, true); if (stat != IS_OK) { ycbcr_image = false; if (stat == IS_OPERATION_NOT_SUPPORTED) stat = decoder->DecodeImg(bmp, thumbnail_size, true); } if (stat != IS_OK || !bmp.IsValid()) { failed_.push_back(path); continue; } // if EXIF indicates rotation and photo is already physically rotated AND exif reset EXIF orientation // flag back to normal to avoid problems later on... PhotoInfo::ImgOrientation orient= photo->GetOrientation(); if ((orient == PhotoInfo::ORIENT_90CCW || orient == PhotoInfo::ORIENT_90CW) && photo->GetWidth() > photo->GetHeight() && bmp.GetWidth() < bmp.GetHeight()) { //photo->orientation_ = 0; std::swap(img.img_width_, img.img_height_); uint32 w= photo->GetWidth(); uint32 h= photo->GetHeight(); photo->SetSize(h, w); } else if ((orient == PhotoInfo::ORIENT_NORMAL || orient == PhotoInfo::ORIENT_NO_INFO || orient == PhotoInfo::ORIENT_UNKNOWN) && photo->GetWidth() > photo->GetHeight() && bmp.GetWidth() < bmp.GetHeight()) { // orientation is 'normal', but reported size and size of decoded image do not agree uint32 w= photo->GetWidth(); uint32 h= photo->GetHeight(); photo->SetSize(h, w); } img.photo_width_ = photo->GetWidth(); img.photo_height_ = photo->GetHeight(); //TODO: convert non-ycbcr from rgb if needed // calculate 'index' using YCbCr image photo->index_.CalcHistogram(bmp); photo->index_.Serialize(img.index_); // now to RGB if (ycbcr_image) bmp.ConvertYCbCr2RGB(); Dib thm; // little thumbnail if (img_size > 160) bmp.ResizeToFit(CSize(160, 160), Dib::RESIZE_HALFTONE, thm); CSize size= bmp.GetSize(); int big= img_size; if (size.cx > big || size.cy > big) bmp.ResizeToFit(CSize(big, big), Dib::RESIZE_HALFTONE); img.img_width_ = bmp.GetWidth(); img.img_height_ = bmp.GetHeight(); // compress preview into JPEG JPEGEncoder enc(jpeg_compression_level, false, false); if (thm.IsValid()) { // we have both little thumbnail image and preview image { CMemoryDataDestination memdest; enc.Encode(memdest, &thm); memdest.SwapJPEG(img.thumbnail_); } { CMemoryDataDestination memdest; enc.Encode(memdest, &bmp); memdest.SwapJPEG(img.preview_); } } else { // only small preview available; // store it in the thumbnail leaving preview field empty CMemoryDataDestination memdest; enc.Encode(memdest, &bmp); memdest.SwapJPEG(img.thumbnail_); img.preview_.clear(); } // IPTC present? //if (photo->IPTC_.get()) // img.iptc_.reset(photo->IPTC_.release()); if (photo->HasMetadata()) { img.iptc_.reset(new IPTCRecord()); photo->GetIPTCInfo(*img.iptc_); } img.description_ = photo->GetExifDescription(); img.marker_index_ = photo->GetFileTypeIndex(); //TODO: store XMP too!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //TODO: // grab tags; // and description; // EliminateNonPrintableChars(photo->photo_desc_); // PostProcessTime(photo.get()); CatalogHeader::DirPtr dir= files_[i].second; img.dir_visited_ = dir->id_; // add/modify record std::vector<uint8> buf; img.Serialize(buf, 1); uint64 record_offset= dbImages_.Append(buf); // examine tags if (!photo->GetTags().empty()) // has tags? { PhotoTags::const_iterator end= photo->GetTags().end(); for (PhotoTags::const_iterator it = photo->GetTags().begin(); it != end; ++it) tags_[*it].push_back(record_offset); } if (dir->records_.empty()) dir->records_.reserve(dir->reserved_capacity_); if (dir->records_.size() < dir->reserved_capacity_) dir->records_.push_back(record_offset); else { ASSERT(false); continue; } ++counter_; } catch (MemPointer::MemPtrException&) { CString msg= _T("Error parsing file: "); msg += path.c_str(); ::ShowMessageBox(msg); } catch (CMemoryException*) { CString msg= _T("Out of memory reading file: "); msg += path.c_str(); ::ShowMessageBox(msg); } catch (JPEGException& ex) { CString msg= _T("Error processing file: "); msg += path.c_str(); msg += _T("\n\n"); msg += ex.GetMessage(); ::ShowMessageBox(msg); } #ifndef _DEBUG catch (...) { // ASSERT(false); } #endif } }
QList<QPair<QString, QVariant>> EntryBase::GetVCardRepresentation () const { Account_->GetClientConnection ()->FetchVCard (GetJID ()); const auto vcard = GetVCard (); QList<QPair<QString, QVariant>> result { { tr ("Photo"), QImage::fromData (vcard.photo ()) }, { "JID", vcard.from () }, { tr ("Real name"), vcard.fullName () }, { tr ("Birthday"), vcard.birthday () }, { "URL", vcard.url () }, { tr ("About"), vcard.description () } }; for (const auto& phone : vcard.phones ()) { if (phone.number ().isEmpty ()) continue; QStringList attrs; if (phone.type () & QXmppVCardPhone::Preferred) attrs << tr ("preferred"); if (phone.type () & QXmppVCardPhone::Home) attrs << tr ("home"); if (phone.type () & QXmppVCardPhone::Work) attrs << tr ("work"); if (phone.type () & QXmppVCardPhone::Cell) attrs << tr ("cell"); result.append ({ tr ("Phone"), attrs.isEmpty () ? phone.number () : phone.number () + " (" + attrs.join (", ") + ")" }); } for (const auto& email : vcard.emails ()) { if (email.address ().isEmpty ()) continue; QStringList attrs; if (email.type () == QXmppVCardEmail::Preferred) attrs << tr ("preferred"); if (email.type () == QXmppVCardEmail::Home) attrs << tr ("home"); if (email.type () == QXmppVCardEmail::Work) attrs << tr ("work"); if (email.type () == QXmppVCardEmail::X400) attrs << "X400"; result.append ({ "Email", attrs.isEmpty () ? email.address () : email.address () + " (" + attrs.join (", ") + ")" }); } for (const auto& address : vcard.addresses ()) { if ((address.country () + address.locality () + address.postcode () + address.region () + address.street ()).isEmpty ()) continue; QStringList attrs; if (address.type () & QXmppVCardAddress::Home) attrs << tr ("home"); if (address.type () & QXmppVCardAddress::Work) attrs << tr ("work"); if (address.type () & QXmppVCardAddress::Postal) attrs << tr ("postal"); if (address.type () & QXmppVCardAddress::Preferred) attrs << tr ("preferred"); QString str; QStringList fields; auto addField = [&fields] (const QString& label, const QString& val) { if (!val.isEmpty ()) fields << label.arg (val); }; addField (tr ("Country: %1"), address.country ()); addField (tr ("Region: %1"), address.region ()); addField (tr ("Locality: %1", "User's locality"), address.locality ()); addField (tr ("Street: %1"), address.street ()); addField (tr ("Postal code: %1"), address.postcode ()); result.append ({ tr ("Address"), fields }); } #if QXMPP_VERSION >= 0x000800 const auto& orgInfo = vcard.organization (); result.append ({ tr ("Organization"), orgInfo.organization () }); result.append ({ tr ("Organization unit"), orgInfo.unit () }); result.append ({ tr ("Job title"), orgInfo.title () }); result.append ({ tr ("Job role"), orgInfo.role () }); #endif return result; }
void AddresseeTest::storeTest() { KContacts::Addressee addressee; KContacts::Picture logo(QStringLiteral("http://scottlandyard.info/pics/logo.png")); KContacts::Picture photo(QStringLiteral("http://scottlandyard.info/~sinclair/photo.png")); KContacts::Sound sound(QStringLiteral("http://scottlandyard.info/~sinclair/sound.wav")); QStringList emails; emails << QStringLiteral("*****@*****.**") << QStringLiteral("*****@*****.**"); KContacts::Key::List keys; keys << KContacts::Key(QStringLiteral("SecretKey")); QStringList categories; categories << QStringLiteral("Helper") << QStringLiteral("Friend"); QStringList customs; customs << QStringLiteral("X-Danger: high"); KContacts::Gender gender(QStringLiteral("H")); addressee.setGender(gender); KContacts::Lang lang(QLatin1String("lang")); addressee.setLangs(KContacts::Lang::List() << lang); addressee.setUid(QStringLiteral("My uid")); addressee.setName(QStringLiteral("John Sinclair")); addressee.setFormattedName(QStringLiteral("Sinclair, John")); addressee.setFamilyName(QStringLiteral("Sinclair")); addressee.setGivenName(QStringLiteral("John")); addressee.setAdditionalName(QStringLiteral("Bob")); addressee.setPrefix(QStringLiteral("Sir")); addressee.setSuffix(QStringLiteral("II")); addressee.setNickName(QStringLiteral("ghosthunter")); addressee.setBirthday(QDate(1982, 7, 19)); addressee.setMailer(QStringLiteral("mutt")); addressee.setTimeZone(KContacts::TimeZone(2)); addressee.setGeo(KContacts::Geo(42, 23)); addressee.setTitle(QStringLiteral("Ghost Hunter")); addressee.setRole(QStringLiteral("Leader")); addressee.setOrganization(QStringLiteral("Scottland Yard")); addressee.setNote(QStringLiteral("Don't cross black deads way...")); addressee.setProductId(QStringLiteral("ProductId45")); addressee.setRevision(QDateTime(QDate(1982, 9, 15))); addressee.setSortString(QStringLiteral("Name")); KContacts::ResourceLocatorUrl url; url.setUrl(QUrl(QStringLiteral("www.scottlandyard.info"))); addressee.setUrl(url); addressee.setSecrecy(KContacts::Secrecy(KContacts::Secrecy::Public)); addressee.setLogo(logo); addressee.setPhoto(photo); addressee.setSound(sound); addressee.setEmails(emails); addressee.setKeys(keys); addressee.setCategories(categories); addressee.setCustoms(customs); addressee.setKind(QStringLiteral("foo")); addressee.setChanged(false); KContacts::Impp imp; imp.setType(KContacts::Impp::GaduGadu); imp.setAddress(QStringLiteral("*****@*****.**")); KContacts::Impp::List listImp; listImp << imp; addressee.setImppList(listImp); QVERIFY(addressee.imppList() == listImp); QVERIFY(addressee.langs() == (KContacts::Lang::List() << lang)); QVERIFY(addressee.gender() == gender); QVERIFY(addressee.uid() == QStringLiteral("My uid")); QVERIFY(addressee.name() == QStringLiteral("John Sinclair")); QVERIFY(addressee.formattedName() == QStringLiteral("Sinclair, John")); QVERIFY(addressee.familyName() == QStringLiteral("Sinclair")); QVERIFY(addressee.givenName() == QStringLiteral("John")); QVERIFY(addressee.additionalName() == QStringLiteral("Bob")); QVERIFY(addressee.prefix() == QStringLiteral("Sir")); QVERIFY(addressee.suffix() == QStringLiteral("II")); QVERIFY(addressee.nickName() == QStringLiteral("ghosthunter")); QVERIFY(addressee.birthday().date() == QDate(1982, 7, 19)); QVERIFY(addressee.birthday().time() == QTime(0, 0)); QVERIFY(!addressee.birthdayHasTime()); QVERIFY(addressee.mailer() == QStringLiteral("mutt")); QVERIFY(addressee.timeZone() == KContacts::TimeZone(2)); QVERIFY(addressee.geo() == KContacts::Geo(42, 23)); QVERIFY(addressee.title() == QStringLiteral("Ghost Hunter")); QVERIFY(addressee.role() == QStringLiteral("Leader")); QVERIFY(addressee.organization() == QStringLiteral("Scottland Yard")); QVERIFY(addressee.note() == QStringLiteral("Don't cross black deads way...")); QVERIFY(addressee.productId() == QStringLiteral("ProductId45")); QVERIFY(addressee.revision() == QDateTime(QDate(1982, 9, 15))); QVERIFY(addressee.sortString() == QStringLiteral("Name")); QVERIFY(addressee.url() == url); QVERIFY(addressee.secrecy() == KContacts::Secrecy(KContacts::Secrecy::Public)); QVERIFY(addressee.logo() == logo); QVERIFY(addressee.photo() == photo); QVERIFY(addressee.sound() == sound); QVERIFY(addressee.emails() == emails); QVERIFY(addressee.keys() == keys); QVERIFY(addressee.categories() == categories); QVERIFY(addressee.customs() == customs); QVERIFY(addressee.changed() == false); QCOMPARE(addressee.kind(), QStringLiteral("foo")); }
bool UserProfile::photoIsNull() const { return photo().isNull(); }
void FileLoadTask::process() { const QString stickerMime = qsl("image/webp"); _result = FileLoadResultPtr(new FileLoadResult(_id, _to, _originalText)); QString filename, filemime; qint64 filesize = 0; QByteArray filedata; uint64 thumbId = 0; QString thumbname = "thumb.jpg"; QByteArray thumbdata; bool animated = false, song = false, gif = false, voice = (_type == PrepareAudio); QImage fullimage = _image; if (!_filepath.isEmpty()) { QFileInfo info(_filepath); if (info.isDir()) { _result->filesize = -1; return; } filesize = info.size(); filemime = mimeTypeForFile(info).name(); filename = info.fileName(); if (filesize <= MaxUploadPhotoSize && !voice) { bool opaque = (filemime != stickerMime); fullimage = App::readImage(_filepath, 0, opaque, &animated); } } else if (!_content.isEmpty()) { filesize = _content.size(); if (voice) { filename = filedialogDefaultName(qsl("audio"), qsl(".ogg"), QString(), true); filemime = "audio/ogg"; } else { MimeType mimeType = mimeTypeForData(_content); filemime = mimeType.name(); if (filesize <= MaxUploadPhotoSize && !voice) { bool opaque = (filemime != stickerMime); fullimage = App::readImage(_content, 0, opaque, &animated); } if (filemime == "image/jpeg") { filename = filedialogDefaultName(qsl("image"), qsl(".jpg"), QString(), true); } else { QString ext; QStringList patterns = mimeType.globPatterns(); if (!patterns.isEmpty()) { ext = patterns.front().replace('*', QString()); } filename = filedialogDefaultName(qsl("file"), ext, QString(), true); } } } else if (!_image.isNull()) { _image = QImage(); filemime = mimeTypeForName("image/png").name(); filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true); { QBuffer buffer(&_content); fullimage.save(&buffer, "PNG"); } filesize = _content.size(); if (fullimage.hasAlphaChannel()) { QImage solid(fullimage.width(), fullimage.height(), QImage::Format_ARGB32_Premultiplied); solid.fill(st::white->c); { QPainter(&solid).drawImage(0, 0, fullimage); } fullimage = solid; } } _result->filesize = (int32)qMin(filesize, qint64(INT_MAX)); if (!filesize || filesize > MaxUploadDocumentSize) { return; } PreparedPhotoThumbs photoThumbs; QVector<MTPPhotoSize> photoSizes; QPixmap thumb; QVector<MTPDocumentAttribute> attributes(1, MTP_documentAttributeFilename(MTP_string(filename))); MTPPhotoSize thumbSize(MTP_photoSizeEmpty(MTP_string(""))); MTPPhoto photo(MTP_photoEmpty(MTP_long(0))); MTPDocument document(MTP_documentEmpty(MTP_long(0))); if (!voice) { if (filemime == qstr("audio/mp3") || filemime == qstr("audio/m4a") || filemime == qstr("audio/aac") || filemime == qstr("audio/ogg") || filemime == qstr("audio/flac") || filename.endsWith(qstr(".mp3"), Qt::CaseInsensitive) || filename.endsWith(qstr(".m4a"), Qt::CaseInsensitive) || filename.endsWith(qstr(".aac"), Qt::CaseInsensitive) || filename.endsWith(qstr(".ogg"), Qt::CaseInsensitive) || filename.endsWith(qstr(".flac"), Qt::CaseInsensitive)) { QImage cover; QByteArray coverBytes, coverFormat; MTPDocumentAttribute audioAttribute = audioReadSongAttributes(_filepath, _content, cover, coverBytes, coverFormat); if (audioAttribute.type() == mtpc_documentAttributeAudio) { attributes.push_back(audioAttribute); song = true; if (!cover.isNull()) { // cover to thumb int32 cw = cover.width(), ch = cover.height(); if (cw < 20 * ch && ch < 20 * cw) { QPixmap full = (cw > 90 || ch > 90) ? QPixmap::fromImage(cover.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(cover, Qt::ColorOnly); { QByteArray thumbFormat = "JPG"; int32 thumbQuality = 87; QBuffer buffer(&thumbdata); full.save(&buffer, thumbFormat, thumbQuality); } thumb = full; thumbSize = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); thumbId = rand_value<uint64>(); } } } } if (filemime == qstr("video/mp4") || filename.endsWith(qstr(".mp4"), Qt::CaseInsensitive) || animated) { QImage cover; MTPDocumentAttribute animatedAttribute = clipReadAnimatedAttributes(_filepath, _content, cover); if (animatedAttribute.type() == mtpc_documentAttributeVideo) { int32 cw = cover.width(), ch = cover.height(); if (cw < 20 * ch && ch < 20 * cw) { attributes.push_back(MTP_documentAttributeAnimated()); attributes.push_back(animatedAttribute); gif = true; QPixmap full = (cw > 90 || ch > 90) ? QPixmap::fromImage(cover.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(cover, Qt::ColorOnly); { QByteArray thumbFormat = "JPG"; int32 thumbQuality = 87; QBuffer buffer(&thumbdata); full.save(&buffer, thumbFormat, thumbQuality); } thumb = full; thumbSize = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); thumbId = rand_value<uint64>(); if (filename.endsWith(qstr(".mp4"), Qt::CaseInsensitive)) { filemime = qstr("video/mp4"); } } } } } if (!fullimage.isNull() && fullimage.width() > 0 && !song && !gif && !voice) { int32 w = fullimage.width(), h = fullimage.height(); attributes.push_back(MTP_documentAttributeImageSize(MTP_int(w), MTP_int(h))); if (w < 20 * h && h < 20 * w) { if (animated) { attributes.push_back(MTP_documentAttributeAnimated()); } else if (_type != PrepareDocument) { QPixmap thumb = (w > 100 || h > 100) ? QPixmap::fromImage(fullimage.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(fullimage); photoThumbs.insert('s', thumb); photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0))); QPixmap medium = (w > 320 || h > 320) ? QPixmap::fromImage(fullimage.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(fullimage); photoThumbs.insert('m', medium); photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0))); QPixmap full = (w > 1280 || h > 1280) ? QPixmap::fromImage(fullimage.scaled(1280, 1280, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(fullimage); photoThumbs.insert('y', full); photoSizes.push_back(MTP_photoSize(MTP_string("y"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0))); { QBuffer buffer(&filedata); full.save(&buffer, "JPG", 77); } photo = MTP_photo(MTP_long(_id), MTP_long(0), MTP_int(unixtime()), MTP_vector<MTPPhotoSize>(photoSizes)); } QByteArray thumbFormat = "JPG"; int32 thumbQuality = 87; if (!animated && filemime == stickerMime && w > 0 && h > 0 && w <= StickerMaxSize && h <= StickerMaxSize && filesize < StickerInMemory) { attributes.push_back(MTP_documentAttributeSticker(MTP_string(""), MTP_inputStickerSetEmpty())); thumbFormat = "webp"; thumbname = qsl("thumb.webp"); } QPixmap full = (w > 90 || h > 90) ? QPixmap::fromImage(fullimage.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(fullimage, Qt::ColorOnly); { QBuffer buffer(&thumbdata); full.save(&buffer, thumbFormat, thumbQuality); } thumb = full; thumbSize = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); thumbId = rand_value<uint64>(); } } if (voice) { attributes[0] = MTP_documentAttributeAudio(MTP_flags(MTPDdocumentAttributeAudio::Flag::f_voice | MTPDdocumentAttributeAudio::Flag::f_waveform), MTP_int(_duration), MTPstring(), MTPstring(), MTP_bytes(documentWaveformEncode5bit(_waveform))); attributes.resize(1); document = MTP_document(MTP_long(_id), MTP_long(0), MTP_int(unixtime()), MTP_string(filemime), MTP_int(filesize), thumbSize, MTP_int(MTP::maindc()), MTP_vector<MTPDocumentAttribute>(attributes)); } else { document = MTP_document(MTP_long(_id), MTP_long(0), MTP_int(unixtime()), MTP_string(filemime), MTP_int(filesize), thumbSize, MTP_int(MTP::maindc()), MTP_vector<MTPDocumentAttribute>(attributes)); if (photo.type() == mtpc_photoEmpty) { _type = PrepareDocument; } } _result->type = _type; _result->filepath = _filepath; _result->content = _content; _result->filename = filename; _result->filemime = filemime; _result->setFileData(filedata); _result->thumbId = thumbId; _result->thumbname = thumbname; _result->setThumbData(thumbdata); _result->thumb = thumb; _result->photo = photo; _result->document = document; _result->photoThumbs = photoThumbs; }
AMANetworkReplyProxy::AMANetworkReplyProxy(QObject *parent, const QNetworkRequest &req, const QNetworkAccessManager::Operation op, AMAQtBridge *bridge) : m_bridge(bridge), m_imgs(0), QNetworkReply(parent) { /// [Request stuff] setRequest(req); setOperation(op); setUrl(req.url()); QNetworkReply::open(QIODevice::ReadOnly | QIODevice::Unbuffered); /// End [Request stuff] /// [Response-data stuff] m_lOffset = 0; m_content.clear(); /// End [Response-data stuff] QString sReq = req.url().toString(); QString fileExtension; if (sReq.startsWith("qrc:/data/")) { if (op == QNetworkAccessManager::PostOperation) { /// Upload this->open(QIODevice::ReadOnly | QIODevice::Text); qDebug() << op << QString( this->readAll() ) << this->isOpen() << this->isReadable() << this->size(); this->close(); } else { /// Serving JSON data QStringList dataRequested = req2DataRequested(req); fileExtension = dataRequested.last().toUpper(); QStringList dataRequestOpts; dataRequestOpts << "COMPOUNDDATA" << "RENDERFIELDS" << "RENDERGROUPINFO" << "QUERYFIELDS" << "QUERYGROUPINFO" << "HRFCORR" << "AMAVIEWS" << "LEGEND"; QJsonArray a; QJsonObject o; switch(dataRequestOpts.indexOf(dataRequested.first().toUpper())) { case 0: { QVariantList d = bridge->getData(); a = QJsonArray::fromVariantList(d); break; } case 1: { QVariantList d = bridge->getRenderFields(); a = QJsonArray::fromVariantList(d); break; } case 2: { QVariantMap d = bridge->getRendergroupinfo(); o = QJsonObject::fromVariantMap(d); break; } case 3: { QVariantList d = bridge->getQueryfields(); a = QJsonArray::fromVariantList(d); break; } case 4: { QVariantMap d = bridge->getQuerygroupinfo(); o = QJsonObject::fromVariantMap(d); break; } case 5: { QVariantList d = bridge->getHrfCorr(); a = QJsonArray::fromVariantList(d); break; } case 6: { QVariantList d = bridge->getAmaviews(); a = QJsonArray::fromVariantList(d); break; } case 7: { QString txt = bridge->getMetaSetting("legend"); QVariantMap d; d.insert("legend", txt); o = QJsonObject::fromVariantMap(d); break; } default: qWarning() << "Cannot handle request " << dataRequested.first().toUpper() << ". Unknown resource."; } QJsonDocument doc; if (a.size()) { doc = QJsonDocument(a); } else { doc = QJsonDocument(o); } // Create the JSONP-response // We're using JSONP because this works cross-site in // all browsers, even on localhost or file which is // (the latter is restricted by Opera, for example, even // when doing the AJAX from a HTML page saved on the local // file system) m_content .append( "window['" ) .append( dataRequested.first().toUtf8().replace("'", "\\'") ) .append( "']" ) .append( "(" ) .append( doc.toJson(QJsonDocument::Compact) ) .append( ");" ); } } else if (sReq.startsWith("qrc:/images/GHS/")) { // Since filtered later and the request may arrive from different threads, // better use our own model // This is not the bottlenack; the slow client side JavaScript execution, however is. m_imgs = new QSqlRelationalTableModel(this); m_imgs->setTable("ghs"); // CAVE: Ugly and possibly exploitable (SQL-injection) QStringList filename = req2FilenameParts(req); fileExtension = filename.last().toUpper(); m_imgs->setFilter("ghs_code='" + filename.first() + "'"); m_imgs->select(); // Set response-body content. Since some browsers have the habit // asking multiple times for the same stuff, only parts (HTTP-range-request), // to boost performance, we read them once and store these little // formula files in memory. QByteArray qba = m_imgs->record(0).value("ghs_" + fileExtension.toLower()).toByteArray(); if (qba.length() == 0) { qWarning() << " GHS: No " << fileExtension << " for " << filename.first(); } m_content.append(qba); } else if (sReq.startsWith("qrc:/formulae/")) { // Since filtered later and the request may arrive from different threads, // better use our own model // This is not the bottlenack; the slow client side JavaScript execution, however is. m_imgs = new QSqlRelationalTableModel(this); m_imgs->setTable("FORMULAE"); m_imgs->setRelation(m_imgs->fieldIndex("compound_id"), QSqlRelation("COMPOUNDS", bridge->m_id_field, "c_structure_name")); // CAVE: Ugly and possibly exploitable (SQL-injection) QStringList filename = req2FilenameParts(req); fileExtension = filename.last().toUpper(); m_imgs->setFilter("c_structure_name='" + filename.first() + "'"); m_imgs->select(); // Set response-body content. Since some browsers have the habit // asking multiple times for the same stuff, only parts (HTTP-range-request), // to boost performance, we read them once and store these little // formula files in memory. QByteArray qba = m_imgs->record(0).value(fileExtension).toByteArray(); if (qba.length() == 0) { qWarning() << " FROMULA: No " << fileExtension << " for " << filename.first() << req.url().path(); } m_content.append(qba); } else if (sReq.startsWith("qrc:/images/photos/")) { QStringList photoName = req2FilenameParts(req); QDir photoDir(*(m_bridge->m_app_dir) + "/" + "photos"); if (photoDir.exists()) { QString photoPath = photoDir.absoluteFilePath(photoName.first() + '.' + photoName.last()); QFile photo(photoPath); photo.open(QIODevice::ReadOnly); m_content.append(photo.readAll()); photo.close(); } } QString mime; // C++ cannot switch-by-string, even if constant. Using a helper construct. QStringList fileExtensions; fileExtensions << "PNG" << "JPG" << "JPEG" << "SVG" << "JS"; switch(fileExtensions.indexOf(fileExtension)) { case 0: mime = "image/png"; break; case 1: case 2: mime = "image/jpeg"; break; case 3: mime = "image/svg+xml"; break; case 4: mime = "text/javascript;charset=utf-8"; break; default: mime = "application/octet-stream"; } // Set 200 OK - status setAttribute( QNetworkRequest::HttpStatusCodeAttribute, QVariant( 200 ) ); // Set reply size setHeader( QNetworkRequest::ContentLengthHeader, QVariant( m_content.size() ) ); // Please do not cache (but the browser does anyway) setRawHeader("Cache-Control", "must-revalidate"); setHeader(QNetworkRequest::LastModifiedHeader, QDateTime::currentDateTimeUtc()); // That way the browser does not offer the resource for download or does other strange things if ( mime.length() ) setHeader( QNetworkRequest::ContentTypeHeader, QVariant( mime.toUtf8() ) ); // Allow "cross site resource usage". Nothing confidental here. // Prevents for example that canvas gets polluted, ... setRawHeader( "Access-Control-Allow-Origin", "*" ); // Call notify functions QMetaObject::invokeMethod( this, "metaDataChanged", Qt::QueuedConnection ); QMetaObject::invokeMethod( this, "readyRead", Qt::QueuedConnection ); QMetaObject::invokeMethod( this, "downloadProgress", Qt::QueuedConnection, Q_ARG( qint64, m_content.size() ), Q_ARG( qint64, m_content.size() ) ); QMetaObject::invokeMethod( this, "finished", Qt::QueuedConnection ); setFinished(true); // Created on the heap but not required anymore if (m_imgs) { m_imgs->clear(); m_imgs->deleteLater(); } }
void LocalImageLoaderPrivate::prepareImages() { QString file, filename, mime, stickerMime = qsl("image/webp"); int32 filesize = 0; QImage img; QByteArray data; PeerId peer; uint64 id, thumbId = 0; int32 duration = 0; QString thumbExt = "jpg"; ToPrepareMediaType type; bool animated = false; bool ctrlShiftEnter = false; MsgId replyTo = 0; { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); if (list.isEmpty()) return; file = list.front().file; img = list.front().img; data = list.front().data; peer = list.front().peer; id = list.front().id; type = list.front().type; duration = list.front().duration; ctrlShiftEnter = list.front().ctrlShiftEnter; replyTo = list.front().replyTo; } if (img.isNull()) { if (!file.isEmpty()) { QFileInfo info(file); if (type == ToPrepareAuto) { QString lower(file.toLower()); const QStringList &photoExtensions(cPhotoExtensions()); for (QStringList::const_iterator i = photoExtensions.cbegin(), e = photoExtensions.cend(); i != e; ++i) { if (lower.lastIndexOf(*i) == lower.size() - i->size()) { if (info.size() < MaxUploadPhotoSize) { type = ToPreparePhoto; break; } } } if (type == ToPrepareAuto && info.size() < MaxUploadDocumentSize) { type = ToPrepareDocument; } } if (type == ToPrepareDocument) { mime = mimeTypeForFile(info).name(); } if (type != ToPrepareAuto && info.size() < MaxUploadPhotoSize) { bool opaque = (mime != stickerMime); img = App::readImage(file, 0, opaque, &animated); } filename = info.fileName(); filesize = info.size(); } else if (!data.isEmpty()) { if (type != ToPrepareAudio) { img = App::readImage(data, 0, true, &animated); if (type == ToPrepareAuto) { if (!img.isNull() && data.size() < MaxUploadPhotoSize) { type = ToPreparePhoto; } else if (data.size() < MaxUploadDocumentSize) { type = ToPrepareDocument; } else { img = QImage(); } } } MimeType mimeType = mimeTypeForData(data); if (type == ToPrepareDocument || type == ToPrepareAudio) { mime = mimeType.name(); } if (mime == "image/jpeg") { filename = filedialogDefaultName(qsl("image"), qsl(".jpg"), QString(), true); } else if (type == ToPrepareAudio) { filename = filedialogDefaultName(qsl("audio"), qsl(".ogg"), QString(), true); mime = "audio/ogg"; } else { QString ext; QStringList patterns = mimeType.globPatterns(); if (!patterns.isEmpty()) { ext = patterns.front().replace('*', QString()); } filename = filedialogDefaultName((type == ToPrepareAudio) ? qsl("audio") : qsl("doc"), ext, QString(), true); } filesize = data.size(); } } else { if (type == ToPrepareDocument) { filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true); mime = mimeTypeForName("image/png").name(); data = QByteArray(); { QBuffer b(&data); img.save(&b, "PNG"); } filesize = data.size(); } else { if (img.hasAlphaChannel()) { QImage solid(img.width(), img.height(), QImage::Format_ARGB32_Premultiplied); solid.fill(st::white->c); { QPainter(&solid).drawImage(0, 0, img); } img = solid; } type = ToPreparePhoto; filename = qsl("Untitled.jpg"); filesize = 0; } } if ((img.isNull() && ((type != ToPrepareDocument && type != ToPrepareAudio) || !filesize)) || type == ToPrepareAuto || (img.isNull() && file.isEmpty() && data.isEmpty())) { // if could not decide what type { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); list.pop_front(); } QTimer::singleShot(1, this, SLOT(prepareImages())); emit imageFailed(id); } else { PreparedPhotoThumbs photoThumbs; QVector<MTPPhotoSize> photoSizes; QVector<MTPDocumentAttribute> attributes(1, MTP_documentAttributeFilename(MTP_string(filename))); MTPPhotoSize thumb(MTP_photoSizeEmpty(MTP_string(""))); MTPPhoto photo(MTP_photoEmpty(MTP_long(0))); MTPDocument document(MTP_documentEmpty(MTP_long(0))); MTPAudio audio(MTP_audioEmpty(MTP_long(0))); QByteArray jpeg; if (type == ToPreparePhoto) { int32 w = img.width(), h = img.height(); QPixmap thumb = (w > 100 || h > 100) ? QPixmap::fromImage(img.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img); photoThumbs.insert('s', thumb); photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0))); QPixmap medium = (w > 320 || h > 320) ? QPixmap::fromImage(img.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img); photoThumbs.insert('m', medium); photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0))); QPixmap full = (w > 1280 || h > 1280) ? QPixmap::fromImage(img.scaled(1280, 1280, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img); photoThumbs.insert('y', full); photoSizes.push_back(MTP_photoSize(MTP_string("y"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0))); { QBuffer jpegBuffer(&jpeg); full.save(&jpegBuffer, "JPG", 77); } if (!filesize) filesize = jpeg.size(); photo = MTP_photo(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes)); thumbId = id; } else if ((type == ToPrepareVideo || type == ToPrepareDocument) && !img.isNull()) { int32 w = img.width(), h = img.height(); QByteArray thumbFormat = "JPG"; int32 thumbQuality = 87; if (animated) { attributes.push_back(MTP_documentAttributeAnimated()); } else if (mime == stickerMime && w > 0 && h > 0 && w <= StickerMaxSize && h <= StickerMaxSize && filesize < StickerInMemory) { attributes.push_back(MTP_documentAttributeSticker(MTP_string(""), MTP_inputStickerSetEmpty())); thumbFormat = "webp"; thumbExt = qsl("webp"); } attributes.push_back(MTP_documentAttributeImageSize(MTP_int(w), MTP_int(h))); if (w < 20 * h && h < 20 * w) { QPixmap full = (w > 90 || h > 90) ? QPixmap::fromImage(img.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img, Qt::ColorOnly); { QBuffer jpegBuffer(&jpeg); full.save(&jpegBuffer, thumbFormat, thumbQuality); } photoThumbs.insert('0', full); thumb = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); thumbId = MTP::nonce<uint64>(); } } if (type == ToPrepareDocument) { document = MTP_document(MTP_long(id), MTP_long(0), MTP_int(unixtime()), MTP_string(mime), MTP_int(filesize), thumb, MTP_int(MTP::maindc()), MTP_vector<MTPDocumentAttribute>(attributes)); } else if (type == ToPrepareAudio) { audio = MTP_audio(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_int(duration), MTP_string(mime), MTP_int(filesize), MTP_int(MTP::maindc())); } { QMutexLocker lock(loader->readyMutex()); loader->readyList().push_back(ReadyLocalMedia(type, file, filename, filesize, data, id, thumbId, thumbExt, peer, photo, audio, photoThumbs, document, jpeg, ctrlShiftEnter, replyTo)); } { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); list.pop_front(); } QTimer::singleShot(1, this, SLOT(prepareImages())); emit imageReady(); } }
void FileLoadTask::process() { const QString stickerMime = qsl("image/webp"); _result = MakeShared<FileLoadResult>(_id, _to, _caption); QString filename, filemime; qint64 filesize = 0; QByteArray filedata; uint64 thumbId = 0; QString thumbname = "thumb.jpg"; QByteArray thumbdata; auto animated = false; auto song = false; auto gif = false; auto voice = (_type == SendMediaType::Audio); auto fullimage = base::take(_image); auto info = _filepath.isEmpty() ? QFileInfo() : QFileInfo(_filepath); if (info.exists()) { if (info.isDir()) { _result->filesize = -1; return; } filesize = info.size(); filemime = mimeTypeForFile(info).name(); filename = info.fileName(); auto opaque = (filemime != stickerMime); fullimage = App::readImage(_filepath, 0, opaque, &animated); } else if (!_content.isEmpty()) { filesize = _content.size(); if (voice) { filename = filedialogDefaultName(qsl("audio"), qsl(".ogg"), QString(), true); filemime = "audio/ogg"; } else { auto mimeType = mimeTypeForData(_content); filemime = mimeType.name(); if (filemime != stickerMime) { fullimage = Images::prepareOpaque(std_::move(fullimage)); } if (filemime == "image/jpeg") { filename = filedialogDefaultName(qsl("photo"), qsl(".jpg"), QString(), true); } else if (filemime == "image/png") { filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true); } else { QString ext; QStringList patterns = mimeType.globPatterns(); if (!patterns.isEmpty()) { ext = patterns.front().replace('*', QString()); } filename = filedialogDefaultName(qsl("file"), ext, QString(), true); } } } else if (!fullimage.isNull() && fullimage.width() > 0) { if (_type == SendMediaType::Photo) { auto w = fullimage.width(), h = fullimage.height(); if (w >= 20 * h || h >= 20 * w) { _type = SendMediaType::File; } else { filesize = -1; // Fill later. filemime = mimeTypeForName("image/jpeg").name(); filename = filedialogDefaultName(qsl("image"), qsl(".jpg"), QString(), true); } } if (_type == SendMediaType::File) { filemime = mimeTypeForName("image/png").name(); filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true); { QBuffer buffer(&_content); fullimage.save(&buffer, "PNG"); } filesize = _content.size(); } fullimage = Images::prepareOpaque(std_::move(fullimage)); } _result->filesize = (int32)qMin(filesize, qint64(INT_MAX)); if (!filesize || filesize > App::kFileSizeLimit) { return; } PreparedPhotoThumbs photoThumbs; QVector<MTPPhotoSize> photoSizes; QPixmap thumb; QVector<MTPDocumentAttribute> attributes(1, MTP_documentAttributeFilename(MTP_string(filename))); MTPPhotoSize thumbSize(MTP_photoSizeEmpty(MTP_string(""))); MTPPhoto photo(MTP_photoEmpty(MTP_long(0))); MTPDocument document(MTP_documentEmpty(MTP_long(0))); if (!voice) { if (filemime == qstr("audio/mp3") || filemime == qstr("audio/m4a") || filemime == qstr("audio/aac") || filemime == qstr("audio/ogg") || filemime == qstr("audio/flac") || filename.endsWith(qstr(".mp3"), Qt::CaseInsensitive) || filename.endsWith(qstr(".m4a"), Qt::CaseInsensitive) || filename.endsWith(qstr(".aac"), Qt::CaseInsensitive) || filename.endsWith(qstr(".ogg"), Qt::CaseInsensitive) || filename.endsWith(qstr(".flac"), Qt::CaseInsensitive)) { QImage cover; QByteArray coverBytes, coverFormat; MTPDocumentAttribute audioAttribute = audioReadSongAttributes(_filepath, _content, cover, coverBytes, coverFormat); if (audioAttribute.type() == mtpc_documentAttributeAudio) { attributes.push_back(audioAttribute); song = true; if (!cover.isNull()) { // cover to thumb int32 cw = cover.width(), ch = cover.height(); if (cw < 20 * ch && ch < 20 * cw) { QPixmap full = (cw > 90 || ch > 90) ? App::pixmapFromImageInPlace(cover.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : App::pixmapFromImageInPlace(std_::move(cover)); { QByteArray thumbFormat = "JPG"; int32 thumbQuality = 87; QBuffer buffer(&thumbdata); full.save(&buffer, thumbFormat, thumbQuality); } thumb = full; thumbSize = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); thumbId = rand_value<uint64>(); } } } } if (filemime == qstr("video/mp4") || filename.endsWith(qstr(".mp4"), Qt::CaseInsensitive) || animated) { QImage cover; MTPDocumentAttribute animatedAttribute = Media::Clip::readAttributes(_filepath, _content, cover); if (animatedAttribute.type() == mtpc_documentAttributeVideo) { int32 cw = cover.width(), ch = cover.height(); if (cw < 20 * ch && ch < 20 * cw) { attributes.push_back(MTP_documentAttributeAnimated()); attributes.push_back(animatedAttribute); gif = true; QPixmap full = (cw > 90 || ch > 90) ? App::pixmapFromImageInPlace(cover.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : App::pixmapFromImageInPlace(std_::move(cover)); { QByteArray thumbFormat = "JPG"; int32 thumbQuality = 87; QBuffer buffer(&thumbdata); full.save(&buffer, thumbFormat, thumbQuality); } thumb = full; thumbSize = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); thumbId = rand_value<uint64>(); if (filename.endsWith(qstr(".mp4"), Qt::CaseInsensitive)) { filemime = qstr("video/mp4"); } } } } } if (!fullimage.isNull() && fullimage.width() > 0 && !song && !gif && !voice) { auto w = fullimage.width(), h = fullimage.height(); attributes.push_back(MTP_documentAttributeImageSize(MTP_int(w), MTP_int(h))); if (w < 20 * h && h < 20 * w) { if (animated) { attributes.push_back(MTP_documentAttributeAnimated()); } else if (_type != SendMediaType::File) { auto thumb = (w > 100 || h > 100) ? App::pixmapFromImageInPlace(fullimage.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(fullimage); photoThumbs.insert('s', thumb); photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0))); auto medium = (w > 320 || h > 320) ? App::pixmapFromImageInPlace(fullimage.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(fullimage); photoThumbs.insert('m', medium); photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0))); auto full = (w > 1280 || h > 1280) ? App::pixmapFromImageInPlace(fullimage.scaled(1280, 1280, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(fullimage); photoThumbs.insert('y', full); photoSizes.push_back(MTP_photoSize(MTP_string("y"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0))); { QBuffer buffer(&filedata); full.save(&buffer, "JPG", 87); } MTPDphoto::Flags photoFlags = 0; photo = MTP_photo(MTP_flags(photoFlags), MTP_long(_id), MTP_long(0), MTP_int(unixtime()), MTP_vector<MTPPhotoSize>(photoSizes)); if (filesize < 0) { filesize = _result->filesize = filedata.size(); } } QByteArray thumbFormat = "JPG"; int32 thumbQuality = 87; if (!animated && filemime == stickerMime && w > 0 && h > 0 && w <= StickerMaxSize && h <= StickerMaxSize && filesize < StickerInMemory) { MTPDdocumentAttributeSticker::Flags stickerFlags = 0; attributes.push_back(MTP_documentAttributeSticker(MTP_flags(stickerFlags), MTP_string(""), MTP_inputStickerSetEmpty(), MTPMaskCoords())); thumbFormat = "webp"; thumbname = qsl("thumb.webp"); } QPixmap full = (w > 90 || h > 90) ? App::pixmapFromImageInPlace(fullimage.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(fullimage, Qt::ColorOnly); { QBuffer buffer(&thumbdata); full.save(&buffer, thumbFormat, thumbQuality); } thumb = full; thumbSize = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); thumbId = rand_value<uint64>(); } } if (voice) { attributes[0] = MTP_documentAttributeAudio(MTP_flags(MTPDdocumentAttributeAudio::Flag::f_voice | MTPDdocumentAttributeAudio::Flag::f_waveform), MTP_int(_duration), MTPstring(), MTPstring(), MTP_bytes(documentWaveformEncode5bit(_waveform))); attributes.resize(1); document = MTP_document(MTP_long(_id), MTP_long(0), MTP_int(unixtime()), MTP_string(filemime), MTP_int(filesize), thumbSize, MTP_int(MTP::maindc()), MTP_int(0), MTP_vector<MTPDocumentAttribute>(attributes)); } else if (_type != SendMediaType::Photo) { document = MTP_document(MTP_long(_id), MTP_long(0), MTP_int(unixtime()), MTP_string(filemime), MTP_int(filesize), thumbSize, MTP_int(MTP::maindc()), MTP_int(0), MTP_vector<MTPDocumentAttribute>(attributes)); _type = SendMediaType::File; } _result->type = _type; _result->filepath = _filepath; _result->content = _content; _result->filename = filename; _result->filemime = filemime; _result->setFileData(filedata); _result->thumbId = thumbId; _result->thumbname = thumbname; _result->setThumbData(thumbdata); _result->thumb = thumb; _result->photo = photo; _result->document = document; _result->photoThumbs = photoThumbs; }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->setWindowTitle("La CubiRoulette!"); srand(time(NULL)); QFile *f = new QFile("data/eleves.csv"); unknown = QPixmap ("data/img/unknown.png"); if(f->open(QFile::ReadOnly)) { QString content = QString(f->readAll()); content = content.remove("\n"); playersList = content.split(";"); qDebug() << playersList.size() << " noms chargés!"; } else { QMessageBox::warning(this,"Erreur","Problème d'ouverture du fichier data/eleves.csv","OK"); for(int i=0;i<48;i++) { playersList << QString::number(i); } } std::random_shuffle(playersList.begin(), playersList.end()); for(int i=0;i<playersList.size();i++) { QString path = "data/img/"+playersList[i].replace(" ","_")+".png"; QPixmap photo(path); if(photo.isNull()) { QString name = playersList[i]; QString init = ""; for(int c=0;c<name.size();c++) { if(name[c].isUpper()) { init += name[c]; } } QPixmap u("data/img/unknown.png"); QPainter p(&u); p.setRenderHint(QPainter::Antialiasing); int fontSize = 42; if(init.size() == 2) { fontSize = 130; } else if(init.size() == 3) { fontSize = 100; } else { fontSize = 70; } p.setFont(QFont("Ubuntu",fontSize)); QFontMetrics fm = p.fontMetrics(); QPoint center = QPoint( ( u.width()-fm.width(init))/2,300+( - fm.height())/2 ); p.drawText(center,init); photos.append(u); } else { photos.append(photo); } playersList[i].replace("_"," "); } graphicalInit(); rsim = new RouletteSimulator(playersList.size()); connect(rsim, SIGNAL(afterUpdate(int)),this,SLOT(graphicalUpdate(int))); }
void PhotoSaveClickHandler::onClickImpl() const { auto data = photo(); if (!data->date) return; data->download(context()); }