Exemplo n.º 1
0
def toImageFromBuf(buf):
    return wx.ImageFromStream(
        StringIO.StringIO(base64.b64decode(buf[len(srcPrefix):])),
        wx.BITMAP_TYPE_PNG)
Exemplo n.º 2
0
 def GetImage(self):
     stream = cStringIO.StringIO(self.GetData())
     return wx.ImageFromStream(stream)
Exemplo n.º 3
0
def GetPhotos(listeIndividus=[],
              taillePhoto=None,
              qualite=wx.IMAGE_QUALITY_HIGH):
    """ Retourne les photos de plusieurs individus """
    """ listeIndividus = [(IDindividu1, nomFichierDefaut), (IDindividu2, nomFichierDefaut), etc...] """
    # Recherche les images par défaut sur le disque dur
    dictImagesDefaut = {}
    listeIDindividus = []
    for IDindividu, nomFichier in listeIndividus:
        listeIDindividus.append(IDindividu)
        if nomFichier != None and dictImagesDefaut.has_key(
                nomFichier) == False:
            if os.path.isfile(nomFichier):
                bmp = wx.Bitmap(nomFichier, wx.BITMAP_TYPE_ANY)
                if taillePhoto != None:
                    img = bmp.ConvertToImage()
                    img = img.Rescale(width=taillePhoto[0],
                                      height=taillePhoto[1],
                                      quality=qualite)
                    bmp = img.ConvertToBitmap()
                dictImagesDefaut[nomFichier] = bmp

    # Récupère les photos dans la DB
    dictPhotosDB = {}
    DB = GestionDB.DB(suffixe="PHOTOS")
    if DB.echec == 0:
        if len(listeIDindividus) == 1: condition = "(%d)" % listeIDindividus[0]
        else: condition = str(tuple(listeIDindividus))
        req = "SELECT IDphoto, IDindividu, photo FROM photos WHERE IDindividu IN %s;" % condition
        DB.ExecuterReq(req)
        listeDonnees = DB.ResultatReq()
        DB.Close()
        for IDphoto, IDindividu, bufferPhoto in listeDonnees:
            dictPhotosDB[IDindividu] = {
                "IDphoto": IDphoto,
                "bufferPhoto": bufferPhoto
            }

    # Traite les photos de chaque individu
    dictPhotos = {}
    for IDindividu, nomFichier in listeIndividus:
        if dictPhotosDB.has_key(IDindividu):
            # Si photo existe dans DB
            IDphoto = dictPhotosDB[IDindividu]["IDphoto"]
            bufferPhoto = dictPhotosDB[IDindividu]["bufferPhoto"]
            io = cStringIO.StringIO(bufferPhoto)
            if 'phoenix' in wx.PlatformInfo:
                img = wx.Image(io, wx.BITMAP_TYPE_JPEG)
            else:
                img = wx.ImageFromStream(io, wx.BITMAP_TYPE_JPEG)
            if taillePhoto != None:
                img = img.Rescale(width=taillePhoto[0],
                                  height=taillePhoto[1],
                                  quality=qualite)
            bmp = img.ConvertToBitmap()
        else:
            # Si aucune photo dans DB
            IDphoto = None
            if dictImagesDefaut.has_key(nomFichier):
                bmp = dictImagesDefaut[nomFichier]
            else:
                bmp = None
        # Mémorisation de la photo
        dictPhotos[IDindividu] = {"bmp": bmp, "IDphoto": IDphoto}

    return dictPhotos
Exemplo n.º 4
0
def getPyImage(shellName='PyCrust'):
    stream = cStringIO.StringIO(getPyData(shellName))
    return wx.ImageFromStream(stream)
Exemplo n.º 5
0
def getPyImage():
    stream = cStringIO.StringIO(getPyData())
    return wx.ImageFromStream(stream)
Exemplo n.º 6
0
 def set_play_button_image(self, data):
     stream = StringIO.StringIO(data)
     image = wx.ImageFromStream(stream)
     bitmap = wx.BitmapFromImage(image)
     self.play_button.SetBitmapLabel(bitmap)
Exemplo n.º 7
0

#FOCUS_PATTERN = b64decode(
#    "iVBORw0KGgoAAAANSUhEUgAAACgAAAAoAQMAAAC2MCouAAAABlBMVEUAAAD///+l2Z/d"
#    "AAAAAnRSTlMA/1uRIrUAAABkSURBVHjaY2AAg/p/DPb/oWQCE4MCM0N+1ff11QyZXlNW"
#    "ekPJ/F//1/9mSHQSUXSGslFkweoheuv/AwEDA5DNwMAPFK9g4ASq8YCS/EC9PxgYgeY4"
#    "QNkosmD1EL0Qc6jgHoTvAMSAW32HrwidAAAAAElFTkSuQmCC"
#)
FOCUS_PATTERN = b64decode(
    "iVBORw0KGgoAAAANSUhEUgAAACgAAAAoAQMAAAC2MCouAAAABlBMVEUAAAD///+l2Z/d"
    "AAAAZElEQVR4nGNgAIP6fwz2/6FkAhODAjNDftX39dUMmV5TVnpDyfxf/9f/Zkh0ElF0"
    "hrJRZMHqIXrr/wMBAwOQzcDADxSvYOAEqvGAkvxAvT8YGIHmOEDZKLJg9RC9EHOo4B6E"
    "7wDEgFt9VLehNwAAAABJRU5ErkJggg=="
)

FOCUS_IMAGE = wx.ImageFromStream(cStringIO.StringIO(FOCUS_PATTERN))

ASPECT_RATIOS = [
    # aspectRatio, isCCIR601
    (None, False),
    (4.0 / 3.0, False),
    (16.0 / 9.0, False),
    ((720.0 / 702.0) * (4.0 / 3.0), True),
    ((720.0 / 702.0) * (16.0 / 9.0), True),
]


def AddColon(txt):
    return "%s%s" % (txt, ":")

class DrawingFrame(wx.Frame):
def GetIndicatorImage():
    stream = cStringIO.StringIO(GetIndicatorData())
    return wx.ImageFromStream(stream)
Exemplo n.º 9
0
 def getPhoto(self):
     if self.jpg is None:
         return None
     return self.addPhotoHeaderToImage(
         wx.ImageFromStream(StringIO.StringIO(self.jpg),
                            wx.BITMAP_TYPE_JPEG))
Exemplo n.º 10
0
def getSmilesImage():
    stream = cStringIO.StringIO(getSmilesData())
    return wx.ImageFromStream(stream)
Exemplo n.º 11
0
def GetPlusBitmap():
    stream = cStringIO.StringIO(GetPlusData())
    return wx.BitmapFromImage(wx.ImageFromStream(stream))
Exemplo n.º 12
0
    def MAJ(self):
        self.ClearAll()

        DB = GestionDB.DB()
        req = """SELECT IDmodele, documents_modeles.nom,
        produits_categories.IDcategorie, produits_categories.nom, produits_categories.image
        FROM documents_modeles
        LEFT JOIN produits_categories ON produits_categories.IDcategorie = documents_modeles.IDdonnee
        WHERE documents_modeles.categorie='produits_categories'
        ORDER BY documents_modeles.nom;"""
        DB.ExecuterReq(req)
        listeDonnees = DB.ResultatReq()
        DB.Close()

        self.liste_images = []
        for IDmodele, nomModele, IDcategorie, nomCategorie, image in listeDonnees :

            # Conversion en bmp de l'image
            if image != None :
                io = cStringIO.StringIO(image)
                if 'phoenix' in wx.PlatformInfo:
                    img = wx.Image(io, wx.BITMAP_TYPE_PNG)
                else:
                    img = wx.ImageFromStream(io, wx.BITMAP_TYPE_PNG)
                img = UTILS_Images.RecadreImg(img, self.taillePhoto)
                bmp = img.ConvertToBitmap()
            else :
                bmp = None

            # Mémorisation
            dictTemp = {"IDmodele" : IDmodele, "nomModele" : nomModele, "IDcategorie" : IDcategorie,
                        "nomCategorie": nomCategorie, "bmp" : bmp}
            self.liste_images.append(dictTemp)

        # liste images
        dictPhotos = {}
        il = wx.ImageList(self.taillePhoto[0], self.taillePhoto[1], True)

        # Image par défaut
        bmp = wx.Bitmap(Chemins.GetStaticPath("Images/32x32/Categorie_produits_nb.png"), wx.BITMAP_TYPE_PNG)
        img = bmp.ConvertToImage()
        img = UTILS_Images.RecadreImg(img, self.taillePhoto)
        bmp = img.ConvertToBitmap()
        il.Add(bmp)

        for dictImage in self.liste_images :
            if dictImage["bmp"] != None :
                dictPhotos[dictImage["IDmodele"]] = il.Add(dictImage["bmp"])
        self.AssignImageList(il, wx.IMAGE_LIST_NORMAL)

        # Création des items
        index = 0
        for dictImage in self.liste_images:
            label = dictImage["nomModele"]
            if dictPhotos.has_key(dictImage["IDmodele"]):
                indexPhoto = dictPhotos[dictImage["IDmodele"]]
            else :
                indexPhoto = 0
            self.InsertImageStringItem(index, label, indexPhoto)
            self.SetItemData(index, dictImage["IDmodele"])
            self.SetDisabledTextColour(wx.Colour(255, 0, 0))
            index += 1

        # Binds
        self.Bind(ULC.EVT_LIST_ITEM_ACTIVATED, self.OnActivated)
Exemplo n.º 13
0
def getfoldersearchImage():
    stream = cStringIO.StringIO(getfoldersearchData())
    return wx.ImageFromStream(stream)
Exemplo n.º 14
0
 def decode(self, string):
     """Return is wx.Bitmap."""
     input = StringIO.StringIO(base64.b64decode(string))
     image = wx.ImageFromStream(input, wx.BITMAP_TYPE_PNG)
     return image.ConvertToBitmap()
Exemplo n.º 15
0
import wx

tick_data = (
    'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29'
    'mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAGrSURBVDjLvZPZLkNhFIV75zjvYm7VGFNCqoZUJ+r'
    'oKUUpjRuqp61Wq0NKDMelGGqOxBSUIBKXWtWGZxAvobr8lWjChRgSF//dv9be+9trCwAI/vIE/26gXmv'
    'iW5bqnb8yUK028qZjPfoPWEj4Ku5HBspgAz941IXZeze8N1bottSo8BTZviVWrEh546EO03EXpuJOdG6'
    '3otJbjBKHkEp/Ml6yNYYzpuezWL4s5VMtT8acCMQcb5XL3eJE8VgBlR7BeMGW9Z4yT9y1CeyucuhdTGD'
    'xfftaBO7G4L+zg91UocxVmCiy51NpiP3n2treUPujL8xhOjYOzZYsQWANyRYlU4Y9Br6oHd5bDh0bCpS'
    'OixJiWx71YY09J5pM/WEbzFcDmHvwwBu2wnikg+lEj4mwBe5bC5h1OUqcwpdC60dxegRmR06TyjCF9G9'
    'z+qM2uCJmuMJmaNZaUrCSIi6X+jJIBBYtW5Cge7cd7sgoHDfDaAvKQGAlRZYc6ltJlMxX03UzlaRlBdQ'
    'rzSCwksLRbOpHUSb7pcsnxCCwngvM2Rm/ugUCi84fycr4l2t8Bb6iqTxSCgNIAAAAAElFTkSuQmCC'
)

cross_data = (
    'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29'
    'mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAIhSURBVDjLlZPrThNRFIWJicmJz6BWiYbIkYDEG0J'
    'bBiitDQgm0PuFXqSAtKXtpE2hNuoPTXwSnwtExd6w0pl2OtPlrphKLSXhx07OZM769qy19wwAGLhM1dd'
    'C184+d18QMzoq3lfsD3LZ7Y3XbE5DL6Atzuyilc5Ciyd7IHVfgNcDYTQ2tvDr5crn6uLSvX+Av2Lk36F'
    'FpSVENDe3OxDZu8apO5rROJDLo30+Nlvj5RnTlVNAKs1aCVFr7b4BPn6Cls21AWgEQlz2+Dl1h7IdA+i'
    '97A/geP65WhbmrnZZ0GIJpr6OqZqYAd5/gJpKox4Mg7pD2YoC2b0/54rJQuJZdm6Izcgma4TW1WZ0h+y'
    '8BfbyJMwBmSxkjw+VObNanp5h/adwGhaTXF4NWbLj9gEONyCmUZmd10pGgf1/vwcgOT3tUQE0DdicwIo'
    'd2EmSbwsKE1P8QoDkcHPJ5YESjgBJkYQpIEZ2KEB51Y6y3ojvY+P8XEDN7uKS0w0ltA7QGCWHCxSWWpw'
    'yaCeLy0BkA7UXyyg8fIzDoWHeBaDN4tQdSvAVdU1Aok+nsNTipIEVnkywo/FHatVkBoIhnFisOBoZxcG'
    'tQd4B0GYJNZsDSiAEadUBCkstPtN3Avs2Msa+Dt9XfxoFSNYF/Bh9gP0bOqHLAm2WUF1YQskwrVFYPWk'
    'f3h1iXwbvqGfFPSGW9Eah8HSS9fuZDnS32f71m8KFY7xs/QZyu6TH2+2+FAAAAABJRU5ErkJggg=='
)

tick = wx.ImageFromStream(StringIO(base64.b64decode(tick_data)))
cross = wx.ImageFromStream(StringIO(base64.b64decode(cross_data)))
Exemplo n.º 16
0
    def initializeBitmaps(self):

        try:
            self.path = self.pathToATPlatform + 'multimedia/music/'
            directories = [
                directory for directory in os.listdir(self.path)
                if os.path.isdir(os.path.join(self.path, directory))
            ]
            #directories.sort( key=lambda directory: os.path.getmtime( os.path.join(self.path, directory) ) )

            directories = sorted(directories,
                                 key=lambda x: int(x.split("_")[0]))

            self.existingLogos, self.existingMedia = [], []

            for item in directories:
                if 'playlist.m3u' in os.listdir(self.path + item):

                    self.existingMedia.append(self.path + item +
                                              '/playlist.m3u')
                    self.existingLogos.append(self.path + item + '/cover.jpg')

                else:
                    ositem = item.replace(' ',
                                          '\ ').replace('(', '\(').replace(
                                              ')', '\)').replace('&', '\&')
                    os.system('ls -d -1 %s/*.mp3 > %s/playlist.m3u' %
                              (self.path.replace(' ', '\ ') + ositem,
                               self.path.replace(' ', '\ ') + ositem))

                    self.existingMedia.append(self.path + item +
                                              '/playlist.m3u')
                    self.existingLogos.append(self.path + item + '/cover.jpg')

            self.numberOfPanels = 1 + len(self.existingMedia) / (
                (self.numberOfRows[0] - 1) * self.numberOfColumns[0] + 1)

            self.newHeight = 0.9 * self.winHeight / self.numberOfRows[0]

            self.panels = {}

            for number in range(self.numberOfPanels):
                logoNames = self.existingLogos[number *
                                               (self.numberOfRows[0] - 1) *
                                               self.numberOfColumns[0]:
                                               (number + 1) *
                                               (self.numberOfRows[0] - 1) *
                                               self.numberOfColumns[0]]

                logos = [
                    wx.ImageFromStream(open(logo, "rb")) for logo in logoNames
                ]
                logos = [
                    logo.Rescale(
                        logo.GetSize()[0] *
                        (self.newHeight / float(logo.GetSize()[1])),
                        self.newHeight, wx.IMAGE_QUALITY_HIGH)
                    for logo in logos
                ]
                logoBitmaps = [wx.BitmapFromImage(logo) for logo in logos]

                self.panels[number + 1] = [logoNames, logoBitmaps]

        except OSError:
            self.panels = {1: [[], []]}
            self.numberOfPanels = 1
            print "Błąd w strukturze plików."

        self.functionButtonPath = [
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToATPlatform + 'icons/volume down.png',
                         'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToATPlatform + 'icons/volume up.png',
                         'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToATPlatform + 'icons/show.png', 'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToATPlatform + 'icons/delete.png', 'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToATPlatform + 'icons/back.png', 'rb')))
        ]

        if self.numberOfPanels == 1:
            self.flag = 'row'
        else:
            self.flag = 'panel'
Exemplo n.º 17
0
 def getImage(imgDataString):
     stream = cStringIO.StringIO(imgDataString)
     return wx.ImageFromStream(stream)
Exemplo n.º 18
0
def convert_icon(icon_data):
    stream = cStringIO.StringIO(icon_data)
    image = wx.ImageFromStream(stream)
    stream.close()
    return wx.BitmapFromImage(image)
Exemplo n.º 19
0
 def make_bitmap_button(self, data):
     stream = StringIO.StringIO(data)
     image = wx.ImageFromStream(stream)
     bitmap = wx.BitmapFromImage(image)
     button = wx.BitmapButton(self, -1, bitmap)
     return button
Exemplo n.º 20
0
    def initializeBitmaps(self):

        dict = self.pathToAP + 'multimedia/youtube/*'
        pages = sorted([
            item for item in glob.glob(dict)
            if item[item.rfind('/') + 1:].isdigit()
        ])
        self.numberOfpages = len(pages)

        self.blissBook = {
        }  #dictionary with keys as number of page and values as list of tuples (each tuple discribes one symbol) in form [bitmap, bitmap's position in sizer, bitmap's label]
        self.numberOfRows, self.numberOfColumns, self.numberOfCells = [], [], []

        for page in pages:
            try:
                pageNumber = int(page[page.rfind('/') + 1:])
            except ValueError:
                print 'Folderowi %s nadano nieprawidłową nazwę. Dopuszczalna jest tylko nazwa numeryczna.' % page[
                    page.rfind('/') + 1:]
                pass

            sizerTopology = open(page + '/sizer')

            for line in sizerTopology:

                if line[:12] == 'numberOfRows':
                    self.numberOfRows.append(int(line[-2]))
                elif line[:15] == 'numberOfColumns':
                    self.numberOfColumns.append(int(line[-2]))
                else:
                    print 'Niewłaściwie opisana tablica na stronie %' % page
                    self.numberOfColumns.append(self.defaultNumberOfColumns)
                    self.numberOfRows.append(self.defaultNumberOfRows)

            symbols = glob.glob(page + '/*.jpg') + glob.glob(
                page + '/*.png') + glob.glob(page +
                                             '/*.JPG') + glob.glob(page +
                                                                   '/*jpeg')
            symbols = [item.decode('utf-8') for item in symbols]

            symbolInfo = []

            self.newHeight = 0.6 * self.winHeight / self.numberOfRows[-1]

            for symbol in symbols:

                image = wx.ImageFromStream(open(symbol, "rb"))

                self.newWidth = image.GetSize()[0] * (
                    self.newHeight / float(image.GetSize()[1]))

                image.Rescale(self.newWidth, self.newHeight,
                              wx.IMAGE_QUALITY_HIGH)
                bitmapSymbol = wx.BitmapFromImage(image)

                symbolName = symbol[symbol.rfind('/') + 1:symbol.rfind('.')]

                try:
                    symbolPosition = int(symbolName.split('_')[0])
                    symbolTranslate = symbolName[symbolName.find('_') +
                                                 1:].replace('_', ' ')
                    symbolInfo.append(
                        [bitmapSymbol, symbolPosition, symbolTranslate])
                except ValueError:
                    print 'Symbol %s w folderze %s ma nieprawidłową nazwę.' % (
                        symbolName.split('_')[0], page[page.rfind('/') + 1:])
                    pass

            symbolInfo.sort(key=lambda symbolInfo: symbolInfo[1])
            self.blissBook[pageNumber] = symbolInfo
Exemplo n.º 21
0
def export_chat(chat, messages, filename, db):
    """
    Exports the chat messages to file.

    @param   chat      chat data dict, as returned from SkypeDatabase
    @param   messages  list of message data dicts
    @param   filename  full path and filename of resulting file, file extension
                       .html|.txt determines file format
    @param   db        SkypeDatabase instance
    """
    result = False
    f = None
    try:
        is_html = filename.lower().endswith(".html")
        is_csv = filename.lower().endswith(".csv")
        is_txt = filename.lower().endswith(".txt")
        if is_txt:
            f = codecs.open(filename, "w", "utf-8")
        else:
            f = open(filename, "w")

        # @todo add stats?
        parser = skypedata.MessageParser(db)
        chat_title = chat["title_long_lc"]
        main_data = {
            "title":          chat_title,
            "date1":          messages[0]["datetime"].strftime("%d.%m.%Y") \
                              if len(messages) else "",
            "date2":          messages[-1]["datetime"].strftime("%d.%m.%Y") \
                              if len(messages) else "",
            "messages_total": util.plural("message", chat["message_count"]),
            "chat_created":   chat["created_datetime"].strftime("%d.%m.%Y") \
                              if chat["created_datetime"] else "",
            "app":            conf.Title,
            "now":            datetime.datetime.now() \
                              .strftime("%d.%m.%Y %H:%M"),
            "db":             db.filename,
            "count":          str(len(messages)),
            "chat_info":      "Showing %s" \
                              % util.plural("message", len(messages)),
        }
        if is_html:
            # Write HTML header and table header
            header_data = dict([(k, escape(v)) for k, v in main_data.items()])
            if header_data["date1"] and header_data["date2"]:
                header_data["chat_info"] += \
                    " from <b>%(date1)s</b> to <b>%(date2)s</b>" % header_data
            header_data["chat_info"] += ".<br />"
            if header_data["chat_created"]:
                header_data["chat_info"] += \
                    "Chat created on <b>%(chat_created)s</b>" % header_data
            if header_data["messages_total"]:
                header_data["chat_info"] += \
                    ("," if header_data["chat_created"] else "Chat has") +\
                    " <b>%(messages_total)s</b> in total" % header_data
            if header_data["chat_created"] or header_data["messages_total"]:
                header_data["chat_info"] += ".<br />"
            header_data.update({
                "title":
                "History of Skype " + header_data["title"],
                "css_avatars":
                "",
                "css_chat_picture":
                "",
                "header_left":
                "",
                "header_right":
                "",
                "header_link":
                ""
            })
            if chat["meta_picture"]:
                raw = chat["meta_picture"].encode("latin1")
                if raw.startswith("\0"):
                    # For some reason, Skype image blobs
                    # can start with a null byte.
                    raw = raw[1:]
                if raw.startswith("\0"):
                    raw = "\xFF" + raw[1:]
                header_data["header_left"] = htmltag("span", {
                    "class": "chat_picture",
                    "title": chat["title"]
                })
                img = wx.ImageFromStream(cStringIO.StringIO(raw))
                header_data["css_chat_picture"] = cssrule("span.chat_picture",{
                    "background":
                        "url(data:image/jpg;base64,%s) " \
                        "center center no-repeat" % base64.b64encode(raw),
                    "margin": "0px 10px 0px 10px",
                    "display": "block",
                    "width": "%spx" % img.Width,
                    "height": "%spx" % img.Height,
                })
            if chat["participants"]:
                for p in chat["participants"]:
                    avatar_class = "avatar__default"
                    if "avatar_image" in p["contact"] \
                    and p["contact"]["avatar_image"]:
                        raw = p["contact"]["avatar_image"].encode("latin1")
                        if raw.startswith("\0"):
                            # For some reason, Skype avatar image blobs
                            # can start with a null byte.
                            raw = raw[1:]
                        if raw.startswith("\0"):
                            #raw = raw[1:]
                            raw = "\xFF" + raw[1:]
                        # Replace dots and commas, as they are
                        # not valid CSS identifier characters
                        avatar_class = "avatar_" \
                            + p["identity"].replace(".", "___") \
                              .replace(",", "---")
                        header_data["css_avatars"] += cssrule(
                            "span.%s" % avatar_class, {
                                "background":
                                    "url(data:image/jpg;base64,%s) center " \
                                    "center no-repeat" % base64.b64encode(raw)
                        })
                    if skypedata.CHATS_TYPE_SINGLE == chat["type"]:
                        title = p["contact"]["name"]
                        name = escape(p["contact"]["name"])
                        if p["contact"]["name"] != p["identity"]:
                            title += " (%s)" % p["identity"]
                            name += "<br />(%s)" % escape(p["identity"])
                        side = "right" if (p["identity"] == db.id) else "left"
                        header_data["header_%s" % side] = "<div>%s" \
                            "<br />%s</div>" % (
                                htmltag("span", {"title": title,
                                    "class": "avatar header %s" % avatar_class}
                                ), name
                            )
            if skypedata.CHATS_TYPE_SINGLE != chat["type"]:
                header_data["header_link"] = PARTICIPANTS_LINK
            for k, v in header_data.items():
                header_data[k] = str(v)
            f.write(CHAT_HTML_HEADER % header_data)
            if skypedata.CHATS_TYPE_SINGLE != chat["type"]:
                for p in sorted(chat["participants"],
                                key=lambda a: a["contact"]["name"].lower()):
                    img_attr = {"class": "avatar avatar__default"}
                    img_attr["title"] = p["contact"]["name"]
                    if p["contact"]["name"] != p["identity"]:
                        img_attr["title"] += " (%s)" % p["identity"]
                    if "avatar_image" in p["contact"] \
                    and p["contact"]["avatar_image"]:
                        # Replace dots and commas, as they are not valid
                        # CSS identifier characters
                        img_attr["class"] = "avatar avatar_%s" \
                            % p["identity"].replace(".", "___") \
                              .replace(",", "---")
                    name = escape(p["contact"]["name"])
                    if p["contact"]["name"] != p["identity"]:
                        name += "<br />(%s)" % escape(p["identity"])
                    f.write("            <span>%(img)s%(name)s</span>\n" % {
                        "name": name,
                        "img": htmltag("span", img_attr),
                    })
            f.write("        </div>\r\n    </td>\r\n</tr>\r\n</table>\r\n" \
              "</td></tr><tr><td><table class='content_table'>\r\n")
        elif is_txt:
            main_data["hr"] = "-" * 79
            f.write("History of Skype %(title)s.\r\n" \
                    "Showing %(count)s messages" % main_data)
            if main_data["date1"] and main_data["date2"]:
                f.write(" from %(date1)s to %(date2)s" % main_data)
            f.write(".\r\n")
            if main_data["chat_created"]:
                f.write("Chat created on %(chat_created)s" % main_data)
            else:
                f.write("Chat has")
            if main_data["messages_total"]:
                f.write(("," if main_data["chat_created"] else "") +
                        " %(messages_total)s in total" % main_data)
            f.write(".\r\n")
            f.write(
                    "Source: %(db)s.\r\n" \
                    "Exported with %(app)s on %(now)s." \
                    "\r\n%(hr)s\r\n" % main_data
            )
        elif is_csv:
            # Initialize CSV writer and write header row
            dialect = csv.excel
            # Default is "," which is actually not Excel
            dialect.delimiter = ";"
            # Default is "\r\n", which causes another "\r" to be written
            dialect.lineterminator = "\r"
            csv_writer = csv.writer(f, dialect)
            csv_writer.writerow(["Time", "Author", "Message"])

        colourmap = collections.defaultdict(lambda: "remote")
        colourmap[db.id] = "local"
        previous_day = datetime.date.fromtimestamp(0)
        for m in messages:
            if m["datetime"].date() != previous_day:
                # Day has changed: insert a date header
                previous_day = m["datetime"].date()
                weekday = previous_day.strftime("%A").capitalize()
                date = previous_day.strftime("%d. %B %Y")
                if locale.getpreferredencoding():
                    weekday = weekday.decode(locale.getpreferredencoding())
                    date = date.decode(locale.getpreferredencoding())
                if is_html:
                    f.write(
                        "<tr>\r\n\t<td class='t1'></td>\r\n\t" \
                        "<td class='day t2'></td>\r\n\t" \
                        "<td class='day t3'></td>\r\n\t" \
                        "<td class='day' colspan='2'><span class='weekday'>" \
                        "%(weekday)s</span>, %(date)s</td>\r\n</tr>\r\n" % {
                            "weekday": escape(weekday),
                            "date": escape(date)
                    })
                elif is_txt:
                    f.write("\r\n%(weekday)s, %(date)s\r\n%(hr)s\r\n\r\n" % {
                        "weekday": weekday,
                        "date": date,
                        "hr": "-" * 40
                    })

            if is_html:
                body = parser.parse(m, html={"w": -1, "export": True})
                f.write("<tr>\r\n\t" \
                    "<td class='author %(authorclass)s' colspan='2'>" \
                    "%(name)s</td>\r\n\t" \
                    "<td class='t3'></td>\r\n\t<td>%(text)s</td>\r\n\t" \
                    "<td class='timestamp'>%(time)s</td>\r\n</tr>\r\n" % {
                        "authorclass": colourmap[m["author"]],
                        "time": m["datetime"].strftime("%H:%S"),
                        "name": escape(m["from_dispname"]),
                        "text": body
                })
            else:
                parsed_text = parser.parse(m, text=True)
                try:
                    parsed_text = parsed_text.decode("utf-8")
                except Exception, e:
                    pass
            if is_txt:
                f.write(
                    "%(datetime)s %(name)s:\r\n%(text)s\r\n\r\n" % {
                        "datetime": m["datetime"].strftime("%H:%S"),
                        "name": m["from_dispname"],
                        "text": parsed_text
                    })
            elif is_csv:
                try:
                    parsed_text = parser.parse(m, text=True)
                    parsed_text = parsed_text.decode("utf-8")
                except Exception, e:
                    pass
                values = [
                    m["datetime"].strftime("%Y-%m-%d %H:%M:%S"),
                    m["from_dispname"].encode("utf-8"),
                    parsed_text.encode("utf-8")
                ]
                csv_writer.writerow(values)
Exemplo n.º 22
0
 def GetBmp(self, qualite=wx.IMAGE_QUALITY_HIGH):
     buffer = self.GetBuffer()
     img = wx.ImageFromStream(buffer, wx.BITMAP_TYPE_ANY)
     ##        img = img.Rescale(width=taillePhoto[0], height=taillePhoto[1], quality=qualite)
     bmp = img.ConvertToBitmap()
     return bmp
Exemplo n.º 23
0
def GetExpandedIconImage():
    import cStringIO
    stream = cStringIO.StringIO(GetExpandedIconData())
    return wx.ImageFromStream(stream)
Exemplo n.º 24
0
def GetMondrianBitmap():
    stream = GetMondrianStream()
    image = wx.ImageFromStream(stream)
    return wx.BitmapFromImage(image)
Exemplo n.º 25
0
def GetMondrianImage():
    stream = cStringIO.StringIO(GetMondrianData())
    return wx.ImageFromStream(stream)
Exemplo n.º 26
0
def GetMondrianImage(i=0, fn=None):
    import cStringIO

    stream = cStringIO.StringIO(GetMondrianData(i, fn))
    return wx.ImageFromStream(stream)
Exemplo n.º 27
0
def CreateRemote(plugin, xPos, yPos, alwaysOnTop):
    data = plugin.data
    borderSize = plugin.borderSize

    if plugin.frame:
        plugin.frame.Destroy()
    plugin.frame = frame = RemoteFrame(plugin, (xPos, yPos), alwaysOnTop)
    panel = RemotePanel(frame, plugin)
    mainSizer = wx.BoxSizer(wx.VERTICAL)
    mainSizer.Add((0, borderSize))
    lineSizer = wx.BoxSizer(wx.HORIZONTAL)
    x = 0
    y = 0

    def MakeButtonDownFunc(eventstring):
        if not eventstring:
            return

        def OnButtonDown(event):
            event.Skip()
            plugin.lastEvent = plugin.TriggerEnduringEvent(eventstring)

        return OnButtonDown

    for itemType, args in data:
        if itemType is ButtonType:
            kwargs = args

            def GetOption(name):
                return kwargs.get(name, plugin.defaults.get(name))

            label = kwargs.get("label")
            event = kwargs.get("event")
            image = kwargs.get("image", None)
            invisible = kwargs.get("invisible", False)
            size = (GetOption("width"), GetOption("height"))
            if invisible:
                # create a spacer
                button = size
            else:
                if image:
                    stream = StringIO(b64decode(image))
                    bmp = wx.BitmapFromImage(wx.ImageFromStream(stream))
                    stream.close()
                    button = GenBitmapButton(panel, -1, bmp, size=size)
                    button.SetLabel(label)
                else:
                    button = GenButton(panel, -1, label, size=size)
                button.SetFont(
                    wx.FontFromNativeInfoString(GetOption("fontInfo")))

                button.SetBezelWidth(3)
                button.SetBackgroundColour(GetOption("backgroundColour"))
                button.SetForegroundColour(GetOption("foregroundColour"))

                OnButtonDown = MakeButtonDownFunc(event)
                if OnButtonDown:
                    button.Bind(wx.EVT_LEFT_DOWN, OnButtonDown)
                    button.Bind(wx.EVT_LEFT_DCLICK, OnButtonDown)
                    button.Bind(wx.EVT_LEFT_UP, plugin.OnButtonUp)
            if x == 0:
                lineSizer.Add(button)
            else:
                lineSizer.Add(button, 0, wx.LEFT, plugin.rowGap)
            x += 1
        elif itemType is LineType:
            height = args[0]
            mainSizer.Add(lineSizer, 0, wx.BOTTOM | wx.ALIGN_CENTER_HORIZONTAL,
                          height + plugin.columnGap)
            lineSizer = wx.BoxSizer(wx.HORIZONTAL)
            y += 1
            x = 0

    mainSizer.Add(lineSizer, 0, wx.LEFT | wx.RIGHT, borderSize)
    mainSizer.Add((0, borderSize))
    panel.SetSizerAndFit(mainSizer)
    frame.SetClientSize(panel.GetSize())
    frame.Show(True)
    frame.Update()
Exemplo n.º 28
0
 def __init__(self, *args, **kwds):
     kwds["style"] = wx.DEFAULT_FRAME_STYLE
     wx.Frame.__init__(self, *args, **kwds)
     font = wx.Font(9,
                    wx.FONTFAMILY_DEFAULT,
                    style=wx.FONTSTYLE_NORMAL,
                    weight=wx.FONTWEIGHT_NORMAL)
     self.lbl_query = wx.StaticText(self,
                                    -1,
                                    "  Song:  ",
                                    style=wx.ALIGN_CENTRE)
     self.lbl_query.SetFont(font)
     self.txt_query = wx.TextCtrl(self, 1, "", style=wx.TE_PROCESS_ENTER)
     self.fb = wx.StaticBitmap(self,
                               bitmap=wx.BitmapFromImage(
                                   wx.ImageFromStream(
                                       fbicon, wx.BITMAP_TYPE_PNG)),
                               size=(22, 22))
     self.folder_chooser = wx.Button(
         self,
         -1,
         "Choose Destination",
         size=[-1, self.txt_query.GetSize().GetHeight()])
     self.lst_results = ObjectListView(self, -1, style=wx.LC_REPORT)
     self.lst_downloads = GroupListView(self, -1, style=wx.LC_REPORT)
     self.lst_artists = ObjectListView(self, -1, style=wx.LC_REPORT)
     self.lst_albums = ObjectListView(self, -1, style=wx.LC_REPORT)
     self.lst_songs = ObjectListView(self, -1, style=wx.LC_REPORT)
     self.lst_songs.ToggleWindowStyle(wx.HSCROLL)
     self.frame_statusbar = self.CreateStatusBar(1, wx.SB_RAISED)
     self.__set_properties()
     self.__do_layout()
     self.Bind(EVT_EXEC_FUNC, self._ExecFunc)
     self.Bind(wx.EVT_TEXT_ENTER, self._TextEnter, self.txt_query)
     self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self._ResultsContext,
               self.lst_results)
     self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self._ResultsContext,
               self.lst_songs)
     self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._DoubleClick,
               self.lst_results)
     self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._DoubleClick,
               self.lst_songs)
     self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._DoubleClick,
               self.lst_downloads)
     self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self._DownloadsContext,
               self.lst_downloads)
     self.Bind(wx.EVT_BUTTON, self._ChooseFolder, self.folder_chooser)
     self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._ObjectSelected,
               self.lst_artists)
     self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._ObjectSelected,
               self.lst_albums)
     self.fb.Bind(wx.EVT_LEFT_DOWN, self._FBClick)
     self.txt_query.Bind(wx.EVT_KEY_DOWN, self._Tab)
     self.Bind(wx.EVT_CLOSE, self._Close)
     self.menu_results = {}
     self.menu_downloads = {}
     self.menu_results[ID_DOWNLOAD] = "Download"
     self.menu_downloads[ID_REMOVE] = "Remove"
     self.artists = []
     if sys.platform == 'win32':
         self.SetIcon(wx.Icon(sys.executable, wx.BITMAP_TYPE_ICO))
     else:
         if os.path.exists("groove.ico"):
             self.SetIcon(wx.Icon("groove.ico", wx.BITMAP_TYPE_ICO))
Exemplo n.º 29
0
def getdevidelogo32x32Image():
    stream = cStringIO.StringIO(getdevidelogo32x32Data())
    return wx.ImageFromStream(stream)
Exemplo n.º 30
0
    def createGui(self):

        if self.PicNr == len(self.WordsList):
            self.PicNr = 0

        if self.control != 'tracker':
            event = eval('wx.EVT_LEFT_DOWN')
        else:
            event = eval('wx.EVT_BUTTON')

        self.picture = self.WordsList[self.PicNr]
        self.PicNr += 1
        self.path = self.pathToAP + 'multimedia/ewriting/pictures/'
        im = wx.ImageFromStream(open(self.path + self.picture, "rb"))
        x = im.GetWidth()
        y = im.GetHeight()

        if x > y:
            im = im.Scale(500, 400)
        elif x == y:
            im = im.Scale(500, 500)
        else:
            im = im.Scale(400, 500)

        picture = wx.BitmapFromImage(im)
        self.word = self.picture[:self.picture.index('.')]

        self.WORD = self.word.upper()

        self.extraWords = []  #wybiera dodatkowe slowa
        while len(self.extraWords) < self.numberOfExtraWords:
            slowo = self.WordsList[np.random.randint(0, len(self.WordsList),
                                                     1)[0]]
            slowo = slowo[:slowo.index('.')]
            SLOWO = slowo.upper()
            if SLOWO not in self.extraWords and SLOWO != self.WORD:
                self.extraWords.append(SLOWO)

        b = bt.GenBitmapButton(self, -1, bitmap=picture)

        obiekty_wyrazow = []
        self.wyrazy_w_kolejnosci = []
        gdzie_poprawne = np.random.randint(0, self.numberOfExtraWords, 1)[0]

        for i, j in enumerate(self.extraWords):
            be = bt.GenButton(self, -1, j)
            be.name = j
            be.SetFont(
                wx.Font(self.tableFontSize, eval(self.tableFont),
                        wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False))
            be.SetBackgroundColour(self.backgroundColour)
            be.Bind(event, self.onPress)
            obiekty_wyrazow.append(be)
            self.wyrazy_w_kolejnosci.append(j)

        be = bt.GenButton(self, -1, self.WORD)
        be.SetFont(
            wx.Font(self.tableFontSize, eval(self.tableFont),
                    wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False))
        be.name = self.WORD
        be.SetBackgroundColour(self.backgroundColour)
        be.Bind(event, self.onPress)
        obiekty_wyrazow.insert(gdzie_poprawne, be)
        self.wyrazy_w_kolejnosci.insert(gdzie_poprawne, self.WORD)

        res = bt.GenButton(
            self, -1,
            u'TWÓJ WYNIK:   ' + str(self.result) + ' / ' + str(self.maxPoints))
        res.SetFont(
            wx.Font(int(self.tableFontSize * 0.6), eval(self.tableFont),
                    wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False))

        self.wordSizer = wx.GridSizer(self.numberOfExtraWords + 1, 1,
                                      self.xBorder, self.yBorder)
        for item in obiekty_wyrazow:
            self.wordSizer.Add(item, proportion=1, flag=wx.EXPAND)

        try:
            self.subSizerP.Hide(0)
            self.subSizerP.Remove(0)
            self.subSizerP.Add(res, 0, wx.EXPAND)  #dodanie wyniku
            self.subSizer0.Hide(0)
            self.subSizer0.Remove(0)
            self.subSizer0.Hide(0)
            self.subSizer0.Remove(0)
            self.subSizer0.Add(
                self.wordSizer, 0, wx.EXPAND
            )  #tutaj trzeba dodac caly zagniezdzony subsizer ze slowami
            self.subSizer0.Add(b, 0, wx.EXPAND)  #dodanie zdjecia
            items = self.subSizer.GetChildren()
            for item in items:
                b = item.GetWindow()
                b.SetBackgroundColour(self.backgroundColour)
                b.Update

        except AttributeError:
            if self.czyBack:
                self.czyBack = False
            else:
                self.mainSizer = wx.BoxSizer(wx.VERTICAL)

            self.subSizerP = wx.GridSizer(1, 1, self.xBorder, self.yBorder)
            self.subSizer0 = wx.GridSizer(1, 2, self.xBorder, self.yBorder)
            self.subSizer = wx.GridSizer(1, 4, self.xBorder, self.yBorder)
            self.subSizerP.Add(res, 0, wx.EXPAND)
            self.subSizer0.Add(self.wordSizer, 0, wx.EXPAND)
            self.subSizer0.Add(b, 0, wx.EXPAND)
            self.icons = sorted(os.listdir(self.pathToAP + 'icons/ewriting/'))[
                1:]  #bo pierwszy to 1speller a tu ma go nie byc
            self.path = self.pathToAP + 'icons/ewriting/'

            for idx, icon in enumerate(self.icons):

                if icon[0].isdigit():
                    k = wx.BitmapFromImage(
                        wx.ImageFromStream(open(self.path + icon, "rb")))
                    b = bt.GenBitmapButton(self, -1, bitmap=k)
                    b.name = self.labels[idx]
                    b.SetBackgroundColour(self.backgroundColour)
                    b.Bind(event, self.onPress)
                    self.subSizer.Add(b, 0, wx.EXPAND)

            self.mainSizer.Add(self.subSizerP,
                               1,
                               wx.EXPAND | wx.TOP | wx.RIGHT | wx.LEFT,
                               border=self.xBorder)
            self.mainSizer.Add(self.subSizer0,
                               7,
                               wx.EXPAND | wx.TOP | wx.BOTTOM | wx.LEFT
                               | wx.RIGHT,
                               border=self.xBorder)
            self.mainSizer.Add(self.subSizer,
                               2,
                               wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT,
                               border=self.xBorder)

            self.SetSizer(self.mainSizer, deleteOld=True)

        self.SetBackgroundColour('black')
        self.Layout()
        self.Refresh()
        self.Center()
        self.MakeModal(True)
        self.flaga = 0
        self.poczatek = True