def getringtones(self, result):
     result=com_lgvx4400.Phone.getringtones(self, result)
     if not conversions.helperavailable('pvconv'):
         return result
     media=result['ringtone']
     _qcp_file=common.gettempfilename('qcp')
     _wav_file=common.gettempfilename('wav')
     try:
         vmemo_files=self.listfiles(self.VoiceMemoDir)
         keys=vmemo_files.keys()
         for k in keys:
             if k.endswith('.qcp'):
                 key_name='VoiceMemo'+k[-8:-4]
                 file(_qcp_file, 'wb').write(self.getfilecontents(k, True))
                 conversions.convertqcptowav(_qcp_file, _wav_file)
                 media[key_name]=file(_wav_file, 'rb').read()
     except:
         if __debug__:
             raise
     try:
         os.remove(_qcp_file)
         os.remove(_wav_file)
     except:
         pass
     result['ringtone']=media
     return result
 def __init__(self, parent, file, convertinfo):
     wx.Dialog.__init__(self, parent, title="Convert Audio File", style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.SYSTEM_MENU|wx.MAXIMIZE_BOX)
     self.file=file
     self.convertinfo=convertinfo
     self.afi=None
     self.temporaryfiles=[]
     self.wavfile=common.gettempfilename("wav")      # full length wav equivalent
     self.clipwavfile=common.gettempfilename("wav")  # used for clips from full length wav
     self.temporaryfiles.extend([self.wavfile, self.clipwavfile])
     getattr(self, self.PARAMETERS[convertinfo.format]['setup'])()
     vbs=wx.BoxSizer(wx.VERTICAL)
     self.create_convert_pane(vbs, file, convertinfo)
     self.create_crop_panel(vbs)
     vbs.Add(self.CreateButtonSizer(wx.OK|wx.CANCEL|wx.HELP), 0, wx.ALL|wx.ALIGN_RIGHT, 5)
     self.SetSizer(vbs)
     vbs.Fit(self)
     self.FindWindowById(wx.ID_OK).Enable(False)
     for i in self.cropids:
         self.FindWindowById(i).Enable(False)
     wx.EVT_BUTTON(self, wx.ID_OK, self.OnOk)
     wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnCancel)
     wx.EVT_TIMER(self, self.ID_TIMER, self.OnTimer)
     wx.EVT_BUTTON(self, wx.ID_HELP, lambda _: wx.GetApp().displayhelpid(helpids.ID_DLG_AUDIOCONVERT))
     self.sound=None
     self.timer=wx.Timer(self, self.ID_TIMER)
     if guihelper.IsMac():
         self.zerolenwav=guihelper.getresourcefile("zerolen.wav")
def convertto8bitpng_joe(pngdata):
    "Convert a PNG file to 8bit color map"
    "Separate routine for now so not to screw up existing one, may merge later"
    if pngdata[1:4]!='PNG':
        return pngdata
    pngtopnmbin=gethelperbinary('pngtopnm')
    ppmquantbin=gethelperbinary('ppmquant')
    pnmtopngbin=gethelperbinary('pnmtopng')
    print "pngtopnm: "+pngtopnmbin
    print "ppmquant: "+ppmquantbin
    print "pnmtopng: "+pnmtopngbin
    png=common.gettempfilename("png")
    open(png, "wb").write(pngdata)
    num_of_colors=wx.Image(png).ComputeHistogram(wx.ImageHistogram())
    print 'number of colors:', num_of_colors
    if num_of_colors>256:
        os.remove(png)
        return pngdata
    pnm=common.gettempfilename("pnm")
    s='"'+pngtopnmbin+'"' + ' < '+png+' > '+pnm
    os.system(s)
    os.remove(png)
    pnmq=common.gettempfilename("pnm")
    s='"'+ppmquantbin+'"'+' '+`num_of_colors`+' '+pnm+ ' > '+pnmq
    os.system(s)
    s ='"'+pnmtopngbin+'"' + ' < ' + pnmq + ' > '+png
    os.system(s)
    os.remove(pnmq)
    pngquantdata=open(png, 'rb').read()
    os.remove(png)
    os.remove(pnm)
    print 'old size: ',len(pngdata),', new size: ',len(pngquantdata)
    return pngquantdata
def convertjpgtoavi(jpg_data, avi_file_name, fps=4, new_file=False):

    bmp2avi=shortfilename(gethelperbinary('bmp2avi'))

    if new_file:

        try:

            os.remove(avi_file_name)

        except:

            pass

    jpg_name=shortfilename(common.gettempfilename("jpg"))

    bmp_name=shortfilename(common.gettempfilename("bmp"))

    open(jpg_name, "wb").write(jpg_data)

    wx.Image(jpg_name).SaveFile(bmp_name, wx.BITMAP_TYPE_BMP)

    run(bmp2avi, '-f', `fps`, '-i', bmp_name, '-o', avi_file_name)

    try:

        os.remove(jpg_name)

        os.remove(bmp_name)

    except:

        pass
def convertto8bitpng(pngdata, maxsize):
    "Convert a PNG file to 8bit color map"
    size=len(pngdata)
    if size<=maxsize or pngdata[1:4]!='PNG':
        return pngdata
    p=sys.path[0]
    if os.path.isfile(p):
        p=os.path.dirname(p)
    helpersdirectory=os.path.abspath(os.path.join(p, 'helpers'))
    print "Helper Directory: "+helpersdirectory
    if sys.platform=='win32':
        osext=".exe"
    if sys.platform=='darwin':
        osext=".mbin"
    if sys.platform=='linux2':
        osext=".lbin"
    pngtopnmbin=gethelperbinary('pngtopnm')
    ppmquantbin=gethelperbinary('ppmquant')
    pnmtopngbin=gethelperbinary('pnmtopng')
    print "pngtopnm: "+pngtopnmbin
    print "ppmquant: "+ppmquantbin
    print "pnmtopng: "+pnmtopngbin
    png=common.gettempfilename("png")
    open(png, "wb").write(pngdata)
    pnm=common.gettempfilename("pnm")
    s='"'+pngtopnmbin+'"' + ' < '+png+' > '+pnm
    os.system(s)
    os.remove(png)
    ncolormax=257
    ncolormin=1
    ncolortry=256
    ncolor=ncolortry
    pnmq=common.gettempfilename("pnm")
    while size>maxsize or ncolormax-ncolor>1:
        ncolor=ncolortry
        s='"'+ppmquantbin+'"'+' '+`ncolortry`+' '+pnm+ ' > '+pnmq
        os.system(s)
        s ='"'+pnmtopngbin+'"' + ' < ' + pnmq + ' > '+png
        os.system(s)
        os.remove(pnmq)
        pngquantdata=open(png,"rb").read()
        os.remove(png)
        size=len(pngquantdata)
        print `ncolor`+' '+`size`
        if size>maxsize:
            ncolormax=ncolor
            ncolortry=(ncolor+ncolormin)/2
        else:
            ncolormin=ncolor
            ncolortry=(ncolor+ncolormax)/2
    os.remove(pnm)
    return pngquantdata
def adjustwavfilevolume(wavfilename, gain):
    """ Ajdust the volume of a wav file.
    """
    f=open(wavfilename, 'rb')
    headers=f.read(20)
    subchunk1size=common.LSBUint32(headers[16:20])
    headers+=f.read(subchunk1size)
    headers+=f.read(8)  # 4 byte ID and 4 byte length
    subchunk2size=common.LSBUint32(headers[-4:])
    bitspersample=common.LSBUint16(headers[34:36])
    if bitspersample!=16:
        print 'Volume adjustment only works with 16-bit wav file',bitspersample
        f.close()
        return
    sample_num=subchunk2size/2  # always 16-bit per channel per sample
    temp_name=common.gettempfilename("wav")
    f_temp=file(temp_name, 'wb')
    f_temp.write(headers)
    delta=pow(10.0, (gain/10.0))
    for i in range(sample_num):
        d=int(struct.unpack('<h', f.read(2))[0]*delta)
        if d>32767:
            d=32767
        elif d<-32768:
            d=-32768
        f_temp.write(struct.pack('<h', d))
    f_temp.close()
    f.close()
    os.remove(wavfilename)
    os.rename(temp_name, wavfilename)
def converttomp3(inputfilename, bitrate, samplerate, channels):

    """Reads inputfilename and returns data for an mp3 conversion
    @param bitrate: bitrate to use in khz (ie 16 is 16000 bits per second)
    @param samplerate: audio sampling rate in Hertz
    @param channels: 1 is mono, 2 is stereo
    """

    ffmpeg=gethelperbinary("ffmpeg")

    mp3file=common.gettempfilename("mp3")

    try:

        try:

            run(ffmpeg, "-i", shortfilename(inputfilename), "-hq", "-ab", `bitrate`, "-ar", `samplerate`, "-ac", `channels`, shortfilename(mp3file))

        except common.CommandExecutionFailed:

            raise ConversionFailed()

        return open(mp3file, "rb").read()

    finally:

        try: os.remove(mp3file)

        except: pass
def convertavitobmp(avi_data, frame_num=0):
    avi_file=shortfilename(common.gettempfilename("avi"))
    f=open(avi_file, "wb")
    f.write(avi_data)
    f.close()
    img=convertfileavitobmp(avi_file, frame_num)
    try:
        os.remove(avi_file)
    except:
        pass
    return img
def convertfileavitobmp(avi_file_name, frame_num=0):
    bmp2avi=shortfilename(gethelperbinary('bmp2avi'))
    bmp_file_name=shortfilename(common.gettempfilename("bmp"))
    run(bmp2avi, '-t', `frame_num`, '-i', shortfilename(avi_file_name),
        '-o', bmp_file_name)
    img=wx.Image(bmp_file_name)
    try:
        os.remove(bmp_file_name)
    except:
        pass
    return img
def convertfilelgbittobmp(bit_file_name):
    "File-based wrapper for convertlgbittobmp."
    bmp=common.gettempfilename("png")
    bmpdata=convertlgbittobmp(open(bit_file_name,"rb").read())
    open(bmp, "wb").write(bmpdata)
    img=wx.Image(bmp)
    try:
        os.remove(bmp)
    except:
        pass
    return img
 def saveimage_PNG(self, img, imgparams):
     f=common.gettempfilename("png")
     rc = img.SaveFile(f, wx.BITMAP_TYPE_PNG)
     if rc:
         data = open(f, 'rb').read()
     try:    
         os.remove(f)
     except: 
         pass
     if not rc:
         return False
     return data
 def saveimage_JPEG(self, img, imgparams):
     img.SetOptionInt("quality", 100)        
     f=common.gettempfilename("jpg")
     rc = img.SaveFile(f, wx.BITMAP_TYPE_JPEG)
     if rc:
         data = open(f, 'rb').read()
     try:    
         os.remove(f)
     except: 
         pass
     if not rc:
         return False
     return data
 def saveimage_BMP(self, img, imgparams):
     if img.ComputeHistogram(wx.ImageHistogram())<=236: # quantize only does 236 or less
         img.SetOptionInt(wx.IMAGE_OPTION_BMP_FORMAT, wx.BMP_8BPP)
     f=common.gettempfilename("bmp")
     rc = img.SaveFile(f, wx.BITMAP_TYPE_BMP)
     if rc:
         data = open(f, 'rb').read()
     try:    
         os.remove(f)
     except: 
         pass
     if not rc:
         return False
     return data
 def OnLaunch(self, _):
     item=self.GetSelectedItems()[0]
     temp=common.gettempfilename(common.getext(item.name))
     me=self._data[self.database_key][item.key]
     f=open(temp, "wb")
     f.write(me.mediadata)
     f.close()
     if guihelper.IsMac():
         import findertools
         findertools.launch(temp)
         return
     cmd=guihelper.GetOpenCommand(item.mimetypes, temp)
     if cmd is None:
         wx.Bell()
     else:
         wx.Execute(cmd, wx.EXEC_ASYNC)
 def __init__(self, calwidget, mainwindow, config):
     super(CalendarPrintDialog, self).__init__(mainwindow, -1, 'Print Calendar')
     self._cal_widget=calwidget
     self._xcp=self._html=self._dns=None
     self._dt_index=self._dt_start=self._dt_end=None
     self._date_changed=self._style_changed=False
     self._tmp_file=common.gettempfilename("htm")
     vbs=wx.BoxSizer(wx.VERTICAL)
     hbs=wx.BoxSizer(wx.HORIZONTAL)
     sbs=wx.StaticBoxSizer(wx.StaticBox(self, -1, 'Print Range'),
                           wx.VERTICAL)
     gs=wx.FlexGridSizer(-1, 2, 5, 5)
     gs.AddGrowableCol(1)
     gs.Add(wx.StaticText(self, -1, 'Start:'), 0, wx.ALL, 0)
     self._start_date=wx.DatePickerCtrl(self, style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
     wx.EVT_DATE_CHANGED(self, self._start_date.GetId(),
                         self.OnDateChanged)
     gs.Add(self._start_date, 0, wx.ALL, 0)
     gs.Add(wx.StaticText(self, -1, 'End:'), 0, wx.ALL, 0)
     self._end_date=wx.DatePickerCtrl(self, style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
     wx.EVT_DATE_CHANGED(self, self._end_date.GetId(),
                         self.OnDateChanged)
     gs.Add(self._end_date, 0, wx.ALL, 0)
     sbs.Add(gs, 1, wx.EXPAND|wx.ALL, 5)
     hbs.Add(sbs, 0, wx.ALL, 5)
     self._print_style=wx.RadioBox(self, -1, 'Print Style',
                                    choices=['List View', 'Month View'],
                                    style=wx.RA_SPECIFY_ROWS)
     wx.EVT_RADIOBOX(self, self._print_style.GetId(), self.OnStyleChanged)
     hbs.Add(self._print_style, 0, wx.ALL, 5)
     vbs.Add(hbs, 0, wx.ALL, 5)
     vbs.Add(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)
     hbs=wx.BoxSizer(wx.HORIZONTAL)
     for b in (('Print', -1, self.OnPrint),
               ('Page Setup', -1, self.OnPageSetup),
               ('Print Preview', -1, self.OnPrintPreview),
               ('Close', wx.ID_CANCEL, self.OnClose)):
         btn=wx.Button(self, b[1], b[0])
         hbs.Add(btn, 0, wx.ALIGN_CENTER|wx.ALL, 5)
         if b[2] is not None:
             wx.EVT_BUTTON(self, btn.GetId(), b[2])
     vbs.Add(hbs, 0, wx.ALIGN_CENTRE|wx.EXPAND|wx.ALL, 5)
     self.SetSizer(vbs)
     self.SetAutoLayout(True)
     vbs.Fit(self)
    def get_video(self, result, video_file_name):
        if not conversions.helperavailable('bmp2avi'):
            # helper not available , just bail
            self.__phone.log('Helper bmp2avi not found, cannot retrieve '+\
                             video_file_name)
            return result
        self.__phone.log('Getting video file '+video_file_name)
        media=result.get(self.__file_type, {})
        idx=result.get(self.__index_type, {})
        tmp_avi_name=common.gettempfilename("avi")
        try:
            file_list=self.__phone.listfiles(self.__path)
        except com_brew.BrewNoSuchDirectoryException:
            file_list={}
        except:
            file_list={}
            if __debug__: raise

        if not len(file_list):
            # empty directory
            return result
        file_keys=file_list.keys()
        file_keys.sort();
        for k in file_keys:
            try:
                conversions.convertjpgtoavi(self.__phone.getfilecontents(k, True)[96:],
                                            tmp_avi_name)
            except:
                self.__phone.log('Failed to read video files')
                if __debug__: raise
        # got the avi file, now prep to send it back
        if len(idx):
            idx_k=max(idx.keys())+1
        else:
            idx_k=0
        media[video_file_name]=open(tmp_avi_name, 'rb').read()
        idx[idx_k]={ 'name': video_file_name, 'origin': 'video' }
        result[self.__file_type]=media
        result[self.__index_type]=idx
        try:
            os.remove(tmp_avi_name)
        except:
            pass
        return result
 def _rescale_and_cache(self, wp, filename,
                        fundamentals):
     try:
         _data=self.getfilecontents(filename, True)
         _tmpname=common.gettempfilename('tmp')
         file(_tmpname, 'wb').write(_data)
         _img=wx.Image(_tmpname)
         if not _img.Ok():
             self.log('Failed to understand image: '+filename)
             return
         _img.Rescale(128, 96)
         _img.SaveFile(_tmpname, wx.BITMAP_TYPE_JPEG)
         _newfilename=self.protocolclass.PB_WP_CACHE_PATH+'/$'+filename.replace('/', '$')
         _data=file(_tmpname, 'rb').read()
         self.writefile(_newfilename, _data)
         return _newfilename
     except:
         if __debug__:
             self.log('Failed to add cache image: '+wp)
             raise
def BPFSImageFile(fshandler, location, name=None, img=None, width=-1, height=-1, valign="center", bgcolor=None):

    """Handles image files
    If we have to do any conversion on the file then we return PNG
    data.  This used to be a class derived from wx.FSFile, but due to
    various wxPython bugs it instead returns the parameters to make a
    wx.FSFile since a new one has to be made every time.
    """

    if img is None and width<0 and height<0:

        mime=guihelper.getwxmimetype(name)

        if mime not in (None, "image/x-bmp"):

            return (open(name, "rb"), location, mime, "", wx.DateTime_Now())

    if img is None:

        img=wx.Image(name)

    if width>0 and height>0:

        b=ScaleImageIntoBitmap(img, width, height, bgcolor, valign)

    else:

        b=img.ConvertToBitmap()

    f=common.gettempfilename("png")

    if not b.SaveFile(f, wx.BITMAP_TYPE_PNG):

        raise Exception, "Saving to png failed"

    data=open(f, "rb").read()

    os.remove(f)

    return (cStringIO.StringIO(data), location, "image/png", "", wx.DateTime_Now())
 def _rescale_and_cache(self, wp, filename, idx,
                        fundamentals):
     # rescale the wp and add it to the cache dir
     try:
         _data=self.getfilecontents(filename, True)
         _tmpname=common.gettempfilename('tmp')
         file(_tmpname, 'wb').write(_data)
         _img=wx.Image(_tmpname)
         if not _img.Ok():
             self.log('Failed to understand image: '+filename)
             return
         _img.Rescale(self.protocolclass.PB_WP_CACHE_WIDTH,
                      self.protocolclass.PB_WP_CACHE_HEIGHT)
         _img.SaveFile(_tmpname, wx.BITMAP_TYPE_JPEG)
         _newfilename='%(prefix)s/%(index)d.jpg'%\
                       { 'prefix': self.protocolclass.PB_WP_CACHE_PATH,
                         'index': idx }
         _data=file(_tmpname, 'rb').read()
         self.writefile(_newfilename, _data)
         return _newfilename
     except:
         if __debug__:
             self.log('Failed to add cache image: '+wp)
             raise
 def mp3setup(self):
     self.mp3file=common.gettempfilename("mp3")
     self.tmp_mp3file=common.gettempfilename('mp3')
     self.temporaryfiles.append(self.mp3file)
     self.temporaryfiles.append(self.tmp_mp3file)
 def qcpsetup(self):
     self.qcpfile=common.gettempfilename("qcp")
     self.temporaryfiles.append(self.qcpfile)
Example #22
0
def convertto8bitpng(pngdata, maxsize):
    "Convert a PNG file to 8bit color map"

    # Return files small enough, or not PNG as is
    size=len(pngdata)
    if size<=maxsize or pngdata[1:4]!='PNG':
        return pngdata

    p=sys.path[0]
    if os.path.isfile(p):
        p=os.path.dirname(p)
    helpersdirectory=os.path.abspath(os.path.join(p, 'helpers'))
    print "Helper Directory: "+helpersdirectory
    if sys.platform=='win32':
        osext=".exe"
    if sys.platform=='darwin':
        osext=".mbin"
    if sys.platform=='linux2':
        osext=".lbin"
        
    pngtopnmbin=gethelperbinary('pngtopnm')
    ppmquantbin=gethelperbinary('ppmquant')
    pnmtopngbin=gethelperbinary('pnmtopng')
    print "pngtopnm: "+pngtopnmbin
    print "ppmquant: "+ppmquantbin
    print "pnmtopng: "+pnmtopngbin

    # Write original image to a temp file
    png=common.gettempfilename("png")
    open(png, "wb").write(pngdata)

    # Convert this image to pnm
    pnm=common.gettempfilename("pnm")
    s='"'+pngtopnmbin+'"' + ' < '+png+' > '+pnm
    os.system(s)
    #self.log(s)
    os.remove(png)

    # Binary search to find largest # of colors with a file size still
    # less than maxsize

    ncolormax=257
    ncolormin=1
    ncolortry=256
    ncolor=ncolortry
    pnmq=common.gettempfilename("pnm")

    while size>maxsize or ncolormax-ncolor>1:
        ncolor=ncolortry
        s='"'+ppmquantbin+'"'+' '+`ncolortry`+' '+pnm+ ' > '+pnmq
        #self.log(s)
        os.system(s)
        s ='"'+pnmtopngbin+'"' + ' < ' + pnmq + ' > '+png
        #self.log(s)
        os.system(s)
        os.remove(pnmq)
        pngquantdata=open(png,"rb").read()
        os.remove(png)
        size=len(pngquantdata)
        print `ncolor`+' '+`size`
        if size>maxsize:
            ncolormax=ncolor
            ncolortry=(ncolor+ncolormin)/2
        else:
            ncolormin=ncolor
            ncolortry=(ncolor+ncolormax)/2

    os.remove(pnm)
    return pngquantdata
	def getringtones(self, result):

        result=com_lgvx4400.Phone.getringtones(self, result)

        if not conversions.helperavailable('pvconv'):

            return result

        media=result['ringtone']

        _qcp_file=common.gettempfilename('qcp')

        _wav_file=common.gettempfilename('wav')

        try:

            vmemo_files=self.listfiles(self.VoiceMemoDir)

            keys=vmemo_files.keys()

            for k in keys:

                if k.endswith('.qcp'):

                    key_name='VoiceMemo'+k[-8:-4]

                    file(_qcp_file, 'wb').write(self.getfilecontents(k, True))

                    conversions.convertqcptowav(_qcp_file, _wav_file)

                    media[key_name]=file(_wav_file, 'rb').read()

        except:

            if __debug__:

                raise

        try:

            os.remove(_qcp_file)

            os.remove(_wav_file)

        except:

            pass

        result['ringtone']=media

        return result

	def saveringtones(self, results, merge):

        _new_ringtones=results.get('ringtone', {})

        _rt_index=results.get('ringtone-index', {})

        _voice_memo_l=[x['name'] for k,x in _rt_index.items() \
                       if x.get('origin', '')=='voicememo']

        _del_keys=[k for k,x in _new_ringtones.items() \
                   if x.get('name', None) in _voice_memo_l]

        for k in _del_keys:

            del _new_ringtones[k]

        results['ringtone']=_new_ringtones

        return com_lgvx4400.Phone.saveringtones(self, results, merge)

	def savephonebook(self, data):

        "Saves out the phonebook"

        res=com_lgvx4400.Phone.savephonebook(self, data)

        pbook=res.get('phonebook', {})

        wallpaper_index=res.get('wallpaper-index', {})

        r1={}

        for k,e in pbook.items():

            r1[e['bitpimserial']['id']]={ 'wallpaper': \
                                          self._findmediainindex(wallpaper_index,
                                                                 e['wallpaper'],
                                                                 e['name'],
                                                                 'wallpaper'),
                                          'group': e['group'] }

        serialupdates=data.get("serialupdates", [])

        r2={}

        for bps, serials in serialupdates:

            r2[serials['serial1']]=r1[bps['id']]

        if self._update_wallpaper_index(r2):

            data["rebootphone"]=True

        return res

	def _update_wallpaper_index(self, wpi):

        buf=prototypes.buffer(self.getfilecontents(
            self.protocolclass.pb_file_name))

        pb=self.protocolclass.pbfile()

        pb.readfrombuffer(buf)

        update_flg=False

        for e in pb.items:

            _info=wpi.get(e.serial1, None)

            if _info:

                wp=_info.get('wallpaper', None)

                if wp is not None and wp!=e.wallpaper:

                    update_flg=True

                    e.wallpaper=wp

                gr=_info.get('group', None)

                if gr is not None and gr!=e.group:

                    update_flg=True

                    e.group=gr

        if update_flg:

            self.log('Updating wallpaper index')

            buf=prototypes.buffer()

            pb.writetobuffer(buf)

            self.writefile(self.protocolclass.pb_file_name, buf.getvalue())

        return update_flg

	_call_history_info={
        call_history.CallHistoryEntry.Folder_Incoming: protocolclass.incoming_call_file,
        call_history.CallHistoryEntry.Folder_Outgoing: protocolclass.outgoing_call_file,
        call_history.CallHistoryEntry.Folder_Missed: protocolclass.missed_call_file
        }
	    def getcallhistory(self, result):

        res={}

        for _folder, _file_name in Phone._call_history_info.items():

            try:

                buf=prototypes.buffer(self.getfilecontents(_file_name))

                hist_file=self.protocolclass.callhistoryfile()

                hist_file.readfrombuffer(buf)

                for i in range(hist_file.itemcount):

                    hist_call=hist_file.items[i]

                    entry=call_history.CallHistoryEntry()

                    entry.folder=_folder

                    entry.datetime=hist_call.datetime

                    entry.number=hist_call.number

                    entry.name=hist_call.name

                    if _folder!=call_history.CallHistoryEntry.Folder_Missed:

                        entry.duration=hist_call.duration

                    res[entry.id]=entry

            except com_brew.BrewNoSuchFileException:

                pass

        result['call_history']=res

        return result

	def _setquicktext(self, result):

        canned_file=Phone.SMSCannedFile()

        canned_file.set_sms_canned_data(result.get('canned_msg', []))

        buf=prototypes.buffer()

        canned_file.writetobuffer(buf)

        self.writefile(self.protocolclass.sms_canned_file, buf.getvalue())

	def _getquicktext(self):

        try:

            buf=prototypes.buffer(self.getfilecontents(
                self.protocolclass.sms_canned_file))

            canned_file=Phone.SMSCannedFile()

            canned_file.readfrombuffer(buf)

            return canned_file.get_sms_canned_data()

        except:

            if __debug__:

                raise

            return []

	my_model='VX4650'
	class  SMSCannedFile (protocolclass.SMSCannedFile) :
		def __init__(self, *args, **kwargs):

            Phone.protocolclass.SMSCannedFile.__init__(self, *args, **kwargs)

		def get_sms_canned_data(self):

            return [{ 'text': e.text,
                      'type': sms.CannedMsgEntry.user_type } for e in self.items]

		def set_sms_canned_data(self, canned_list):

            msg_lst=[x['text'] for x in canned_list \
                     if x['type']==sms.CannedMsgEntry.user_type]

            item_count=min(Phone.protocolclass.SMS_CANNED_MAX_ITEMS, len(msg_lst))

            for i in range(item_count):

                entry=Phone.protocolclass.SMSCannedMsg()

                entry.text=msg_lst[i]

                self.items.append(entry)

            entry=Phone.protocolclass.SMSCannedMsg()

            entry.text=''

            for i in range(item_count, Phone.protocolclass.SMS_CANNED_MAX_ITEMS):

                self.items.append(entry)


	def _get_phone_number(self):

        s=''

        try:

            buf=self.getfilecontents('nvm/nvm/nvm_0000')

            ofs=0x240

            if buf[ofs]=='\x01':

                ofs+=1

                while buf[ofs]!='\x01':

                    s+=buf[ofs]

                    ofs+=1

        except:

            if __debug__:

                raise

        return s

	def getphoneinfo(self, phone_info):

        try:

            if self.getfilecontents(self.brew_version_file)[:len(self.my_model)]==self.my_model:

                phone_info.model=self.my_model

                phone_info.manufacturer=Profile.phone_manufacturer

                phone_info.phone_number=self._get_phone_number()

                phone_info.firmware_version=self.getfirmwareinformation().firmwareversion

                phone_info.esn=self.get_esn()

        except:

            if __debug__:

                raise

	"Talk to the LG VX4650 cell phone"
parentprofile=com_lgvx4400.Profile
class  Profile (parentprofile) :
	protocolclass=Phone.protocolclass
	    serialsname=Phone.serialsname
	    WALLPAPER_WIDTH=128
	    WALLPAPER_HEIGHT=128
	    MAX_WALLPAPER_BASENAME_LENGTH=19
	    WALLPAPER_FILENAME_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ."
	    WALLPAPER_CONVERT_FORMAT="bmp"
	    MAX_RINGTONE_BASENAME_LENGTH=19
	    RINGTONE_FILENAME_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ."
	    BP_Calendar_Version=3
	    phone_manufacturer='LG Electronics Inc'
	    phone_model='VX4650'
	    imageorigins={}
	    imageorigins.update(common.getkv(parentprofile.stockimageorigins, "images"))
	    def GetImageOrigins(self):

        return self.imageorigins

	imagetargets={}
	    imagetargets.update(common.getkv(parentprofile.stockimagetargets, "wallpaper",
                                      {'width': 128, 'height': 114, 'format': "JPEG"}))
	    imagetargets.update(common.getkv(parentprofile.stockimagetargets, "fullscreen",
                                      {'width': 128, 'height': 128, 'format': "JPEG"}))
	    def GetTargetsForImageOrigin(self, origin):

        return self.imagetargets

	_supportedsyncs=(
        ('phonebook', 'read', None),  
        ('calendar', 'read', None),   
        ('wallpaper', 'read', None),  
        ('ringtone', 'read', None),   
        ('phonebook', 'write', 'OVERWRITE'),  
        ('calendar', 'write', 'OVERWRITE'),   
        ('wallpaper', 'write', 'MERGE'),      
        ('wallpaper', 'write', 'OVERWRITE'),
        ('ringtone', 'write', 'MERGE'),      
        ('ringtone', 'write', 'OVERWRITE'),
        ('memo', 'read', None),     
        ('memo', 'write', 'OVERWRITE'),  
        ('call_history', 'read', None),
        ('sms', 'read', None),
        ('sms', 'write', 'OVERWRITE'),
       )
	    def __init__(self):

        parentprofile.__init__(self)

	    imageorigins.update(common.getkv(parentprofile.stockimageorigins, "images"))
	    imagetargets.update(common.getkv(parentprofile.stockimagetargets, "wallpaper",
                                      {'width': 128, 'height': 114, 'format': "JPEG"}))
	    imagetargets.update(common.getkv(parentprofile.stockimagetargets, "fullscreen",
                                      {'width': 128, 'height': 128, 'format': "JPEG"}))
	def _convert_weekly_events(self, e, d, idx):

        """
        Convert a weekly event from v3 to v2
        """

        rp=e.repeat

        dow=rp.dow

        t0=datetime.date(*e.start[:3])

        t1=t3=datetime.date(*e.end[:3])

        delta_t=datetime.timedelta(1)

        delta_t7=datetime.timedelta(7)

        if (t1-t0).days>6:

            t1=t0+datetime.timedelta(6)

        d['repeat']='weekly'

        res={}

        while t0<=t1:

            dow_0=t0.isoweekday()%7

            if (1<<dow_0)&dow:

                dd=copy.deepcopy(d)

                dd['start']=(t0.year, t0.month, t0.day, e.start[3], e.start[4])

                dd['daybitmap']=self.getdaybitmap(dd['start'], dd['repeat'])

                t2=t0

                while t2<=t3:

                    if not e.is_active(t2.year, t2.month, t2.day):

                        dd['exceptions'].append((t2.year, t2.month, t2.day))

                    t2+=delta_t7

                dd['pos']=idx

                res[idx]=dd

                idx+=1

            t0+=delta_t

        return idx, res

	def _convert3to2(self, dict, ringtone_index):

        """Convert calendar dict from version 3 to 2."""

        r={}

        idx=0

        for k,e in dict.items():

            d={}

            d['start']=e.start

            d['end']=e.end

            d['description']=e.description

            d['alarm']=e.alarm

            d['changeserial']=1

            d['snoozedelay']=0

            d['ringtone']=0 

            try:

                d['ringtone']=[i for i,r in ringtone_index.items() \
                               if r.get('name', '')==e.ringtone][0]

            except:

                pass

            rp=e.repeat

            if rp is None:

                d['repeat']=None

                d['exceptions']=[]

                d['daybitmap']=0

            else:

                s=[]

                for n in rp.suppressed:

                    s.append(n.get()[:3])

                d['exceptions']=s

                if rp.repeat_type==rp.daily:

                    self._convert_daily_events(e, d)

                elif rp.repeat_type==rp.weekly:

                    idx, rr=self._convert_weekly_events(e, d, idx)

                    r.update(rr)

                    continue

                elif rp.repeat_type==rp.monthly:

                    d['repeat']='monthly'

                elif rp.repeat_type==rp.yearly:

                    d['repeat']='yearly'

                d['daybitmap']=self.getdaybitmap(d['start'], d['repeat'])

            d['pos']=idx

            r[idx]=d

            idx+=1

        if __debug__:

            print 'Calendar._convert3to2: V2 dict:'

            print r

        return r

	"""A class encapsulating the GUI and data of the calendar (all days).  A seperate dialog is
    used to edit the content of one particular day."""

class  CalendarPrintDialog (wx.Dialog) :
	_regular_template='cal_regular.xy'
	    _regular_style='cal_regular_style.xy'
	    _monthly_template='cal_monthly.xy'
	    _monthly_style='cal_monthly_style.xy'
	    def __init__(self, calwidget, mainwindow, config):

        super(CalendarPrintDialog, self).__init__(mainwindow, -1, 'Print Calendar')

        self._cal_widget=calwidget

        self._xcp=self._html=self._dns=None

        self._dt_index=self._dt_start=self._dt_end=None

        self._date_changed=self._style_changed=False

        self._tmp_file=common.gettempfilename("htm")

        vbs=wx.BoxSizer(wx.VERTICAL)

        hbs=wx.BoxSizer(wx.HORIZONTAL)

        sbs=wx.StaticBoxSizer(wx.StaticBox(self, -1, 'Print Range'),
                              wx.VERTICAL)

        gs=wx.FlexGridSizer(-1, 2, 5, 5)

        gs.AddGrowableCol(1)

        gs.Add(wx.StaticText(self, -1, 'Start:'), 0, wx.ALL, 0)

        self._start_date=wx.DatePickerCtrl(self, style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)

        wx.EVT_DATE_CHANGED(self, self._start_date.GetId(),
                            self.OnDateChanged)

        gs.Add(self._start_date, 0, wx.ALL, 0)

        gs.Add(wx.StaticText(self, -1, 'End:'), 0, wx.ALL, 0)

        self._end_date=wx.DatePickerCtrl(self, style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)

        wx.EVT_DATE_CHANGED(self, self._end_date.GetId(),
                            self.OnDateChanged)

        gs.Add(self._end_date, 0, wx.ALL, 0)

        sbs.Add(gs, 1, wx.EXPAND|wx.ALL, 5)

        hbs.Add(sbs, 0, wx.ALL, 5)

        self._print_style=wx.RadioBox(self, -1, 'Print Style',
                                       choices=['List View', 'Month View'],
                                       style=wx.RA_SPECIFY_ROWS)

        wx.EVT_RADIOBOX(self, self._print_style.GetId(), self.OnStyleChanged)

        hbs.Add(self._print_style, 0, wx.ALL, 5)

        vbs.Add(hbs, 0, wx.ALL, 5)

        vbs.Add(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5)

        hbs=wx.BoxSizer(wx.HORIZONTAL)

        for b in (('Print', -1, self.OnPrint),
                  ('Page Setup', -1, self.OnPageSetup),
                  ('Print Preview', -1, self.OnPrintPreview),
                  ('Close', wx.ID_CANCEL, self.OnClose)):

            btn=wx.Button(self, b[1], b[0])

            hbs.Add(btn, 0, wx.ALIGN_CENTER|wx.ALL, 5)

            if b[2] is not None:

                wx.EVT_BUTTON(self, btn.GetId(), b[2])

        vbs.Add(hbs, 0, wx.ALIGN_CENTRE|wx.EXPAND|wx.ALL, 5)

        self.SetSizer(vbs)

        self.SetAutoLayout(True)

        vbs.Fit(self)

	_one_day=wx.DateSpan(days=1)
	    _empty_day=['', []]
	    def _one_day_data(self):