def out_tel(vals, formatter):

    phones=['phone'+str(x) for x in ['']+range(2,len(vals)+1)]

    res=""

    first=True

    idx=0

    for v in vals:

        sp=v.get('speeddial', None)

        if sp is None:

            res+=out_line("TEL",
                          ["TYPE=%s%s" % (_out_tel_mapping[v['type']], ("", ",PREF")[first])],
                          phonenumber.format(v['number']), formatter)

        else:

            res+=out_line(phones[idx]+".TEL",
                          ["TYPE=%s%s" % (_out_tel_mapping[v['type']], ("", ",PREF")[first])],
                          phonenumber.format(v['number']), formatter)

            res+=out_line(phones[idx]+".X-SPEEDDIAL", None, str(sp), formatter)

            idx+=1

        first=False

    return res
 def _OnSelChanged(self, evt):
     item=evt.GetIndex()
     k=self._item_list.GetItemData(item)
     if k is None:
         self._item_info.Clear()
         self._item_text.Set(None)
         return
     entry=self._stats._data.get(k, None)
     if entry is None:
         return
     e=copy.deepcopy(entry)
     s=self._name_map.get(e._from, None)
     if s is None:
         e._from=phonenumber.format(e._from)
     else:
         e._from=s
     s=self._name_map.get(e._to, None)
     if s is None:
         e._to=phonenumber.format(e._to)
     else:
         e._to=s
     s=self._name_map.get(e.callback, None)
     if s is None:
         e.callback=phonenumber.format(e.callback)
     else:
         e.callback=s
     self._item_info.Set(e)
     self._item_text.Set({'memo': e.text})
 def _populate_each(self, k):
     if k is None:
         self._item_info.Clear()
         self._item_text.Set(None)
         return
     entry=self._data.get(k, None)
     if entry is None:
         return
     self._item_info.Enable(True)
     e=copy.deepcopy(entry)
     s=self._name_map.get(e._from, None)
     if s is None:
         e._from=phonenumber.format(e._from)
     else:
         e._from=s
     s=self._name_map.get(e._to, None)
     if s is None:
         e._to=phonenumber.format(e._to)
     else:
         e._to=s
     s=self._name_map.get(e.callback, None)
     if s is None:
         e.callback=phonenumber.format(e.callback)
     else:
         e.callback=s
     self._item_info.Set(e)
     self._item_text.Set({'memo': e.text})
 def _display_by_number(self):
     self._item_list.CollapseAndReset(self._root)
     self._nodes={}
     number_list=[]
     for k,e in self._data.items():
         s=phonenumber.format(e.number)
         if s not in number_list:
             number_list.append(s)
     number_list.sort()
     for s in number_list:
         self._nodes[s]=self._item_list.AppendItem(self._root, s)
     for k,e in self._data.items():
         i=self._item_list.AppendItem(self._nodes[phonenumber.format(e.number)],
                                       e.get_repr(self._name_map.get(e.number, None)))
         self._item_list.SetItemPyData(i, k)
示例#5
0
def out_tel_scp6600(vals, formatter):
    res=""
    _pref=len(vals)>1
    for v in vals:
        res+=out_line("TEL",
                      ["TYPE=%s%s" % ("PREF," if _pref else "",
                                      _out_tel_mapping[v['type']])],
                      phonenumber.format(v['number']), formatter)
        _pref=False
    return res
示例#6
0
def out_tel_scp6600(vals, formatter):
    res = ""
    _pref = len(vals) > 1
    for v in vals:
        res += out_line("TEL", [
            "TYPE=%s%s" %
            ("PREF," if _pref else "", _out_tel_mapping[v['type']])
        ], phonenumber.format(v['number']), formatter)
        _pref = False
    return res
	def _phonenumber_str(self, v):

        return phonenumber.format(v)

	def _hms(self, v):

        if v is None or not isinstance(v, int):

            return ''

        else:

            return '%02d:%02d:%02d'%(v/3600, v/60, v%60)

	_csv_template=(
        ('Date', 'datetime', _datetime_str),
        ('Number', 'number', _phonenumber_str),
        ('Name', 'name', None),
        ('Duration', 'duration', _hms),
        ('Type', 'folder', None))
	    def _export_csv(self, fp, ch):

        fp.write(','.join(['"'+e[0]+'"' for e in self._csv_template])+'\n')

        _keys=ch.keys()

        _keys.sort()

        for k in _keys:

            try:

                e=ch[k]

                _l=[]

                for _c in self._csv_template:

                    if _c[2] is None:

                        _s=str(getattr(e, _c[1], ''))

                    else:

                        _s=_c[2](self, getattr(e, _c[1], None))

                    _l.append('"'+_s.replace('"', '')+'"')

                fp.write(','.join(_l)+'\n')

            except:

                if __debug__:

                    raise
 def summary(self, name=None):
     s=self.datetime
     if s:
         s=s[4:6]+'/'+s[6:8]+' '+s[9:11]+':'+s[11:13]+' '
     else:
         s='**/** **:** '
     if name:
         s+=name
     elif self.name:
         s+=self.name
     else:
         s+=phonenumber.format(self.number)
     return s
示例#9
0
 def getphoneinfo(self, phone_info):
     self.log('Getting Phone Info')
     try:
         s=self.getfilecontents('brew/version.txt')
         if s[:7]==self.my_model:
             phone_info.append('Manufacturer:', Profile.phone_manufacturer)
             phone_info.append('Model:', self.my_model)
             phone_info.append('Name:', self.desc[12:21])
             phone_info.append('ESN:', self.get_brew_esn())
             phone_info.append('Firmware Version:', self.get_firmware_version())
             #get the phone number from 'My Name Card'
             namecard=self.getfilecontents2('pim/pbmyentry.dat', 208, 10)
             phone_info.append('Phone Number:', phonenumber.format(namecard))
     except Exception, e:
         pass
示例#10
0
 def summary(self, name=None):
     # return a short summary for this entry in the format of
     # MM/DD hh:mm <Number/Name>
     s=self.datetime
     if s:
         s=s[4:6]+'/'+s[6:8]+' '+s[9:11]+':'+s[11:13]+' '
     else:
         s='**/** **:** '
     if name:
         s+=name
     elif self.name:
         s+=self.name
     else:
         s+=phonenumber.format(self.number)
     return s
示例#11
0
def out_tel(vals, formatter):
    # ::TODO:: limit to one type of each number
    phones = ['phone' + str(x) for x in [''] + range(2, len(vals) + 1)]
    res = ""
    first = True
    idx = 0
    for v in vals:
        sp = v.get('speeddial', None)
        if sp is None:
            # no speed dial
            res += out_line("TEL", [
                "TYPE=%s%s" % (_out_tel_mapping[v['type']],
                               ("", ",PREF")[first])
            ], phonenumber.format(v['number']), formatter)
        else:
            res += out_line(phones[idx] + ".TEL", [
                "TYPE=%s%s" % (_out_tel_mapping[v['type']],
                               ("", ",PREF")[first])
            ], phonenumber.format(v['number']), formatter)
            res += out_line(phones[idx] + ".X-SPEEDDIAL", None, str(sp),
                            formatter)
            idx += 1
        first = False
    return res
示例#12
0
 def summary(self, name=None):
     # return a short summary for this entry in the format of
     # MM/DD hh:mm <Number/Name>
     s = self.datetime
     if s:
         s = s[4:6] + '/' + s[6:8] + ' ' + s[9:11] + ':' + s[11:13] + ' '
     else:
         s = '**/** **:** '
     if name:
         s += name
     elif self.name:
         s += self.name
     else:
         s += phonenumber.format(self.number)
     return s
示例#13
0
 def getphoneinfo(self, phone_info):
     self.log('Getting Phone Info')
     try:
         s = self.getfilecontents('brew/version.txt')
         if s[:7] == self.my_model:
             phone_info.append('Manufacturer:', Profile.phone_manufacturer)
             phone_info.append('Model:', self.my_model)
             phone_info.append('Name:', self.desc[12:21])
             phone_info.append('ESN:', self.get_brew_esn())
             phone_info.append('Firmware Version:',
                               self.get_firmware_version())
             #get the phone number from 'My Name Card'
             namecard = self.getfilecontents2('pim/pbmyentry.dat', 208, 10)
             phone_info.append('Phone Number:',
                               phonenumber.format(namecard))
     except Exception, e:
         pass
示例#14
0
 def populate(self):
     self.nodes={}
     self.nodes_keys={}
     index=0
     for k,e in self._stats._data.items():
         if self._display_filter=="All" or e.folder==self._display_filter:
             name=e.name
             if name==None or name=="":
                 temp=self._stats._name_map.get(e.number, None)
                 if temp !=None:
                     name=temp
                 else:
                     name=""
             self.nodes[index]=(e.folder, e.get_date_time_str(),
                                phonenumber.format(e.number),
                                e.durationstr, name)
             self.nodes_keys[index]=k
             index+=1
     self._item_list.ResetView(self.nodes, self.nodes_keys)
 def get_repr(self, name=None):
     f=self.folder[0].upper()
     s=self.datetime
     if self.duration is None:
         _duration=''
     else:
         _duration='<%dm%ds>'%(self.duration/60, self.duration%60)
     if not len(s):
         s=f+'['+self._unknown_datetime+_duration+']'
     else:
         s=f+'['+s[:4]+'-'+s[4:6]+'-'+s[6:8]+' '+s[9:11]+':'+s[11:13]+\
            ':'+s[13:]+_duration+']  -  '
     if name:
         s+=name
     elif self.name:
         s+=self.name
     else:
         s+=phonenumber.format(self.number)
     return s
示例#16
0
 def populate(self):
     self.nodes = {}
     self.nodes_keys = {}
     index = 0
     for k, e in self._stats._data.items():
         if self._display_filter == "All" or e.folder == self._display_filter:
             name = e.name
             if name == None or name == "":
                 temp = self._stats._name_map.get(e.number, None)
                 if temp != None:
                     name = temp
                 else:
                     name = ""
             self.nodes[index] = (e.folder, e.get_date_time_str(),
                                  phonenumber.format(e.number),
                                  e.durationstr, name)
             self.nodes_keys[index] = k
             index += 1
     self._item_list.ResetView(self.nodes, self.nodes_keys)
示例#17
0
 def _phonenumber_str(self, v):
     return phonenumber.format(v)
	def _populate_each(self, k):

        if k is None:

            self._item_info.Clear()

            self._item_text.Set(None)

            return

        entry=self._data.get(k, None)

        if entry is None:

            return

        self._item_info.Enable(True)

        e=copy.deepcopy(entry)

        s=self._name_map.get(e._from, None)

        if s is None:

            e._from=phonenumber.format(e._from)

        else:

            e._from=s

        s=self._name_map.get(e._to, None)

        if s is None:

            e._to=phonenumber.format(e._to)

        else:

            e._to=s

        s=self._name_map.get(e.callback, None)

        if s is None:

            e.callback=phonenumber.format(e.callback)

        else:

            e.callback=s

        self._item_info.Set(e)

        self._item_text.Set({'memo': e.text})

	def Set(self, data, canned_data):

        self._data=data

        self.canned_data=canned_data

        self._populate()

	def Get(self):

        self.canned_data.user_list=self.canned_list.GetStrings()

        return self._data, self.canned_data

	def delete_selection(self, data):

        sel_ids=self._item_list.GetSelections()

        if not sel_ids:

            return False

        for sel_idx in sel_ids:

            k=self._item_list.GetPyData(sel_idx)

            if k is None:

                continue

            self._item_list.Delete(sel_idx)

            self._clear_info()

            del data[k]

            del self._data_map[k]

        sel_ids=self._item_list.GetSelections()

        if sel_ids and sel_ids[0].Ok():

            self._populate_each(self._item_list.GetPyData(sel_ids[0]))

        return True

	def publish_today_data(self):

        keys=[(x.datetime,k) for k,x in self._data.items()]

        keys.sort()

        keys.reverse()

        today_event=today.TodaySMSEvent()

        for _,k in keys:

            if self._data[k].folder==sms.SMSEntry.Folder_Inbox:

                today_event.append(self._data[k].text,
                                   { 'id': self._data_map[k] } )

        today_event.broadcast()

	def OnTodaySelection(self, evt):

        if evt.data:

            self._item_list.SelectItem(evt.data['id'])

	def get_sel_data(self):

        res={}

        for sel_idx in self._item_list.GetSelections():

            k=self._item_list.GetPyData(sel_idx)

            if k:

                res[k]=self._data[k]

        return res


class  SMSWidget (wx.Panel) :
	_data_key='sms'
	    _canned_data_key='canned_msg'
	    def __init__(self, mainwindow, parent):

        super(SMSWidget, self).__init__(parent, -1)

        self._main_window=mainwindow

        self._data=self._canned_data={}

        vbs=wx.BoxSizer(wx.VERTICAL)

        hbs=wx.BoxSizer(wx.HORIZONTAL)

        self.read_only=False

        self.historical_date=None

        static_bs=wx.StaticBoxSizer(wx.StaticBox(self, -1,
                                                 'Historical Data Status:'),
                                    wx.VERTICAL)

        self.historical_data_label=wx.StaticText(self, -1, 'Current Data')

        static_bs.Add(self.historical_data_label, 1, wx.EXPAND|wx.ALL, 5)

        hbs.Add(static_bs, 1, wx.EXPAND|wx.ALL, 5)

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

        self._sms=FolderPage(self)

        wx.EVT_BUTTON(self, self._sms.save_btn.GetId(), self.OnSaveCannedMsg)

        vbs.Add(self._sms, 1, wx.EXPAND|wx.ALL, 5)

        self.SetSizer(vbs)

        self.SetAutoLayout(True)

        vbs.Fit(self)

        today.bind_notification_event(self._sms.OnTodaySelection,
                                      today.Today_Group_IncomingSMS)

	def _populate(self):

        self._sms.Set(self._data, self._canned_data)

        self._sms.publish_today_data()

	def OnSaveCannedMsg(self, _):

        if self.read_only:

            wx.MessageBox('You are viewing historical data which cannot be changed or saved',
                          'Cannot Save SMS Data',
                          style=wx.OK|wx.ICON_ERROR)

            return

        self._data, self._canned_data=self._sms.Get()

        self._save_to_db(canned_msg_dict=self._canned_data)

	def OnDelete(self, _):

        if self.read_only:

            return

        if self._sms.delete_selection(self._data):

            self._save_to_db(sms_dict=self._data)

	def getdata(self,dict,want=None):

        dict[self._data_key]=copy.deepcopy(self._data, {})

        dict[self._canned_data_key]=self._canned_data.get().get(
            self._canned_data_key, {})

	def get_selected_data(self):

        return self._sms.get_sel_data()

	def get_data(self):

        return self._data

	def populate(self, dict, force=False):

        if self.read_only and not force:

            return

        if not self.read_only:

            self._canned_data=sms.CannedMsgEntry()

            self._canned_data.set({ self._canned_data_key: dict.get(self._canned_data_key, [])})

        self._data=dict.get(self._data_key, {})

        self._populate()

	def _save_to_db(self, sms_dict=None, canned_msg_dict=None):

        if self.read_only:

            return

        if sms_dict is not None:

            db_rr={}

            for k, e in sms_dict.items():

                db_rr[k]=sms.SMSDataObject(e)

            database.ensurerecordtype(db_rr, sms.smsobjectfactory)

            self._main_window.database.savemajordict(self._data_key, db_rr)

        if canned_msg_dict is not None:

            db_rr={}

            db_rr[self._canned_data_key]=sms.CannedMsgDataObject(
                canned_msg_dict)

            database.ensurerecordtype(db_rr, sms.cannedmsgobjectfactory)

            self._main_window.database.savemajordict(self._canned_data_key,
                                                      db_rr)

	def populatefs(self, dict):

        if self.read_only:

            wx.MessageBox('You are viewing historical data which cannot be changed or saved',
                          'Cannot Save SMS Data',
                          style=wx.OK|wx.ICON_ERROR)

            return

        canned_msg=sms.CannedMsgEntry()

        canned_msg.set({ self._canned_data_key: dict.get(self._canned_data_key, [])})

        self._save_to_db(sms_dict=dict.get(self._data_key, []),
                          canned_msg_dict=canned_msg)

        return dict

	def getfromfs(self, result, timestamp=None):

        sms_dict=self._main_window.database.\
                   getmajordictvalues(self._data_key, sms.smsobjectfactory,
                                      at_time=timestamp)

        r={}

        for k,e in sms_dict.items():

            ce=sms.SMSEntry()

            ce.set_db_dict(e)

            r[ce.id]=ce

        result.update({ self._data_key: r })

        canned_msg_dict=self._main_window.database.\
                         getmajordictvalues(self._canned_data_key,
                                            sms.cannedmsgobjectfactory)

        for k,e in canned_msg_dict.items():

            ce=sms.CannedMsgEntry()

            ce.set_db_dict(e)

            result.update(ce.get())

        return result

	def merge(self, dict):

        if self.read_only:

            wx.MessageBox('You are viewing historical data which cannot be changed or saved',
                          'Cannot Save SMS Data',
                          style=wx.OK|wx.ICON_ERROR)

            return

        existing_id=[e.msg_id for k,e in self._data.items()]

        d=dict.get(self._data_key, {})

        for k,e in d.items():

            if e.msg_id not in existing_id:

                self._data[e.id]=e

        self._canned_data=sms.CannedMsgEntry()

        self._canned_data.set({ self._canned_data_key: dict.get(self._canned_data_key, []) } )

        self._populate()

        self._save_to_db(sms_dict=self._data,
                         canned_msg_dict=self._canned_data)

	def OnHistoricalData(self):

        """Display current or historical data"""

        if self.read_only:

            current_choice=guiwidgets.HistoricalDataDialog.Historical_Data

        else:

            current_choice=guiwidgets.HistoricalDataDialog.Current_Data

        dlg=guiwidgets.HistoricalDataDialog(self,
                                            current_choice=current_choice,
                                            historical_date=self.historical_date,
                                            historical_events=\
                                            self._main_window.database.getchangescount(self._data_key))

        if dlg.ShowModal()==wx.ID_OK:

            self._main_window.OnBusyStart()

            current_choice, self.historical_date=dlg.GetValue()

            r={}

            if current_choice==guiwidgets.HistoricalDataDialog.Current_Data:

                self.read_only=False

                msg_str='Current Data'

                self.getfromfs(r)

            else:

                self.read_only=True

                msg_str='Historical Data as of %s'%\
                         str(wx.DateTimeFromTimeT(self.historical_date))

                self.getfromfs(r, self.historical_date)

            self.populate(r, True)

            self.historical_data_label.SetLabel(msg_str)

            self._main_window.OnBusyEnd()

        dlg.Destroy()
示例#19
0
 def _phonenumber_str(self, v):
     return phonenumber.format(v)
示例#20
0
 def _number2name(self, numstr):
     # Lookup name from number string
     _s = self._name_map.get(numstr, None)
     if _s is None:
         return phonenumber.format(numstr)
     return _s
	def _display_by_number(self):

        self._item_list.CollapseAndReset(self._root)

        self._nodes={}

        number_list=[]

        for k,e in self._data.items():

            s=phonenumber.format(e.number)

            if s not in number_list:

                number_list.append(s)

        number_list.sort()

        for s in number_list:

            self._nodes[s]=self._item_list.AppendItem(self._root, s)

        for k,e in self._data.items():

            i=self._item_list.AppendItem(self._nodes[phonenumber.format(e.number)],
                                          e.get_repr(self._name_map.get(e.number, None)))

            self._item_list.SetItemPyData(i, k)

	def _display_by_type(self):

        self._item_list.CollapseAndReset(self._root)

        self._nodes={}

        for s in CallHistoryEntry.Valid_Folders:

            self._nodes[s]=self._item_list.AppendItem(self._root, s)

        node_dict={}

        for k,e in self._data.items():

            node_dict[e.get_repr(self._name_map.get(e.number, None))]=k

        keys=node_dict.keys()

        keys.sort()

        for k in keys:

            data_key=node_dict[k]

            n=self._data[data_key]

            i=self._item_list.AppendItem(self._nodes[n.folder], k)

            self._item_list.SetItemPyData(i, data_key)

	def _publish_today_data(self):

        keys=[(x.datetime, k) for k,x in self._data.items()]

        keys.sort()

        keys.reverse()

        today_event=today.TodayIncomingCallsEvent()

        today_event.names=[self._data[k].summary(self._name_map.get(self._data[k].number, None))\
                                    for _,k in keys \
                                    if self._data[k].folder==CallHistoryEntry.Folder_Incoming]

        today_event.broadcast()

        today_event=today.TodayMissedCallsEvent()

        today_event.names=[self._data[k].summary(self._name_map.get(self._data[k].number, None))\
                                    for _,k in keys \
                                    if self._data[k].folder==CallHistoryEntry.Folder_Missed]

        today_event.broadcast()

	def _populate(self):

        self._clear()

        self._node_dict={}

        for k,e in self._data.items():

            if e.name:

                if not self._name_map.has_key(e.number):

                    self._name_map[e.number]=e.name

            else:

                if not self._name_map.has_key(e.number):

                    pubsub.publish(pubsub.REQUEST_PB_LOOKUP,
                                   { 'item': e.number } )

        self._display_func[self._by_mode]()

        self._OnExpandAll(None)

        self._publish_today_data()

	def OnDelete(self, _):

        if self.read_only:

            return

        sels_idx=self._item_list.GetSelections()

        if not sels_idx:

            return

        for sel_idx in sels_idx:

            if not sel_idx.Ok():

                continue

            k=self._item_list.GetPyData(sel_idx)

            if k is None:

                continue

            self._item_list.Delete(sel_idx)

            del self._data[k]

        self._save_to_db(self._data)

	def getdata(self, dict, want=None):

        dict[self._data_key]=copy.deepcopy(self._data)

	def populate(self, dict, force=False):

        if self.read_only and not force:

            return

        self._data=dict.get(self._data_key, {})

        self._populate()

	def _save_to_db(self, dict):

        if self.read_only:

            return

        db_rr={}

        for k,e in dict.items():

            db_rr[k]=CallHistoryDataobject(e)

        database.ensurerecordtype(db_rr, callhistoryobjectfactory)

        self._main_window.database.savemajordict(self._data_key, db_rr)

	def populatefs(self, dict):

        if self.read_only:

            wx.MessageBox('You are viewing historical data which cannot be changed or saved',
                             'Cannot Save Call History Data',
                             style=wx.OK|wx.ICON_ERROR)

        else:

            self._save_to_db(dict.get(self._data_key, {}))

        return dict

	def getfromfs(self, result, timestamp=None):

        dict=self._main_window.database.\
                   getmajordictvalues(self._data_key,
                                      callhistoryobjectfactory,
                                      at_time=timestamp)

        r={}

        for k,e in dict.items():

            ce=CallHistoryEntry()

            ce.set_db_dict(e)

            r[ce.id]=ce

        result.update({ self._data_key: r})

        return result

	def merge(self, dict):

        if self.read_only:

            wx.MessageBox('You are viewing historical data which cannot be changed or saved',
                             'Cannot Save Call History Data',
                             style=wx.OK|wx.ICON_ERROR)

            return

        d=dict.get(self._data_key, {})

        l=[e for k,e in self._data.items()]

        for k,e in d.items():

            if e not in l:

                self._data[e.id]=e

        self._save_to_db(self._data)

        self._populate()

	def OnHistoricalData(self):

        """Display current or historical data"""

        if self.read_only:

            current_choice=guiwidgets.HistoricalDataDialog.Historical_Data

        else:

            current_choice=guiwidgets.HistoricalDataDialog.Current_Data

        dlg=guiwidgets.HistoricalDataDialog(self,
                                            current_choice=current_choice,
                                            historical_date=self.historical_date,
                                            historical_events=\
                                            self._main_window.database.getchangescount(self._data_key))

        if dlg.ShowModal()==wx.ID_OK:

            self._main_window.OnBusyStart()

            current_choice, self.historical_date=dlg.GetValue()

            r={}

            if current_choice==guiwidgets.HistoricalDataDialog.Current_Data:

                self.read_only=False

                msg_str='Current Data'

                self.getfromfs(r)

            else:

                self.read_only=True

                msg_str='Historical Data as of %s'%\
                         str(wx.DateTimeFromTimeT(self.historical_date))

                self.getfromfs(r, self.historical_date)

            self.populate(r, True)

            self.historical_data_label.SetLabel(msg_str)

            self._main_window.OnBusyEnd()

        dlg.Destroy()

	def get_selected_data(self):

        res={}

        for sel_idx in self._item_list.GetSelections():

            k=self._item_list.GetPyData(sel_idx)

            if k:

                res[k]=self._data[k]

        return res

	def get_data(self):

        return self._data
	def summary(self, name=None):

        s=self.datetime

        if s:

            s=s[4:6]+'/'+s[6:8]+' '+s[9:11]+':'+s[11:13]+' '

        else:

            s='**/** **:** '

        if name:

            s+=name

        elif self.name:

            s+=self.name

        else:

            s+=phonenumber.format(self.number)

        return s

	def _get_date_str(self):

        s=self.datetime

        if not len(s):

            return '****-**-**'

        else:

            return s[:4]+'-'+s[4:6]+'-'+s[6:8]

	date_str=property(fget=_get_date_str)

class  CallHistoryWidget (scrolled.ScrolledPanel) :
	_data_key='call_history'
	    _by_type=0
	    _by_date=1
	    _by_number=2
	    def __init__(self, mainwindow, parent):

        super(CallHistoryWidget, self).__init__(parent, -1)

        self._main_window=mainwindow

        self._data={}

        self._node_dict={}

        self._name_map={}

        self._by_mode=self._by_type

        self._display_func=(self._display_by_type, self._display_by_date,
                             self._display_by_number)

        vbs=wx.BoxSizer(wx.VERTICAL)

        hbs=wx.BoxSizer(wx.HORIZONTAL)

        self.read_only=False

        self.historical_date=None

        static_bs=wx.StaticBoxSizer(wx.StaticBox(self, -1,
                                                 'Historical Data Status:'),
                                    wx.VERTICAL)

        self.historical_data_label=wx.StaticText(self, -1, 'Current Data')

        static_bs.Add(self.historical_data_label, 1, wx.EXPAND|wx.ALL, 5)

        hbs.Add(static_bs, 1, wx.EXPAND|wx.ALL, 5)

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

        self._item_list=wx.TreeCtrl(self, wx.NewId(),
                                    style=wx.TR_MULTIPLE|wx.TR_HAS_BUTTONS)

        vbs.Add(self._item_list, 1, wx.EXPAND|wx.ALL, 5)

        self._root=self._item_list.AddRoot('Call History')

        self._nodes={}

        organize_menu=wx.Menu()

        organize_menu_data=(
            ('Type', self._OnOrganizedByType),
            ('Date', self._OnOrganizedByDate),
            ('Number', self._OnOrganizedByNumber))

        for e in organize_menu_data:

            id=wx.NewId()

            organize_menu.AppendRadioItem(id, e[0])

            wx.EVT_MENU(self, id, e[1])

        context_menu_data=(
            ('Expand All', self._OnExpandAll),
            ('Collapse All', self._OnCollapseAll))

        self._bgmenu=wx.Menu()

        self._bgmenu.AppendMenu(wx.NewId(), 'Organize Items by', organize_menu)

        for e in context_menu_data:

            id=wx.NewId()

            self._bgmenu.Append(id, e[0])

            wx.EVT_MENU(self, id, e[1])

        pubsub.subscribe(self._OnPBLookup, pubsub.RESPONSE_PB_LOOKUP)

        wx.EVT_RIGHT_UP(self._item_list, self._OnRightClick)

        self.SetSizer(vbs)

        self.SetAutoLayout(True)

        vbs.Fit(self)

        self.SetupScrolling()

        self._populate()

	def _OnPBLookup(self, msg):

        d=msg.data

        k=d.get('item', None)

        name=d.get('name', None)

        if k is None:

            return

        self._name_map[k]=name

	def _OnRightClick(self, evt):

        self._item_list.PopupMenu(self._bgmenu, evt.GetPosition())

	def _OnOrganizedByType(self, evt):

        evt.GetEventObject().Check(evt.GetId(), True)

        if self._by_mode!=self._by_type:

            self._by_mode=self._by_type

            self._display_func[self._by_type]()

            self._expand_all()

	def _OnOrganizedByDate(self, evt):

        evt.GetEventObject().Check(evt.GetId(), True)

        if self._by_mode!=self._by_date:

            self._by_mode=self._by_date

            self._display_func[self._by_date]()

            self._expand_all()

	def _OnOrganizedByNumber(self, evt):

        evt.GetEventObject().Check(evt.GetId(), True)

        if self._by_mode!=self._by_number:

            self._by_mode=self._by_number

            self._display_func[self._by_number]()

            self._expand_all()

	def _expand_all(self, sel_id=None):

        if sel_id is None:

            sel_id=self._root

        self._item_list.Expand(sel_id)

        id, cookie=self._item_list.GetFirstChild(sel_id)

        while id.IsOk():

            self._item_list.Expand(id)

            id, cookie=self._item_list.GetNextChild(sel_id, cookie)

	def _OnExpandAll(self, _):

        sel_ids=self._item_list.GetSelections()

        if not sel_ids:

            sel_ids=[self._root]

        for sel_id in sel_ids:

            if not sel_id.IsOk():

                sel_id=self._root

            self._expand_all(sel_id)

	def _OnCollapseAll(self, _):

        sel_ids=self._item_list.GetSelections()

        if not sel_ids:

            sel_ids=[self._root]

        for sel_id in sel_ids:

            if not sel_id.IsOk():

                sel_id=self._root

            self._item_list.Collapse(sel_id)

            id, cookie=self._item_list.GetFirstChild(sel_id)

            while id.IsOk():

                self._item_list.Collapse(id)

                id, cookie=self._item_list.GetNextChild(sel_id, cookie)

	def _clear(self):

        self._item_list.Collapse(self._root)

        for k,e in self._nodes.items():

            self._item_list.DeleteChildren(e)

	def _display_by_date(self):

        self._item_list.CollapseAndReset(self._root)

        self._nodes={}

        date_list=[]

        for k,e in self._data.items():

            if e.date_str not in date_list:

                date_list.append(e.date_str)

        date_list.sort()

        for s in date_list:

            self._nodes[s]=self._item_list.AppendItem(self._root, s)

        for k,e in self._data.items():

            i=self._item_list.AppendItem(self._nodes[e.date_str],
                                          e.get_repr(self._name_map.get(e.number, None)))

            self._item_list.SetItemPyData(i, k)

	def _display_by_number(self):

        self._item_list.CollapseAndReset(self._root)

        self._nodes={}

        number_list=[]

        for k,e in self._data.items():

            s=phonenumber.format(e.number)

            if s not in number_list:

                number_list.append(s)

        number_list.sort()

        for s in number_list:

            self._nodes[s]=self._item_list.AppendItem(self._root, s)

        for k,e in self._data.items():

            i=self._item_list.AppendItem(self._nodes[phonenumber.format(e.number)],
                                          e.get_repr(self._name_map.get(e.number, None)))

            self._item_list.SetItemPyData(i, k)

	def _display_by_type(self):

        self._item_list.CollapseAndReset(self._root)

        self._nodes={}

        for s in CallHistoryEntry.Valid_Folders:

            self._nodes[s]=self._item_list.AppendItem(self._root, s)

        node_dict={}

        for k,e in self._data.items():

            node_dict[e.get_repr(self._name_map.get(e.number, None))]=k

        keys=node_dict.keys()

        keys.sort()

        for k in keys:

            data_key=node_dict[k]

            n=self._data[data_key]

            i=self._item_list.AppendItem(self._nodes[n.folder], k)

            self._item_list.SetItemPyData(i, data_key)

	def _publish_today_data(self):

        keys=[(x.datetime, k) for k,x in self._data.items()]

        keys.sort()

        keys.reverse()

        today_event=today.TodayIncomingCallsEvent()

        today_event.names=[self._data[k].summary(self._name_map.get(self._data[k].number, None))\
                                    for _,k in keys \
                                    if self._data[k].folder==CallHistoryEntry.Folder_Incoming]

        today_event.broadcast()

        today_event=today.TodayMissedCallsEvent()

        today_event.names=[self._data[k].summary(self._name_map.get(self._data[k].number, None))\
                                    for _,k in keys \
                                    if self._data[k].folder==CallHistoryEntry.Folder_Missed]

        today_event.broadcast()

	def _populate(self):

        self._clear()

        self._node_dict={}

        for k,e in self._data.items():

            if e.name:

                if not self._name_map.has_key(e.number):

                    self._name_map[e.number]=e.name

            else:

                if not self._name_map.has_key(e.number):

                    pubsub.publish(pubsub.REQUEST_PB_LOOKUP,
                                   { 'item': e.number } )

        self._display_func[self._by_mode]()

        self._OnExpandAll(None)

        self._publish_today_data()

	def OnDelete(self, _):

        if self.read_only:

            return

        sels_idx=self._item_list.GetSelections()

        if not sels_idx:

            return

        for sel_idx in sels_idx:

            if not sel_idx.Ok():

                continue

            k=self._item_list.GetPyData(sel_idx)

            if k is None:

                continue

            self._item_list.Delete(sel_idx)

            del self._data[k]

        self._save_to_db(self._data)

	def getdata(self, dict, want=None):

        dict[self._data_key]=copy.deepcopy(self._data)

	def populate(self, dict, force=False):

        if self.read_only and not force:

            return

        self._data=dict.get(self._data_key, {})

        self._populate()

	def _save_to_db(self, dict):

        if self.read_only:

            return

        db_rr={}

        for k,e in dict.items():

            db_rr[k]=CallHistoryDataobject(e)

        database.ensurerecordtype(db_rr, callhistoryobjectfactory)

        self._main_window.database.savemajordict(self._data_key, db_rr)

	def populatefs(self, dict):

        if self.read_only:

            wx.MessageBox('You are viewing historical data which cannot be changed or saved',
                             'Cannot Save Call History Data',
                             style=wx.OK|wx.ICON_ERROR)

        else:

            self._save_to_db(dict.get(self._data_key, {}))

        return dict

	def getfromfs(self, result, timestamp=None):

        dict=self._main_window.database.\
                   getmajordictvalues(self._data_key,
                                      callhistoryobjectfactory,
                                      at_time=timestamp)

        r={}

        for k,e in dict.items():

            ce=CallHistoryEntry()

            ce.set_db_dict(e)

            r[ce.id]=ce

        result.update({ self._data_key: r})

        return result

	def merge(self, dict):

        if self.read_only:

            wx.MessageBox('You are viewing historical data which cannot be changed or saved',
                             'Cannot Save Call History Data',
                             style=wx.OK|wx.ICON_ERROR)

            return

        d=dict.get(self._data_key, {})

        l=[e for k,e in self._data.items()]

        for k,e in d.items():

            if e not in l:

                self._data[e.id]=e

        self._save_to_db(self._data)

        self._populate()

	def OnHistoricalData(self):

        """Display current or historical data"""

        if self.read_only:

            current_choice=guiwidgets.HistoricalDataDialog.Historical_Data

        else:

            current_choice=guiwidgets.HistoricalDataDialog.Current_Data

        dlg=guiwidgets.HistoricalDataDialog(self,
                                            current_choice=current_choice,
                                            historical_date=self.historical_date,
                                            historical_events=\
                                            self._main_window.database.getchangescount(self._data_key))

        if dlg.ShowModal()==wx.ID_OK:

            self._main_window.OnBusyStart()

            current_choice, self.historical_date=dlg.GetValue()

            r={}

            if current_choice==guiwidgets.HistoricalDataDialog.Current_Data:

                self.read_only=False

                msg_str='Current Data'

                self.getfromfs(r)

            else:

                self.read_only=True

                msg_str='Historical Data as of %s'%\
                         str(wx.DateTimeFromTimeT(self.historical_date))

                self.getfromfs(r, self.historical_date)

            self.populate(r, True)

            self.historical_data_label.SetLabel(msg_str)

            self._main_window.OnBusyEnd()

        dlg.Destroy()

	def get_selected_data(self):

        res={}

        for sel_idx in self._item_list.GetSelections():

            k=self._item_list.GetPyData(sel_idx)

            if k:

                res[k]=self._data[k]

        return res

	def get_data(self):

        return self._data
示例#23
0
 def _number2name(self, numstr):
     # Lookup name from number string
     _s=self._name_map.get(numstr, None)
     if _s is None:
         return phonenumber.format(numstr)
     return _s