Example #1
0
    def _create_metallic_roughness_map(self, metal_map, rough_map):

        metal = QImage(metal_map)
        rough = QImage(rough_map)
        metal_pixel = QColor()

        metal = metal.convertToFormat(QImage.Format_RGB32);
        rough = rough.convertToFormat(QImage.Format_RGB32);
        metal_uchar_ptr = metal.bits()
        rough_uchar_ptr = rough.bits()
        if (not metal.width() == rough.width()
                or not metal.height() == rough.height()):
            raise RuntimeError("Error processing material: {}. Metallic map and roughness map must have same dimensions.".format(self.maya_node))
        width = metal.width();
        height = metal.height();

        i = 0
        for y in range(height):
            for x in range(width):
                metal_color = struct.unpack('I', metal_uchar_ptr[i:i+4])[0]
                rough_color = struct.unpack('I', rough_uchar_ptr[i:i+4])[0]
                metal_pixel.setRgb(0, qGreen(rough_color), qBlue(metal_color))
                metal_uchar_ptr[i:i+4] = struct.pack('I', metal_pixel.rgb())
                i+=4
                
        output = ExportSettings.out_dir + "/"+self.name+"_metalRough.jpg"
        return output, metal
Example #2
0
    def _create_metallic_roughness_map(self, metal_map, rough_map):

        metal = QImage(metal_map)
        rough = QImage(rough_map)
        metal_pixel = QColor()

        metal = metal.convertToFormat(QImage.Format_RGB32)
        rough = rough.convertToFormat(QImage.Format_RGB32)
        metal_uchar_ptr = metal.bits()
        rough_uchar_ptr = rough.bits()
        if (not metal.width() == rough.width()
                or not metal.height() == rough.height()):
            raise RuntimeError(
                "Error processing material: {}. Metallic map and roughness map must have same dimensions."
                .format(self.maya_node))
        width = metal.width()
        height = metal.height()

        i = 0
        for y in range(height):
            for x in range(width):
                metal_color = struct.unpack('I', metal_uchar_ptr[i:i + 4])[0]
                rough_color = struct.unpack('I', rough_uchar_ptr[i:i + 4])[0]
                metal_pixel.setRgb(0, qGreen(rough_color), qBlue(metal_color))
                metal_uchar_ptr[i:i + 4] = struct.pack('I', metal_pixel.rgb())
                i += 4

        output = ExportSettings.out_dir + "/" + self.name + "_metalRough.jpg"
        return output, metal
Example #3
0
	def sendLocation(self, jid, latitude, longitude, rotate):
		latitude = latitude[:10]
		longitude = longitude[:10]

		self._d("Capturing preview...")
		QPixmap.grabWindow(QApplication.desktop().winId()).save(WAConstants.CACHE_PATH+"/tempimg.png", "PNG")
		img = QImage(WAConstants.CACHE_PATH+"/tempimg.png")

		if rotate == "true":
			rot = QTransform()
			rot = rot.rotate(90)
			img = img.transformed(rot)

		if img.height() > img.width():
			result = img.scaledToWidth(320,Qt.SmoothTransformation);
			result = result.copy(result.width()/2-50,result.height()/2-50,100,100);
		elif img.height() < img.width():
			result = img.scaledToHeight(320,Qt.SmoothTransformation);
			result = result.copy(result.width()/2-50,result.height()/2-50,100,100);
		#result = img.scaled(96, 96, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation);

		result.save( WAConstants.CACHE_PATH+"/tempimg2.jpg", "JPG" );

		f = open(WAConstants.CACHE_PATH+"/tempimg2.jpg", 'r')
		stream = base64.b64encode(f.read())
		f.close()


		os.remove(WAConstants.CACHE_PATH+"/tempimg.png")
		os.remove(WAConstants.CACHE_PATH+"/tempimg2.jpg")

		fmsg = WAXMPP.message_store.createMessage(jid);
		
		mediaItem = WAXMPP.message_store.store.Media.create()
		mediaItem.mediatype_id = WAConstants.MEDIA_TYPE_LOCATION
		mediaItem.remote_url = None
		mediaItem.preview = stream
		mediaItem.local_path ="%s,%s"%(latitude,longitude)
		mediaItem.transfer_status = 2

		fmsg.content = QtCore.QCoreApplication.translate("WAEventHandler", "Location")
		fmsg.Media = mediaItem

		if fmsg.Conversation.type == "group":
			contact = WAXMPP.message_store.store.Contact.getOrCreateContactByJid(self.conn.jid)
			fmsg.setContact(contact);
		
		fmsg.setData({"status":0,"content":fmsg.content,"type":1})
		WAXMPP.message_store.pushMessage(jid,fmsg)
		
		
		resultId = self.interfaceHandler.call("message_locationSend", (jid, latitude, longitude, stream))
		k = Key(jid, True, resultId)
		fmsg.key = k.toString()
		fmsg.save()
Example #4
0
class RatingDelegate(NoFocusDelegate):
    """
    Star Rating Item Delegate
    
    Model View Delegate which draws a rating score between zero and five as a
    line of zero to five star glyphs.  A custom star glyph can be passed to the
    constructor, otherwise a resource named '/icons/star.png' is used.
    
    See also RatingEditor.
    """

    # TODO: Create RatingEditor and link here
    def __init__(self, parent=None, star=None):
        super(RatingDelegate, self).__init__(parent)

        if star is None:
            self._star = QImage(":/icons/star.png")
        elif not isinstance(star, QImage):
            raise TypeError("Star Image must be a descendant of QImage")
        else:
            self._star = star

    def paint(self, p, option, index):
        p.save()

        self.drawBackground(p, option, index)
        rating = index.data()
        width = self._star.width()

        y = (option.rect.height() - self._star.height()) / 2
        p.translate(option.rect.left(), option.rect.top())

        for i in range(0, 5):
            if rating >= (i + 1):
                p.drawImage(i * (width + 1), y, self._star)

        p.restore()

    def sizeHint(self, option, index):
        return QSize((self._star.width() + 2) * 5, self._star.height() + 2)

    def setStarImage(self, star):
        "Set the Star Image"
        if not isinstance(star, QImage):
            raise TypeError("Star Image must be a descendant of QImage")
        self._star = star

    def starImage(self):
        return self._star
Example #5
0
	def sendMediaVideoFile(self,jid,video,image):
		self._d("creating VIDEO MMS for " +jid + " - file: " + video)
		fmsg = WAXMPP.message_store.createMessage(jid);

		if image == "NOPREVIEW":
			m = hashlib.md5()
			url = QtCore.QUrl(video).toEncoded()
			m.update(url)
			image = WAConstants.THUMBS_PATH + "/screen/" + m.hexdigest() + ".jpeg"
		else:
			image = image.replace("file://","")

		user_img = QImage(image)
		if user_img.height() > user_img.width():
			preimg = QPixmap.fromImage(QImage(user_img.scaledToWidth(64, Qt.SmoothTransformation)))
		elif user_img.height() < user_img.width():
			preimg = QPixmap.fromImage(QImage(user_img.scaledToHeight(64, Qt.SmoothTransformation)))
		else:
			preimg = QPixmap.fromImage(QImage(user_img.scaled(64, 64, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)))
		preimg.save(WAConstants.CACHE_PATH+"/temp2.png", "PNG")

		f = open(WAConstants.CACHE_PATH+"/temp2.png", 'r')
		stream = base64.b64encode(f.read())
		f.close()

		mediaItem = WAXMPP.message_store.store.Media.create()
		mediaItem.mediatype_id = 4
		mediaItem.local_path = video.replace("file://","")
		mediaItem.transfer_status = 0
		mediaItem.preview = stream
		
		try:
			mediaItem.size = os.path.getsize(mediaItem.local_path)
		except:
			pass

		fmsg.content = QtCore.QCoreApplication.translate("WAEventHandler", "Video")
		fmsg.Media = mediaItem

		if fmsg.Conversation.type == "group":
			contact = WAXMPP.message_store.store.Contact.getOrCreateContactByJid(self.conn.jid)
			fmsg.setContact(contact);
		
		fmsg.setData({"status":0,"content":fmsg.content,"type":1})
		WAXMPP.message_store.pushMessage(jid,fmsg)
Example #6
0
	def _getPictureForSending(self, jid, filepath):
		print "Preparing picture " + filepath + " for " + jid
		image = filepath.replace("file://","")
		rotation = 0

		ret = {}
		im = Image.open(image)
		try:
			info = im._getexif()
			for tag, value in info.items():
				decoded = TAGS.get(tag, value)
				ret[decoded] = value
			if ret['Orientation'] == 6:
				rotation = 90
		except:
			rotation = 0

		user_img = QImage(image)

		if rotation == 90:
			rot = QTransform()
			rot = rot.rotate(90)
			user_img = user_img.transformed(rot)


		if user_img.height() > user_img.width():
			preimg = user_img.scaledToWidth(480, Qt.SmoothTransformation)
			preimg = preimg.copy( 0, preimg.height()/2-240, 480, 480);
		elif user_img.height() < user_img.width():
			preimg = user_img.scaledToHeight(480, Qt.SmoothTransformation)
			preimg = preimg.copy( preimg.width()/2-240, 0, 480, 480);
		else:
			preimg = user_img.scaled(480, 480, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)

		preimg.save(WAConstants.CACHE_PATH+"/temp.jpg", "JPG")

		''''f = open(WAConstants.CACHE_PATH+"/temp.jpg", 'r')
		stream = f.read()
		stream = bytearray(stream)
		f.close()
		'''
		
		return WAConstants.CACHE_PATH+"/temp.jpg"
Example #7
0
 def init_gl(self):
     if self.is_initialized:
         return
     self.texture_id = glGenTextures(1)
     glEnable(GL_TEXTURE_CUBE_MAP)
     glBindTexture(GL_TEXTURE_CUBE_MAP, self.texture_id)
     # Define all 6 faces
     glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE)
     if True:
         img = QImage()
         img.load("skybox/miramar_lf.tif")
         glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA8, img.width(), img.height(), 
                      0, GL_RGBA, GL_UNSIGNED_BYTE, fname_to_tex("skybox/miramar_ft.tif"))
         glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGBA8, img.width(), img.height(), 
                      0, GL_RGBA, GL_UNSIGNED_BYTE, fname_to_tex("skybox/miramar_bk.tif"))
         glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGBA8, img.width(), img.height(), 
                      0, GL_RGBA, GL_UNSIGNED_BYTE, fname_to_tex("skybox/miramar_dn.tif"))
         glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGBA8, img.width(), img.height(), 
                      0, GL_RGBA, GL_UNSIGNED_BYTE, fname_to_tex("skybox/miramar_up.tif"))
         glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGBA8, img.width(), img.height(), 
                      0, GL_RGBA, GL_UNSIGNED_BYTE, fname_to_tex("skybox/miramar_rt.tif"))
         glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGBA8, img.width(), img.height(), 
                      0, GL_RGBA, GL_UNSIGNED_BYTE, fname_to_tex("skybox/miramar_lf.tif"))
     else:
         test_img = numpy.array(256 * [50,50,128,255], 'uint8')
         glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA8, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, test_img)
         glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGBA8, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, test_img)
         glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGBA8, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, test_img)
         glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGBA8, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, test_img)
         glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGBA8, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, test_img)
         glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGBA8, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, test_img)
     glDisable(GL_TEXTURE_CUBE_MAP)
     self.shader.init_gl()
     self.is_initialized = True
Example #8
0
	def sendMediaImageFile(self,jid,image):
		image = image.replace("file://","")

		user_img = QImage(image)

		if user_img.height() > user_img.width():
			preimg = QPixmap.fromImage(QImage(user_img.scaledToWidth(64, Qt.SmoothTransformation)))
		elif user_img.height() < user_img.width():
			preimg = QPixmap.fromImage(QImage(user_img.scaledToHeight(64, Qt.SmoothTransformation)))
		else:
			preimg = QPixmap.fromImage(QImage(user_img.scaled(64, 64, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)))

		preimg.save(WAConstants.CACHE_PATH+"/temp2.png", "PNG")
		f = open(WAConstants.CACHE_PATH+"/temp2.png", 'r')
		stream = base64.b64encode(f.read())
		f.close()

		self._d("creating PICTURE MMS for " +jid + " - file: " + image)
		fmsg = WAXMPP.message_store.createMessage(jid);
		
		mediaItem = WAXMPP.message_store.store.Media.create()
		mediaItem.mediatype_id = 2
		mediaItem.local_path = image
		mediaItem.transfer_status = 0
		mediaItem.preview = stream
		try:
			mediaItem.size = os.path.getsize(mediaItem.local_path)
		except:
			pass

		fmsg.content = QtCore.QCoreApplication.translate("WAEventHandler", "Image")
		fmsg.Media = mediaItem

		if fmsg.Conversation.type == "group":
			contact = WAXMPP.message_store.store.Contact.getOrCreateContactByJid(self.conn.jid)
			fmsg.setContact(contact);
		
		fmsg.setData({"status":0,"content":fmsg.content,"type":1})
		WAXMPP.message_store.pushMessage(jid,fmsg)
Example #9
0
    def __init__(self, directory, filename):
        self.directory = directory
        self.filename = filename

        image = QImage(self.directory + QDir.separator() + self.filename)

        Rect.__init__(self, Point(), Size(image.width(), image.height()))

        cropped_image, x, y, width, height = self.__getCrop(image, False)

        self.crop = Rect(Point(x, y), Size(width, height))

        self.rotated = False
Example #10
0
 def end_adding(self, gl):
     self.texture.bind(gl)
     
     '''
     IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT
     The image has to be mirrored for some reason
     '''
     img = QImage(self.bitmap.toImage()).mirrored()
     img = QGLWidget.convertToGLFormat(img)
     
     gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width(), img.height(), 0, gl.GL_RGBA, 
                     gl.GL_UNSIGNED_BYTE, str(img.bits()))
     
     # This particular bitmap is no longer needed
     self.bitmap = None
Example #11
0
class Texture(Tool):
    image = None

    def initialize(self):
        name = QtGui.QFileDialog.getOpenFileName(self.editor,
                                                 'Select texture file',
                                                 filter=IMAGE_OPEN_FILTER)[0]
        if not name:
            return
        self.image = QImage(name)

    def draw(self, painter, old_x, old_y, x, y):
        if self.image is None:
            return
        painter.drawImage(x - self.image.width() / 2.0,
                          y - self.image.height() / 2.0, self.image)
Example #12
0
    def test_fire_png(self):
        fire = QImage("data/fire.png")

        cropper = CropTransparent(fire.width(), fire.height(), 50, str(fire.constBits()))

        self.assertEqual(cropper.getCroppedOffsetX(), 16)
        self.assertEqual(cropper.getCroppedOffsetY(), 15)
        self.assertEqual(cropper.getCroppedHeight(), 226)
        self.assertEqual(cropper.getCroppedWidth(), 226)

        crop_rect = cropper.getRect()

        self.assertEqual(crop_rect.x, 16)
        self.assertEqual(crop_rect.y, 15)
        self.assertEqual(crop_rect.width, 226)
        self.assertEqual(crop_rect.height, 226)
Example #13
0
    def project(screen, size, tiles, rotate, tilecolor, backcolor = None):
        backcolor = Qt.white if backcolor is None else backcolor

        res = len(tiles)
        template = QImage(size[0]/res, 2*size[1]/res, QImage.Format_RGB32)

        screen.setBrush(backcolor)
        screen.drawEllipse(0, 0, res * template.width()/2, res * template.height()/2)
        screen.drawEllipse(res * template.width()/2, 0, res * template.width()/2, res * template.height()/2)

        for y in range(res):
            r = rotate
            o = (r + 90) * len(tiles[y])/360

            # draw each hemisphere from outside to center
            sections = [[] for s in range(4)]
            i = 0
            while i < len(tiles[y]) and tiles[y][i].vector[0] < 0:
                sections[0].append(i)
                i += 1
            while i < len(tiles[y]) and tiles[y][i].vector[0] > tiles[y][i-1].vector[0]:
                sections[1].append(i)
                i += 1
            while i < len(tiles[y]) and tiles[y][i].vector[0] > 0:
                sections[2].append(i)
                i += 1
            while i < len(tiles[y]):
                sections[3].append(i)
                i += 1
                
            for x in sections[0] + list(reversed(sections[3])) + sections[2] + list(reversed(sections[1])):
                block = template.copy()

                xo = x + o
                if xo > len(tiles[y])-1:
                    xo -= len(tiles[y])
                elif xo < 0:
                    xo += len(tiles[y])

                v = tiles[y][x].vector
                sx, sy = [(v[i+1]+1)/2 for i in range(2)]
                sx = 1 + (sx if v[0] > 0 else -sx)

                block.fill(tilecolor(tiles[y][xo]).rgb())

                screen.drawImage(sx*res*block.width()/2, sy*res*block.height()/2, block)
Example #14
0
class Texture(Tool):
    image = None
    
    def initialize(self):
        name = QtGui.QFileDialog.getOpenFileName(self.editor,
            'Select texture file', filter = IMAGE_OPEN_FILTER)[0]
        if not name:
            return
        self.image = QImage(name)
    
    def draw(self, painter, old_x, old_y, x, y):
        if self.image is None:
            return
        painter.drawImage(
            x - self.image.width() / 2.0, 
            y - self.image.height() / 2.0, 
            self.image)
Example #15
0
 def create_texture_from_resource(self, gl, resource_id):
     '''
     Unlike the original java source, convertToGLFormat is used
     '''
     text = self.create_texture_internal(gl)
     
     img = QImage("assets/drawable/" + self.images[resource_id] + ".png")
     img = QGLWidget.convertToGLFormat(img)
     
     text.bind(gl)
     gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR);
     gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR);
     gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE);
     gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE);
     
     gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width(), img.height(), 0, gl.GL_RGBA, 
                     gl.GL_UNSIGNED_BYTE, str(img.bits()))
     
     return text
Example #16
0
    def requestImage(self, name, rsize, size):
        """@reimp @public
    @param[in]  providerId  unicode  unused
    @param[out]  rsize  QSize
    @param[in]  size  QSize
    @return  QImage not None

    virtual QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize)
    """
        ret = QImage(rc.image_path(name))
        if ret.isNull():
            derror("failed to load image: '%s'" % name)
        elif ret.size() != size:
            ret = (
                ret.scaled(size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                if not size.isEmpty() else ret.scaledToWidth(
                    size.width(), Qt.SmoothTransformation) if size.width() > 0
                else ret.scaledToHeight(size.height(), Qt.SmoothTransformation)
                if size.height() > 0 else ret)
        rsize.setWidth(ret.width())
        rsize.setHeight(ret.height())
        return ret
Example #17
0
    def push(self, image):
        #image = urllib.quote(image)
        image = image.replace("file://", "")

        self.sock = socket.socket()
        HOST, PORT = 'mms.whatsapp.net', 443
        self.sock.connect((HOST, PORT))
        ssl_sock = ssl.wrap_socket(self.sock)

        filename = os.path.basename(image)
        filetype = mimetypes.guess_type(filename)[0]
        filesize = os.path.getsize(image)

        if self.resizeImages is True and "image" in filetype and not "image/gif" in filetype:
            user_img = QImage(image)
            preimg = user_img
            if user_img.height() > user_img.width() and user_img.width() > 600:
                preimg = user_img.scaledToWidth(600, Qt.SmoothTransformation)
            elif user_img.height() < user_img.width() and user_img.height(
            ) > 800:
                preimg = user_img.scaledToHeight(800, Qt.SmoothTransformation)
            elif user_img.height() == user_img.width(
            ) and user_img.height() > 600:
                preimg = user_img.scaled(600, 600,
                                         Qt.KeepAspectRatioByExpanding,
                                         Qt.SmoothTransformation)
            preimg.save(WAConstants.CACHE_PATH + "/" + os.path.basename(image))
            image = WAConstants.CACHE_PATH + "/" + os.path.basename(image)

            filename = os.path.basename(image)
            filetype = mimetypes.guess_type(filename)[0]
            filesize = os.path.getsize(image)

        print "Uploading " + image + " - type: " + filetype + " - resize:" + str(
            self.resizeImages)

        m = hashlib.md5()
        m.update(filename)
        crypto = m.hexdigest() + os.path.splitext(filename)[1]

        boundary = "-------" + m.hexdigest()  #"zzXXzzYYzzXXzzQQ"
        contentLength = 0

        hBAOS = bytearray()
        hBAOS += "--" + boundary + "\r\n"
        hBAOS += "Content-Disposition: form-data; name=\"to\"\r\n\r\n"
        hBAOS += self.jid + "\r\n"
        hBAOS += "--" + boundary + "\r\n"
        hBAOS += "Content-Disposition: form-data; name=\"from\"\r\n\r\n"
        hBAOS += self.account.replace("@whatsapp.net", "").encode() + "\r\n"

        hBAOS += "--" + boundary + "\r\n"
        hBAOS += "Content-Disposition: form-data; name=\"file\"; filename=\"" + crypto.encode(
        ) + "\"\r\n"
        hBAOS += "Content-Type: " + filetype + "\r\n\r\n"

        fBAOS = bytearray()
        fBAOS += "\r\n--" + boundary + "--\r\n"

        contentLength += len(hBAOS)
        contentLength += len(fBAOS)
        contentLength += filesize

        userAgent = "WhatsApp/2.8.4 S60Version/5.2 Device/C7-00"

        POST = bytearray()
        POST += "POST https://mms.whatsapp.net/client/iphone/upload.php HTTP/1.1\r\n"
        POST += "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n"
        POST += "Host: mms.whatsapp.net\r\n"
        POST += "User-Agent: WhatsApp/2.8.14 S60Version/5.3 Device/C7-00\r\n"
        POST += "Content-Length: " + str(contentLength) + "\r\n\r\n"

        print "sending REQUEST "
        print hBAOS
        ssl_sock.write(str(POST))
        ssl_sock.write(str(hBAOS))

        totalsent = 0
        buf = 1024
        f = open(image, 'r')
        stream = f.read()
        f.close()
        status = 0
        lastEmit = 0

        while totalsent < int(filesize):
            #print "sending " + str(totalsent) + " to " + str(totalsent+buf) + " - real: " + str(len(stream[:buf]))
            ssl_sock.write(str(stream[:buf]))
            status = totalsent * 100 / filesize
            if lastEmit != status and status != 100 and filesize > 12288:
                self.progressUpdated.emit(status)
            lastEmit = status
            stream = stream[buf:]
            totalsent = totalsent + buf

        ssl_sock.write(str(fBAOS))

        if self.resizeImages is True and "image" in filetype:
            os.remove(WAConstants.CACHE_PATH + "/" + os.path.basename(image))

        sleep(1)
        print "Done!"
        print "Reading response..."
        data = ssl_sock.recv(8192)
        data += ssl_sock.recv(8192)
        data += ssl_sock.recv(8192)
        data += ssl_sock.recv(8192)
        data += ssl_sock.recv(8192)
        data += ssl_sock.recv(8192)
        data += ssl_sock.recv(8192)
        print data
        self.progressUpdated.emit(100)

        if "<string>https://mms" in data:
            n = data.find("<string>https://mms") + 8
            url = data[n:]
            n = url.find("</string>")
            url = url[:n]
            #print "MMS ADDRESS: "+url
            self.success.emit(url + "," + filename + "," + str(filesize),
                              "upload")

        else:
            self.error.emit()
Example #18
0
	def push(self,image):
		#image = urllib.quote(image)
		image = image.replace("file://","")

		self.sock = socket.socket();
		HOST, PORT = 'mms.whatsapp.net', 443
		self.sock.connect((HOST, PORT));
		ssl_sock = ssl.wrap_socket(self.sock)

		filename = os.path.basename(image)
		filetype = mimetypes.guess_type(filename)[0]
		filesize = os.path.getsize(image)

		if self.resizeImages is True and "image" in filetype and not "image/gif" in filetype:
			user_img = QImage(image)
			preimg = user_img
			if user_img.height() > user_img.width() and user_img.width() > 600:
				preimg = user_img.scaledToWidth(600, Qt.SmoothTransformation)
			elif user_img.height() < user_img.width() and user_img.height() > 800:
				preimg = user_img.scaledToHeight(800, Qt.SmoothTransformation)
			elif user_img.height() == user_img.width() and user_img.height() > 600:
				preimg = user_img.scaled(600, 600, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)
			preimg.save(WAConstants.CACHE_PATH+"/" + os.path.basename(image))
			image = WAConstants.CACHE_PATH+"/" + os.path.basename(image)

			filename = os.path.basename(image)
			filetype = mimetypes.guess_type(filename)[0]
			filesize = os.path.getsize(image)

		print "Uploading " + image + " - type: " + filetype + " - resize:" + str(self.resizeImages);


		m = hashlib.md5()
		m.update(filename)
		crypto = m.hexdigest() + os.path.splitext(filename)[1]

		boundary = "-------" + m.hexdigest() #"zzXXzzYYzzXXzzQQ"
		contentLength = 0
		
		hBAOS = bytearray()
		hBAOS += "--" + boundary + "\r\n"
		hBAOS += "Content-Disposition: form-data; name=\"to\"\r\n\r\n"
		hBAOS += self.jid + "\r\n"
		hBAOS += "--" + boundary + "\r\n"
		hBAOS += "Content-Disposition: form-data; name=\"from\"\r\n\r\n"
		hBAOS += self.account.replace("@whatsapp.net","").encode() + "\r\n"

		hBAOS += "--" + boundary + "\r\n"
		hBAOS += "Content-Disposition: form-data; name=\"file\"; filename=\"" + crypto.encode() + "\"\r\n"
		hBAOS += "Content-Type: " + filetype + "\r\n\r\n"

		fBAOS = bytearray()
		fBAOS += "\r\n--" + boundary + "--\r\n"
		
		contentLength += len(hBAOS)
		contentLength += len(fBAOS)
		contentLength += filesize

		userAgent = "WhatsApp/2.8.4 S60Version/5.2 Device/C7-00"

		POST = bytearray()
		POST += "POST https://mms.whatsapp.net/client/iphone/upload.php HTTP/1.1\r\n"
		POST += "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n"
		POST += "Host: mms.whatsapp.net\r\n"
		POST += "User-Agent: WhatsApp/2.8.14 S60Version/5.3 Device/C7-00\r\n"
		POST += "Content-Length: " + str(contentLength) + "\r\n\r\n"

		print "sending REQUEST "
		print hBAOS
		ssl_sock.write(str(POST))
		ssl_sock.write(str(hBAOS))

		totalsent = 0
		buf = 1024
		f = open(image, 'r')
		stream = f.read()
		f.close()
		status = 0
		lastEmit = 0

		while totalsent < int(filesize):
			#print "sending " + str(totalsent) + " to " + str(totalsent+buf) + " - real: " + str(len(stream[:buf]))
			ssl_sock.write(str(stream[:buf]))
			status = totalsent * 100 / filesize
			if lastEmit!=status and status!=100 and filesize>12288:
				self.progressUpdated.emit(status)
			lastEmit = status
			stream = stream[buf:]
			totalsent = totalsent + buf

		ssl_sock.write(str(fBAOS))

		if self.resizeImages is True and "image" in filetype:
			os.remove(WAConstants.CACHE_PATH+"/" + os.path.basename(image))

		sleep(1)
		print "Done!"
		print "Reading response..."
		data = ssl_sock.recv(8192)
		data += ssl_sock.recv(8192)
		data += ssl_sock.recv(8192)
		data += ssl_sock.recv(8192)
		data += ssl_sock.recv(8192)
		data += ssl_sock.recv(8192)
		data += ssl_sock.recv(8192)
		print data;
		self.progressUpdated.emit(100)

		if "<string>https://mms" in data:
			n = data.find("<string>https://mms") +8
			url = data[n:]
			n = url.find("</string>")
			url = url[:n]
			#print "MMS ADDRESS: "+url
			self.success.emit(url + "," + filename + "," + str(filesize), "upload")

		else:
			self.error.emit()
Example #19
0
class RatingEditor(QWidget):
    '''
    Star Rating Editor
    
    Editor class to edit a 5-star rating.  Clicking the control enables dragging
    the mouse to select the rating.  This control is compatible with Qt MVF.
    '''
    editingFinished = QtCore.Signal()
    
    def __init__(self, parent=None):
        super(RatingEditor, self).__init__(parent)
        
        self.setAutoFillBackground(True)
        self.setFocusPolicy(Qt.ClickFocus)
        self._sopt = QStyleOptionFrameV3()
        
        self._star = QImage(':/icons/star.png')
        self._blue = QImage(':/icons/star-blue.png')
        self._dot = QImage(':/icons/star-dot.png')
        
        self._rating = 0
        self._active = False
    
    def _updateRating(self, e):
        'Update the Rating based on the Mouse Event'
        r = int(round(float(e.x()) / self._star.width()))
        self.setRating(r)
        
    def mousePressEvent(self, e):
        'Mouse Press Event'
        if e.buttons() == Qt.LeftButton:
            self._active = True
            self._updateRating(e)
        
    def mouseMoveEvent(self, e):
        'Mouse Move Event'
        if self._active:
            self._updateRating(e)
            
    def mouseReleaseEvent(self, e):
        'Mouse Release Event'
        if self._active:
            self._active = False
            self.update()
            self.editingFinished.emit()
    
    def paintEvent(self, e):
        'Custom Paint Event'
        p = QPainter(self)
        
        opt = QStyleOptionFrameV3()
        opt.initFrom(self)
        opt.rect = self.contentsRect()
        opt.lineWidth = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth, opt, self)
        opt.midLineWidth = 0
        opt.state = opt.state | QStyle.State_Sunken
        
        if self._active:
            opt.state = opt.state | QStyle.State_HasFocus
        else:
            opt.state = opt.state & ~QStyle.State_HasFocus;
        
        self.style().drawPrimitive(QStyle.PE_PanelLineEdit, opt, p)

        y = (opt.rect.height() - self._star.height()) / 2 
        width = self._star.width()
        
        for i in range(0, 5):
            x = i*(width + 1) + opt.lineWidth
            
            if self._rating >= i+0.5:
                p.drawImage(x, y, self._star if not self._active else self._blue)
            else:
                p.drawImage(x, y, self._dot)
    
    def rating(self):
        'Return the Rating'
        return self._rating
        
    def sizeHint(self):
        'Return the Size Hint'
        return QSize((self._star.width()+2) * 5, self._star.height()+2)
    
    @QtCore.Slot(int)
    def setRating(self, r):
        'Set the new Rating'
        if r < 0:
            r = 0
        elif r > 5:
            r = 5
        
        self._rating = r
        self.update()
Example #20
0
class UpngGui:
    def __init__(self):
        self.ui = None
        self.image = None
        
    def main(self, argv=None):
        
        if argv is None:
            argv = sys.argv

        self.app = QApplication(argv)

        loader = QUiLoader()
        self.ui = loader.load('./upng.ui')

        self.ui.openButton.clicked.connect(self.openImage)
        self.ui.resizeButton.clicked.connect(self.resizeImage)
        self.ui.saveButton.clicked.connect(self.saveImage)
        
        self.ui.show()
        
        return self.app.exec_()
    
    def openImage(self):
        
        fileName = QFileDialog.getOpenFileName(self.ui, 
            tr("Open Image"), "./", 
            tr("Image Files (*.png *.jpg *.bmp *.ppm)"))
        
        if fileName:
            fileName = fileName[0]
            
            self.image = QImage()
            self.image.load(fileName)
            w = self.image.width()
            h = self.image.height()
            
            self.ui.spinBoxWidth.setValue(w)
            self.ui.spinBoxHeight.setValue(h)
            
            self.resizeImage()
    
    def resizeImage(self):
        
        if not self.image:
            self.ui.scrollArea.takeWidget()
            return
        
        w = self.ui.spinBoxWidth.value()
        h = self.ui.spinBoxHeight.value()
        
        img = self.image.scaled(w,h)
        pix = QPixmap.fromImage(img)
        
        lbl = QLabel()
        lbl.setPixmap(pix)
        self.ui.scrollArea.takeWidget()
        self.ui.scrollArea.setWidget(lbl)
    
    def saveImage(self):
        
        if not self.image:
            return
        
        w = self.ui.spinBoxWidth.value()
        h = self.ui.spinBoxHeight.value()
        
        img = self.image.scaled(w,h).convertToFormat(QImage.Format_ARGB32)
        
        fileName = QFileDialog.getSaveFileName(self.ui, 
            tr("Save Simple Png Image"), "./", 
            tr("Image Files (*.png *.ppm)"))
        
        if fileName:
            fileName = fileName[0]
            
            self.app.setOverrideCursor(QCursor(Qt.WaitCursor))
            self.ui.setEnabled(False)
            
            if fileName.endswith('ppm'):
                writePpm(fileName, img)
            if fileName.endswith('png'):
                writeSPangImage(fileName, img, self.app)
            else:
                writeSPangImage(fileName + ".png", img, self.app)
            
            self.ui.setEnabled(True)
            self.app.restoreOverrideCursor()
class CircuitItem(QGraphicsItem):
    """Graphical wrapper around the engine Circuit class."""

    textH = 12
    """Height of text."""
    ioH = 20
    """Height between to I/O pins."""
    ioW = 15
    """Length of I/O pins."""
    radius = 10
    """Radius of I/O pin heads."""

    def __init__(self, circuit):
        super(CircuitItem, self).__init__()
        self.setFlag(QGraphicsItem.ItemIsMovable)
        self.setFlag(QGraphicsItem.ItemIsSelectable)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges)
        imgDir = filePath('icons/')
        self.data = circuit
        """The real info. The class CircuitItem is just a graphical container
        around it. data is saved / loaded to / from file.
        """
        self.image = QImage(imgDir + circuit.__class__.__name__ + '.png')
        """The graphical representation of our item on screen."""
        if not self.image:
            self.image = QImage(imgDir + 'Default.png')
            self.showCategory = True
        self.showName = True
        """Is the item's name shown on screen?"""
        self.showCategory = False
        """Is the item's category (circuit class) shown on screen?"""
        self.name = QGraphicsSimpleTextItem(self)
        # that won't rotate when the PlugItem is rotated by the user.
        self.name.setFlag(QGraphicsItem.ItemIgnoresTransformations)
        self.name.setText(self.data.name)
        self.category = QGraphicsSimpleTextItem(self)
        self.category.setFlag(QGraphicsItem.ItemIgnoresTransformations)
        self.category.setText(self.data.category)
        self.setupPaint()

    def boundingRect(self):
        """Qt requires overloading this when overloading QGraphicsItem."""
        W = 2 * self.radius + 2 * self.ioW + self.imgW
        ni = self.data.nb_inputs()
        no = self.data.nb_outputs()
        t = (1 - int(max(ni, no) / 2)) * self.ioH - self.radius / 2
        b = (1 + int(max(ni, no) / 2)) * self.ioH + self.radius / 2
        return (
            QRectF(-self.ioW - self.radius, t, W, b - t) if max(ni, no) > 1
            else QRectF(-self.ioW - self.radius, 0, W, self.image.height()))

    def handleAtPos(self, pos):
        """Is there an interactive handle where the mouse is? Return it."""
        for i in range(self.nIn):
            if self.inputPaths[i].contains(pos):
                return self.data.inputList[i]
        for i in range(self.nOut):
            if self.outputPaths[i].contains(pos):
                return self.data.outputList[i]

    def itemChange(self, change, value):
        """Warning view it will soon have to correct pos."""
        if change == QGraphicsItem.ItemPositionHasChanged:
            # Restart till we stop moving.
            self.scene().views()[0].timer.start()
        return QGraphicsItem.itemChange(self, change, value)

    def paint(self, painter, option, widget):
        """Draws the item."""
        painter.setPen(QPen(QColor('black'), 2))
        ni = self.data.nb_inputs()
        no = self.data.nb_outputs()
        for i in range(1 - int(ni / 2), 2 + int(ni / 2)):
            if i != 1 or ni % 2:
                painter.drawLine(-self.ioW, i * self.ioH, 0, i * self.ioH)
        for i in range(1 - int(no / 2), 2 + int(no / 2)):
            if i != 1 or no % 2:
                painter.drawLine(
                    self.imgW, i * self.ioH, self.imgW + self.ioW,
                    i * self.ioH)
        painter.drawImage(QRectF(0, 0, self.imgW, self.imgH), self.image)
        for i in range(ni):
            painter.drawPath(self.inputPaths[i])
        painter.drawLine(
            0, (1 - int(ni / 2)) * self.ioH, 0, (1 + int(ni / 2)) * self.ioH)
        for i in range(no):
            painter.drawPath(self.outputPaths[i])
        painter.drawLine(
            self.imgW,
            (1 - int(no / 2)) * self.ioH,
            self.imgW,
            (1 + int(no / 2)) * self.ioH)
        # Default selection box doesn't work; simple reimplementation.
        if option.state & QStyle.State_Selected:
            pen = QPen(Qt.black, 1, Qt.DashLine)
            painter.setPen(pen)
            painter.drawRect(self.boundingRect())

    def setCategoryVisibility(self, isVisible):
        """Show/Hide circuit category (mostly useful for user circuits)."""
        self.showCategory = isVisible
        self.setupPaint()

    def setNameVisibility(self, isVisible):
        """Shows/Hide the item name in the graphical view."""
        self.showName = isVisible
        self.setupPaint()

    def setNbInputs(self, nb):
        """Add/Remove inputs (for logical gates)."""
        if nb > self.data.nb_inputs():
            for x in range(nb - self.data.nb_inputs()):
                Plug(True, None, self.data)
        elif nb < self.data.nb_inputs():
            for x in range(self.data.nb_inputs() - nb):
                self.data.remove_input(self.data.inputList[0])
        self.setupPaint()

    def setupPaint(self):
        """Offscreen rather than onscreen redraw (few changes)."""
        self.nIn = self.data.nb_inputs()
        self.nOut = self.data.nb_outputs()
        # 3 sections with different heights must be aligned :
        self.imgH = self.image.size().height()   # central (png image)
        self.imgW = self.image.size().width()
        self.inH = (self.nIn - 1) * self.ioH + 2 * self.radius  # inputs
        self.outH = (self.nOut - 1) * self.ioH + 2 * self.radius    # outputs
        # therefore we calculate a vertical offset for each section :
        self.maxH = max(self.imgH, self.inH, self.outH)
        self.imgOff = (
            0 if self.maxH == self.imgH else (self.maxH - self.imgH) / 2.)
        self.inOff = (
            0 if self.maxH == self.inH else (self.maxH - self.inH) / 2.)
        self.outOff = (
            0 if self.maxH == self.outH else (self.maxH - self.outH) / 2.)
        # i/o mouseover detection. Create once, use on each mouseMoveEvent.
        self.inputPaths = []
        self.outputPaths = []
        ni = self.data.nb_inputs()
        no = self.data.nb_outputs()
        for i in range(1 - int(ni / 2), 2 + int(ni / 2)):
            if i != 1 or ni % 2:
                path = QPainterPath()
                path.addEllipse(
                    -self.ioW - self.radius, i * self.ioH - self.radius / 2,
                    self.radius, self.radius)
                self.inputPaths.append(path)
        for i in range(1 - int(no / 2), 2 + int(no / 2)):
            if i != 1 or no % 2:
                path = QPainterPath()
                path.addEllipse(
                    self.imgW + self.ioW, i * self.ioH - self.radius / 2,
                    self.radius, self.radius)
                self.outputPaths.append(path)
        self.name.setVisible(self.showName)
        self.category.setVisible(self.showCategory)
        if self.showName or self.showCategory:
            br = self.mapToScene(self.boundingRect())
            w = self.boundingRect().width()
            h = self.boundingRect().height()
            realX = min([i.x() for i in br])
            realY = min([i.y() for i in br])
            firstY = realY + (w if self.rotation() % 180 else h) + 1
            secondY = firstY + self.textH
            if self.showName:
                self.name.setBrush(QColor('red'))
                self.name.setText(self.data.name)
                self.name.setPos(self.mapFromScene(realX, firstY))
            if self.showCategory:
                self.category.setBrush(QColor('green'))
                self.category.setText(
                    self.data.category if self.data.category
                    else self.data.__class__.__name__)
                self.category.setPos(self.mapFromScene(
                    realX, secondY if self.showName else firstY))
        self.prepareGeometryChange()    # Must be called (cf Qt doc)
        self.update()       # Force onscreen redraw after changes.