-rw-r--r-- | gammu/emb/common/service/gsmmisc.c | 4 | ||||
-rw-r--r-- | gammu/emb/common/service/gsmpbk.c | 17 | ||||
-rw-r--r-- | gammu/emb/gammu/gammu.c | 2 | ||||
-rw-r--r-- | kabc/addressbook.cpp | 148 | ||||
-rw-r--r-- | kabc/addressbook.h | 2 | ||||
-rw-r--r-- | kabc/addressee.cpp | 46 | ||||
-rw-r--r-- | kabc/addressee.h | 1 | ||||
-rw-r--r-- | kabc/phonenumber.cpp | 4 | ||||
-rw-r--r-- | kaddressbook/kabcore.cpp | 86 | ||||
-rw-r--r-- | libkdepim/ksyncprefsdialog.cpp | 11 |
10 files changed, 217 insertions, 104 deletions
diff --git a/gammu/emb/common/service/gsmmisc.c b/gammu/emb/common/service/gsmmisc.c index 6959a22..1c6ec8b 100644 --- a/gammu/emb/common/service/gsmmisc.c +++ b/gammu/emb/common/service/gsmmisc.c @@ -1,262 +1,262 @@ /* (c) 2002-2004 by Marcin Wiacek */ #include <string.h> #include <stdlib.h> #include <sys/stat.h> #ifdef WIN32 # include <io.h> # include <fcntl.h> #endif #include "../misc/coding/coding.h" #include "../gsmcomon.h" #include "gsmmisc.h" struct keys_table_position { char whatchar; int whatcode; }; static struct keys_table_position Keys[] = { {'m',GSM_KEY_MENU}, {'M',GSM_KEY_MENU}, {'n',GSM_KEY_NAMES}, {'N',GSM_KEY_NAMES}, {'p',GSM_KEY_POWER}, {'P',GSM_KEY_POWER}, {'u',GSM_KEY_UP}, {'U',GSM_KEY_UP}, {'d',GSM_KEY_DOWN}, {'D',GSM_KEY_DOWN}, {'+',GSM_KEY_INCREASEVOLUME}, {'-',GSM_KEY_DECREASEVOLUME}, {'1',GSM_KEY_1}, {'2',GSM_KEY_2}, {'3',GSM_KEY_3}, {'4',GSM_KEY_4}, {'5',GSM_KEY_5}, {'6',GSM_KEY_6}, {'7',GSM_KEY_7}, {'8',GSM_KEY_8}, {'9',GSM_KEY_9}, {'*',GSM_KEY_ASTERISK}, {'0',GSM_KEY_0}, {'#',GSM_KEY_HASH}, {'g',GSM_KEY_GREEN}, {'G',GSM_KEY_GREEN}, {'r',GSM_KEY_RED}, {'R',GSM_KEY_RED}, {' ',0} }; GSM_Error MakeKeySequence(char *text, GSM_KeyCode *KeyCode, int *Length) { int i,j; unsigned char key; for (i=0;i<(int)(strlen(text));i++) { key = text[i]; KeyCode[i] = GSM_KEY_NONE; j = 0; while (Keys[j].whatchar!=' ') { if (Keys[j].whatchar==key) { KeyCode[i]=Keys[j].whatcode; break; } j++; } if (KeyCode[i] == GSM_KEY_NONE) { *Length = i; return ERR_NOTSUPPORTED; } } *Length = i; return ERR_NONE; } GSM_Error GSM_ReadFile(char *FileName, GSM_File *File) { int i = 1000; FILE *file; struct stat fileinfo; if (FileName[0] == 0x00) return ERR_UNKNOWN; file = fopen(FileName,"rb"); if (file == NULL) return ERR_CANTOPENFILE; free(File->Buffer); File->Buffer = NULL; File->Used = 0; while (i == 1000) { File->Buffer = realloc(File->Buffer,File->Used + 1000); i = fread(File->Buffer+File->Used,1,1000,file); File->Used = File->Used + i; } File->Buffer = realloc(File->Buffer,File->Used); fclose(file); File->ModifiedEmpty = true; if (stat(FileName,&fileinfo) == 0) { File->ModifiedEmpty = false; dbgprintf("File info read correctly\n"); //st_mtime is time of last modification of file Fill_GSM_DateTime(&File->Modified, fileinfo.st_mtime); File->Modified.Year = File->Modified.Year + 1900; dbgprintf("FileTime: %02i-%02i-%04i %02i:%02i:%02i\n", File->Modified.Day,File->Modified.Month,File->Modified.Year, File->Modified.Hour,File->Modified.Minute,File->Modified.Second); } return ERR_NONE; } static void GSM_JADFindLine(GSM_File File, char *Name, char *Value) { unsigned char Line[2000]; int Pos = 0; Value[0] = 0; while (1) { MyGetLine(File.Buffer, &Pos, Line, File.Used); if (strlen(Line) == 0) break; if (!strncmp(Line,Name,strlen(Name))) { Pos = strlen(Name); while (Line[Pos] == 0x20) Pos++; strcpy(Value,Line+Pos); return; } } } GSM_Error GSM_JADFindData(GSM_File File, char *Vendor, char *Name, char *JAR, char *Version, int *Size) { char Size2[200]; GSM_JADFindLine(File, "MIDlet-Vendor:", Vendor); if (Vendor[0] == 0x00) return ERR_FILENOTSUPPORTED; dbgprintf("Vendor: \"%s\"\n",Vendor); GSM_JADFindLine(File, "MIDlet-Name:", Name); if (Name[0] == 0x00) return ERR_FILENOTSUPPORTED; dbgprintf("Name: \"%s\"\n",Name); GSM_JADFindLine(File, "MIDlet-Jar-URL:", JAR); if (JAR[0] == 0x00) return ERR_FILENOTSUPPORTED; dbgprintf("JAR file URL: \"%s\"\n",JAR); GSM_JADFindLine(File, "MIDlet-Jar-Size:", Size2); *Size = -1; if (Size2[0] == 0x00) return ERR_FILENOTSUPPORTED; dbgprintf("JAR size: \"%s\"\n",Size2); (*Size) = atoi(Size2); GSM_JADFindLine(File, "MIDlet-Version:", Version); dbgprintf("Version: \"%s\"\n",Version); return ERR_NONE; } void GSM_IdentifyFileFormat(GSM_File *File) { File->Type = GSM_File_Other; if (File->Used > 2) { if (memcmp(File->Buffer, "BM",2)==0) { File->Type = GSM_File_Image_BMP; } else if (memcmp(File->Buffer, "GIF",3)==0) { File->Type = GSM_File_Image_GIF; } else if (File->Buffer[0] == 0x00 && File->Buffer[1] == 0x00) { File->Type = GSM_File_Image_WBMP; } else if (memcmp(File->Buffer+1, "PNG",3)==0) { File->Type = GSM_File_Image_PNG; } else if (File->Buffer[0] == 0xFF && File->Buffer[1] == 0xD8) { File->Type = GSM_File_Image_JPG; } else if (memcmp(File->Buffer, "MThd",4)==0) { File->Type = GSM_File_Sound_MIDI; } else if (File->Buffer[0] == 0x00 && File->Buffer[1] == 0x02) { File->Type = GSM_File_Sound_NRT; } } } void SaveVCALDateTime(char *Buffer, int *Length, GSM_DateTime *Date, char *Start) { if (Start != NULL) { *Length+=sprintf(Buffer+(*Length), "%s:",Start); } *Length+=sprintf(Buffer+(*Length), "%04d%02d%02dT%02d%02d%02d%c%c", Date->Year, Date->Month, Date->Day, Date->Hour, Date->Minute, Date->Second,13,10); } void ReadVCALDateTime(char *Buffer, GSM_DateTime *dt) { char year[5]="", month[3]="", day[3]="", hour[3]="", minute[3]="", second[3]=""; memset(dt,0,sizeof(dt)); strncpy(year, Buffer, 4); strncpy(month, Buffer+4, 2); strncpy(day, Buffer+6, 2); strncpy(hour, Buffer+9, 2); strncpy(minute, Buffer+11, 2); strncpy(second, Buffer+13, 2); /* FIXME: Should check ranges... */ dt->Year = atoi(year); dt->Month = atoi(month); dt->Day = atoi(day); dt->Hour = atoi(hour); dt->Minute = atoi(minute); dt->Second = atoi(second); /* FIXME */ dt->Timezone = 0; } void SaveVCALText(char *Buffer, int *Length, char *Text, char *Start) { char buffer[1000]; if (UnicodeLength(Text) != 0) { - EncodeUTF8QuotedPrintable(buffer,Text); + EncodeUTF8(buffer,Text); if (UnicodeLength(Text)==strlen(buffer)) { *Length+=sprintf(Buffer+(*Length), "%s:%s%c%c",Start,DecodeUnicodeString(Text),13,10); } else { - *Length+=sprintf(Buffer+(*Length), "%s;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:%s%c%c",Start,buffer,13,10); + *Length+=sprintf(Buffer+(*Length), "%s:%s%c%c",Start,buffer,13,10); } } } bool ReadVCALText(char *Buffer, char *Start, char *Value) { unsigned char buff[200]; Value[0] = 0x00; Value[1] = 0x00; strcpy(buff,Start); strcat(buff,":"); if (!strncmp(Buffer,buff,strlen(buff))) { EncodeUnicode(Value,Buffer+strlen(Start)+1,strlen(Buffer)-(strlen(Start)+1)); dbgprintf("ReadVCalText is \"%s\"\n",DecodeUnicodeConsole(Value)); return true; } /* SE T68i */ strcpy(buff,Start); strcat(buff,";ENCODING=QUOTED-PRINTABLE:"); if (!strncmp(Buffer,buff,strlen(buff))) { DecodeUTF8QuotedPrintable(Value,Buffer+strlen(Start)+27,strlen(Buffer)-(strlen(Start)+27)); dbgprintf("ReadVCalText is \"%s\"\n",DecodeUnicodeConsole(Value)); return true; } strcpy(buff,Start); strcat(buff,";CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:"); if (!strncmp(Buffer,buff,strlen(buff))) { DecodeUTF8QuotedPrintable(Value,Buffer+strlen(Start)+41,strlen(Buffer)-(strlen(Start)+41)); dbgprintf("ReadVCalText is \"%s\"\n",DecodeUnicodeConsole(Value)); return true; } strcpy(buff,Start); strcat(buff,";CHARSET=UTF-8:"); if (!strncmp(Buffer,buff,strlen(buff))) { DecodeUTF8(Value,Buffer+strlen(Start)+15,strlen(Buffer)-(strlen(Start)+15)); dbgprintf("ReadVCalText is \"%s\"\n",DecodeUnicodeConsole(Value)); return true; } strcpy(buff,Start); strcat(buff,";CHARSET=UTF-7:"); if (!strncmp(Buffer,buff,strlen(buff))) { DecodeUTF7(Value,Buffer+strlen(Start)+15,strlen(Buffer)-(strlen(Start)+15)); dbgprintf("ReadVCalText is \"%s\"\n",DecodeUnicodeConsole(Value)); return true; } return false; } /* How should editor hadle tabs in this file? Add editor commands here. * vim: noexpandtab sw=8 ts=8 sts=8: */ diff --git a/gammu/emb/common/service/gsmpbk.c b/gammu/emb/common/service/gsmpbk.c index 05e5cb9..f7cf7d7 100644 --- a/gammu/emb/common/service/gsmpbk.c +++ b/gammu/emb/common/service/gsmpbk.c @@ -1,370 +1,371 @@ /* (c) 2001-2003 by Marcin Wiacek,... */ #include <string.h> #include "../misc/coding/coding.h" #include "gsmpbk.h" #include "gsmmisc.h" unsigned char *GSM_PhonebookGetEntryName (GSM_MemoryEntry *entry) { /* We possibly store here "LastName, FirstName" so allocate enough memory */ static char dest[(GSM_PHONEBOOK_TEXT_LENGTH*2+2+1)*2]; static char split[] = { '\0', ',', '\0', ' ', '\0', '\0'}; int i; int first = -1, last = -1, name = -1; int len = 0; for (i = 0; i < entry->EntriesNum; i++) { switch (entry->Entries[i].EntryType) { case PBK_Text_LastName: last = i; break; case PBK_Text_FirstName: first = i; break; case PBK_Text_Name: name = i; break; default: break; } } if (name != -1) { CopyUnicodeString(dest, entry->Entries[name].Text); } else { if (last != -1 && first != -1) { len = UnicodeLength(entry->Entries[last].Text); CopyUnicodeString(dest, entry->Entries[last].Text); CopyUnicodeString(dest + 2*len, split); CopyUnicodeString(dest + 2*len + 4, entry->Entries[first].Text); } else if (last != -1) { CopyUnicodeString(dest, entry->Entries[last].Text); } else if (first != -1) { CopyUnicodeString(dest, entry->Entries[first].Text); } else { return NULL; } } return dest; } void GSM_PhonebookFindDefaultNameNumberGroup(GSM_MemoryEntry *entry, int *Name, int *Number, int *Group) { int i; *Name = -1; *Number = -1; *Group = -1; for (i = 0; i < entry->EntriesNum; i++) { switch (entry->Entries[i].EntryType) { case PBK_Number_General : if (*Number == -1) *Number = i; break; case PBK_Text_Name : if (*Name == -1) *Name = i; break; case PBK_Caller_Group : if (*Group == -1) *Group = i; break; default : break; } } if ((*Number) == -1) { for (i = 0; i < entry->EntriesNum; i++) { switch (entry->Entries[i].EntryType) { case PBK_Number_Mobile: case PBK_Number_Work: case PBK_Number_Fax: case PBK_Number_Home: case PBK_Number_Pager: case PBK_Number_Other: *Number = i; break; default: break; } if (*Number != -1) break; } } if ((*Name) == -1) { for (i = 0; i < entry->EntriesNum; i++) { if (entry->Entries[i].EntryType != PBK_Text_LastName) continue; *Name = i; break; } } if ((*Name) == -1) { for (i = 0; i < entry->EntriesNum; i++) { if (entry->Entries[i].EntryType != PBK_Text_FirstName) continue; *Name = i; break; } } } void GSM_EncodeVCARD(char *Buffer, int *Length, GSM_MemoryEntry *pbk, bool header, GSM_VCardVersion Version) { int Name, Number, Group, i; bool ignore; GSM_PhonebookFindDefaultNameNumberGroup(pbk, &Name, &Number, &Group); if (Version == Nokia_VCard10) { if (header) *Length+=sprintf(Buffer+(*Length),"BEGIN:VCARD%c%c",13,10); if (Name != -1) { *Length+=sprintf(Buffer+(*Length),"N:%s%c%c",DecodeUnicodeString(pbk->Entries[Name].Text),13,10); } if (Number != -1) { *Length +=sprintf(Buffer+(*Length),"TEL:%s%c%c",DecodeUnicodeString(pbk->Entries[Number].Text),13,10); } if (header) *Length+=sprintf(Buffer+(*Length),"END:VCARD%c%c",13,10); } else if (Version == Nokia_VCard21) { if (header) *Length+=sprintf(Buffer+(*Length),"BEGIN:VCARD%c%cVERSION:2.1%c%c",13,10,13,10); if (Name != -1) { SaveVCALText(Buffer, Length, pbk->Entries[Name].Text, "N"); } for (i=0; i < pbk->EntriesNum; i++) { if (i != Name) { ignore = false; switch(pbk->Entries[i].EntryType) { case PBK_Text_Name : case PBK_Date : case PBK_Caller_Group : ignore = true; break; case PBK_Number_General : *Length+=sprintf(Buffer+(*Length),"TEL"); - if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF"); + (*Length)+=sprintf(Buffer+(*Length),";PREF"); break; case PBK_Number_Mobile : *Length+=sprintf(Buffer+(*Length),"TEL"); - if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF"); + //if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF"); *Length+=sprintf(Buffer+(*Length),";CELL"); break; case PBK_Number_Work : *Length+=sprintf(Buffer+(*Length),"TEL"); - if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF"); - *Length+=sprintf(Buffer+(*Length),";WORK;VOICE"); + //if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF"); + *Length+=sprintf(Buffer+(*Length),";WORK"); break; case PBK_Number_Fax : *Length+=sprintf(Buffer+(*Length),"TEL"); - if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF"); + //if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF"); *Length+=sprintf(Buffer+(*Length),";FAX"); break; case PBK_Number_Home : *Length+=sprintf(Buffer+(*Length),"TEL"); - if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF"); - *Length+=sprintf(Buffer+(*Length),";HOME;VOICE"); + //if (Number == i) (*Length)+=sprintf(Buffer+(*Length),";PREF"); + *Length+=sprintf(Buffer+(*Length),";HOME"); break; case PBK_Text_Note : *Length+=sprintf(Buffer+(*Length),"NOTE"); break; case PBK_Text_Postal : /* Don't ask why. Nokia phones save postal address * double - once like LABEL, second like ADR */ - SaveVCALText(Buffer, Length, pbk->Entries[i].Text, "LABEL"); + //SaveVCALText(Buffer, Length, pbk->Entries[i].Text, "LABEL"); *Length+=sprintf(Buffer+(*Length),"ADR"); break; case PBK_Text_Email : case PBK_Text_Email2 : *Length+=sprintf(Buffer+(*Length),"EMAIL"); break; case PBK_Text_URL : *Length+=sprintf(Buffer+(*Length),"URL"); break; default : ignore = true; break; } if (!ignore) { SaveVCALText(Buffer, Length, pbk->Entries[i].Text, ""); } } } + *Length+=sprintf(Buffer+(*Length), "X-KADDRESSBOOK-X-ExternalID:%d%c%c",pbk->Location,13,10); if (header) *Length+=sprintf(Buffer+(*Length),"END:VCARD%c%c",13,10); } } GSM_Error GSM_DecodeVCARD(unsigned char *Buffer, int *Pos, GSM_MemoryEntry *Pbk, GSM_VCardVersion Version) { unsigned char Line[2000],Buff[2000]; int Level = 0; Buff[0] = 0; Pbk->EntriesNum = 0; while (1) { MyGetLine(Buffer, Pos, Line, strlen(Buffer)); if (strlen(Line) == 0) break; switch (Level) { case 0: if (strstr(Line,"BEGIN:VCARD")) Level = 1; break; case 1: if (strstr(Line,"END:VCARD")) { if (Pbk->EntriesNum == 0) return ERR_EMPTY; return ERR_NONE; } if (ReadVCALText(Line, "N", Buff)) { CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff); Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Text_Name; Pbk->EntriesNum++; } if (ReadVCALText(Line, "TEL", Buff) || ReadVCALText(Line, "TEL;VOICE", Buff) || ReadVCALText(Line, "TEL;PREF", Buff) || ReadVCALText(Line, "TEL;PREF;VOICE", Buff)) { CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff); Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Number_General; Pbk->EntriesNum++; } if (ReadVCALText(Line, "TEL;CELL", Buff) || ReadVCALText(Line, "TEL;CELL;VOICE", Buff) || ReadVCALText(Line, "TEL;PREF;CELL", Buff) || ReadVCALText(Line, "TEL;PREF;CELL;VOICE", Buff)) { CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff); Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Number_Mobile; Pbk->EntriesNum++; } if (ReadVCALText(Line, "TEL;WORK", Buff) || ReadVCALText(Line, "TEL;PREF;WORK", Buff) || ReadVCALText(Line, "TEL;WORK;VOICE", Buff) || ReadVCALText(Line, "TEL;PREF;WORK;VOICE", Buff)) { CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff); Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Number_Work; Pbk->EntriesNum++; } if (ReadVCALText(Line, "TEL;FAX", Buff) || ReadVCALText(Line, "TEL;PREF;FAX", Buff) || ReadVCALText(Line, "TEL;FAX;VOICE", Buff) || ReadVCALText(Line, "TEL;PREF;FAX;VOICE", Buff)) { CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff); Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Number_Fax; Pbk->EntriesNum++; } if (ReadVCALText(Line, "TEL;HOME", Buff) || ReadVCALText(Line, "TEL;PREF;HOME", Buff) || ReadVCALText(Line, "TEL;HOME;VOICE", Buff) || ReadVCALText(Line, "TEL;PREF;HOME;VOICE", Buff)) { CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff); Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Number_Home; Pbk->EntriesNum++; } if (ReadVCALText(Line, "NOTE", Buff)) { CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff); Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Text_Note; Pbk->EntriesNum++; } if (ReadVCALText(Line, "ADR", Buff)) { CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff); Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Text_Postal; Pbk->EntriesNum++; } if (ReadVCALText(Line, "EMAIL", Buff)) { CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff); Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Text_Email; Pbk->EntriesNum++; } if (ReadVCALText(Line, "URL", Buff)) { CopyUnicodeString(Pbk->Entries[Pbk->EntriesNum].Text,Buff); Pbk->Entries[Pbk->EntriesNum].EntryType = PBK_Text_URL; Pbk->EntriesNum++; } break; } } if (Pbk->EntriesNum == 0) return ERR_EMPTY; return ERR_NONE; } /* -------------- OLD functions (c) by Timo Teras -------------------------- */ #ifndef ENABLE_LGPL static void ParseVCardLine(char **pos, char *Name, char *Parameters, char *Value) { int i; Name[0] = Parameters[0] = Value[0] = 0; if (**pos == 0) return; for (i=0; **pos && **pos != ':' && **pos != ';'; i++, (*pos)++) Name[i] = **pos; Name[i] = 0; //dbgprintf("ParseVCardLine: name tag = '%s'\n", Name); if (**pos == ';') { (*pos)++; for (i=0; **pos && **pos != ':'; i++, (*pos)++) Parameters[i] = **pos; Parameters[i] = ';'; Parameters[i+1] = 0; //dbgprintf("ParseVCardLine: parameter tag = '%s'\n", Parameters); } if (**pos != 0) (*pos)++; i=0; while (**pos) { if ((*pos)[0] == '\x0d' && (*pos)[1] == '\x0a') { (*pos) += 2; if (**pos != '\t' && **pos != ' ') break; while (**pos == '\t' || **pos == ' ') (*pos)++; continue; } Value[i++] = **pos; (*pos)++; } Value[i] = 0; //dbgprintf("ParseVCardLine: value tag = '%s'\n", Value); } void DecodeVCARD21Text(char *VCard, GSM_MemoryEntry *pbk) { char *pos = VCard; char Name[32], Parameters[256], Value[1024]; dbgprintf("Parsing VCard:\n%s\n", VCard); ParseVCardLine(&pos, Name, Parameters, Value); if (!mystrncasecmp(Name, "BEGIN", 0) || !mystrncasecmp(Value, "VCARD", 0)) { dbgprintf("No valid VCARD signature\n"); return; } while (1) { GSM_SubMemoryEntry *pbe = &pbk->Entries[pbk->EntriesNum]; ParseVCardLine(&pos, Name, Parameters, Value); if (Name[0] == 0x00 || (mystrncasecmp(Name, "END", 0) && mystrncasecmp(Value, "VCARD", 0))) return; if (mystrncasecmp(Name, "N", 0)) { //FIXME: Name is tagged field which should be parsed pbe->EntryType = PBK_Text_Name; EncodeUnicode(pbe->Text, Value, strlen(Value)); pbk->EntriesNum++; } else if (mystrncasecmp(Name, "EMAIL", 0)) { pbe->EntryType = PBK_Text_Email; EncodeUnicode(pbe->Text, Value, strlen(Value)); pbk->EntriesNum++; } else if (mystrncasecmp(Name, "TEL", 0)) { if (strstr(Parameters, "WORK;")) pbe->EntryType = PBK_Number_Work; else if (strstr(Name, "HOME;")) pbe->EntryType = PBK_Number_Home; else if (strstr(Name, "FAX;")) pbe->EntryType = PBK_Number_Fax; else pbe->EntryType = PBK_Number_General; EncodeUnicode(pbe->Text, Value, strlen(Value)); pbk->EntriesNum++; } } } #endif /* How should editor hadle tabs in this file? Add editor commands here. * vim: noexpandtab sw=8 ts=8 sts=8: */ diff --git a/gammu/emb/gammu/gammu.c b/gammu/emb/gammu/gammu.c index 8db9afb..684e67c 100644 --- a/gammu/emb/gammu/gammu.c +++ b/gammu/emb/gammu/gammu.c @@ -4305,769 +4305,769 @@ static void Backup(int argc, char *argv[]) if (Info.OperatorLogo) { printmsg("Checking operator logo\n"); Bitmap.Type = GSM_OperatorLogo; error=Phone->GetBitmap(&s,&Bitmap); if (error == ERR_NONE) { if (strcmp(Bitmap.NetworkCode,"000 00")!=0) { if (answer_yes(" Backup operator logo")) DoBackup = true; } } } if (DoBackup) { Backup.OperatorLogo = malloc(sizeof(GSM_Bitmap)); if (Backup.OperatorLogo == NULL) Print_Error(ERR_MOREMEMORY); *Backup.OperatorLogo = Bitmap; } DoBackup = false; if (Info.WAPBookmark) { printmsg("Checking WAP bookmarks\n"); Bookmark.Location = 1; error=Phone->GetWAPBookmark(&s,&Bookmark); if (error==ERR_NONE) { if (answer_yes(" Backup WAP bookmarks")) DoBackup = true; } } if (DoBackup) { used = 0; printmsgerr(" Reading : "); while (error == ERR_NONE) { if (used < GSM_BACKUP_MAX_WAPBOOKMARK) { Backup.WAPBookmark[used] = malloc(sizeof(GSM_WAPBookmark)); if (Backup.WAPBookmark[used] == NULL) Print_Error(ERR_MOREMEMORY); Backup.WAPBookmark[used+1] = NULL; } else { printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_WAPBOOKMARK"); GSM_Terminate(); exit(-1); } *Backup.WAPBookmark[used]=Bookmark; used ++; Bookmark.Location = used+1; error=Phone->GetWAPBookmark(&s,&Bookmark); printmsgerr("*"); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoBackup = false; if (Info.WAPSettings) { printmsg("Checking WAP settings\n"); Settings.Location = 1; error=Phone->GetWAPSettings(&s,&Settings); if (error==ERR_NONE) { if (answer_yes(" Backup WAP settings")) DoBackup = true; } } if (DoBackup) { used = 0; printmsgerr(" Reading : "); while (error == ERR_NONE) { if (used < GSM_BACKUP_MAX_WAPSETTINGS) { Backup.WAPSettings[used] = malloc(sizeof(GSM_MultiWAPSettings)); if (Backup.WAPSettings[used] == NULL) Print_Error(ERR_MOREMEMORY); Backup.WAPSettings[used+1] = NULL; } else { printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_WAPSETTINGS"); GSM_Terminate(); exit(-1); } *Backup.WAPSettings[used]=Settings; used ++; Settings.Location = used+1; error=Phone->GetWAPSettings(&s,&Settings); printmsgerr("*"); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoBackup = false; if (Info.MMSSettings) { printmsg("Checking MMS settings\n"); Settings.Location = 1; error=Phone->GetMMSSettings(&s,&Settings); if (error==ERR_NONE) { if (answer_yes(" Backup MMS settings")) DoBackup = true; } } if (DoBackup) { used = 0; printmsgerr(" Reading : "); while (error == ERR_NONE) { if (used < GSM_BACKUP_MAX_MMSSETTINGS) { Backup.MMSSettings[used] = malloc(sizeof(GSM_MultiWAPSettings)); if (Backup.MMSSettings[used] == NULL) Print_Error(ERR_MOREMEMORY); Backup.MMSSettings[used+1] = NULL; } else { printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_MMSSETTINGS"); GSM_Terminate(); exit(-1); } *Backup.MMSSettings[used]=Settings; used ++; Settings.Location = used+1; error=Phone->GetMMSSettings(&s,&Settings); printmsgerr("*"); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoBackup = false; if (Info.ChatSettings) { printmsg("Checking Chat settings\n"); Chat.Location = 1; error=Phone->GetChatSettings(&s,&Chat); if (error==ERR_NONE) { if (answer_yes(" Backup Chat settings")) DoBackup = true; } } if (DoBackup) { used = 0; printmsgerr(" Reading : "); while (error == ERR_NONE) { if (used < GSM_BACKUP_MAX_CHATSETTINGS) { Backup.ChatSettings[used] = malloc(sizeof(GSM_ChatSettings)); if (Backup.ChatSettings[used] == NULL) Print_Error(ERR_MOREMEMORY); Backup.ChatSettings[used+1] = NULL; } else { printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_CHATSETTINGS"); GSM_Terminate(); exit(-1); } *Backup.ChatSettings[used]=Chat; used ++; Chat.Location = used+1; error=Phone->GetChatSettings(&s,&Chat); printmsgerr("*"); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoBackup = false; if (Info.SyncMLSettings) { printmsg("Checking SyncML settings\n"); SyncML.Location = 1; error=Phone->GetSyncMLSettings(&s,&SyncML); if (error==ERR_NONE) { if (answer_yes(" Backup SyncML settings")) DoBackup = true; } } if (DoBackup) { used = 0; printmsgerr(" Reading : "); while (error == ERR_NONE) { if (used < GSM_BACKUP_MAX_SYNCMLSETTINGS) { Backup.SyncMLSettings[used] = malloc(sizeof(GSM_SyncMLSettings)); if (Backup.SyncMLSettings[used] == NULL) Print_Error(ERR_MOREMEMORY); Backup.SyncMLSettings[used+1] = NULL; } else { printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_SYNCMLSETTINGS"); GSM_Terminate(); exit(-1); } *Backup.SyncMLSettings[used]=SyncML; used ++; SyncML.Location = used+1; error=Phone->GetSyncMLSettings(&s,&SyncML); printmsgerr("*"); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoBackup = false; if (Info.Ringtone) { printmsg("Checking user ringtones\n"); Ringtone.Location = 1; Ringtone.Format = 0; error=Phone->GetRingtone(&s,&Ringtone,false); if (error==ERR_EMPTY || error == ERR_NONE) { if (answer_yes(" Backup user ringtones")) DoBackup = true; } } if (DoBackup) { used = 0; i = 1; printmsgerr(" Reading : "); while (error == ERR_NONE || error == ERR_EMPTY) { if (error == ERR_NONE) { if (used < GSM_BACKUP_MAX_RINGTONES) { Backup.Ringtone[used] = malloc(sizeof(GSM_Ringtone)); if (Backup.Ringtone[used] == NULL) Print_Error(ERR_MOREMEMORY); Backup.Ringtone[used+1] = NULL; } else { printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_RINGTONES"); GSM_Terminate(); exit(-1); } *Backup.Ringtone[used]=Ringtone; used ++; } i++; Ringtone.Location = i; Ringtone.Format = 0; error=Phone->GetRingtone(&s,&Ringtone,false); printmsgerr("*"); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoBackup = false; if (Info.Profiles) { printmsg("Checking phone profiles\n"); Profile.Location = 1; error = Phone->GetProfile(&s,&Profile); if (error == ERR_NONE) { if (answer_yes(" Backup phone profiles")) DoBackup = true; } } if (DoBackup) { used = 0; printmsgerr(" Reading: "); while (true) { Profile.Location = used + 1; error = Phone->GetProfile(&s,&Profile); if (error != ERR_NONE) break; if (used < GSM_BACKUP_MAX_PROFILES) { Backup.Profiles[used] = malloc(sizeof(GSM_Profile)); if (Backup.Profiles[used] == NULL) Print_Error(ERR_MOREMEMORY); Backup.Profiles[used + 1] = NULL; } else { printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_PROFILES"); GSM_Terminate(); exit(-1); } *Backup.Profiles[used]=Profile; used++; printmsgerr("*"); } printmsgerr("\n"); } DoBackup = false; if (Info.FMStation) { printmsg("Checking FM stations\n"); FMStation.Location = 1; error = Phone->GetFMStation(&s,&FMStation); if (error == ERR_NONE || error == ERR_EMPTY) { if (answer_yes(" Backup phone FM stations")) DoBackup=true; } } if (DoBackup) { used = 0; i = 1; printmsgerr(" Reading: "); while (error == ERR_NONE || error == ERR_EMPTY) { error = Phone->GetFMStation(&s,&FMStation); if (error == ERR_NONE) { if (used < GSM_BACKUP_MAX_FMSTATIONS) { Backup.FMStation[used] = malloc(sizeof(GSM_FMStation)); if (Backup.FMStation[used] == NULL) Print_Error(ERR_MOREMEMORY); Backup.FMStation[used + 1] = NULL; } else { printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_FMSTATIONS"); GSM_Terminate(); exit(-1); } *Backup.FMStation[used]=FMStation; used++; } i++; FMStation.Location = i; printmsgerr("*"); } printmsgerr("\n"); } DoBackup = false; if (Info.GPRSPoint) { printmsg("Checking GPRS access points\n"); GPRSPoint.Location = 1; error = Phone->GetGPRSAccessPoint(&s,&GPRSPoint); if (error == ERR_NONE || error == ERR_EMPTY) { if (answer_yes(" Backup GPRS access points")) DoBackup = true; } } if (DoBackup) { used = 0; i = 1; printmsgerr(" Reading: "); while (error == ERR_NONE || error == ERR_EMPTY) { error = Phone->GetGPRSAccessPoint(&s,&GPRSPoint); if (error == ERR_NONE) { if (used < GSM_BACKUP_MAX_GPRSPOINT) { Backup.GPRSPoint[used] = malloc(sizeof(GSM_GPRSAccessPoint)); if (Backup.GPRSPoint[used] == NULL) Print_Error(ERR_MOREMEMORY); Backup.GPRSPoint[used + 1] = NULL; } else { printmsg(" Increase %s\n" , "GSM_BACKUP_MAX_GPRSPOINT"); GSM_Terminate(); exit(-1); } *Backup.GPRSPoint[used]=GPRSPoint; used++; } i++; GPRSPoint.Location = i; printmsgerr("*"); } printmsgerr("\n"); } GSM_Terminate(); GSM_SaveBackupFile(argv[2],&Backup, Info.UseUnicode); GSM_FreeBackup(&Backup); } static void Restore(int argc, char *argv[]) { GSM_Backup Backup; GSM_FMStation FMStation; GSM_DateTime date_time; GSM_CalendarEntry Calendar; GSM_Bitmap Bitmap; GSM_Ringtone Ringtone; GSM_MemoryEntry Pbk; GSM_MemoryStatus MemStatus; GSM_ToDoEntry ToDo; GSM_ToDoStatus ToDoStatus; GSM_Profile Profile; GSM_MultiWAPSettings Settings; GSM_GPRSAccessPoint GPRSPoint; GSM_WAPBookmark Bookmark; int i, used, max = 0; bool Past = true; bool Found, DoRestore; error=GSM_ReadBackupFile(argv[2],&Backup); if (error!=ERR_NOTIMPLEMENTED) { Print_Error(error); } else { printmsgerr("WARNING: Some data not read from file. It can be damaged or restoring some settings from this file format not implemented (maybe higher Gammu required ?)\n"); } signal(SIGINT, interrupt); printmsgerr("Press Ctrl+C to break...\n"); if (Backup.DateTimeAvailable) printmsgerr("Time of backup : %s\n",OSDateTime(Backup.DateTime,false)); if (Backup.Model[0]!=0) printmsgerr("Phone : %s\n",Backup.Model); if (Backup.IMEI[0]!=0) printmsgerr("IMEI : %s\n",Backup.IMEI); if (Backup.Creator[0]!=0) printmsgerr("File created by : %s\n",Backup.Creator); if (Backup.MD5Calculated[0]!=0) { dbgprintf("\"%s\"\n",Backup.MD5Original); dbgprintf("\"%s\"\n",Backup.MD5Calculated); if (strcmp(Backup.MD5Original,Backup.MD5Calculated)) { if (!answer_yes("Checksum in backup file do not match. Continue")) return; } } GSM_Init(true); DoRestore = false; if (Backup.PhonePhonebook[0] != NULL) { MemStatus.MemoryType = MEM_ME; error=Phone->GetMemoryStatus(&s, &MemStatus); if (error==ERR_NONE) { max = 0; while (Backup.PhonePhonebook[max]!=NULL) max++; printmsgerr("%i entries in backup file\n",max); - if (answer_yes("Restore phone phonebook")) DoRestore = true; + /* LR if (answer_yes("Restore phone phonebook")) */DoRestore = true; } } if (DoRestore) { used = 0; for (i=0;i<MemStatus.MemoryUsed+MemStatus.MemoryFree;i++) { Pbk.MemoryType = MEM_ME; Pbk.Location = i + 1; Pbk.EntriesNum = 0; if (used<max) { if (Backup.PhonePhonebook[used]->Location == Pbk.Location) { Pbk = *Backup.PhonePhonebook[used]; used++; dbgprintf("Location %i\n",Pbk.Location); if (Pbk.EntriesNum != 0) error=Phone->SetMemory(&s, &Pbk); } } if (Pbk.EntriesNum == 0) error=Phone->DeleteMemory(&s, &Pbk); Print_Error(error); printmsgerr("%cWriting: %i percent",13,(i+1)*100/(MemStatus.MemoryUsed+MemStatus.MemoryFree)); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoRestore = false; if (Backup.SIMPhonebook[0] != NULL) { MemStatus.MemoryType = MEM_SM; error=Phone->GetMemoryStatus(&s, &MemStatus); if (error==ERR_NONE) { max = 0; while (Backup.SIMPhonebook[max]!=NULL) max++; printmsgerr("%i entries in backup file\n",max); if (answer_yes("Restore SIM phonebook")) DoRestore = true; } } if (DoRestore) { used = 0; for (i=0;i<MemStatus.MemoryUsed+MemStatus.MemoryFree;i++) { Pbk.MemoryType = MEM_SM; Pbk.Location = i + 1; Pbk.EntriesNum = 0; if (used<max) { if (Backup.SIMPhonebook[used]->Location == Pbk.Location) { Pbk = *Backup.SIMPhonebook[used]; used++; dbgprintf("Location %i\n",Pbk.Location); if (Pbk.EntriesNum != 0) error=Phone->SetMemory(&s, &Pbk); } } if (Pbk.EntriesNum == 0) error=Phone->DeleteMemory(&s, &Pbk); Print_Error(error); printmsgerr("%cWriting: %i percent",13,(i+1)*100/(MemStatus.MemoryUsed+MemStatus.MemoryFree)); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoRestore = false; if (Backup.CallerLogos[0] != NULL) { Bitmap.Type = GSM_CallerGroupLogo; Bitmap.Location = 1; error=Phone->GetBitmap(&s,&Bitmap); if (error == ERR_NONE) { if (answer_yes("Restore caller groups and logos")) DoRestore = true; } } if (DoRestore) { max = 0; while (Backup.CallerLogos[max]!=NULL) max++; for (i=0;i<max;i++) { error=Phone->SetBitmap(&s,Backup.CallerLogos[i]); Print_Error(error); printmsgerr("%cWriting: %i percent",13,(i+1)*100/max); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } if (!mystrncasecmp(s.CurrentConfig->SyncTime,"yes",0)) { if ( true /*LRanswer_yes("Do you want to set date/time in phone (NOTE: in some phones it's required to correctly restore calendar notes and other items)")*/) { GSM_GetCurrentDateTime(&date_time); error=Phone->SetDateTime(&s, &date_time); Print_Error(error); } } DoRestore = false; if (Backup.Calendar[0] != NULL) { /* N6110 doesn't support getting calendar status */ error = Phone->GetNextCalendar(&s,&Calendar,true); if (error == ERR_NONE || error == ERR_INVALIDLOCATION || error == ERR_EMPTY) { max = 0; while (Backup.Calendar[max] != NULL) max++; printmsgerr("%i entries in backup file\n",max); // LR //if (answer_yes("Restore calendar notes")) { //Past = answer_yes("Restore notes from the past"); DoRestore = true; //} } } if (DoRestore) { printmsgerr("Deleting old notes: "); error = Phone->DeleteAllCalendar(&s); if (error == ERR_NOTSUPPORTED || error == ERR_NOTIMPLEMENTED) { while (1) { error = Phone->GetNextCalendar(&s,&Calendar,true); if (error != ERR_NONE) break; error = Phone->DeleteCalendar(&s,&Calendar); Print_Error(error); printmsgerr("*"); } printmsgerr("\n"); } else { printmsgerr("Done\n"); Print_Error(error); } for (i=0;i<max;i++) { if (!Past && IsCalendarNoteFromThePast(Backup.Calendar[i])) continue; Calendar = *Backup.Calendar[i]; error=Phone->AddCalendar(&s,&Calendar); Print_Error(error); printmsgerr("%cWriting: %i percent",13,(i+1)*100/max); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoRestore = false; if (Backup.ToDo[0] != NULL) { error = Phone->GetToDoStatus(&s,&ToDoStatus); if (error == ERR_NONE) { max = 0; while (Backup.ToDo[max]!=NULL) max++; printmsgerr("%i entries in backup file\n",max); //LR if (answer_yes("Restore ToDo")) DoRestore = true; } } if (DoRestore) { ToDo = *Backup.ToDo[0]; error = Phone->SetToDo(&s,&ToDo); } if (DoRestore && (error == ERR_NOTSUPPORTED || error == ERR_NOTIMPLEMENTED)) { printmsgerr("Deleting old ToDo: "); error=Phone->DeleteAllToDo(&s); if (error == ERR_NOTSUPPORTED || error == ERR_NOTIMPLEMENTED) { while (1) { error = Phone->GetNextToDo(&s,&ToDo,true); if (error != ERR_NONE) break; error = Phone->DeleteToDo(&s,&ToDo); Print_Error(error); printmsgerr("*"); } printmsgerr("\n"); } else { printmsgerr("Done\n"); Print_Error(error); } for (i=0;i<max;i++) { ToDo = *Backup.ToDo[i]; ToDo.Location = 0; error=Phone->AddToDo(&s,&ToDo); Print_Error(error); printmsgerr("%cWriting: %i percent",13,(i+1)*100/max); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } else if (DoRestore) { /* At first delete entries, that were deleted */ used = 0; error = Phone->GetNextToDo(&s,&ToDo,true); while (error == ERR_NONE) { used++; Found = false; for (i=0;i<max;i++) { if (Backup.ToDo[i]->Location == ToDo.Location) { Found = true; break; } } if (!Found) { error=Phone->DeleteToDo(&s,&ToDo); Print_Error(error); } error = Phone->GetNextToDo(&s,&ToDo,false); printmsgerr("%cCleaning: %i percent",13,used*100/ToDoStatus.Used); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); /* Now write modified/new entries */ for (i=0;i<max;i++) { ToDo = *Backup.ToDo[i]; error = Phone->SetToDo(&s,&ToDo); Print_Error(error); printmsgerr("%cWriting: %i percent",13,(i+1)*100/max); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } if (Backup.SMSC[0] != NULL && answer_yes("Restore SMSC profiles")) { max = 0; while (Backup.SMSC[max]!=NULL) max++; for (i=0;i<max;i++) { error=Phone->SetSMSC(&s,Backup.SMSC[i]); Print_Error(error); printmsgerr("%cWriting: %i percent",13,(i+1)*100/max); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } if (Backup.StartupLogo != NULL && answer_yes("Restore startup logo/text")) { error=Phone->SetBitmap(&s,Backup.StartupLogo); Print_Error(error); } if (Backup.OperatorLogo != NULL && answer_yes("Restore operator logo")) { error=Phone->SetBitmap(&s,Backup.OperatorLogo); Print_Error(error); } DoRestore = false; if (Backup.WAPBookmark[0] != NULL) { Bookmark.Location = 1; error = Phone->GetWAPBookmark(&s,&Bookmark); if (error == ERR_NONE || error == ERR_INVALIDLOCATION) { if (answer_yes("Restore WAP bookmarks")) DoRestore = true; } } if (DoRestore) { printmsgerr("Deleting old bookmarks: "); /* One thing to explain: DCT4 phones seems to have bug here. * When delete for example first bookmark, phone change * numeration for getting frame, not for deleting. So, we try to * get 1'st bookmark. Inside frame is "correct" location. We use * it later */ while (error==ERR_NONE) { error = Phone->DeleteWAPBookmark(&s,&Bookmark); Bookmark.Location = 1; error = Phone->GetWAPBookmark(&s,&Bookmark); printmsgerr("*"); } printmsgerr("\n"); max = 0; while (Backup.WAPBookmark[max]!=NULL) max++; for (i=0;i<max;i++) { Bookmark = *Backup.WAPBookmark[i]; Bookmark.Location = 0; error=Phone->SetWAPBookmark(&s,&Bookmark); Print_Error(error); printmsgerr("%cWriting: %i percent",13,(i+1)*100/max); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoRestore = false; if (Backup.WAPSettings[0] != NULL) { Settings.Location = 1; error = Phone->GetWAPSettings(&s,&Settings); if (error == ERR_NONE) { if (answer_yes("Restore WAP settings")) DoRestore = true; } } if (DoRestore) { max = 0; while (Backup.WAPSettings[max]!=NULL) max++; for (i=0;i<max;i++) { error=Phone->SetWAPSettings(&s,Backup.WAPSettings[i]); Print_Error(error); printmsgerr("%cWriting: %i percent",13,(i+1)*100/max); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoRestore = false; if (Backup.MMSSettings[0] != NULL) { Settings.Location = 1; error = Phone->GetMMSSettings(&s,&Settings); if (error == ERR_NONE) { if (answer_yes("Restore MMS settings")) DoRestore = true; } } if (DoRestore) { max = 0; while (Backup.MMSSettings[max]!=NULL) max++; for (i=0;i<max;i++) { error=Phone->SetMMSSettings(&s,Backup.MMSSettings[i]); Print_Error(error); printmsgerr("%cWriting: %i percent",13,(i+1)*100/max); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoRestore = false; if (Backup.Ringtone[0] != NULL) { Ringtone.Location = 1; Ringtone.Format = 0; error = Phone->GetRingtone(&s,&Ringtone,false); if (error == ERR_NONE || error ==ERR_EMPTY) { if (Phone->DeleteUserRingtones != NOTSUPPORTED) { if (answer_yes("Delete all user ringtones")) DoRestore = true; } } } if (DoRestore) { printmsgerr("Deleting: "); error=Phone->DeleteUserRingtones(&s); Print_Error(error); printmsgerr("Done\n"); DoRestore = false; if (answer_yes("Restore user ringtones")) DoRestore = true; } if (DoRestore) { max = 0; while (Backup.Ringtone[max]!=NULL) max++; for (i=0;i<max;i++) { error=GSM_RingtoneConvert(&Ringtone, Backup.Ringtone[i], Ringtone.Format); Print_Error(error); error=Phone->SetRingtone(&s,&Ringtone,&i); Print_Error(error); printmsgerr("%cWriting: %i percent",13,(i+1)*100/max); if (gshutdown) { GSM_Terminate(); exit(0); } } printmsgerr("\n"); } DoRestore = false; if (Backup.Profiles[0] != NULL) { Profile.Location = 1; error = Phone->GetProfile(&s,&Profile); if (error == ERR_NONE) { if (answer_yes("Restore profiles")) DoRestore = true; } } if (DoRestore) { Profile.Location= 0; max = 0; while (Backup.Profiles[max]!=NULL) max++; for (i=0;i<max;i++) { Profile = *Backup.Profiles[i]; error=Phone->SetProfile(&s,&Profile); Print_Error(error); if (gshutdown) { GSM_Terminate(); diff --git a/kabc/addressbook.cpp b/kabc/addressbook.cpp index d037d2f..ad0f702 100644 --- a/kabc/addressbook.cpp +++ b/kabc/addressbook.cpp @@ -1,980 +1,1102 @@ /* This file is part of libkabc. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Enhanced Version of the file for platform independent KDE tools. Copyright (c) 2004 Ulf Schenk $Id$ */ /*US #include <qfile.h> #include <qregexp.h> #include <qtimer.h> #include <kapplication.h> #include <kinstance.h> #include <kstandarddirs.h> #include "errorhandler.h" */ #include <qptrlist.h> #include <qtextstream.h> #include <qfile.h> #include <qregexp.h> #include <kglobal.h> #include <klocale.h> #include <kmessagebox.h> #include <kdebug.h> #include <libkcal/syncdefines.h> #include <libkdepim/phoneaccess.h> #include "addressbook.h" #include "resource.h" #include "vcardconverter.h" #include "vcardparser/vcardtool.h" //US #include "addressbook.moc" using namespace KABC; struct AddressBook::AddressBookData { Addressee::List mAddressees; Addressee::List mRemovedAddressees; Field::List mAllFields; KConfig *mConfig; KRES::Manager<Resource> *mManager; //US ErrorHandler *mErrorHandler; }; struct AddressBook::Iterator::IteratorData { Addressee::List::Iterator mIt; }; struct AddressBook::ConstIterator::ConstIteratorData { Addressee::List::ConstIterator mIt; }; AddressBook::Iterator::Iterator() { d = new IteratorData; } AddressBook::Iterator::Iterator( const AddressBook::Iterator &i ) { d = new IteratorData; d->mIt = i.d->mIt; } AddressBook::Iterator &AddressBook::Iterator::operator=( const AddressBook::Iterator &i ) { if( this == &i ) return *this; // guard against self assignment delete d; // delete the old data the Iterator was completely constructed before d = new IteratorData; d->mIt = i.d->mIt; return *this; } AddressBook::Iterator::~Iterator() { delete d; } const Addressee &AddressBook::Iterator::operator*() const { return *(d->mIt); } Addressee &AddressBook::Iterator::operator*() { return *(d->mIt); } Addressee *AddressBook::Iterator::operator->() { return &(*(d->mIt)); } AddressBook::Iterator &AddressBook::Iterator::operator++() { (d->mIt)++; return *this; } AddressBook::Iterator &AddressBook::Iterator::operator++(int) { (d->mIt)++; return *this; } AddressBook::Iterator &AddressBook::Iterator::operator--() { (d->mIt)--; return *this; } AddressBook::Iterator &AddressBook::Iterator::operator--(int) { (d->mIt)--; return *this; } bool AddressBook::Iterator::operator==( const Iterator &it ) { return ( d->mIt == it.d->mIt ); } bool AddressBook::Iterator::operator!=( const Iterator &it ) { return ( d->mIt != it.d->mIt ); } AddressBook::ConstIterator::ConstIterator() { d = new ConstIteratorData; } AddressBook::ConstIterator::ConstIterator( const AddressBook::ConstIterator &i ) { d = new ConstIteratorData; d->mIt = i.d->mIt; } AddressBook::ConstIterator &AddressBook::ConstIterator::operator=( const AddressBook::ConstIterator &i ) { if( this == &i ) return *this; // guard for self assignment delete d; // delete the old data because the Iterator was really constructed before d = new ConstIteratorData; d->mIt = i.d->mIt; return *this; } AddressBook::ConstIterator::~ConstIterator() { delete d; } const Addressee &AddressBook::ConstIterator::operator*() const { return *(d->mIt); } const Addressee* AddressBook::ConstIterator::operator->() const { return &(*(d->mIt)); } AddressBook::ConstIterator &AddressBook::ConstIterator::operator++() { (d->mIt)++; return *this; } AddressBook::ConstIterator &AddressBook::ConstIterator::operator++(int) { (d->mIt)++; return *this; } AddressBook::ConstIterator &AddressBook::ConstIterator::operator--() { (d->mIt)--; return *this; } AddressBook::ConstIterator &AddressBook::ConstIterator::operator--(int) { (d->mIt)--; return *this; } bool AddressBook::ConstIterator::operator==( const ConstIterator &it ) { return ( d->mIt == it.d->mIt ); } bool AddressBook::ConstIterator::operator!=( const ConstIterator &it ) { return ( d->mIt != it.d->mIt ); } AddressBook::AddressBook() { init(0, "contact"); } AddressBook::AddressBook( const QString &config ) { init(config, "contact"); } AddressBook::AddressBook( const QString &config, const QString &family ) { init(config, family); } // the default family is "contact" void AddressBook::init(const QString &config, const QString &family ) { blockLSEchange = false; d = new AddressBookData; QString fami = family; if (config != 0) { if ( family == "syncContact" ) { qDebug("creating sync config "); fami = "contact"; KConfig* con = new KConfig( locateLocal("config", "syncContactrc") ); con->setGroup( "General" ); con->writeEntry( "ResourceKeys", QString("sync") ); con->writeEntry( "Standard", QString("sync") ); con->setGroup( "Resource_sync" ); con->writeEntry( "FileName", config ); con->writeEntry( "FileFormat", QString("vcard") ); con->writeEntry( "ResourceIdentifier", QString("sync") ); con->writeEntry( "ResourceName", QString("sync_res") ); if ( config.right(4) == ".xml" ) con->writeEntry( "ResourceType", QString("qtopia") ); else if ( config == "sharp" ) { con->writeEntry( "ResourceType", QString("sharp") ); } else { con->writeEntry( "ResourceType", QString("file") ); } //con->sync(); d->mConfig = con; } else d->mConfig = new KConfig( locateLocal("config", config) ); // qDebug("AddressBook::init 1 config=%s",config.latin1() ); } else { d->mConfig = 0; // qDebug("AddressBook::init 1 config=0"); } //US d->mErrorHandler = 0; d->mManager = new KRES::Manager<Resource>( fami, false ); d->mManager->readConfig( d->mConfig ); if ( family == "syncContact" ) { KRES::Manager<Resource> *manager = d->mManager; KRES::Manager<Resource>::ActiveIterator it; for ( it = manager->activeBegin(); it != manager->activeEnd(); ++it ) { (*it)->setAddressBook( this ); if ( !(*it)->open() ) error( QString( "Unable to open resource '%1'!" ).arg( (*it)->resourceName() ) ); } Resource *res = standardResource(); if ( !res ) { qDebug("ERROR: no standard resource"); res = manager->createResource( "file" ); if ( res ) { addResource( res ); } else qDebug(" No resource available!!!"); } setStandardResource( res ); manager->writeConfig(); } addCustomField( i18n( "Department" ), KABC::Field::Organization, "X-Department", "KADDRESSBOOK" ); addCustomField( i18n( "Profession" ), KABC::Field::Organization, "X-Profession", "KADDRESSBOOK" ); addCustomField( i18n( "Assistant's Name" ), KABC::Field::Organization, "X-AssistantsName", "KADDRESSBOOK" ); addCustomField( i18n( "Manager's Name" ), KABC::Field::Organization, "X-ManagersName", "KADDRESSBOOK" ); addCustomField( i18n( "Spouse's Name" ), KABC::Field::Personal, "X-SpousesName", "KADDRESSBOOK" ); addCustomField( i18n( "Office" ), KABC::Field::Personal, "X-Office", "KADDRESSBOOK" ); addCustomField( i18n( "IM Address" ), KABC::Field::Personal, "X-IMAddress", "KADDRESSBOOK" ); addCustomField( i18n( "Anniversary" ), KABC::Field::Personal, "X-Anniversary", "KADDRESSBOOK" ); //US added this field to become compatible with Opie/qtopia addressbook // values can be "female" or "male" or "". An empty field represents undefined. addCustomField( i18n( "Gender" ), KABC::Field::Personal, "X-Gender", "KADDRESSBOOK" ); addCustomField( i18n( "Children" ), KABC::Field::Personal, "X-Children", "KADDRESSBOOK" ); addCustomField( i18n( "FreeBusyUrl" ), KABC::Field::Personal, "X-FreeBusyUrl", "KADDRESSBOOK" ); addCustomField( i18n( "ExternalID" ), KABC::Field::Personal, "X-ExternalID", "KADDRESSBOOK" ); } AddressBook::~AddressBook() { delete d->mConfig; d->mConfig = 0; delete d->mManager; d->mManager = 0; //US delete d->mErrorHandler; d->mErrorHandler = 0; delete d; d = 0; } bool AddressBook::load() { - clear(); - KRES::Manager<Resource>::ActiveIterator it; bool ok = true; for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it ) if ( !(*it)->load() ) { - error( i18n("Unable to load resource '%1'").arg( (*it)->resourceName() ) ); + qDebug( i18n("Unable to load resource '%1'").arg( (*it)->resourceName() ) ); ok = false; + } else { + qDebug( i18n("Resource loaded: '%1'").arg( (*it)->resourceName() ) ); } - // mark all addressees as unchanged Addressee::List::Iterator addrIt; for ( addrIt = d->mAddressees.begin(); addrIt != d->mAddressees.end(); ++addrIt ) { (*addrIt).setChanged( false ); QString id = (*addrIt).custom( "KADDRESSBOOK", "X-ExternalID" ); if ( !id.isEmpty() ) { //qDebug("setId aa %s ", id.latin1()); (*addrIt).setIDStr(id ); } } blockLSEchange = true; return ok; } bool AddressBook::save( Ticket *ticket ) { kdDebug(5700) << "AddressBook::save()"<< endl; if ( ticket->resource() ) { deleteRemovedAddressees(); return ticket->resource()->save( ticket ); } return false; } void AddressBook::export2File( QString fileName ) { QFile outFile( fileName ); if ( !outFile.open( IO_WriteOnly ) ) { QString text = i18n( "<qt>Unable to open file <b>%1</b> for export.</qt>" ); KMessageBox::error( 0, text.arg( fileName ) ); return ; } QTextStream t( &outFile ); t.setEncoding( QTextStream::UnicodeUTF8 ); Iterator it; KABC::VCardConverter::Version version; version = KABC::VCardConverter::v3_0; for ( it = begin(); it != end(); ++it ) { if ( !(*it).IDStr().isEmpty() ) { (*it).insertCustom( "KADDRESSBOOK", "X-ExternalID", (*it).IDStr() ); } KABC::VCardConverter converter; QString vcard; //Resource *resource() const; converter.addresseeToVCard( *it, vcard, version ); t << vcard << "\r\n"; } t << "\r\n\r\n"; outFile.close(); } +// if QStringList uids is empty, all are exported +bool AddressBook::export2PhoneFormat( QStringList uids ,QString fileName ) +{ + KABC::VCardConverter converter; + QString datastream; + Iterator it; + bool all = uids.isEmpty(); + for ( it = begin(); it != end(); ++it ) { + // for( QStringList::ConstIterator it = uids.begin(); it != uids.end(); ++it ) { + if ( ! all ) { + if ( ! ( uids.contains((*it).uid() ) )) + continue; + } + KABC::Addressee a = ( *it ); + if ( a.isEmpty() ) + continue; + a.simplifyEmails(); + a.simplifyPhoneNumbers(); + a.simplifyPhoneNumberTypes(); + a.simplifyAddresses(); + + QString vcard; + QString vcardnew; + converter.addresseeToVCard( a, vcard ); + int start = 0; + int next; + while ( (next = vcard.find("TYPE=", start) )>= 0 ) { + int semi = vcard.find(";", next); + int dopp = vcard.find(":", next); + int sep; + if ( semi < dopp && semi >= 0 ) + sep = semi ; + else + sep = dopp; + vcardnew +=vcard.mid( start, next - start); + vcardnew +=vcard.mid( next+5,sep -next -5 ).upper(); + start = sep; + } + vcardnew += vcard.mid( start,vcard.length() ); + vcard = ""; + start = 0; + while ( (next = vcardnew.find("ADR", start) )>= 0 ) { + int sep = vcardnew.find(":", next); + vcard +=vcardnew.mid( start, next - start+3); + start = sep; + } + vcard += vcardnew.mid( start,vcardnew.length() ); + vcard.replace ( QRegExp(";;;") , "" ); + vcard.replace ( QRegExp(";;") , "" ); + datastream += vcard; + + } + + QFile outFile(fileName); + if ( outFile.open(IO_WriteOnly) ) { + datastream.replace ( QRegExp("VERSION:3.0") , "VERSION:2.1" ); + QTextStream t( &outFile ); // use a text stream + t.setEncoding( QTextStream::UnicodeUTF8 ); + t <<datastream; + t << "\r\n\r\n"; + outFile.close(); + + } else { + qDebug("Error open temp file "); + return false; + } + return true; + +} void AddressBook::importFromFile( QString fileName, bool replaceLabel, bool removeOld ) { if ( removeOld ) setUntagged(); KABC::Addressee::List list; QFile file( fileName ); file.open( IO_ReadOnly ); QByteArray rawData = file.readAll(); file.close(); QString data; if ( replaceLabel ) { data = QString::fromLatin1( rawData.data(), rawData.size() + 1 ); data.replace ( QRegExp("LABEL") , "ADR" ); data.replace ( QRegExp("CHARSET=ISO-8859-1") , "" ); } else data = QString::fromUtf8( rawData.data(), rawData.size() + 1 ); KABC::VCardTool tool; list = tool.parseVCards( data ); KABC::Addressee::List::Iterator it; for ( it = list.begin(); it != list.end(); ++it ) { + QString id = (*it).custom( "KADDRESSBOOK", "X-ExternalID" ); + if ( !id.isEmpty() ) + (*it).setIDStr(id ); (*it).setResource( 0 ); if ( replaceLabel ) (*it).removeVoice(); if ( removeOld ) (*it).setTagged( true ); insertAddressee( (*it), false, true ); } if ( removeOld ) removeUntagged(); } void AddressBook::setUntagged() { Iterator ait; for ( ait = begin(); ait != end(); ++ait ) { (*ait).setTagged( false ); } } void AddressBook::removeUntagged() { Iterator ait; bool todelete = false; Iterator todel; for ( ait = begin(); ait != end(); ++ait ) { if ( todelete ) removeAddressee( todel ); if (!(*ait).tagged()) { todelete = true; todel = ait; } else todelete = false; } if ( todelete ) removeAddressee( todel ); deleteRemovedAddressees(); } void AddressBook::smplifyAddressees() { Iterator ait; for ( ait = begin(); ait != end(); ++ait ) { (*ait).simplifyEmails(); (*ait).simplifyPhoneNumbers(); (*ait).simplifyPhoneNumberTypes(); (*ait).simplifyAddresses(); } } void AddressBook::preparePhoneSync( QString currentSyncDevice, bool isPreSync ) { Iterator ait; for ( ait = begin(); ait != end(); ++ait ) { QString id = (*ait).IDStr(); (*ait).setIDStr( ":"); (*ait).setExternalUID( id ); (*ait).setOriginalExternalUID( id ); if ( isPreSync ) (*ait).setTempSyncStat( SYNC_TEMPSTATE_NEW_EXTERNAL ); - else + else { (*ait).setTempSyncStat( SYNC_TEMPSTATE_NEW_ID ); + (*ait).setID( currentSyncDevice,id ); + + } + } +} +void AddressBook::findNewExtIds( QString fileName, QString currentSyncDevice ) +{ + + setUntagged(); + KABC::Addressee::List list; + QFile file( fileName ); + file.open( IO_ReadOnly ); + QByteArray rawData = file.readAll(); + file.close(); + QString data; + + data = QString::fromUtf8( rawData.data(), rawData.size() + 1 ); + KABC::VCardTool tool; + list = tool.parseVCards( data ); + KABC::Addressee::List::Iterator it; + for ( it = list.begin(); it != list.end(); ++it ) { + Iterator ait; + for ( ait = begin(); ait != end(); ++ait ) { + if ( !(*ait).tagged() ) { + if ( (*ait).containsAdr(*it)) { + (*ait).setTagged(true); + QString id = (*it).custom( "KADDRESSBOOK", "X-ExternalID" ); + (*it).setIDStr( ":"); + (*it).setID( currentSyncDevice,id ); + (*it).setExternalUID( id ); + (*it).setTempSyncStat( SYNC_TEMPSTATE_NEW_ID ); + (*it).setUid( ( (*ait).uid() )); + break; + } + } + + } + if ( ait == end() ) + qDebug("ERROR:: no ext ID found for uid: %s", (*it).uid().latin1()); + } + clear(); + for ( it = list.begin(); it != list.end(); ++it ) { + insertAddressee( (*it) ); } } + bool AddressBook::saveABphone( QString fileName ) { - smplifyAddressees(); + //smplifyAddressees(); qDebug("saveABphone:: saving AB... "); - if ( ! saveAB() ) + if ( ! export2PhoneFormat( QStringList() ,fileName ) ) return false; qDebug("saveABphone:: writing to phone... "); if ( !PhoneAccess::writeToPhone( fileName) ) { return false; } qDebug("saveABphone:: re-reading from phone... "); if ( !PhoneAccess::readFromPhone( fileName) ) { return false; } - qDebug("reloading phone book... "); - if ( !load() ) - return false; return true; } bool AddressBook::saveAB() { bool ok = true; deleteRemovedAddressees(); Iterator ait; for ( ait = begin(); ait != end(); ++ait ) { if ( !(*ait).IDStr().isEmpty() ) { (*ait).insertCustom( "KADDRESSBOOK", "X-ExternalID", (*ait).IDStr() ); } } KRES::Manager<Resource>::ActiveIterator it; KRES::Manager<Resource> *manager = d->mManager; + qDebug("SaveAB::saving..." ); for ( it = manager->activeBegin(); it != manager->activeEnd(); ++it ) { + qDebug("SaveAB::checking resource..." ); + if ( (*it)->readOnly() ) + qDebug("readonly." ); + if ( (*it)->isOpen() ) + qDebug("open" ); + if ( !(*it)->readOnly() && (*it)->isOpen() ) { Ticket *ticket = requestSaveTicket( *it ); -// qDebug("StdAddressBook::save '%s'", (*it)->resourceName().latin1() ); + qDebug("StdAddressBook::save '%s'", (*it)->resourceName().latin1() ); if ( !ticket ) { - error( i18n( "Unable to save to resource '%1'. It is locked." ) + qDebug( i18n( "Unable to save to resource '%1'. It is locked." ) .arg( (*it)->resourceName() ) ); return false; } //if ( !save( ticket ) ) if ( ticket->resource() ) { if ( ! ticket->resource()->save( ticket ) ) ok = false; + else + qDebug("StdAddressBook::saved '%s'", ticket->resource()->resourceName().latin1() ); + } else ok = false; } } return ok; } AddressBook::Iterator AddressBook::begin() { Iterator it = Iterator(); it.d->mIt = d->mAddressees.begin(); return it; } AddressBook::ConstIterator AddressBook::begin() const { ConstIterator it = ConstIterator(); it.d->mIt = d->mAddressees.begin(); return it; } AddressBook::Iterator AddressBook::end() { Iterator it = Iterator(); it.d->mIt = d->mAddressees.end(); return it; } AddressBook::ConstIterator AddressBook::end() const { ConstIterator it = ConstIterator(); it.d->mIt = d->mAddressees.end(); return it; } void AddressBook::clear() { d->mAddressees.clear(); } Ticket *AddressBook::requestSaveTicket( Resource *resource ) { kdDebug(5700) << "AddressBook::requestSaveTicket()" << endl; if ( !resource ) { qDebug("AddressBook::requestSaveTicket no resource" ); resource = standardResource(); } KRES::Manager<Resource>::ActiveIterator it; for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it ) { if ( (*it) == resource ) { if ( (*it)->readOnly() || !(*it)->isOpen() ) return 0; else return (*it)->requestSaveTicket(); } } return 0; } - +//void insertAddressee( const Addressee &, bool setRev = true, bool takeResource = false); void AddressBook::insertAddressee( const Addressee &a, bool setRev, bool takeResource ) { if ( blockLSEchange && setRev && a.uid().left( 19 ) == QString("last-syncAddressee-") ) { //qDebug("block insert "); return; } //qDebug("inserting.... %s ",a.uid().latin1() ); bool found = false; Addressee::List::Iterator it; for ( it = d->mAddressees.begin(); it != d->mAddressees.end(); ++it ) { if ( a.uid() == (*it).uid() ) { bool changed = false; Addressee addr = a; if ( addr != (*it) ) changed = true; if ( takeResource ) { Resource * res = (*it).resource(); (*it) = a; (*it).setResource( res ); } else { (*it) = a; if ( (*it).resource() == 0 ) (*it).setResource( standardResource() ); } if ( changed ) { if ( setRev ) { // get rid of micro seconds QDateTime dt = QDateTime::currentDateTime(); QTime t = dt.time(); dt.setTime( QTime (t.hour (), t.minute (), t.second () ) ); (*it).setRevision( dt ); } (*it).setChanged( true ); } found = true; } else { if ( (*it).uid().left( 19 ) == QString("last-syncAddressee-") ) { QString name = (*it).uid().mid( 19 ); Addressee b = a; QString id = b.getID( name ); if ( ! id.isEmpty() ) { QString des = (*it).note(); int startN; if( (startN = des.find( id ) ) >= 0 ) { int endN = des.find( ",", startN+1 ); des = des.left( startN ) + des.mid( endN+1 ); (*it).setNote( des ); } } } } } if ( found ) return; d->mAddressees.append( a ); Addressee& addr = d->mAddressees.last(); if ( addr.resource() == 0 ) addr.setResource( standardResource() ); addr.setChanged( true ); } void AddressBook::removeAddressee( const Addressee &a ) { Iterator it; Iterator it2; bool found = false; for ( it = begin(); it != end(); ++it ) { if ( a.uid() == (*it).uid() ) { found = true; it2 = it; } else { if ( (*it).uid().left( 19 ) == QString("last-syncAddressee-") ) { QString name = (*it).uid().mid( 19 ); Addressee b = a; QString id = b.getID( name ); if ( ! id.isEmpty() ) { QString des = (*it).note(); if( des.find( id ) < 0 ) { des += id + ","; (*it).setNote( des ); } } } } } if ( found ) removeAddressee( it2 ); } void AddressBook::removeSyncAddressees( bool removeDeleted ) { Iterator it = begin(); Iterator it2 ; QDateTime dt ( QDate( 2004,1,1) ); while ( it != end() ) { (*it).setRevision( dt ); (*it).removeCustom( "KADDRESSBOOK", "X-ExternalID" ); (*it).setIDStr(""); if ( ( (*it).tempSyncStat() == SYNC_TEMPSTATE_DELETE && removeDeleted )|| (*it).uid().left( 19 ) == QString("last-syncAddressee-")) { it2 = it; //qDebug("removing %s ",(*it).uid().latin1() ); ++it; removeAddressee( it2 ); } else { //qDebug("skipping %s ",(*it).uid().latin1() ); ++it; } } deleteRemovedAddressees(); } void AddressBook::removeAddressee( const Iterator &it ) { d->mRemovedAddressees.append( (*it) ); d->mAddressees.remove( it.d->mIt ); } AddressBook::Iterator AddressBook::find( const Addressee &a ) { Iterator it; for ( it = begin(); it != end(); ++it ) { if ( a.uid() == (*it).uid() ) { return it; } } return end(); } Addressee AddressBook::findByUid( const QString &uid ) { Iterator it; for ( it = begin(); it != end(); ++it ) { if ( uid == (*it).uid() ) { return *it; } } return Addressee(); } void AddressBook::preExternSync( AddressBook* aBook, const QString& csd ) { //qDebug("AddressBook::preExternSync "); AddressBook::Iterator it; for ( it = begin(); it != end(); ++it ) { (*it).setID( csd, (*it).externalUID() ); (*it).computeCsum( csd ); } mergeAB( aBook ,csd ); } void AddressBook::postExternSync( AddressBook* aBook , const QString& csd) { //qDebug("AddressBook::postExternSync "); AddressBook::Iterator it; for ( it = begin(); it != end(); ++it ) { // qDebug("check uid %s ", (*it).uid().latin1() ); if ( (*it).tempSyncStat() == SYNC_TEMPSTATE_NEW_ID || (*it).tempSyncStat() == SYNC_TEMPSTATE_NEW_CSUM ) { Addressee ad = aBook->findByUid( ( (*it).uid() )); if ( ad.isEmpty() ) { qDebug("postExternSync:ERROR addressee is empty: %s ", (*it).uid().latin1()); } else { (*it).computeCsum( csd ); if ( (*it).tempSyncStat() == SYNC_TEMPSTATE_NEW_ID ) ad.setID( csd, (*it).externalUID() ); ad.setCsum( csd, (*it).getCsum( csd ) ); aBook->insertAddressee( ad ); } } } } bool AddressBook::containsExternalUid( const QString& uid ) { Iterator it; for ( it = begin(); it != end(); ++it ) { if ( uid == (*it).externalUID( ) ) return true; } return false; } Addressee AddressBook::findByExternUid( const QString& uid , const QString& profile ) { Iterator it; for ( it = begin(); it != end(); ++it ) { if ( uid == (*it).getID( profile ) ) return (*it); } return Addressee(); } void AddressBook::mergeAB( AddressBook *aBook, const QString& profile ) { Iterator it; Addressee ad; for ( it = begin(); it != end(); ++it ) { ad = aBook->findByExternUid( (*it).externalUID(), profile ); if ( !ad.isEmpty() ) { (*it).mergeContact( ad ); } } #if 0 // test only for ( it = begin(); it != end(); ++it ) { qDebug("uid %s ", (*it).uid().latin1()); } #endif } #if 0 Addressee::List AddressBook::getExternLastSyncAddressees() { Addressee::List results; Iterator it; for ( it = begin(); it != end(); ++it ) { if ( (*it).uid().left( 19 ) == "last-syncAddressee-" ) { if ( (*it).familyName().left(4) == "!E: " ) results.append( *it ); } } return results; } #endif void AddressBook::resetTempSyncStat() { Iterator it; for ( it = begin(); it != end(); ++it ) { (*it).setTempSyncStat ( SYNC_TEMPSTATE_INITIAL ); } } QStringList AddressBook:: uidList() { QStringList results; Iterator it; for ( it = begin(); it != end(); ++it ) { results.append( (*it).uid() ); } return results; } Addressee::List AddressBook::allAddressees() { return d->mAddressees; } Addressee::List AddressBook::findByName( const QString &name ) { Addressee::List results; Iterator it; for ( it = begin(); it != end(); ++it ) { if ( name == (*it).realName() ) { results.append( *it ); } } return results; } Addressee::List AddressBook::findByEmail( const QString &email ) { Addressee::List results; QStringList mailList; Iterator it; for ( it = begin(); it != end(); ++it ) { mailList = (*it).emails(); for ( QStringList::Iterator ite = mailList.begin(); ite != mailList.end(); ++ite ) { if ( email == (*ite) ) { results.append( *it ); } } } return results; } Addressee::List AddressBook::findByCategory( const QString &category ) { Addressee::List results; Iterator it; for ( it = begin(); it != end(); ++it ) { if ( (*it).hasCategory( category) ) { results.append( *it ); } } return results; } void AddressBook::dump() const { kdDebug(5700) << "AddressBook::dump() --- begin ---" << endl; ConstIterator it; for( it = begin(); it != end(); ++it ) { (*it).dump(); } kdDebug(5700) << "AddressBook::dump() --- end ---" << endl; } QString AddressBook::identifier() { QStringList identifier; KRES::Manager<Resource>::ActiveIterator it; for ( it = d->mManager->activeBegin(); it != d->mManager->activeEnd(); ++it ) { if ( !(*it)->identifier().isEmpty() ) identifier.append( (*it)->identifier() ); } return identifier.join( ":" ); } Field::List AddressBook::fields( int category ) { if ( d->mAllFields.isEmpty() ) { d->mAllFields = Field::allFields(); } if ( category == Field::All ) return d->mAllFields; Field::List result; Field::List::ConstIterator it; for( it = d->mAllFields.begin(); it != d->mAllFields.end(); ++it ) { if ( (*it)->category() & category ) result.append( *it ); } return result; } bool AddressBook::addCustomField( const QString &label, int category, const QString &key, const QString &app ) { if ( d->mAllFields.isEmpty() ) { d->mAllFields = Field::allFields(); } //US QString a = app.isNull() ? KGlobal::instance()->instanceName() : app; QString a = app.isNull() ? KGlobal::getAppName() : app; QString k = key.isNull() ? label : key; Field *field = Field::createCustomField( label, category, k, a ); if ( !field ) return false; d->mAllFields.append( field ); return true; } QDataStream &KABC::operator<<( QDataStream &s, const AddressBook &ab ) { if (!ab.d) return s; return s << ab.d->mAddressees; } QDataStream &KABC::operator>>( QDataStream &s, AddressBook &ab ) { if (!ab.d) return s; s >> ab.d->mAddressees; return s; } bool AddressBook::addResource( Resource *resource ) { diff --git a/kabc/addressbook.h b/kabc/addressbook.h index cc755d1..df9048b 100644 --- a/kabc/addressbook.h +++ b/kabc/addressbook.h @@ -1,346 +1,348 @@ /* This file is part of libkabc. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Enhanced Version of the file for platform independent KDE tools. Copyright (c) 2004 Ulf Schenk $Id$ */ #ifndef KABC_ADDRESSBOOK_H #define KABC_ADDRESSBOOK_H #include <qobject.h> #include <kresources/manager.h> #include <qptrlist.h> #include "addressee.h" #include "field.h" namespace KABC { class ErrorHandler; class Resource; class Ticket; /** @short Address Book This class provides access to a collection of address book entries. */ class AddressBook : public QObject { Q_OBJECT friend QDataStream &operator<<( QDataStream &, const AddressBook & ); friend QDataStream &operator>>( QDataStream &, AddressBook & ); friend class StdAddressBook; public: /** @short Address Book Iterator This class provides an iterator for address book entries. */ class Iterator { public: Iterator(); Iterator( const Iterator & ); ~Iterator(); Iterator &operator=( const Iterator & ); const Addressee &operator*() const; Addressee &operator*(); Addressee* operator->(); Iterator &operator++(); Iterator &operator++(int); Iterator &operator--(); Iterator &operator--(int); bool operator==( const Iterator &it ); bool operator!=( const Iterator &it ); struct IteratorData; IteratorData *d; }; /** @short Address Book Const Iterator This class provides a const iterator for address book entries. */ class ConstIterator { public: ConstIterator(); ConstIterator( const ConstIterator & ); ~ConstIterator(); ConstIterator &operator=( const ConstIterator & ); const Addressee &operator*() const; const Addressee* operator->() const; ConstIterator &operator++(); ConstIterator &operator++(int); ConstIterator &operator--(); ConstIterator &operator--(int); bool operator==( const ConstIterator &it ); bool operator!=( const ConstIterator &it ); struct ConstIteratorData; ConstIteratorData *d; }; /** Constructs a address book object. @param format File format class. */ AddressBook(); AddressBook( const QString &config ); AddressBook( const QString &config, const QString &family ); virtual ~AddressBook(); /** Requests a ticket for saving the addressbook. Calling this function locks the addressbook for all other processes. If the address book is already locked the function returns 0. You need the returned @ref Ticket object for calling the @ref save() function. @see save() */ Ticket *requestSaveTicket( Resource *resource=0 ); /** Load address book from file. */ bool load(); /** Save address book. The address book is saved to the file, the Ticket object has been requested for by @ref requestSaveTicket(). @param ticket a ticket object returned by @ref requestSaveTicket() */ bool save( Ticket *ticket ); bool saveAB( ); bool saveABphone( QString fileName ); void smplifyAddressees(); void preparePhoneSync( QString currentSyncDevice, bool isPreSync ); void export2File( QString fileName ); + bool export2PhoneFormat( QStringList uids ,QString fileName ); void importFromFile( QString fileName, bool replaceLabel = false, bool removeOld = false ); void setUntagged(); void removeUntagged(); + void findNewExtIds( QString fileName, QString currentSyncDevice ); /** Returns a iterator for first entry of address book. */ Iterator begin(); /** Returns a const iterator for first entry of address book. */ ConstIterator begin() const; /** Returns a iterator for first entry of address book. */ Iterator end(); /** Returns a const iterator for first entry of address book. */ ConstIterator end() const; /** Removes all entries from address book. */ void clear(); /** Insert an Addressee object into address book. If an object with the same unique id already exists in the address book it it replaced by the new one. If not the new object is appended to the address book. */ void insertAddressee( const Addressee &, bool setRev = true, bool takeResource = false); /** Removes entry from the address book. */ void removeAddressee( const Addressee & ); /** This is like @ref removeAddressee() just above, with the difference that the first element is a iterator, returned by @ref begin(). */ void removeAddressee( const Iterator & ); /** Find the specified entry in address book. Returns end(), if the entry couldn't be found. */ Iterator find( const Addressee & ); /** Find the entry specified by an unique id. Returns an empty Addressee object, if the address book does not contain an entry with this id. */ Addressee findByUid( const QString & ); /** Returns a list of all addressees in the address book. This list can be sorted with @ref KABC::AddresseeList for example. */ Addressee::List allAddressees(); /** Find all entries with the specified name in the address book. Returns an empty list, if no entries could be found. */ Addressee::List findByName( const QString & ); /** Find all entries with the specified email address in the address book. Returns an empty list, if no entries could be found. */ Addressee::List findByEmail( const QString & ); /** Find all entries wich have the specified category in the address book. Returns an empty list, if no entries could be found. */ Addressee::List findByCategory( const QString & ); /** Return a string identifying this addressbook. */ virtual QString identifier(); /** Used for debug output. */ void dump() const; void emitAddressBookLocked() { emit addressBookLocked( this ); } void emitAddressBookUnlocked() { emit addressBookUnlocked( this ); } void emitAddressBookChanged() { emit addressBookChanged( this ); } /** Return list of all Fields known to the address book which are associated with the given field category. */ Field::List fields( int category = Field::All ); /** Add custom field to address book. @param label User visible label of the field. @param category Ored list of field categories. @param key Identifier used as key for reading and writing the field. @param app String used as application key for reading and writing the field. */ bool addCustomField( const QString &label, int category = Field::All, const QString &key = QString::null, const QString &app = QString::null ); /** Add address book resource. */ bool addResource( Resource * ); /** Remove address book resource. */ bool removeResource( Resource * ); /** Return pointer list of all resources. */ QPtrList<Resource> resources(); /** Set the @p ErrorHandler, that is used by @ref error() to provide gui-independend error messages. */ void setErrorHandler( ErrorHandler * ); /** Shows gui independend error messages. */ void error( const QString& ); /** Query all resources to clean up their lock files */ void cleanUp(); // sync stuff //Addressee::List getExternLastSyncAddressees(); void resetTempSyncStat(); QStringList uidList(); void removeSyncAddressees( bool removeDeleted = false ); void mergeAB( AddressBook *aBook, const QString& profile ); Addressee findByExternUid( const QString& uid , const QString& profile ); bool containsExternalUid( const QString& uid ); void preExternSync( AddressBook* aBook, const QString& csd ); void postExternSync( AddressBook* aBook, const QString& csd ); signals: /** Emitted, when the address book has changed on disk. */ void addressBookChanged( AddressBook * ); /** Emitted, when the address book has been locked for writing. */ void addressBookLocked( AddressBook * ); /** Emitted, when the address book has been unlocked. */ void addressBookUnlocked( AddressBook * ); protected: void deleteRemovedAddressees(); void setStandardResource( Resource * ); Resource *standardResource(); KRES::Manager<Resource> *resourceManager(); void init(const QString &config, const QString &family); private: //US QPtrList<Resource> mDummy; // Remove in KDE 4 struct AddressBookData; AddressBookData *d; bool blockLSEchange; }; QDataStream &operator<<( QDataStream &, const AddressBook & ); QDataStream &operator>>( QDataStream &, AddressBook & ); } #endif diff --git a/kabc/addressee.cpp b/kabc/addressee.cpp index 607ae26..548305a 100644 --- a/kabc/addressee.cpp +++ b/kabc/addressee.cpp @@ -1,727 +1,767 @@ /*** Warning! This file has been generated by the script makeaddressee ***/ /* This file is part of libkabc. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Enhanced Version of the file for platform independent KDE tools. Copyright (c) 2004 Ulf Schenk $Id$ */ #include <kconfig.h> #include <ksharedptr.h> #include <kdebug.h> #include <kapplication.h> #include <klocale.h> #include <kidmanager.h> //US #include <kstandarddirs.h> #include <libkcal/syncdefines.h> //US #include "resource.h" #include "addressee.h" using namespace KABC; static bool matchBinaryPattern( int value, int pattern ); static bool matchBinaryPatternA( int value, int pattern ); static bool matchBinaryPatternP( int value, int pattern ); struct Addressee::AddresseeData : public KShared { QString uid; QString name; QString formattedName; QString familyName; QString givenName; QString additionalName; QString prefix; QString suffix; QString nickName; QDateTime birthday; QString mailer; TimeZone timeZone; Geo geo; QString title; QString role; QString organization; QString note; QString productId; QDateTime revision; QString sortString; QString externalUID; QString originalExternalUID; KURL url; Secrecy secrecy; Picture logo; Picture photo; Sound sound; Agent agent; QString mExternalId; PhoneNumber::List phoneNumbers; Address::List addresses; Key::List keys; QStringList emails; QStringList categories; QStringList custom; int mTempSyncStat; Resource *resource; bool empty :1; bool changed :1; bool tagged :1; }; Addressee::Addressee() { mData = new AddresseeData; mData->empty = true; mData->changed = false; mData->resource = 0; mData->mExternalId = ":"; mData->revision = QDateTime ( QDate( 2003,1,1)); mData->mTempSyncStat = SYNC_TEMPSTATE_INITIAL; } Addressee::~Addressee() { } Addressee::Addressee( const Addressee &a ) { mData = a.mData; } Addressee &Addressee::operator=( const Addressee &a ) { mData = a.mData; return (*this); } Addressee Addressee::copy() { Addressee a; *(a.mData) = *mData; return a; } void Addressee::detach() { if ( mData.count() == 1 ) return; *this = copy(); } bool Addressee::operator==( const Addressee &a ) const { if ( uid() != a.uid() ) return false; if ( mData->name != a.mData->name ) return false; if ( mData->formattedName != a.mData->formattedName ) return false; if ( mData->familyName != a.mData->familyName ) return false; if ( mData->givenName != a.mData->givenName ) return false; if ( mData->additionalName != a.mData->additionalName ) return false; if ( mData->prefix != a.mData->prefix ) return false; if ( mData->suffix != a.mData->suffix ) return false; if ( mData->nickName != a.mData->nickName ) return false; if ( mData->birthday != a.mData->birthday ) return false; if ( mData->mailer != a.mData->mailer ) return false; if ( mData->timeZone != a.mData->timeZone ) return false; if ( mData->geo != a.mData->geo ) return false; if ( mData->title != a.mData->title ) return false; if ( mData->role != a.mData->role ) return false; if ( mData->organization != a.mData->organization ) return false; if ( mData->note != a.mData->note ) return false; if ( mData->productId != a.mData->productId ) return false; //if ( mData->revision != a.mData->revision ) return false; if ( mData->sortString != a.mData->sortString ) return false; if ( mData->secrecy != a.mData->secrecy ) return false; if ( mData->logo != a.mData->logo ) return false; if ( mData->photo != a.mData->photo ) return false; if ( mData->sound != a.mData->sound ) return false; if ( mData->agent != a.mData->agent ) return false; if ( ( mData->url.isValid() || a.mData->url.isValid() ) && ( mData->url != a.mData->url ) ) return false; if ( mData->phoneNumbers != a.mData->phoneNumbers ) return false; if ( mData->addresses != a.mData->addresses ) return false; if ( mData->keys != a.mData->keys ) return false; if ( mData->emails != a.mData->emails ) return false; if ( mData->categories != a.mData->categories ) return false; if ( mData->custom != a.mData->custom ) return false; return true; } bool Addressee::operator!=( const Addressee &a ) const { return !( a == *this ); } bool Addressee::isEmpty() const { return mData->empty; } ulong Addressee::getCsum4List( const QStringList & attList) { int max = attList.count(); ulong cSum = 0; int j,k,i; int add; for ( i = 0; i < max ; ++i ) { QString s = attList[i]; if ( ! s.isEmpty() ){ j = s.length(); for ( k = 0; k < j; ++k ) { int mul = k +1; add = s[k].unicode (); if ( k < 16 ) mul = mul * mul; int ii = i+1; add = add * mul *ii*ii*ii; cSum += add; } } } //QString dump = attList.join(","); //qDebug("csum: %d %s", cSum,dump.latin1()); return cSum; } void Addressee::computeCsum(const QString &dev) { QStringList l; if ( !mData->name.isEmpty() ) l.append(mData->name); if ( !mData->formattedName.isEmpty() ) l.append(mData->formattedName ); if ( !mData->familyName.isEmpty() ) l.append( mData->familyName ); if ( !mData->givenName.isEmpty() ) l.append(mData->givenName ); if ( !mData->additionalName ) l.append( mData->additionalName ); if ( !mData->prefix.isEmpty() ) l.append( mData->prefix ); if ( !mData->suffix.isEmpty() ) l.append( mData->suffix ); if ( !mData->nickName.isEmpty() ) l.append( mData->nickName ); if ( mData->birthday.isValid() ) l.append( mData->birthday.toString() ); if ( !mData->mailer.isEmpty() ) l.append( mData->mailer ); if ( mData->timeZone.isValid() ) l.append( mData->timeZone.asString() ); if ( mData->geo.isValid() ) l.append( mData->geo.asString() ); if ( !mData->title .isEmpty() ) l.append( mData->title ); if ( !mData->role.isEmpty() ) l.append( mData->role ); if ( !mData->organization.isEmpty() ) l.append( mData->organization ); if ( !mData->note.isEmpty() ) l.append( mData->note ); if ( !mData->productId.isEmpty() ) l.append(mData->productId ); if ( !mData->sortString.isEmpty() ) l.append( mData->sortString ); if ( mData->secrecy.isValid() ) l.append( mData->secrecy.asString()); // if ( !mData->logo.isEmpty() ) l.append( ); //if ( !mData->photo.isEmpty() ) l.append( ); //if ( !mData->sound.isEmpty() ) l.append( ); //if ( !mData->agent.isEmpty() ) l.append( ); //if ( mData->url.isValid() ) l.append( ); #if 0 if ( !mData->phoneNumbers.isEmpty() ) l.append( ); if ( !mData->addresses.isEmpty() ) l.append( ); //if ( !mData->keys.isEmpty() ) l.append( ); if ( !mData->emails.isEmpty() ) l.append( ); if ( !mData->categories .isEmpty() ) l.append( ); if ( !mData->custom.isEmpty() ) l.append( ); #endif KABC::PhoneNumber::List phoneNumbers; KABC::PhoneNumber::List::Iterator phoneIter; QStringList t; for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end(); ++phoneIter ) t.append( ( *phoneIter ).number()+QString::number( ( *phoneIter ).type() ) ); t.sort(); uint iii; for ( iii = 0; iii < t.count(); ++iii) l.append( t[iii] ); t = mData->emails; t.sort(); for ( iii = 0; iii < t.count(); ++iii) l.append( t[iii] ); t = mData->categories; t.sort(); for ( iii = 0; iii < t.count(); ++iii) l.append( t[iii] ); t = mData->custom; t.sort(); for ( iii = 0; iii < t.count(); ++iii) l.append( t[iii] ); KABC::Address::List::Iterator addressIter; for ( addressIter = mData->addresses.begin(); addressIter != mData->addresses.end(); ++addressIter ) { t = (*addressIter).asList(); t.sort(); for ( iii = 0; iii < t.count(); ++iii) l.append( t[iii] ); } uint cs = getCsum4List(l); // qDebug("CSUM computed %d %s %s", cs,QString::number (cs ).latin1(), uid().latin1() ); setCsum( dev, QString::number (cs )); } void Addressee::mergeContact( const Addressee& ad ) { detach(); if ( mData->name.isEmpty() ) mData->name = ad.mData->name; if ( mData->formattedName.isEmpty() ) mData->formattedName = ad.mData->formattedName; if ( mData->familyName.isEmpty() ) mData->familyName = ad.mData->familyName; if ( mData->givenName.isEmpty() ) mData->givenName = ad.mData->givenName ; if ( mData->additionalName ) mData->additionalName = ad.mData->additionalName; if ( mData->prefix.isEmpty() ) mData->prefix = ad.mData->prefix; if ( mData->suffix.isEmpty() ) mData->suffix = ad.mData->suffix; if ( mData->nickName.isEmpty() ) mData->nickName = ad.mData->nickName; if ( !mData->birthday.isValid() ) if ( ad.mData->birthday.isValid()) mData->birthday = ad.mData->birthday; if ( mData->mailer.isEmpty() ) mData->mailer = ad.mData->mailer; if ( !mData->timeZone.isValid() ) mData->timeZone = ad.mData->timeZone; if ( !mData->geo.isValid() ) mData->geo = ad.mData->geo; if ( mData->title .isEmpty() ) mData->title = ad.mData->title ; if ( mData->role.isEmpty() ) mData->role = ad.mData->role ; if ( mData->organization.isEmpty() ) mData->organization = ad.mData->organization ; if ( mData->note.isEmpty() ) mData->note = ad.mData->note ; if ( mData->productId.isEmpty() ) mData->productId = ad.mData->productId; if ( mData->sortString.isEmpty() ) mData->sortString = ad.mData->sortString; if ( !mData->secrecy.isValid() ) mData->secrecy = ad.mData->secrecy; if ( ( !mData->url.isValid() && ad.mData->url.isValid() ) ) mData->url = ad.mData->url ; + PhoneNumber::List phoneAD = phoneNumbers(); + PhoneNumber::List::Iterator phoneItAD; + bool found = false; + for ( phoneItAD = phoneAD.begin(); phoneItAD != phoneAD.end(); ++phoneItAD ) { + + } // pending: // merging phonenumbers // merging addresses // merging emails; // merging categories; // merging custom; // merging keys - qDebug("merge contact %s ", ad.uid().latin1()); + //qDebug("merge contact %s ", ad.uid().latin1()); setUid( ad.uid() ); setRevision( ad.revision() ); } bool Addressee::removeVoice() { PhoneNumber::List phoneN = phoneNumbers(); PhoneNumber::List::Iterator phoneIt; bool found = false; for ( phoneIt = phoneN.begin(); phoneIt != phoneN.end(); ++phoneIt ) { if ( (*phoneIt).type() & PhoneNumber::Voice) { // voice found if ((*phoneIt).type() - PhoneNumber::Voice ) { (*phoneIt).setType((*phoneIt).type() - PhoneNumber::Voice ); insertPhoneNumber( (*phoneIt) ); found = true; } } } return found; } + +bool Addressee::containsAdr(const Addressee& ad ) +{ + if ( ! ad.mData->familyName.isEmpty() ) if ( mData->familyName != ad.mData->familyName) return false; + if ( ! ad.mData->givenName.isEmpty() )if ( mData->givenName != ad.mData->givenName ) return false; + if ( ad.mData->url.isValid() ) if (mData->url != ad.mData->url) return false ; + if ( ! ad.mData->role.isEmpty() ) if (mData->role != ad.mData->role) return false ; + if ( ! ad.mData->organization.isEmpty() ) if (mData->organization != ad.mData->organization) return false ; + if ( ! ad.mData->note.isEmpty() ) if (mData->note != ad.mData->note) return false ; + if ( ! ad.mData->title .isEmpty() ) if (mData->title != ad.mData->title ) return false ; + + // compare phone numbers + PhoneNumber::List phoneN = ad.phoneNumbers(); + PhoneNumber::List::Iterator phoneIt; + bool found = false; + for ( phoneIt = phoneN.begin(); phoneIt != phoneN.end(); ++phoneIt ) { + bool found = false; + PhoneNumber::List phoneL = ad.phoneNumbers(); + PhoneNumber::List::Iterator phoneItL; + for ( phoneItL = phoneL.begin(); phoneItL != phoneL.end(); ++phoneItL ) { + if ( ( *phoneItL ).number() == ( *phoneIt ).number() ) { + found = true; + break; + } + } + if ( ! found ) + return false; + } + return true; + +} void Addressee::simplifyAddresses() { - if ( mData->addresses.count() < 3 ) return ; + int max = 2; + if ( mData->url.isValid() ) + max = 1; + if ( mData->addresses.count() <= max ) return ; int count = 0; Address::List list; Address::List::Iterator it; for( it = mData->addresses.begin(); it != mData->addresses.end(); ++it ) { - if ( count > 1 ) + if ( count >= max ) list.append( *it ); ++count; } for( it = list.begin(); it != list.end(); ++it ) { removeAddress( (*it) ); } } // removes all emails but the first // needed by phone sync void Addressee::simplifyEmails() { if ( mData->emails.count() == 0 ) return ; QString email = mData->emails.first(); detach(); mData->emails.clear(); mData->emails.append( email ); } void Addressee::simplifyPhoneNumbers() { KABC::PhoneNumber::List removeNumbers; KABC::PhoneNumber::List::Iterator phoneIter; for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end(); ++phoneIter ) { if ( ! ( *phoneIter ).simplifyNumber() ) removeNumbers.append( ( *phoneIter ) ); } for ( phoneIter = removeNumbers.begin(); phoneIter != removeNumbers.end(); ++phoneIter ) { removePhoneNumber(( *phoneIter )); } } void Addressee::simplifyPhoneNumberTypes() { KABC::PhoneNumber::List::Iterator phoneIter; for ( phoneIter = mData->phoneNumbers.begin(); phoneIter != mData->phoneNumbers.end(); ++phoneIter ) ( *phoneIter ).simplifyType(); } void Addressee::removeID(const QString &prof) { detach(); mData->mExternalId = KIdManager::removeId ( mData->mExternalId, prof); } void Addressee::setID( const QString & prof , const QString & id ) { detach(); mData->mExternalId = KIdManager::setId ( mData->mExternalId, prof, id ); //qDebug("setID2 %s %s %s",mData->mExternalId.latin1(), prof.latin1(), id.latin1() ); } void Addressee::setTempSyncStat( int id ) { if ( mData->mTempSyncStat == id ) return; detach(); mData->mTempSyncStat = id; } int Addressee::tempSyncStat() const { return mData->mTempSyncStat; } QString Addressee::getID( const QString & prof) { return KIdManager::getId ( mData->mExternalId, prof ); } void Addressee::setCsum( const QString & prof , const QString & id ) { detach(); //qDebug("setcsum1 %s %s %s",mData->mExternalId.latin1(), prof.latin1(), id.latin1() ); mData->mExternalId = KIdManager::setCsum ( mData->mExternalId, prof, id ); //qDebug("setcsum2 %s ",mData->mExternalId.latin1() ); } QString Addressee::getCsum( const QString & prof) { return KIdManager::getCsum ( mData->mExternalId, prof ); } void Addressee::setIDStr( const QString & s ) { detach(); mData->mExternalId = s; } QString Addressee::IDStr() const { return mData->mExternalId; } void Addressee::setExternalUID( const QString &id ) { if ( id == mData->externalUID ) return; detach(); mData->empty = false; mData->externalUID = id; } QString Addressee::externalUID() const { return mData->externalUID; } void Addressee::setOriginalExternalUID( const QString &id ) { if ( id == mData->originalExternalUID ) return; detach(); mData->empty = false; //qDebug("*******Set orig uid %s ", id.latin1()); mData->originalExternalUID = id; } QString Addressee::originalExternalUID() const { return mData->originalExternalUID; } void Addressee::setUid( const QString &id ) { if ( id == mData->uid ) return; detach(); //qDebug("****setuid %s ", id.latin1()); mData->empty = false; mData->uid = id; } QString Addressee::uid() const { if ( mData->uid.isEmpty() ) mData->uid = KApplication::randomString( 10 ); return mData->uid; } QString Addressee::uidLabel() { return i18n("Unique Identifier"); } void Addressee::setName( const QString &name ) { if ( name == mData->name ) return; detach(); mData->empty = false; mData->name = name; } QString Addressee::name() const { return mData->name; } QString Addressee::nameLabel() { return i18n("Name"); } void Addressee::setFormattedName( const QString &formattedName ) { if ( formattedName == mData->formattedName ) return; detach(); mData->empty = false; mData->formattedName = formattedName; } QString Addressee::formattedName() const { return mData->formattedName; } QString Addressee::formattedNameLabel() { return i18n("Formatted Name"); } void Addressee::setFamilyName( const QString &familyName ) { if ( familyName == mData->familyName ) return; detach(); mData->empty = false; mData->familyName = familyName; } QString Addressee::familyName() const { return mData->familyName; } QString Addressee::familyNameLabel() { return i18n("Family Name"); } void Addressee::setGivenName( const QString &givenName ) { if ( givenName == mData->givenName ) return; detach(); mData->empty = false; mData->givenName = givenName; } QString Addressee::givenName() const { return mData->givenName; } QString Addressee::givenNameLabel() { return i18n("Given Name"); } void Addressee::setAdditionalName( const QString &additionalName ) { if ( additionalName == mData->additionalName ) return; detach(); mData->empty = false; mData->additionalName = additionalName; } QString Addressee::additionalName() const { return mData->additionalName; } QString Addressee::additionalNameLabel() { return i18n("Additional Names"); } void Addressee::setPrefix( const QString &prefix ) { if ( prefix == mData->prefix ) return; detach(); mData->empty = false; mData->prefix = prefix; } QString Addressee::prefix() const { return mData->prefix; } QString Addressee::prefixLabel() { return i18n("Honorific Prefixes"); } void Addressee::setSuffix( const QString &suffix ) { if ( suffix == mData->suffix ) return; detach(); mData->empty = false; mData->suffix = suffix; } QString Addressee::suffix() const { return mData->suffix; } QString Addressee::suffixLabel() { return i18n("Honorific Suffixes"); } void Addressee::setNickName( const QString &nickName ) { if ( nickName == mData->nickName ) return; detach(); mData->empty = false; mData->nickName = nickName; } QString Addressee::nickName() const { return mData->nickName; } QString Addressee::nickNameLabel() { return i18n("Nick Name"); } void Addressee::setBirthday( const QDateTime &birthday ) { if ( birthday == mData->birthday ) return; detach(); mData->empty = false; mData->birthday = birthday; } QDateTime Addressee::birthday() const { return mData->birthday; } QString Addressee::birthdayLabel() { return i18n("Birthday"); } QString Addressee::homeAddressStreetLabel() { return i18n("Home Address Street"); } QString Addressee::homeAddressLocalityLabel() { return i18n("Home Address Locality"); } QString Addressee::homeAddressRegionLabel() { return i18n("Home Address Region"); } QString Addressee::homeAddressPostalCodeLabel() { return i18n("Home Address Postal Code"); } QString Addressee::homeAddressCountryLabel() { return i18n("Home Address Country"); } QString Addressee::homeAddressLabelLabel() { return i18n("Home Address Label"); } QString Addressee::businessAddressStreetLabel() { return i18n("Business Address Street"); } QString Addressee::businessAddressLocalityLabel() { return i18n("Business Address Locality"); } QString Addressee::businessAddressRegionLabel() { return i18n("Business Address Region"); } QString Addressee::businessAddressPostalCodeLabel() { return i18n("Business Address Postal Code"); } QString Addressee::businessAddressCountryLabel() { return i18n("Business Address Country"); } QString Addressee::businessAddressLabelLabel() { return i18n("Business Address Label"); } QString Addressee::homePhoneLabel() diff --git a/kabc/addressee.h b/kabc/addressee.h index 0aa2c51..03138f6 100644 --- a/kabc/addressee.h +++ b/kabc/addressee.h @@ -1,508 +1,509 @@ /*** Warning! This file has been generated by the script makeaddressee ***/ /* This file is part of libkabc. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Enhanced Version of the file for platform independent KDE tools. Copyright (c) 2004 Ulf Schenk $Id$ */ #ifndef KABC_ADDRESSEE_H #define KABC_ADDRESSEE_H #include <qdatetime.h> #include <qstring.h> #include <qstringlist.h> #include <qvaluelist.h> #include <ksharedptr.h> #include <kurl.h> #include "address.h" #include "agent.h" #include "geo.h" #include "key.h" #include "phonenumber.h" #include "picture.h" #include "secrecy.h" #include "sound.h" #include "timezone.h" namespace KABC { class Resource; /** @short address book entry This class represents an entry in the address book. The data of this class is implicitly shared. You can pass this class by value. If you need the name of a field for presenting it to the user you should use the functions ending in Label(). They return a translated string which can be used as label for the corresponding field. About the name fields: givenName() is the first name and familyName() the last name. In some countries the family name comes first, that's the reason for the naming. formattedName() is the full name with the correct formatting. It is used as an override, when the correct formatting can't be generated from the other name fields automatically. realName() returns a fully formatted name(). It uses formattedName, if set, otherwise it constucts the name from the name fields. As fallback, if nothing else is set it uses name(). name() is the NAME type of RFC2426. It can be used as internal name for the data enty, but shouldn't be used for displaying the data to the user. */ class Addressee { friend QDataStream &operator<<( QDataStream &, const Addressee & ); friend QDataStream &operator>>( QDataStream &, Addressee & ); public: typedef QValueList<Addressee> List; /** Construct an empty address book entry. */ Addressee(); ~Addressee(); Addressee( const Addressee & ); Addressee &operator=( const Addressee & ); bool operator==( const Addressee & ) const; bool operator!=( const Addressee & ) const; // sync stuff void setTempSyncStat(int id); int tempSyncStat() const; void setIDStr( const QString & ); QString IDStr() const; void setID( const QString &, const QString & ); QString getID( const QString & ); void setCsum( const QString &, const QString & ); QString getCsum( const QString & ); void removeID(const QString &); void computeCsum(const QString &dev); ulong getCsum4List( const QStringList & attList); /** Return, if the address book entry is empty. */ bool isEmpty() const; void setExternalUID( const QString &id ); QString externalUID() const; void setOriginalExternalUID( const QString &id ); QString originalExternalUID() const; void mergeContact( const Addressee& ad ); void simplifyEmails(); void simplifyAddresses(); void simplifyPhoneNumbers(); void simplifyPhoneNumberTypes(); bool removeVoice(); + bool containsAdr(const Addressee& addr ); /** Set unique identifier. */ void setUid( const QString &uid ); /** Return unique identifier. */ QString uid() const; /** Return translated label for uid field. */ static QString uidLabel(); /** Set name. */ void setName( const QString &name ); /** Return name. */ QString name() const; /** Return translated label for name field. */ static QString nameLabel(); /** Set formatted name. */ void setFormattedName( const QString &formattedName ); /** Return formatted name. */ QString formattedName() const; /** Return translated label for formattedName field. */ static QString formattedNameLabel(); /** Set family name. */ void setFamilyName( const QString &familyName ); /** Return family name. */ QString familyName() const; /** Return translated label for familyName field. */ static QString familyNameLabel(); /** Set given name. */ void setGivenName( const QString &givenName ); /** Return given name. */ QString givenName() const; /** Return translated label for givenName field. */ static QString givenNameLabel(); /** Set additional names. */ void setAdditionalName( const QString &additionalName ); /** Return additional names. */ QString additionalName() const; /** Return translated label for additionalName field. */ static QString additionalNameLabel(); /** Set honorific prefixes. */ void setPrefix( const QString &prefix ); /** Return honorific prefixes. */ QString prefix() const; /** Return translated label for prefix field. */ static QString prefixLabel(); /** Set honorific suffixes. */ void setSuffix( const QString &suffix ); /** Return honorific suffixes. */ QString suffix() const; /** Return translated label for suffix field. */ static QString suffixLabel(); /** Set nick name. */ void setNickName( const QString &nickName ); /** Return nick name. */ QString nickName() const; /** Return translated label for nickName field. */ static QString nickNameLabel(); /** Set birthday. */ void setBirthday( const QDateTime &birthday ); /** Return birthday. */ QDateTime birthday() const; /** Return translated label for birthday field. */ static QString birthdayLabel(); /** Return translated label for homeAddressStreet field. */ static QString homeAddressStreetLabel(); /** Return translated label for homeAddressLocality field. */ static QString homeAddressLocalityLabel(); /** Return translated label for homeAddressRegion field. */ static QString homeAddressRegionLabel(); /** Return translated label for homeAddressPostalCode field. */ static QString homeAddressPostalCodeLabel(); /** Return translated label for homeAddressCountry field. */ static QString homeAddressCountryLabel(); /** Return translated label for homeAddressLabel field. */ static QString homeAddressLabelLabel(); /** Return translated label for businessAddressStreet field. */ static QString businessAddressStreetLabel(); /** Return translated label for businessAddressLocality field. */ static QString businessAddressLocalityLabel(); /** Return translated label for businessAddressRegion field. */ static QString businessAddressRegionLabel(); /** Return translated label for businessAddressPostalCode field. */ static QString businessAddressPostalCodeLabel(); /** Return translated label for businessAddressCountry field. */ static QString businessAddressCountryLabel(); /** Return translated label for businessAddressLabel field. */ static QString businessAddressLabelLabel(); /** Return translated label for homePhone field. */ static QString homePhoneLabel(); /** Return translated label for businessPhone field. */ static QString businessPhoneLabel(); /** Return translated label for mobilePhone field. */ static QString mobilePhoneLabel(); /** Return translated label for homeFax field. */ static QString homeFaxLabel(); /** Return translated label for businessFax field. */ static QString businessFaxLabel(); /** Return translated label for carPhone field. */ static QString carPhoneLabel(); /** Return translated label for isdn field. */ static QString isdnLabel(); /** Return translated label for pager field. */ static QString pagerLabel(); /** Return translated label for sip field. */ static QString sipLabel(); /** Return translated label for email field. */ static QString emailLabel(); /** Set mail client. */ void setMailer( const QString &mailer ); /** Return mail client. */ QString mailer() const; /** Return translated label for mailer field. */ static QString mailerLabel(); /** Set time zone. */ void setTimeZone( const TimeZone &timeZone ); /** Return time zone. */ TimeZone timeZone() const; /** Return translated label for timeZone field. */ static QString timeZoneLabel(); /** Set geographic position. */ void setGeo( const Geo &geo ); /** Return geographic position. */ Geo geo() const; /** Return translated label for geo field. */ static QString geoLabel(); /** Set title. */ void setTitle( const QString &title ); /** Return title. */ QString title() const; /** Return translated label for title field. */ static QString titleLabel(); /** Set role. */ void setRole( const QString &role ); /** Return role. */ QString role() const; /** Return translated label for role field. */ static QString roleLabel(); /** Set organization. */ void setOrganization( const QString &organization ); /** Return organization. */ QString organization() const; /** Return translated label for organization field. */ static QString organizationLabel(); /** Set note. */ void setNote( const QString ¬e ); /** Return note. */ QString note() const; /** Return translated label for note field. */ static QString noteLabel(); /** Set product identifier. */ void setProductId( const QString &productId ); /** Return product identifier. */ QString productId() const; /** Return translated label for productId field. */ static QString productIdLabel(); /** Set revision date. */ void setRevision( const QDateTime &revision ); /** Return revision date. */ QDateTime revision() const; /** Return translated label for revision field. */ static QString revisionLabel(); /** Set sort string. */ void setSortString( const QString &sortString ); /** Return sort string. */ QString sortString() const; /** Return translated label for sortString field. */ static QString sortStringLabel(); /** Set URL. */ void setUrl( const KURL &url ); /** Return URL. */ KURL url() const; /** Return translated label for url field. */ static QString urlLabel(); diff --git a/kabc/phonenumber.cpp b/kabc/phonenumber.cpp index e5abc0e..6e94c7e 100644 --- a/kabc/phonenumber.cpp +++ b/kabc/phonenumber.cpp @@ -1,225 +1,223 @@ /* This file is part of libkabc. Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Enhanced Version of the file for platform independent KDE tools. Copyright (c) 2004 Ulf Schenk $Id$ */ #include <kapplication.h> #include <klocale.h> #include "phonenumber.h" using namespace KABC; PhoneNumber::PhoneNumber() : mType( Home ) { init(); } PhoneNumber::PhoneNumber( const QString &number, int type ) : mType( type ), mNumber( number ) { init(); } PhoneNumber::~PhoneNumber() { } void PhoneNumber::init() { mId = KApplication::randomString( 8 ); } bool PhoneNumber::operator==( const PhoneNumber &p ) const { if ( mNumber != p.mNumber ) return false; if ( mType != p.mType ) return false; return true; } bool PhoneNumber::operator!=( const PhoneNumber &p ) const { return !( p == *this ); } bool PhoneNumber::simplifyNumber() { QString Number; int i; Number = mNumber.stripWhiteSpace (); mNumber = ""; - if ( Number.at(0) == '+' ) - mNumber += "+"; for ( i = 0; i < Number.length(); ++i) { - if ( Number.at(i).isDigit() ) + if ( Number.at(i).isDigit() || Number.at(i) == '+'|| Number.at(i) == '*'|| Number.at(i) == '#' ) mNumber += Number.at(i); } return ( mNumber.length() > 0 ); } // make cellphone compatible void PhoneNumber::simplifyType() { if ( mType & Fax ) mType = Fax; else if ( mType & Cell ) mType = Cell; else if ( mType & Work ) mType = Work ; else if ( mType & Home ) mType = Home; else mType = Pref; } void PhoneNumber::setId( const QString &id ) { mId = id; } QString PhoneNumber::id() const { return mId; } void PhoneNumber::setNumber( const QString &number ) { mNumber = number; } QString PhoneNumber::number() const { return mNumber; } void PhoneNumber::setType( int type ) { mType = type; } int PhoneNumber::type() const { return mType; } QString PhoneNumber::typeLabel() const { QString label; bool first = true; TypeList list = typeList(); TypeList::Iterator it; for ( it = list.begin(); it != list.end(); ++it ) { if ( ( type() & (*it) ) && ( (*it) != Pref ) ) { label.append( ( first ? "" : "/" ) + typeLabel( *it ) ); if ( first ) first = false; } } return label; } QString PhoneNumber::label() const { return typeLabel( type() ); } PhoneNumber::TypeList PhoneNumber::typeList() { TypeList list; list << Home << Work << Msg << Pref << Voice << Fax << Cell << Video << Bbs << Modem << Car << Isdn << Pcs << Pager << Sip; return list; } QString PhoneNumber::label( int type ) { return typeLabel( type ); } QString PhoneNumber::typeLabel( int type ) { QString typeString; if ((type & Home) == Home) typeString += i18n("Home"); else if ((type & Work) == Work) typeString += i18n("Work"); if (!typeString.isEmpty()) typeString += " "; if ((type & Cell) == Cell) typeString += i18n("Mobile"); else if ((type & Fax) == Fax) typeString += i18n("Fax"); else if ((type & Msg) == Msg) typeString += i18n("Messenger"); else if ((type & Voice) == Voice) { // add nothing in case of the Voice flag // typeString += i18n("Voice"); } else if ((type & Video) == Video) typeString += i18n("Video"); else if ((type & Bbs) == Bbs) typeString += i18n("Mailbox"); else if ((type & Modem) == Modem) typeString += i18n("Modem"); else if ((type & Car) == Car) typeString += i18n("Car"); else if ((type & Isdn) == Isdn) typeString += i18n("ISDN"); else if ((type & Pcs) == Pcs) typeString += i18n("PCS"); else if ((type & Pager) == Pager) typeString += i18n("Pager"); else if ((type & Sip) == Sip) typeString += i18n("SIP"); // add the prefered flag if (!typeString.isEmpty()) typeString += " "; if ((type & Pref) == Pref) typeString += i18n("(p)"); //if we still have no match, return "other" if (typeString.isEmpty()) return i18n("Other"); return typeString; } QDataStream &KABC::operator<<( QDataStream &s, const PhoneNumber &phone ) { return s << phone.mId << phone.mType << phone.mNumber; } QDataStream &KABC::operator>>( QDataStream &s, PhoneNumber &phone ) { s >> phone.mId >> phone.mType >> phone.mNumber; return s; } diff --git a/kaddressbook/kabcore.cpp b/kaddressbook/kabcore.cpp index a7967cb..cd261f6 100644 --- a/kaddressbook/kabcore.cpp +++ b/kaddressbook/kabcore.cpp @@ -1,1148 +1,1093 @@ /* This file is part of KAddressbook. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ /*s Enhanced Version of the file for platform independent KDE tools. Copyright (c) 2004 Ulf Schenk $Id$ */ #include "kabcore.h" #include <stdaddressbook.h> #include <klocale.h> #include <kfiledialog.h> #include <qtimer.h> #include <qlabel.h> #include <qregexp.h> #include <qlineedit.h> #include <qcheckbox.h> #include <qpushbutton.h> #include <qprogressbar.h> #include <libkdepim/phoneaccess.h> #ifndef KAB_EMBEDDED #include <qclipboard.h> #include <qdir.h> #include <qfile.h> #include <qapplicaton.h> #include <qprogressbar.h> #include <qlayout.h> #include <qregexp.h> #include <qvbox.h> #include <kabc/addresseelist.h> #include <kabc/errorhandler.h> #include <kabc/resource.h> #include <kabc/vcardconverter.h> #include <kapplication.h> #include <kactionclasses.h> #include <kcmultidialog.h> #include <kdebug.h> #include <kdeversion.h> #include <kkeydialog.h> #include <kmessagebox.h> #include <kprinter.h> #include <kprotocolinfo.h> #include <kresources/selectdialog.h> #include <kstandarddirs.h> #include <ktempfile.h> #include <kxmlguiclient.h> #include <kaboutdata.h> #include <libkdepim/categoryselectdialog.h> #include "addresseeutil.h" #include "addresseeeditordialog.h" #include "extensionmanager.h" #include "kstdaction.h" #include "kaddressbookservice.h" #include "ldapsearchdialog.h" #include "printing/printingwizard.h" #else // KAB_EMBEDDED #include <kapplication.h> #include "KDGanttMinimizeSplitter.h" #include "kaddressbookmain.h" #include "kactioncollection.h" #include "addresseedialog.h" //US #include <addresseeview.h> #include <qapp.h> #include <qmenubar.h> //#include <qtoolbar.h> #include <qmessagebox.h> #include <kdebug.h> #include <kiconloader.h> // needed for SmallIcon #include <kresources/kcmkresources.h> #include <ktoolbar.h> //#include <qlabel.h> #ifndef DESKTOP_VERSION #include <qpe/ir.h> #include <qpe/qpemenubar.h> #include <qtopia/qcopenvelope_qws.h> #else #include <qmenubar.h> #endif #endif // KAB_EMBEDDED #include "kcmconfigs/kcmkabconfig.h" #include "kcmconfigs/kcmkdepimconfig.h" #include "kpimglobalprefs.h" #include "externalapphandler.h" #include <kresources/selectdialog.h> #include <kmessagebox.h> #include <picture.h> #include <resource.h> //US#include <qsplitter.h> #include <qmap.h> #include <qdir.h> #include <qfile.h> #include <qvbox.h> #include <qlayout.h> #include <qclipboard.h> #include <qtextstream.h> #include <libkdepim/categoryselectdialog.h> #include <kabc/vcardconverter.h> #include "addresseeutil.h" #include "undocmds.h" #include "addresseeeditordialog.h" #include "viewmanager.h" #include "details/detailsviewcontainer.h" #include "kabprefs.h" #include "xxportmanager.h" #include "incsearchwidget.h" #include "jumpbuttonbar.h" #include "extensionmanager.h" #include "addresseeconfig.h" #include <kcmultidialog.h> #ifdef _WIN32_ #include "kaimportoldialog.h" #else #include <unistd.h> #endif // sync includes #include <libkdepim/ksyncprofile.h> #include <libkdepim/ksyncprefsdialog.h> class KAex2phonePrefs : public QDialog { public: KAex2phonePrefs( QWidget *parent=0, const char *name=0 ) : QDialog( parent, name, true ) { setCaption( i18n("Export to phone options") ); QVBoxLayout* lay = new QVBoxLayout( this ); lay->setSpacing( 3 ); lay->setMargin( 3 ); QLabel *lab; lay->addWidget(lab = new QLabel( i18n("Please read Help-Sync Howto\nto know what settings to use."), this ) ); lab->setAlignment (AlignHCenter ); QHBox* temphb; temphb = new QHBox( this ); new QLabel( i18n("I/O device: "), temphb ); mPhoneDevice = new QLineEdit( temphb); lay->addWidget( temphb ); temphb = new QHBox( this ); new QLabel( i18n("Connection: "), temphb ); mPhoneConnection = new QLineEdit( temphb); lay->addWidget( temphb ); temphb = new QHBox( this ); new QLabel( i18n("Model(opt.): "), temphb ); mPhoneModel = new QLineEdit( temphb); lay->addWidget( temphb ); - mWriteToSim= new QCheckBox( i18n("Write Contacts to SIM card\n(if not, write to phone memory)"), this ); - lay->addWidget( mWriteToSim ); + // mWriteToSim = new QCheckBox( i18n("Write Contacts to SIM card\n(if not, write to phone memory)"), this ); + // lay->addWidget( mWriteToSim ); lay->addWidget(lab = new QLabel( i18n("NOTE: This will remove all old\ncontact data on phone!"), this ) ); lab->setAlignment (AlignHCenter ); QPushButton * ok = new QPushButton( i18n("Export to mobile phone!"), this ); lay->addWidget( ok ); QPushButton * cancel = new QPushButton( i18n("Cancel"), this ); lay->addWidget( cancel ); connect ( ok,SIGNAL(clicked() ),this , SLOT ( accept() ) ); connect (cancel, SIGNAL(clicked() ), this, SLOT ( reject()) ); resize( 220, 240 ); } public: QLineEdit* mPhoneConnection, *mPhoneDevice, *mPhoneModel; QCheckBox* mWriteToSim; }; bool pasteWithNewUid = true; #ifdef KAB_EMBEDDED KABCore::KABCore( KAddressBookMain *client, bool readWrite, QWidget *parent, const char *name ) : QWidget( parent, name ), KSyncInterface(), mGUIClient( client ), mViewManager( 0 ), mExtensionManager( 0 ),mConfigureDialog( 0 ),/*US mLdapSearchDialog( 0 ),*/ mReadWrite( readWrite ), mModified( false ), mMainWindow(client) #else //KAB_EMBEDDED KABCore::KABCore( KXMLGUIClient *client, bool readWrite, QWidget *parent, const char *name ) : QWidget( parent, name ), KSyncInterface(), mGUIClient( client ), mViewManager( 0 ), mExtensionManager( 0 ), mConfigureDialog( 0 ), mLdapSearchDialog( 0 ), mReadWrite( readWrite ), mModified( false ) #endif //KAB_EMBEDDED { // syncManager = new KSyncManager((QWidget*)this, (KSyncInterface*)this, KSyncManager::KAPI, KABPrefs::instance(), syncMenu); // syncManager->setBlockSave(false); mExtensionBarSplitter = 0; mIsPart = !parent->inherits( "KAddressBookMain" ); mAddressBook = KABC::StdAddressBook::self(); KABC::StdAddressBook::setAutomaticSave( false ); #ifndef KAB_EMBEDDED mAddressBook->setErrorHandler( new KABC::GUIErrorHandler ); #endif //KAB_EMBEDDED connect( mAddressBook, SIGNAL( addressBookChanged( AddressBook * ) ), SLOT( addressBookChanged() ) ); #if 0 // LP moved to addressbook init method mAddressBook->addCustomField( i18n( "Department" ), KABC::Field::Organization, "X-Department", "KADDRESSBOOK" ); mAddressBook->addCustomField( i18n( "Profession" ), KABC::Field::Organization, "X-Profession", "KADDRESSBOOK" ); mAddressBook->addCustomField( i18n( "Assistant's Name" ), KABC::Field::Organization, "X-AssistantsName", "KADDRESSBOOK" ); mAddressBook->addCustomField( i18n( "Manager's Name" ), KABC::Field::Organization, "X-ManagersName", "KADDRESSBOOK" ); mAddressBook->addCustomField( i18n( "Spouse's Name" ), KABC::Field::Personal, "X-SpousesName", "KADDRESSBOOK" ); mAddressBook->addCustomField( i18n( "Office" ), KABC::Field::Personal, "X-Office", "KADDRESSBOOK" ); mAddressBook->addCustomField( i18n( "IM Address" ), KABC::Field::Personal, "X-IMAddress", "KADDRESSBOOK" ); mAddressBook->addCustomField( i18n( "Anniversary" ), KABC::Field::Personal, "X-Anniversary", "KADDRESSBOOK" ); //US added this field to become compatible with Opie/qtopia addressbook // values can be "female" or "male" or "". An empty field represents undefined. mAddressBook->addCustomField( i18n( "Gender" ), KABC::Field::Personal, "X-Gender", "KADDRESSBOOK" ); mAddressBook->addCustomField( i18n( "Children" ), KABC::Field::Personal, "X-Children", "KADDRESSBOOK" ); mAddressBook->addCustomField( i18n( "FreeBusyUrl" ), KABC::Field::Personal, "X-FreeBusyUrl", "KADDRESSBOOK" ); #endif initGUI(); mIncSearchWidget->setFocus(); connect( mViewManager, SIGNAL( selected( const QString& ) ), SLOT( setContactSelected( const QString& ) ) ); connect( mViewManager, SIGNAL( executed( const QString& ) ), SLOT( executeContact( const QString& ) ) ); connect( mViewManager, SIGNAL( deleteRequest( ) ), SLOT( deleteContacts( ) ) ); connect( mViewManager, SIGNAL( modified() ), SLOT( setModified() ) ); connect( mExtensionManager, SIGNAL( modified( const KABC::Addressee::List& ) ), this, SLOT( extensionModified( const KABC::Addressee::List& ) ) ); connect( mExtensionManager, SIGNAL( changedActiveExtension( int ) ), this, SLOT( extensionChanged( int ) ) ); connect( mXXPortManager, SIGNAL( modified() ), SLOT( setModified() ) ); connect( mJumpButtonBar, SIGNAL( jumpToLetter( const QString& ) ), SLOT( incrementalSearch( const QString& ) ) ); connect( mIncSearchWidget, SIGNAL( fieldChanged() ), mJumpButtonBar, SLOT( recreateButtons() ) ); connect( mDetails, SIGNAL( sendEmail( const QString& ) ), SLOT( sendMail( const QString& ) ) ); connect( ExternalAppHandler::instance(), SIGNAL (requestForNameEmailUidList(const QString&, const QString&)),this, SLOT(requestForNameEmailUidList(const QString&, const QString&))); connect( ExternalAppHandler::instance(), SIGNAL (requestForDetails(const QString&, const QString&, const QString&, const QString&, const QString&)),this, SLOT(requestForDetails(const QString&, const QString&, const QString&, const QString&, const QString&))); connect( ExternalAppHandler::instance(), SIGNAL (requestForBirthdayList(const QString&, const QString&)),this, SLOT(requestForBirthdayList(const QString&, const QString&))); #ifndef KAB_EMBEDDED connect( mViewManager, SIGNAL( urlDropped( const KURL& ) ), mXXPortManager, SLOT( importVCard( const KURL& ) ) ); connect( mDetails, SIGNAL( browse( const QString& ) ), SLOT( browse( const QString& ) ) ); mAddressBookService = new KAddressBookService( this ); #endif //KAB_EMBEDDED mEditorDialog = 0; createAddresseeEditorDialog( this ); setModified( false ); } KABCore::~KABCore() { // save(); //saveSettings(); //KABPrefs::instance()->writeConfig(); delete AddresseeConfig::instance(); mAddressBook = 0; KABC::StdAddressBook::close(); delete syncManager; } void KABCore::recieve( QString fn ) { //qDebug("KABCore::recieve "); mAddressBook->importFromFile( fn, true ); mViewManager->refreshView(); topLevelWidget()->raise(); } void KABCore::restoreSettings() { mMultipleViewsAtOnce = KABPrefs::instance()->mMultipleViewsAtOnce; bool state; if (mMultipleViewsAtOnce) state = KABPrefs::instance()->mDetailsPageVisible; else state = false; mActionDetails->setChecked( state ); setDetailsVisible( state ); state = KABPrefs::instance()->mJumpButtonBarVisible; mActionJumpBar->setChecked( state ); setJumpButtonBarVisible( state ); /*US QValueList<int> splitterSize = KABPrefs::instance()->mDetailsSplitter; if ( splitterSize.count() == 0 ) { splitterSize.append( width() / 2 ); splitterSize.append( width() / 2 ); } mMiniSplitter->setSizes( splitterSize ); if ( mExtensionBarSplitter ) { splitterSize = KABPrefs::instance()->mExtensionsSplitter; if ( splitterSize.count() == 0 ) { splitterSize.append( width() / 2 ); splitterSize.append( width() / 2 ); } mExtensionBarSplitter->setSizes( splitterSize ); } */ mViewManager->restoreSettings(); mIncSearchWidget->setCurrentItem( KABPrefs::instance()->mCurrentIncSearchField ); mExtensionManager->restoreSettings(); #ifdef DESKTOP_VERSION int wid = width(); if ( wid < 10 ) wid = 400; #else int wid = QApplication::desktop()->width(); if ( wid < 640 ) wid = QApplication::desktop()->height(); #endif QValueList<int> splitterSize;// = KABPrefs::instance()->mDetailsSplitter; if ( true /*splitterSize.count() == 0*/ ) { splitterSize.append( wid / 2 ); splitterSize.append( wid / 2 ); } mMiniSplitter->setSizes( splitterSize ); if ( mExtensionBarSplitter ) { //splitterSize = KABPrefs::instance()->mExtensionsSplitter; if ( true /*splitterSize.count() == 0*/ ) { splitterSize.append( wid / 2 ); splitterSize.append( wid / 2 ); } mExtensionBarSplitter->setSizes( splitterSize ); } } void KABCore::saveSettings() { KABPrefs::instance()->mJumpButtonBarVisible = mActionJumpBar->isChecked(); if ( mExtensionBarSplitter ) KABPrefs::instance()->mExtensionsSplitter = mExtensionBarSplitter->sizes(); KABPrefs::instance()->mDetailsPageVisible = mActionDetails->isChecked(); KABPrefs::instance()->mDetailsSplitter = mMiniSplitter->sizes(); #ifndef KAB_EMBEDDED KABPrefs::instance()->mExtensionsSplitter = mExtensionBarSplitter->sizes(); KABPrefs::instance()->mDetailsSplitter = mDetailsSplitter->sizes(); #endif //KAB_EMBEDDED mExtensionManager->saveSettings(); mViewManager->saveSettings(); KABPrefs::instance()->mCurrentIncSearchField = mIncSearchWidget->currentItem(); } KABC::AddressBook *KABCore::addressBook() const { return mAddressBook; } KConfig *KABCore::config() { #ifndef KAB_EMBEDDED return KABPrefs::instance()->config(); #else //KAB_EMBEDDED return KABPrefs::instance()->getConfig(); #endif //KAB_EMBEDDED } KActionCollection *KABCore::actionCollection() const { return mGUIClient->actionCollection(); } KABC::Field *KABCore::currentSearchField() const { if (mIncSearchWidget) return mIncSearchWidget->currentField(); else return 0; } QStringList KABCore::selectedUIDs() const { return mViewManager->selectedUids(); } KABC::Resource *KABCore::requestResource( QWidget *parent ) { QPtrList<KABC::Resource> kabcResources = addressBook()->resources(); QPtrList<KRES::Resource> kresResources; QPtrListIterator<KABC::Resource> resIt( kabcResources ); KABC::Resource *resource; while ( ( resource = resIt.current() ) != 0 ) { ++resIt; if ( !resource->readOnly() ) { KRES::Resource *res = static_cast<KRES::Resource*>( resource ); if ( res ) kresResources.append( res ); } } KRES::Resource *res = KRES::SelectDialog::getResource( kresResources, parent ); return static_cast<KABC::Resource*>( res ); } #ifndef KAB_EMBEDDED KAboutData *KABCore::createAboutData() #else //KAB_EMBEDDED void KABCore::createAboutData() #endif //KAB_EMBEDDED { #ifndef KAB_EMBEDDED KAboutData *about = new KAboutData( "kaddressbook", I18N_NOOP( "KAddressBook" ), "3.1", I18N_NOOP( "The KDE Address Book" ), KAboutData::License_GPL_V2, I18N_NOOP( "(c) 1997-2003, The KDE PIM Team" ) ); about->addAuthor( "Tobias Koenig", I18N_NOOP( "Current maintainer " ), "tokoe@kde.org" ); about->addAuthor( "Don Sanders", I18N_NOOP( "Original author " ) ); about->addAuthor( "Cornelius Schumacher", I18N_NOOP( "Co-maintainer, libkabc port, CSV import/export " ), "schumacher@kde.org" ); about->addAuthor( "Mike Pilone", I18N_NOOP( "GUI and framework redesign " ), "mpilone@slac.com" ); about->addAuthor( "Greg Stern", I18N_NOOP( "DCOP interface" ) ); about->addAuthor( "Mark Westcott", I18N_NOOP( "Contact pinning" ) ); about->addAuthor( "Michel Boyer de la Giroday", I18N_NOOP( "LDAP Lookup\n" ), "michel@klaralvdalens-datakonsult.se" ); about->addAuthor( "Steffen Hansen", I18N_NOOP( "LDAP Lookup " ), "hansen@kde.org" ); return about; #endif //KAB_EMBEDDED QString version; #include <../version> QMessageBox::about( this, "About KAddressbook/Pi", "KAddressbook/Platform-independent\n" "(KA/Pi) " +version + " - " + #ifdef DESKTOP_VERSION "Desktop Edition\n" #else "PDA-Edition\n" "for: Zaurus 5500 / 7x0 / 8x0\n" #endif "(c) 2004 Ulf Schenk\n" "(c) 2004 Lutz Rogowski\n" "(c) 1997-2003, The KDE PIM Team\n" "Tobias Koenig Current maintainer\ntokoe@kde.org\n" "Don Sanders Original author\n" "Cornelius Schumacher Co-maintainer\nschumacher@kde.org\n" "Mike Pilone GUI and framework redesign\nmpilone@slac.com\n" "Greg Stern DCOP interface\n" "Mark Westcot Contact pinning\n" "Michel Boyer de la Giroday LDAP Lookup\n" "michel@klaralvdalens-datakonsult.se\n" "Steffen Hansen LDAP Lookup\nhansen@kde.org\n" #ifdef _WIN32_ "(c) 2004 Lutz Rogowski Import from OL\nrogowski@kde.org\n" #endif ); } void KABCore::setContactSelected( const QString &uid ) { KABC::Addressee addr = mAddressBook->findByUid( uid ); if ( !mDetails->isHidden() ) mDetails->setAddressee( addr ); if ( !addr.isEmpty() ) { emit contactSelected( addr.formattedName() ); KABC::Picture pic = addr.photo(); if ( pic.isIntern() ) { //US emit contactSelected( pic.data() ); //US instead use: QPixmap px; if (pic.data().isNull() != true) { px.convertFromImage(pic.data()); } emit contactSelected( px ); } } mExtensionManager->setSelectionChanged(); // update the actions bool selected = !uid.isEmpty(); if ( mReadWrite ) { mActionCut->setEnabled( selected ); mActionPaste->setEnabled( selected ); } mActionCopy->setEnabled( selected ); mActionDelete->setEnabled( selected ); mActionEditAddressee->setEnabled( selected ); mActionMail->setEnabled( selected ); mActionMailVCard->setEnabled( selected ); //if (mActionBeam) //mActionBeam->setEnabled( selected ); if (mActionBeamVCard) mActionBeamVCard->setEnabled( selected ); mActionExport2phone->setEnabled( selected ); mActionWhoAmI->setEnabled( selected ); mActionCategories->setEnabled( selected ); } void KABCore::sendMail() { sendMail( mViewManager->selectedEmails().join( ", " ) ); } void KABCore::sendMail( const QString& emaillist ) { // the parameter has the form "name1 <abc@aol.com>,name2 <abc@aol.com>;... " if (emaillist.contains(",") > 0) ExternalAppHandler::instance()->mailToMultipleContacts( emaillist, QString::null ); else ExternalAppHandler::instance()->mailToOneContact( emaillist ); } void KABCore::mailVCard() { QStringList uids = mViewManager->selectedUids(); if ( !uids.isEmpty() ) mailVCard( uids ); } void KABCore::mailVCard( const QStringList& uids ) { QStringList urls; // QString tmpdir = locateLocal("tmp", KGlobal::getAppName()); QString dirName = "/tmp/" + KApplication::randomString( 8 ); QDir().mkdir( dirName, true ); for( QStringList::ConstIterator it = uids.begin(); it != uids.end(); ++it ) { KABC::Addressee a = mAddressBook->findByUid( *it ); if ( a.isEmpty() ) continue; QString name = a.givenName() + "_" + a.familyName() + ".vcf"; QString fileName = dirName + "/" + name; QFile outFile(fileName); if ( outFile.open(IO_WriteOnly) ) { // file opened successfully KABC::VCardConverter converter; QString vcard; converter.addresseeToVCard( a, vcard ); QTextStream t( &outFile ); // use a text stream t.setEncoding( QTextStream::UnicodeUTF8 ); t << vcard; outFile.close(); urls.append( fileName ); } } bool result = ExternalAppHandler::instance()->mailToMultipleContacts( QString::null, urls.join(", ") ); /*US kapp->invokeMailer( QString::null, QString::null, QString::null, QString::null, // subject QString::null, // body QString::null, urls ); // attachments */ } /** Beams the "WhoAmI contact. */ void KABCore::beamMySelf() { KABC::Addressee a = KABC::StdAddressBook::self()->whoAmI(); if (!a.isEmpty()) { QStringList uids; uids << a.uid(); beamVCard(uids); } else { KMessageBox::information( this, i18n( "Your personal contact is\nnot set! Please select it\nand set it with menu:\nSettings - Set Who Am I\n" ) ); } } void KABCore::export2phone() { KAex2phonePrefs ex2phone; ex2phone.mPhoneConnection->setText( KPimGlobalPrefs::instance()->mEx2PhoneConnection ); ex2phone.mPhoneDevice->setText( KPimGlobalPrefs::instance()->mEx2PhoneDevice ); ex2phone.mPhoneModel->setText( KPimGlobalPrefs::instance()->mEx2PhoneModel ); if ( !ex2phone.exec() ) { return; } KPimGlobalPrefs::instance()->mEx2PhoneConnection = ex2phone.mPhoneConnection->text(); KPimGlobalPrefs::instance()->mEx2PhoneDevice = ex2phone.mPhoneDevice->text(); KPimGlobalPrefs::instance()->mEx2PhoneModel = ex2phone.mPhoneModel->text(); PhoneAccess::writeConfig( KPimGlobalPrefs::instance()->mEx2PhoneDevice, KPimGlobalPrefs::instance()->mEx2PhoneConnection, KPimGlobalPrefs::instance()->mEx2PhoneModel ); QStringList uids = mViewManager->selectedUids(); if ( uids.isEmpty() ) return; #ifdef _WIN32_ - QString fileName = locateLocal("tmp", "tempfile.vcf"); + QString fileName = locateLocal("tmp", "phonefile.vcf"); #else - QString fileName = "/tmp/kdepimtemp.vcf"; + QString fileName = "/tmp/phonefile.vcf"; #endif - KABC::VCardConverter converter; - QString description; - QString datastream; - for( QStringList::ConstIterator it = uids.begin(); it != uids.end(); ++it ) { - KABC::Addressee a = mAddressBook->findByUid( *it ); - - if ( a.isEmpty() ) - continue; - a.simplifyEmails(); - a.simplifyPhoneNumbers(); - a.simplifyPhoneNumberTypes(); - a.simplifyAddresses(); - - if (description.isEmpty()) - description = a.formattedName(); - QString vcard; - QString vcardnew; - converter.addresseeToVCard( a, vcard ); - int start = 0; - int next; - while ( (next = vcard.find("TYPE=", start) )>= 0 ) { - int semi = vcard.find(";", next); - int dopp = vcard.find(":", next); - int sep; - if ( semi < dopp && semi >= 0 ) - sep = semi ; - else - sep = dopp; - vcardnew +=vcard.mid( start, next - start); - vcardnew +=vcard.mid( next+5,sep -next -5 ).upper(); - start = sep; - } - vcardnew += vcard.mid( start,vcard.length() ); - vcard = ""; - start = 0; - while ( (next = vcardnew.find("ADR", start) )>= 0 ) { - int sep = vcardnew.find(":", next); - vcard +=vcardnew.mid( start, next - start+3); - start = sep; - } - vcard += vcardnew.mid( start,vcardnew.length() ); - vcard.replace ( QRegExp(";;;") , "" ); - vcard.replace ( QRegExp(";;") , "" ); - datastream += vcard; - - } - QFile outFile(fileName); - if ( outFile.open(IO_WriteOnly) ) { - datastream.replace ( QRegExp("VERSION:3.0") , "VERSION:2.1" ); - QTextStream t( &outFile ); // use a text stream - t.setEncoding( QTextStream::UnicodeUTF8 ); - t <<datastream; - outFile.close(); - if ( PhoneAccess::writeToPhone( fileName ) ) - qDebug("Export okay "); - else - qDebug("Error export contacts "); - - } else { - qDebug("Error open temp file "); + if ( ! mAddressBook->export2PhoneFormat( uids ,fileName ) ) return; - } - + + if ( PhoneAccess::writeToPhone( fileName ) ) + qDebug("Export okay "); + else + qDebug("Error export contacts "); + #if 0 setCaption( i18n("Writing to phone...")); if ( PhoneFormat::writeToPhone( cal ) ) setCaption( i18n("Export to phone successful!")); else setCaption( i18n("Error exporting to phone!")); #endif } void KABCore::beamVCard() { QStringList uids = mViewManager->selectedUids(); if ( !uids.isEmpty() ) beamVCard( uids ); } void KABCore::beamVCard(const QStringList& uids) { /*US QString beamFilename; Opie::OPimContact c; if ( actionPersonal->isOn() ) { beamFilename = addressbookPersonalVCardName(); if ( !QFile::exists( beamFilename ) ) return; // can't beam a non-existent file Opie::OPimContactAccessBackend* vcard_backend = new Opie::OPimContactAccessBackend_VCard( QString::null, beamFilename ); Opie::OPimContactAccess* access = new Opie::OPimContactAccess ( "addressbook", QString::null , vcard_backend, true ); Opie::OPimContactAccess::List allList = access->allRecords(); Opie::OPimContactAccess::List::Iterator it = allList.begin(); // Just take first c = *it; delete access; } else { unlink( beamfile ); // delete if exists mkdir("/tmp/obex/", 0755); c = m_abView -> currentEntry(); Opie::OPimContactAccessBackend* vcard_backend = new Opie::OPimContactAccessBackend_VCard( QString::null, beamfile ); Opie::OPimContactAccess* access = new Opie::OPimContactAccess ( "addressbook", QString::null , vcard_backend, true ); access->add( c ); access->save(); delete access; beamFilename = beamfile; } owarn << "Beaming: " << beamFilename << oendl; */ #if 0 QString tmpdir = locateLocal("tmp", KGlobal::getAppName()); QString dirName = tmpdir + "/" + KApplication::randomString( 8 ); QString name = "contact.vcf"; QString fileName = dirName + "/" + name; #endif // LR: we should use the /tmp dir, because: /tmp = RAM, (HOME)/kdepim = flash memory // QString fileName = "/tmp/kapibeamfile.vcf"; //QDir().mkdir( dirName, true ); KABC::VCardConverter converter; QString description; QString datastream; for( QStringList::ConstIterator it = uids.begin(); it != uids.end(); ++it ) { KABC::Addressee a = mAddressBook->findByUid( *it ); if ( a.isEmpty() ) continue; if (description.isEmpty()) description = a.formattedName(); QString vcard; converter.addresseeToVCard( a, vcard ); int start = 0; int next; while ( (next = vcard.find("TYPE=", start) )>= 0 ) { int semi = vcard.find(";", next); int dopp = vcard.find(":", next); int sep; if ( semi < dopp && semi >= 0 ) sep = semi ; else sep = dopp; datastream +=vcard.mid( start, next - start); datastream +=vcard.mid( next+5,sep -next -5 ).upper(); start = sep; } datastream += vcard.mid( start,vcard.length() ); } #ifndef DESKTOP_VERSION QFile outFile(fileName); if ( outFile.open(IO_WriteOnly) ) { datastream.replace ( QRegExp("VERSION:3.0") , "VERSION:2.1" ); QTextStream t( &outFile ); // use a text stream t.setEncoding( QTextStream::UnicodeUTF8 ); t <<datastream; outFile.close(); Ir *ir = new Ir( this ); connect( ir, SIGNAL( done(Ir*) ), this, SLOT( beamDone(Ir*) ) ); ir->send( fileName, description, "text/x-vCard" ); } else { qDebug("Error open temp beam file "); return; } #endif } void KABCore::beamDone( Ir *ir ) { #ifndef DESKTOP_VERSION delete ir; #endif } void KABCore::browse( const QString& url ) { #ifndef KAB_EMBEDDED kapp->invokeBrowser( url ); #else //KAB_EMBEDDED qDebug("KABCore::browse must be fixed"); #endif //KAB_EMBEDDED } void KABCore::selectAllContacts() { mViewManager->setSelected( QString::null, true ); } void KABCore::deleteContacts() { QStringList uidList = mViewManager->selectedUids(); deleteContacts( uidList ); } void KABCore::deleteContacts( const QStringList &uids ) { if ( uids.count() > 0 ) { PwDeleteCommand *command = new PwDeleteCommand( mAddressBook, uids ); UndoStack::instance()->push( command ); RedoStack::instance()->clear(); // now if we deleted anything, refresh setContactSelected( QString::null ); setModified( true ); } } void KABCore::copyContacts() { KABC::Addressee::List addrList = mViewManager->selectedAddressees(); QString clipText = AddresseeUtil::addresseesToClipboard( addrList ); kdDebug(5720) << "KABCore::copyContacts: " << clipText << endl; QClipboard *cb = QApplication::clipboard(); cb->setText( clipText ); } void KABCore::cutContacts() { QStringList uidList = mViewManager->selectedUids(); //US if ( uidList.size() > 0 ) { if ( uidList.count() > 0 ) { PwCutCommand *command = new PwCutCommand( mAddressBook, uidList ); UndoStack::instance()->push( command ); RedoStack::instance()->clear(); setModified( true ); } } void KABCore::pasteContacts() { QClipboard *cb = QApplication::clipboard(); KABC::Addressee::List list = AddresseeUtil::clipboardToAddressees( cb->text() ); pasteContacts( list ); } void KABCore::pasteContacts( KABC::Addressee::List &list ) { KABC::Resource *resource = requestResource( this ); KABC::Addressee::List::Iterator it; for ( it = list.begin(); it != list.end(); ++it ) (*it).setResource( resource ); PwPasteCommand *command = new PwPasteCommand( this, list ); UndoStack::instance()->push( command ); RedoStack::instance()->clear(); setModified( true ); } void KABCore::setWhoAmI() { KABC::Addressee::List addrList = mViewManager->selectedAddressees(); if ( addrList.count() > 1 ) { KMessageBox::sorry( this, i18n( "Please select only one contact." ) ); return; } QString text( i18n( "<qt>Do you really want to use <b>%1</b> as your new personal contact?</qt>" ) ); if ( KMessageBox::questionYesNo( this, text.arg( addrList[ 0 ].assembledName() ) ) == KMessageBox::Yes ) static_cast<KABC::StdAddressBook*>( KABC::StdAddressBook::self() )->setWhoAmI( addrList[ 0 ] ); } void KABCore::setCategories() { KPIM::CategorySelectDialog dlg( KABPrefs::instance(), this, "", true ); if ( !dlg.exec() ) return; bool merge = false; QString msg = i18n( "Merge with existing categories?" ); if ( KMessageBox::questionYesNo( this, msg ) == KMessageBox::Yes ) merge = true; QStringList categories = dlg.selectedCategories(); QStringList uids = mViewManager->selectedUids(); QStringList::Iterator it; for ( it = uids.begin(); it != uids.end(); ++it ) { KABC::Addressee addr = mAddressBook->findByUid( *it ); if ( !addr.isEmpty() ) { if ( !merge ) addr.setCategories( categories ); else { QStringList addrCategories = addr.categories(); QStringList::Iterator catIt; for ( catIt = categories.begin(); catIt != categories.end(); ++catIt ) { if ( !addrCategories.contains( *catIt ) ) addrCategories.append( *catIt ); } addr.setCategories( addrCategories ); } mAddressBook->insertAddressee( addr ); } } if ( uids.count() > 0 ) setModified( true ); } void KABCore::setSearchFields( const KABC::Field::List &fields ) { mIncSearchWidget->setFields( fields ); } void KABCore::incrementalSearch( const QString& text ) { mViewManager->doSearch( text, mIncSearchWidget->currentField() ); } void KABCore::setModified() { setModified( true ); } void KABCore::setModifiedWOrefresh() { // qDebug("KABCore::setModifiedWOrefresh() "); mModified = true; mActionSave->setEnabled( mModified ); #ifdef DESKTOP_VERSION mDetails->refreshView(); #endif } void KABCore::setModified( bool modified ) { mModified = modified; mActionSave->setEnabled( mModified ); if ( modified ) mJumpButtonBar->recreateButtons(); mViewManager->refreshView(); mDetails->refreshView(); } bool KABCore::modified() const { return mModified; } void KABCore::contactModified( const KABC::Addressee &addr ) { Command *command = 0; QString uid; // check if it exists already KABC::Addressee origAddr = mAddressBook->findByUid( addr.uid() ); if ( origAddr.isEmpty() ) command = new PwNewCommand( mAddressBook, addr ); else { command = new PwEditCommand( mAddressBook, origAddr, addr ); uid = addr.uid(); } UndoStack::instance()->push( command ); RedoStack::instance()->clear(); setModified( true ); } void KABCore::newContact() { QPtrList<KABC::Resource> kabcResources = mAddressBook->resources(); QPtrList<KRES::Resource> kresResources; QPtrListIterator<KABC::Resource> it( kabcResources ); KABC::Resource *resource; while ( ( resource = it.current() ) != 0 ) { ++it; if ( !resource->readOnly() ) { KRES::Resource *res = static_cast<KRES::Resource*>( resource ); if ( res ) kresResources.append( res ); } } KRES::Resource *res = KRES::SelectDialog::getResource( kresResources, this ); resource = static_cast<KABC::Resource*>( res ); if ( resource ) { KABC::Addressee addr; addr.setResource( resource ); mEditorDialog->setAddressee( addr ); KApplication::execDialog ( mEditorDialog ); } else return; // mEditorDict.insert( dialog->addressee().uid(), dialog ); } void KABCore::addEmail( QString aStr ) { #ifndef KAB_EMBEDDED QString fullName, email; KABC::Addressee::parseEmailAddress( aStr, fullName, email ); // Try to lookup the addressee matching the email address bool found = false; QStringList emailList; KABC::AddressBook::Iterator it; for ( it = mAddressBook->begin(); !found && (it != mAddressBook->end()); ++it ) { emailList = (*it).emails(); if ( emailList.contains( email ) > 0 ) { found = true; (*it).setNameFromString( fullName ); editContact( (*it).uid() ); } } if ( !found ) { KABC::Addressee addr; addr.setNameFromString( fullName ); @@ -2462,463 +2407,466 @@ int KABCore::takeAddressee( KABC::Addressee* local, KABC::Addressee* remote, i if ( lastSync > remoteMod ) return 1; if ( lastSync > localMod ) return 2; localIsNew = localMod >= remoteMod; //qDebug("conflict! ************************************** "); { KPIM::AddresseeChooser acd ( *local,*remote, localIsNew , this ); result = acd.executeD(localIsNew); return result; } break; case SYNC_PREF_FORCE_LOCAL: return 1; break; case SYNC_PREF_FORCE_REMOTE: return 2; break; default: // SYNC_PREF_TAKE_BOTH not implemented break; } return 0; } bool KABCore::synchronizeAddressbooks( KABC::AddressBook* local, KABC::AddressBook* remote,int mode) { bool syncOK = true; int addedAddressee = 0; int addedAddresseeR = 0; int deletedAddresseeR = 0; int deletedAddresseeL = 0; int changedLocal = 0; int changedRemote = 0; QString mCurrentSyncName = syncManager->getCurrentSyncName(); QString mCurrentSyncDevice = syncManager->getCurrentSyncDevice(); //QPtrList<Addressee> el = local->rawAddressees(); Addressee addresseeR; QString uid; int take; Addressee addresseeL; Addressee addresseeRSync; Addressee addresseeLSync; // KABC::Addressee::List addresseeRSyncSharp = remote->getExternLastSyncAddressees(); //KABC::Addressee::List addresseeLSyncSharp = local->getExternLastSyncAddressees(); bool fullDateRange = false; local->resetTempSyncStat(); mLastAddressbookSync = QDateTime::currentDateTime(); QDateTime modifiedCalendar = mLastAddressbookSync;; addresseeLSync = getLastSyncAddressee(); qDebug("Last Sync %s ", addresseeLSync.revision().toString().latin1()); addresseeR = remote->findByUid("last-syncAddressee-"+mCurrentSyncName ); if ( !addresseeR.isEmpty() ) { addresseeRSync = addresseeR; remote->removeAddressee(addresseeR ); } else { if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) { addresseeRSync = addresseeLSync ; } else { qDebug("FULLDATE 1"); fullDateRange = true; Addressee newAdd; addresseeRSync = newAdd; addresseeRSync.setFamilyName(mCurrentSyncName + i18n(" - sync addressee")); addresseeRSync.setUid("last-syncAddressee-"+mCurrentSyncName ); addresseeRSync.setRevision( mLastAddressbookSync ); addresseeRSync.setCategories( i18n("SyncAddressee") ); } } if ( addresseeLSync.revision() == mLastAddressbookSync ) { qDebug("FULLDATE 2"); fullDateRange = true; } if ( ! fullDateRange ) { if ( addresseeLSync.revision() != addresseeRSync.revision() ) { // qDebug("set fulldate to true %s %s" ,addresseeLSync->dtStart().toString().latin1(), addresseeRSync->dtStart().toString().latin1() ); //qDebug("%d %d %d %d ", addresseeLSync->dtStart().time().second(), addresseeLSync->dtStart().time().msec() , addresseeRSync->dtStart().time().second(), addresseeRSync->dtStart().time().msec()); fullDateRange = true; qDebug("FULLDATE 3 %s %s", addresseeLSync.revision().toString().latin1() , addresseeRSync.revision().toString().latin1() ); } } // fullDateRange = true; // debug only! if ( fullDateRange ) mLastAddressbookSync = QDateTime::currentDateTime().addDays( -100*365); else mLastAddressbookSync = addresseeLSync.revision(); // for resyncing if own file has changed // PENDING fixme later when implemented #if 0 if ( mCurrentSyncDevice == "deleteaftersync" ) { mLastAddressbookSync = loadedFileVersion; qDebug("setting mLastAddressbookSync "); } #endif //qDebug("*************************** "); // qDebug("mLastAddressbookSync %s ",mLastAddressbookSync.toString().latin1() ); QStringList er = remote->uidList(); Addressee inR ;//= er.first(); Addressee inL; syncManager->showProgressBar(0, i18n("Syncing - close to abort!"), er.count()); int modulo = (er.count()/10)+1; int incCounter = 0; while ( incCounter < er.count()) { if (syncManager->isProgressBarCanceled()) return false; if ( incCounter % modulo == 0 ) syncManager->showProgressBar(incCounter); uid = er[ incCounter ]; bool skipIncidence = false; if ( uid.left(19) == QString("last-syncAddressee-") ) skipIncidence = true; QString idS,OidS; qApp->processEvents(); if ( !skipIncidence ) { inL = local->findByUid( uid ); inR = remote->findByUid( uid ); //inL.setResource( 0 ); //inR.setResource( 0 ); if ( !inL.isEmpty() ) { // maybe conflict - same uid in both calendars if ( take = takeAddressee( &inL, &inR, mode, fullDateRange ) ) { //qDebug("take %d %s ", take, inL.summary().latin1()); if ( take == 3 ) return false; if ( take == 1 ) {// take local if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) { inL.setCsum( mCurrentSyncDevice, inR.getCsum(mCurrentSyncDevice) ); inL.setID( mCurrentSyncDevice, inR.getID(mCurrentSyncDevice) ); local->insertAddressee( inL, false ); idS = inR.externalUID(); OidS = inR.originalExternalUID(); } else idS = inR.IDStr(); remote->removeAddressee( inR ); inR = inL; inR.setTempSyncStat( SYNC_TEMPSTATE_INITIAL ); if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) { inR.setOriginalExternalUID( OidS ); inR.setExternalUID( idS ); } else { inR.setIDStr( idS ); } inR.setResource( 0 ); remote->insertAddressee( inR , false); ++changedRemote; } else { // take == 2 take remote if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) { if ( inR.revision().date().year() < 2004 ) inR.setRevision( modifiedCalendar ); } idS = inL.IDStr(); local->removeAddressee( inL ); inL = inR; inL.setIDStr( idS ); if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) { inL.setCsum( mCurrentSyncDevice, inR.getCsum(mCurrentSyncDevice) ); inL.setID( mCurrentSyncDevice, inR.getID(mCurrentSyncDevice) ); } inL.setResource( 0 ); local->insertAddressee( inL , false ); ++changedLocal; } } } else { // no conflict if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) { QString des = addresseeLSync.note(); if ( des.find( inR.getID(mCurrentSyncDevice) +"," ) >= 0 && mode != 5) { // delete it inR.setTempSyncStat( SYNC_TEMPSTATE_DELETE ); remote->insertAddressee( inR, false ); ++deletedAddresseeR; } else { inR.setRevision( modifiedCalendar ); remote->insertAddressee( inR, false ); inL = inR; inL.setResource( 0 ); local->insertAddressee( inL , false); ++addedAddressee; } } else { if ( inR.revision() > mLastAddressbookSync || mode == 5 ) { inR.setRevision( modifiedCalendar ); remote->insertAddressee( inR, false ); inR.setResource( 0 ); local->insertAddressee( inR, false ); ++addedAddressee; } else { // pending checkExternSyncAddressee(addresseeRSyncSharp, inR); remote->removeAddressee( inR ); ++deletedAddresseeR; } } } } ++incCounter; } er.clear(); QStringList el = local->uidList(); modulo = (el.count()/10)+1; syncManager->showProgressBar(0, i18n("Add / remove addressees"), el.count()); incCounter = 0; while ( incCounter < el.count()) { qApp->processEvents(); if (syncManager->isProgressBarCanceled()) return false; if ( incCounter % modulo == 0 ) syncManager->showProgressBar(incCounter); uid = el[ incCounter ]; bool skipIncidence = false; if ( uid.left(19) == QString("last-syncAddressee-") ) skipIncidence = true; if ( !skipIncidence ) { inL = local->findByUid( uid ); inR = remote->findByUid( uid ); if ( inR.isEmpty() ) { if ( mGlobalSyncMode == SYNC_MODE_EXTERNAL ) { if ( !inL.getID(mCurrentSyncDevice).isEmpty() && mode != 4 ) { // pending checkExternSyncAddressee(addresseeLSyncSharp, inL); local->removeAddressee( inL ); ++deletedAddresseeL; } else { if ( ! syncManager->mWriteBackExistingOnly ) { inL.removeID(mCurrentSyncDevice ); ++addedAddresseeR; inL.setRevision( modifiedCalendar ); local->insertAddressee( inL, false ); inR = inL; inR.setTempSyncStat( SYNC_TEMPSTATE_ADDED_EXTERNAL ); inR.setResource( 0 ); remote->insertAddressee( inR, false ); } } } else { if ( inL.revision() < mLastAddressbookSync && mode != 4 ) { // pending checkExternSyncAddressee(addresseeLSyncSharp, inL); local->removeAddressee( inL ); ++deletedAddresseeL; } else { if ( ! syncManager->mWriteBackExistingOnly ) { ++addedAddresseeR; inL.setRevision( modifiedCalendar ); local->insertAddressee( inL, false ); inR = inL; inR.setResource( 0 ); remote->insertAddressee( inR, false ); } } } } } ++incCounter; } el.clear(); syncManager->hideProgressBar(); mLastAddressbookSync = QDateTime::currentDateTime().addSecs( 1 ); // get rid of micro seconds QTime t = mLastAddressbookSync.time(); mLastAddressbookSync.setTime( QTime (t.hour (), t.minute (), t.second () ) ); addresseeLSync.setRevision( mLastAddressbookSync ); addresseeRSync.setRevision( mLastAddressbookSync ); addresseeRSync.setRole( i18n("!Remote from: ")+mCurrentSyncName ) ; addresseeLSync.setRole(i18n("!Local from: ") + mCurrentSyncName ); addresseeRSync.setGivenName( i18n("!DO NOT EDIT!") ) ; addresseeLSync.setGivenName(i18n("!DO NOT EDIT!") ); addresseeRSync.setOrganization( "!"+mLastAddressbookSync.toString() ) ; addresseeLSync.setOrganization("!"+ mLastAddressbookSync.toString() ); addresseeRSync.setNote( "" ) ; addresseeLSync.setNote( "" ); if ( mGlobalSyncMode == SYNC_MODE_NORMAL) remote->insertAddressee( addresseeRSync, false ); local->insertAddressee( addresseeLSync, false ); QString mes; mes .sprintf( i18n("Synchronization summary:\n\n %d items added to local\n %d items added to remote\n %d items updated on local\n %d items updated on remote\n %d items deleted on local\n %d items deleted on remote\n"),addedAddressee, addedAddresseeR, changedLocal, changedRemote, deletedAddresseeL, deletedAddresseeR ); if ( syncManager->mShowSyncSummary ) { KMessageBox::information(this, mes, i18n("KA/Pi Synchronization") ); } qDebug( mes ); return syncOK; } //this is a overwritten callbackmethods from the syncinterface bool KABCore::sync(KSyncManager* manager, QString filename, int mode) { //pending prepare addresseeview for output //pending detect, if remote file has REV field. if not switch to external sync mGlobalSyncMode = SYNC_MODE_NORMAL; QString mCurrentSyncDevice = manager->getCurrentSyncDevice(); AddressBook abLocal(filename,"syncContact"); bool syncOK = false; if ( abLocal.load() ) { qDebug("AB loaded %s,sync mode %d",filename.latin1(), mode ); bool external = false; bool isXML = false; if ( filename.right(4) == ".xml") { mGlobalSyncMode = SYNC_MODE_EXTERNAL; isXML = true; abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice ); } else { Addressee lse = mAddressBook->findByUid( "last-syncAddressee-"+mCurrentSyncDevice ); if ( ! lse.isEmpty() ) { if ( lse.familyName().left(4) == "!E: " ) external = true; } else { bool found = false; AddressBook::Iterator it; for ( it = abLocal.begin(); it != abLocal.end(); ++it ) { if ( (*it).revision().date().year() > 2003 ) { found = true; break; } } external = ! found; } if ( external ) { qDebug("Setting vcf mode to external "); mGlobalSyncMode = SYNC_MODE_EXTERNAL; AddressBook::Iterator it; for ( it = abLocal.begin(); it != abLocal.end(); ++it ) { (*it).setID( mCurrentSyncDevice, (*it).uid() ); (*it).computeCsum( mCurrentSyncDevice ); } } } //AddressBook::Iterator it; //QStringList vcards; //for ( it = abLocal.begin(); it != abLocal.end(); ++it ) { // qDebug("Name %s ", (*it).familyName().latin1()); //} syncOK = synchronizeAddressbooks( mAddressBook, &abLocal, mode ); if ( syncOK ) { if ( syncManager->mWriteBackFile ) { if ( external ) abLocal.removeSyncAddressees( !isXML); qDebug("Saving remote AB "); if ( ! abLocal.saveAB()) qDebug("Error writing back AB to file "); if ( isXML ) { // afterwrite processing abLocal.postExternSync( mAddressBook,mCurrentSyncDevice ); } } } setModified(); } if ( syncOK ) mViewManager->refreshView(); return syncOK; } //this is a overwritten callbackmethods from the syncinterface bool KABCore::syncExternal(KSyncManager* manager, QString resource) { if ( resource == "phone" ) return syncPhone(); QString mCurrentSyncDevice = manager->getCurrentSyncDevice(); AddressBook abLocal( resource,"syncContact"); bool syncOK = false; if ( abLocal.load() ) { qDebug("AB sharp loaded ,sync device %s",mCurrentSyncDevice.latin1()); mGlobalSyncMode = SYNC_MODE_EXTERNAL; abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice ); syncOK = synchronizeAddressbooks( mAddressBook, &abLocal, syncManager->mSyncAlgoPrefs ); if ( syncOK ) { if ( syncManager->mWriteBackFile ) { + abLocal.removeSyncAddressees( false ); abLocal.saveAB(); abLocal.postExternSync( mAddressBook,mCurrentSyncDevice ); } } setModified(); } if ( syncOK ) mViewManager->refreshView(); return syncOK; } void KABCore::message( QString m ) { topLevelWidget()->setCaption( m ); QTimer::singleShot( 15000, this , SLOT ( setCaptionBack())); } bool KABCore::syncPhone() { QString mCurrentSyncDevice = syncManager->getCurrentSyncDevice(); QString fileName; #ifdef _WIN32_ fileName = locateLocal("tmp", "phonefile.vcf"); #else fileName = "/tmp/phonefile.vcf"; #endif if ( !PhoneAccess::readFromPhone( fileName) ) { message(i18n("Phone access failed!")); return false; } AddressBook abLocal( fileName,"syncContact"); bool syncOK = false; - if ( abLocal.load() ) { + { + abLocal.importFromFile( fileName ); qDebug("AB phone loaded ,sync device %s",mCurrentSyncDevice.latin1()); mGlobalSyncMode = SYNC_MODE_EXTERNAL; abLocal.preparePhoneSync( mCurrentSyncDevice, true ); abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice ); syncOK = synchronizeAddressbooks( mAddressBook, &abLocal, syncManager->mSyncAlgoPrefs ); if ( syncOK ) { if ( syncManager->mWriteBackFile ) { + abLocal.removeSyncAddressees( true ); abLocal.saveABphone( fileName ); - abLocal.preparePhoneSync( mCurrentSyncDevice, false ); - abLocal.preExternSync( mAddressBook ,mCurrentSyncDevice ); + abLocal.findNewExtIds( fileName, mCurrentSyncDevice ); + //abLocal.preparePhoneSync( mCurrentSyncDevice, false ); abLocal.postExternSync( mAddressBook,mCurrentSyncDevice ); } } setModified(); } if ( syncOK ) mViewManager->refreshView(); return syncOK; } void KABCore::getFile( bool success ) { if ( ! success ) { message( i18n("Error receiving file. Nothing changed!") ); return; } mAddressBook->importFromFile( sentSyncFile() , false, true ); message( i18n("Pi-Sync successful!") ); mViewManager->refreshView(); } void KABCore::syncFileRequest() { mAddressBook->export2File( sentSyncFile() ); } QString KABCore::sentSyncFile() { #ifdef _WIN32_ return locateLocal( "tmp", "copysyncab.vcf" ); #else return QString( "/tmp/copysyncab.vcf" ); #endif } void KABCore::setCaptionBack() { topLevelWidget()->setCaption( i18n("KAddressbook/Pi") ); } diff --git a/libkdepim/ksyncprefsdialog.cpp b/libkdepim/ksyncprefsdialog.cpp index 84cc448..cf8f996 100644 --- a/libkdepim/ksyncprefsdialog.cpp +++ b/libkdepim/ksyncprefsdialog.cpp @@ -1,731 +1,732 @@ /* This file is part of KOrganizer. Copyright (c) 2004 Lutz Rogowski <rogowski@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qlayout.h> #include <qlabel.h> #include <qgroupbox.h> #include <qbuttongroup.h> #include <qlineedit.h> #include <qfont.h> #include <qslider.h> #include <qfile.h> #include <qdir.h> #include <qtextstream.h> #include <qcombobox.h> #include <qvbox.h> #include <qhbox.h> #include <qspinbox.h> #include <qdatetime.h> #include <qcheckbox.h> #include <qradiobutton.h> #include <qpushbutton.h> #include <qstrlist.h> #include <qapplication.h> #include <qlayout.h> #include <qscrollview.h> #include <kcolorbutton.h> #include <kdebug.h> #include <klocale.h> #include <kglobal.h> #include <kfontdialog.h> #include <kmessagebox.h> #include <kcolordialog.h> #include <kiconloader.h> #include <kemailsettings.h> #include <kstandarddirs.h> #include <kfiledialog.h> #include <kmessagebox.h> //#include <kurlrequester.h> #include <klineedit.h> #include "ksyncprofile.h" //#include "koprefs.h" #include "ksyncprefsdialog.h" //#include "koglobals.h" KSyncPrefsDialog::KSyncPrefsDialog(QWidget *parent, char *name, bool modal) : KDialog(parent,name,true) { setCaption( i18n("Synchronization Preferences")); mSyncProfiles.setAutoDelete( true ); setupSyncAlgTab(); } KSyncPrefsDialog::~KSyncPrefsDialog() { } void KSyncPrefsDialog::setupSyncAlgTab() { QLabel * lab; //QFrame *page = addPage(i18n("Sync Prefs"),0,0); QVBox * mainbox = new QVBox( this ); QScrollView* sv = new QScrollView( mainbox ); QHBoxLayout * lay = new QHBoxLayout( this ); lay->addWidget( mainbox ); QHBox * b_box = new QHBox( mainbox ); QPushButton* button = new QPushButton( i18n("Ok"), b_box ); connect ( button, SIGNAL( clicked()), this, SLOT (slotOK() ) ); button = new QPushButton( i18n("Cancel"), b_box ); connect ( button, SIGNAL( clicked()), this, SLOT (reject() ) ); //QBoxLayout * sl = new QVBoxLayout(this ); //sl->addWidget ( sv ); sv->setResizePolicy ( QScrollView::AutoOneFit ); QFrame *topFrame = new QFrame ( sv ); sv->addChild( topFrame ); mSetupSyncAlgTab = topFrame; QGridLayout *topLayout = new QGridLayout(topFrame,6,2); topLayout->setSpacing(spacingHint()); topLayout->setMargin(marginHint()); //lab = new QLabel(i18n("Sync settings not yet implemented. DO NOT USE!"), topFrame); int iii = 0; //topLayout->addMultiCellWidget(lab , iii,iii,0,1); //++iii; mMyMachineName = new QLineEdit(topFrame); lab = new QLabel(mMyMachineName, i18n("Local device name:"), topFrame); topLayout->addWidget(lab ,iii,0); topLayout->addWidget(mMyMachineName,iii,1); ++iii; QHBox* buttonbox = new QHBox( topFrame); topLayout->addMultiCellWidget(buttonbox, iii,iii,0,1); ++iii; button = new QPushButton( i18n("New profile"), buttonbox ); connect ( button, SIGNAL( clicked()), this, SLOT (newProfile() ) ); button = new QPushButton( i18n("Clone profile"), buttonbox ); connect ( button, SIGNAL( clicked()), this, SLOT ( cloneProfile() ) ); button = new QPushButton( i18n("Delete profile"), buttonbox ); connect ( button, SIGNAL( clicked()), this, SLOT (deleteProfile() ) ); mProfileBox = new QComboBox(topFrame); mProfileBox->setEditable ( true ); mProfileBox->setInsertionPolicy(QComboBox::NoInsertion); connect ( mProfileBox, SIGNAL(activated ( int ) ), this, SLOT (profileChanged( int ) ) ); connect ( mProfileBox, SIGNAL( textChanged ( const QString & ) ), this, SLOT (textChanged( const QString & ) ) ); lab = new QLabel(mProfileBox, i18n("Profile:"), topFrame); topLayout->addWidget(lab ,iii,0); topLayout->addWidget(mProfileBox, iii,1); ++iii; QHBox *iims = new QHBox( topFrame ); new QLabel( i18n("Include in multiple "), iims ); mIncludeInRing = new QCheckBox( i18n("calendar "), iims ); mIncludeInRingAB = new QCheckBox( i18n("addressbook "), iims ); mIncludeInRingPWM = new QCheckBox( i18n("pwmanager"), iims ); new QLabel( i18n(" sync"), iims ); topLayout->addMultiCellWidget(iims, iii,iii,0,1); ++iii; mAskForPreferences = new QCheckBox( i18n("Ask for preferences before sync"), topFrame ); topLayout->addMultiCellWidget(mAskForPreferences, iii,iii,0,1); ++iii; QButtonGroup* gr = new QButtonGroup ( 1, Qt::Horizontal, i18n("Sync preferences"), topFrame); topLayout->addMultiCellWidget(gr, iii,iii,0,1); ++iii; loc = new QRadioButton ( i18n("Take local entry on conflict"), gr ); rem = new QRadioButton ( i18n("Take remote entry on conflict"), gr ); newest = new QRadioButton ( i18n("Take newest entry on conflict"), gr ); ask = new QRadioButton ( i18n("Ask for every entry on conflict"), gr ); f_loc= new QRadioButton ( i18n("Force: Take local entry always"), gr ); f_rem = new QRadioButton ( i18n("Force: Take remote entry always"), gr ); // both = new QRadioButton ( i18n("Take both on conflict"), gr ); mShowSummaryAfterSync = new QCheckBox( i18n("Show summary after sync"), topFrame ); topLayout->addMultiCellWidget(mShowSummaryAfterSync, iii,iii,0,1); ++iii; mWriteBackFile = new QCheckBox( i18n("Write back synced data"), topFrame ); topLayout->addMultiCellWidget(mWriteBackFile, iii,iii,0,1); ++iii; mWriteBackExisting= new QCheckBox( i18n("-- Write back (on remote) existing entries only"), topFrame ); topLayout->addMultiCellWidget(mWriteBackExisting, iii,iii,0,1); ++iii; mWriteBackFuture= new QCheckBox( i18n("-- Write back (calendar) entries in future only"), topFrame ); topLayout->addMultiCellWidget(mWriteBackFuture, iii,iii,0,1); ++iii; topLayout->addMultiCellWidget(new QLabel( i18n("---- Max. weeks in future: ") , topFrame ), iii,iii,0,0); mWriteBackFutureWeeks= new QSpinBox(1,104, 1, topFrame); topLayout->addMultiCellWidget(mWriteBackFutureWeeks, iii,iii,1,1); ++iii; proGr = new QButtonGroup ( 1, Qt::Horizontal, i18n("Profile kind"), topFrame); gr = proGr; topLayout->addMultiCellWidget(gr, iii,iii,0,1); ++iii; mIsLocal = new QRadioButton ( i18n("Local file"), gr ); mIsPi = new QRadioButton ( i18n("Pi-Sync ( direct Kx/Pi to Kx/Pi sync )"), gr ); connect (mIsPi, SIGNAL( toggled(bool)), this, SLOT (kindChanged(bool) ) ); mIsNotLocal = new QRadioButton ( i18n("Remote file (w down/upload command)"), gr ); connect (mIsLocal, SIGNAL( toggled(bool)), this, SLOT (kindChanged(bool) ) ); mIsPhone = new QRadioButton ( i18n("Mobile device (cell phone)"), gr ); connect (mIsPhone, SIGNAL( toggled(bool)), this, SLOT (kindChanged(bool) ) ); phoneWidget = new QVBox( topFrame); topLayout->addMultiCellWidget(phoneWidget, iii,iii,0,1); ++iii; - mWriteContactToSIM= new QCheckBox( i18n("Sync contacts with phone SIM card (If not, sync with phone memory)"), phoneWidget ); + mWriteContactToSIM = 0;//new QCheckBox( i18n("Sync contacts with phone SIM card (If not, sync with phone memory)"), phoneWidget ); QHBox* temphb = new QHBox( phoneWidget ); new QLabel( i18n("I/O device: "), temphb ); mPhoneDevice = new QLineEdit( temphb); button = new QPushButton( i18n("Help..."), temphb ); connect ( button, SIGNAL( clicked()), this, SLOT ( helpDevice() ) ); temphb = new QHBox( phoneWidget ); new QLabel( i18n("Connection: "), temphb ); mPhoneConnection = new QLineEdit( temphb); button = new QPushButton( i18n("Help..."), temphb ); connect ( button, SIGNAL( clicked()), this, SLOT ( helpConnection() ) ); temphb = new QHBox( phoneWidget ); new QLabel( i18n("Model(opt.): "), temphb ); mPhoneModel = new QLineEdit( temphb); button = new QPushButton( i18n("Help..."), temphb ); connect ( button, SIGNAL( clicked()), this, SLOT ( helpModel() ) ); // *** local localFileWidget = new QVBox( topFrame); topLayout->addMultiCellWidget(localFileWidget, iii,iii,0,1); ++iii; temphb = new QHBox( localFileWidget ); lab = new QLabel( i18n("Local file Cal:"), temphb ); lab = new QLabel( i18n("Local file ABook:"), temphb ); lab = new QLabel( i18n("Local file PWMgr:"), temphb ); temphb = new QHBox( localFileWidget ); button = new QPushButton( i18n("Choose..."), temphb ); connect ( button, SIGNAL( clicked()), this, SLOT ( chooseFile() ) ); button = new QPushButton( i18n("Choose..."), temphb ); connect ( button, SIGNAL( clicked()), this, SLOT ( chooseFileAB() ) ); button = new QPushButton( i18n("Choose..."), temphb ); connect ( button, SIGNAL( clicked()), this, SLOT ( chooseFilePWM() ) ); temphb = new QHBox( localFileWidget ); mRemoteFile = new QLineEdit( temphb); mRemoteFileAB = new QLineEdit( temphb); mRemoteFilePWM = new QLineEdit( temphb); // *** remote remoteFileWidget = new QVBox( topFrame); topLayout->addMultiCellWidget(remoteFileWidget, iii,iii,0,1); ++iii; temphb = new QHBox( remoteFileWidget ); new QLabel( i18n("Calendar:"), temphb); new QLabel( i18n("AddressBook:"), temphb); new QLabel( i18n("PWManager:"), temphb); lab = new QLabel( i18n("Pre sync (download) command:"), remoteFileWidget); temphb = new QHBox( remoteFileWidget ); mRemotePrecommand = new QLineEdit(temphb); mRemotePrecommandAB = new QLineEdit(temphb); mRemotePrecommandPWM = new QLineEdit(temphb); lab = new QLabel( i18n("Local temp file:"), remoteFileWidget); temphb = new QHBox( remoteFileWidget ); mLocalTempFile = new QLineEdit(temphb); mLocalTempFileAB = new QLineEdit(temphb); mLocalTempFilePWM = new QLineEdit(temphb); lab = new QLabel( i18n("Post sync (upload) command:"), remoteFileWidget); temphb = new QHBox( remoteFileWidget ); mRemotePostcommand = new QLineEdit(temphb ); mRemotePostcommandAB = new QLineEdit(temphb ); mRemotePostcommandPWM = new QLineEdit(temphb ); lab = new QLabel( i18n("Fill in default values for:"), remoteFileWidget); temphb = new QHBox( remoteFileWidget ); button = new QPushButton( i18n("ssh/scp"), temphb ); connect ( button, SIGNAL( clicked()), this, SLOT (fillSSH() ) ); button = new QPushButton( i18n("ftp"), temphb ); connect ( button, SIGNAL( clicked()), this, SLOT (fillFTP() ) ); lab = new QLabel( i18n("Hint: Use $PWD$ for placeholder of password!"), remoteFileWidget); // *** pi-sync piWidget = new QVBox( topFrame); topLayout->addMultiCellWidget(piWidget, iii,iii,0,1); ++iii; temphb = new QHBox( piWidget ); new QLabel( i18n("Calendar:"), temphb); new QLabel( i18n("AddressBook:"), temphb); new QLabel( i18n("PWManager:"), temphb); lab = new QLabel( i18n("Password for remote access: (could be the same for each)"), piWidget); temphb = new QHBox( piWidget ); mRemotePw = new QLineEdit(temphb); mRemotePwAB = new QLineEdit(temphb); mRemotePwPWM = new QLineEdit(temphb); lab = new QLabel( i18n("Remote IP address: (could be the same for each)"), piWidget); temphb = new QHBox( piWidget ); mRemoteIP = new QLineEdit(temphb); mRemoteIPAB = new QLineEdit(temphb); mRemoteIPPWM = new QLineEdit(temphb); lab = new QLabel( i18n("Remote port number: (should be different for each)"), piWidget); temphb = new QHBox( piWidget ); mRemotePort = new QLineEdit(temphb); mRemotePortAB = new QLineEdit(temphb); mRemotePortPWM = new QLineEdit(temphb); } void KSyncPrefsDialog::slotOK() { if ( mMyMachineName->text() == "undefined" ) { KMessageBox::error(this,i18n("Local device name undefined!\nPlease define device name!"),i18n("KO/Pi config error")); return; } int i; for (i = 0; i < mSyncProfileNames.count(); ++ i) { if ( mSyncProfileNames.contains( mSyncProfileNames[i]) > 1 ) { KMessageBox::error(this,i18n("Multiple profiles with same name!\nPlease use unique profile names!"),i18n("KO/Pi config error")); return; } } usrWriteConfig(); QDialog::accept(); } void KSyncPrefsDialog::accept() { slotOK(); } void KSyncPrefsDialog::chooseFile() { QString fn = QDir::homeDirPath(); fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename(*.ics/*.vcs)"), this ); if ( fn == "" ) return; mRemoteFile->setText( fn ); } void KSyncPrefsDialog::chooseFileAB() { QString fn = QDir::homeDirPath(); fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename(*.vcf)"), this ); if ( fn == "" ) return; mRemoteFileAB->setText( fn ); } void KSyncPrefsDialog::chooseFilePWM() { QString fn = QDir::homeDirPath(); fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename(*.pwm)"), this ); if ( fn == "" ) return; mRemoteFilePWM->setText( fn ); } void KSyncPrefsDialog::textChanged( const QString & s ) { if ( mProfileBox->count() == 0 ) return; if ( currentSelection < 3 ) { //KMessageBox::error(this,i18n("This profil name\ncannot be edited!\n"),i18n("KO/Pi config error")); mProfileBox->blockSignals( true ); mProfileBox->setCurrentItem(mProfileBox-> currentItem ()); mProfileBox->blockSignals( false ); return; } //qDebug("cur i %d ",mProfileBox-> currentItem () ); mProfileBox->changeItem ( s, mProfileBox-> currentItem () ) ; KSyncProfile* prof = mSyncProfiles.at(mProfileBox-> currentItem ()) ; prof->setName( s ); mSyncProfileNames[mProfileBox-> currentItem ()] = s; } void KSyncPrefsDialog::profileChanged( int item ) { //qDebug("KSyncPrefsDialog::profileChanged before %d, count %d ", item, mProfileBox->count() ); KSyncProfile* prof; saveProfile(); currentSelection = item; prof = mSyncProfiles.at(item) ; mRemotePw->setText(prof->getRemotePw()); mRemoteIP->setText(prof->getRemoteIP()); mRemotePort->setText(prof->getRemotePort()); mRemotePwAB->setText(prof->getRemotePwAB()); mRemoteIPAB->setText(prof->getRemoteIPAB()); mRemotePortAB->setText(prof->getRemotePortAB()); mRemotePwPWM->setText(prof->getRemotePwPWM()); mRemoteIPPWM->setText(prof->getRemoteIPPWM()); mRemotePortPWM->setText(prof->getRemotePortPWM()); mRemotePrecommand->setText(prof->getPreSyncCommand()); mRemotePostcommand->setText(prof->getPostSyncCommand()); mLocalTempFile->setText(prof->getLocalTempFile()); mRemoteFile->setText(prof->getRemoteFileName()) ; mRemotePrecommandAB->setText(prof->getPreSyncCommandAB()); mRemotePostcommandAB->setText(prof->getPostSyncCommandAB()); mLocalTempFileAB->setText(prof->getLocalTempFileAB()); mRemoteFileAB->setText(prof->getRemoteFileNameAB()) ; mRemotePrecommandPWM->setText(prof->getPreSyncCommandPWM()); mRemotePostcommandPWM->setText(prof->getPostSyncCommandPWM()); mLocalTempFilePWM->setText(prof->getLocalTempFilePWM()); mRemoteFilePWM->setText(prof->getRemoteFileNamePWM()) ; - mWriteContactToSIM->setChecked( prof->getWriteContactToSIM()); + if ( mWriteContactToSIM ) + mWriteContactToSIM->setChecked( prof->getWriteContactToSIM()); mPhoneDevice->setText(prof->getPhoneDevice()); mPhoneConnection->setText(prof->getPhoneConnection()); mPhoneModel->setText(prof->getPhoneModel()); mShowSummaryAfterSync->setChecked( prof->getShowSummaryAfterSync()); mAskForPreferences->setChecked( prof->getAskForPreferences()); mWriteBackExisting->setChecked( prof->getWriteBackExisting() ); mWriteBackFile->setChecked( prof->getWriteBackFile()); mIncludeInRing->setChecked( prof->getIncludeInRingSync() ); mIncludeInRingAB->setChecked( prof->getIncludeInRingSyncAB() ); mIncludeInRingPWM->setChecked( prof->getIncludeInRingSyncPWM() ); mWriteBackFuture->setChecked( prof->getWriteBackFuture()); mWriteBackFutureWeeks->setValue( prof->getWriteBackFutureWeeks() ); switch ( prof->getSyncPrefs() ) { case 0: loc->setChecked( true); break; case 1: rem->setChecked( true ); break; case 2: newest->setChecked( true); break; case 3: ask->setChecked( true); break; case 4: f_loc->setChecked( true); break; case 5: f_rem->setChecked( true); break; case 6: //both->setChecked( true); break; default: break; } mIsLocal->setChecked(prof->getIsLocalFileSync()) ; mIsPhone->setChecked(prof->getIsPhoneSync()) ; mIsPi->setChecked(prof->getIsPiSync()) ; mIsNotLocal->setChecked(!prof->getIsLocalFileSync() && !prof->getIsPhoneSync() &&!prof->getIsPiSync() ); proGr->setEnabled( item > 2 ); if ( item < 3 ) { localFileWidget->hide(); remoteFileWidget->hide(); phoneWidget->hide(); piWidget->hide(); } else kindChanged( prof->getIsLocalFileSync() ); } void KSyncPrefsDialog::fillSSH() { mRemotePrecommand->setText("scp zaurus@192.168.0.65:/home/zaurus/kdepim/apps/korganizer/mycalendar.ics /tmp/mycalendar.ics" ); mLocalTempFile->setText("/tmp/mycalendar.ics" ); mRemotePostcommand->setText("scp /tmp/mycalendar.ics zaurus@192.168.0.65:/home/zaurus/kdepim/apps/korganizer/mycalendar.ics" ); mRemotePrecommandAB->setText("scp zaurus@192.168.0.65:/home/zaurus/kdepim/apps/kabc/std.vcf /tmp/std.vcf" ); mLocalTempFileAB->setText("/tmp/std.vcf" ); mRemotePostcommandAB->setText("scp /tmp/std.vcf zaurus@192.168.0.65:/home/zaurus/kdepim/apps/kabc/std.vcf" ); mRemotePrecommandPWM->setText("scp zaurus@192.168.0.65:/home/zaurus/kdepim/apps/pwmanager/passwords.pwm /tmp/passwords.pwm" ); mLocalTempFilePWM->setText("/tmp/passwords.pwm" ); mRemotePostcommandPWM->setText("scp /tmp/passwords.pwm zaurus@192.168.0.65:/home/zaurus/kdepim/apps/pwmanager/pwmanager.pwm" ); } void KSyncPrefsDialog::fillFTP() { mRemotePrecommand->setText("cd /tmp;ftp ftp://zaurus:a@192.168.0.65/kdepim/apps/korganizer/mycalendar.ics" ); mLocalTempFile->setText("/tmp/mycalendar.ics" ); mRemotePostcommand->setText("ftp -u ftp://zaurus:a@192.168.0.65/kdepim/apps/korganizer/mycalendar.ics /tmp/mycalendar.ics" ); mRemotePrecommandAB->setText("cd /tmp;ftp ftp://zaurus:a@192.168.0.65/kdepim/apps/kabc/std.vcf" ); mLocalTempFileAB->setText("/tmp/std.vcf" ); mRemotePostcommandAB->setText("ftp -u ftp://zaurus:a@192.168.0.65/kdepim/apps/kabc/std.vcf /tmp/std.vcf" ); mRemotePrecommandPWM->setText("cd /tmp;ftp ftp://zaurus:a@192.168.0.65/kdepim/apps/pwmanager/passwords.pwm" ); mLocalTempFilePWM->setText("/tmp/passwords.pwm" ); mRemotePostcommandPWM->setText("ftp -u ftp://zaurus:a@192.168.0.65/kdepim/apps/pwmanager/passwords.pwm /tmp/passwords.pwm" ); } void KSyncPrefsDialog::kindChanged( bool b ) { if ( mIsLocal->isChecked () ) localFileWidget->show(); else localFileWidget->hide(); if ( mIsNotLocal->isChecked () ) remoteFileWidget->show(); else remoteFileWidget->hide(); if ( mIsPhone->isChecked () ) { phoneWidget->show(); } else { phoneWidget->hide(); } if ( mIsPi->isChecked () ) { piWidget->show(); } else { piWidget->hide(); } } void KSyncPrefsDialog::deleteProfile() { //qDebug("KSyncPrefsDialog::deleteProfile() "); if ( currentSelection >= 0 ) { if ( currentSelection < 3 ) { KMessageBox::error(this,i18n("This profil cannot be deleted!\n"),i18n("KO/Pi config error")); return; } KSyncProfile* temp = mSyncProfiles.at(currentSelection); mSyncProfiles.remove( temp ); mSyncProfileNames.remove( mSyncProfileNames.at( currentSelection )); insertProfiles(); } } void KSyncPrefsDialog::saveProfile() { KSyncProfile* prof; if ( currentSelection >= 0 ) { prof = mSyncProfiles.at(currentSelection) ; prof->setRemotePw( mRemotePw->text()); prof->setRemoteIP( mRemoteIP->text()); prof->setRemotePort( mRemotePort->text()); prof->setRemotePwAB( mRemotePwAB->text()); prof->setRemoteIPAB( mRemoteIPAB->text()); prof->setRemotePortAB( mRemotePortAB->text()); prof->setRemotePwPWM( mRemotePwPWM->text()); prof->setRemoteIPPWM( mRemoteIPPWM->text()); prof->setRemotePortPWM( mRemotePortPWM->text()); prof->setPreSyncCommand( mRemotePrecommand->text()); prof->setPostSyncCommand( mRemotePostcommand->text() ); prof->setLocalTempFile( mLocalTempFile->text()); prof->setRemoteFileName( mRemoteFile->text() ); prof->setPreSyncCommandAB( mRemotePrecommandAB->text()); prof->setPostSyncCommandAB( mRemotePostcommandAB->text() ); prof->setLocalTempFileAB( mLocalTempFileAB->text()); prof->setRemoteFileNameAB( mRemoteFileAB->text() ); prof->setPreSyncCommandPWM( mRemotePrecommandPWM->text()); prof->setPostSyncCommandPWM( mRemotePostcommandPWM->text() ); prof->setLocalTempFilePWM( mLocalTempFilePWM->text()); prof->setRemoteFileNamePWM( mRemoteFilePWM->text() ); prof->setShowSummaryAfterSync( mShowSummaryAfterSync->isChecked() ); prof->setAskForPreferences( mAskForPreferences->isChecked()); prof->setWriteBackExisting(mWriteBackExisting->isChecked() ); prof->setWriteBackFile( mWriteBackFile->isChecked()); prof->setIncludeInRingSync( mIncludeInRing->isChecked() ); prof->setIncludeInRingSyncAB( mIncludeInRingAB->isChecked() ); prof->setIncludeInRingSyncPWM( mIncludeInRingPWM->isChecked() ); int syncprefs = rem->isChecked()*1+newest->isChecked()*2+ ask->isChecked()*3+ f_loc->isChecked()*4+ f_rem->isChecked()*5 ;//+ both->isChecked()*6 ; prof->setSyncPrefs( syncprefs); prof->setIsLocalFileSync( mIsLocal->isChecked() ); prof->setIsPhoneSync( mIsPhone->isChecked() ); prof->setIsPiSync( mIsPi->isChecked() ); prof->setWriteBackFuture(mWriteBackFuture->isChecked()); prof->setWriteBackFutureWeeks(mWriteBackFutureWeeks->value()); - - prof->setWriteContactToSIM(mWriteContactToSIM->isChecked()); + if ( mWriteContactToSIM ) + prof->setWriteContactToSIM(mWriteContactToSIM->isChecked()); prof->setPhoneDevice( mPhoneDevice->text() ); prof->setPhoneConnection( mPhoneConnection->text() ); prof->setPhoneModel( mPhoneModel->text() ); } } void KSyncPrefsDialog::insertProfiles() { int curItem = mProfileBox->currentItem(); mProfileBox->blockSignals( true ); mProfileBox->clear(); mProfileBox->insertStringList (mSyncProfileNames ); int item = mSyncProfileNames.count() -1; if ( curItem >= 0 && mSyncProfileNames.count() > 0 && curItem < mSyncProfileNames.count() ) mProfileBox->setCurrentItem( curItem ); else if ( item >= 0 ) { mProfileBox->setCurrentItem( item ); } currentSelection = -1; if ( mSyncProfileNames.count() > 0 ) { //qDebug(" profileChanged( mProfileBox->currentItem() "); profileChanged( mProfileBox->currentItem() ); currentSelection = mProfileBox->currentItem(); } mProfileBox->blockSignals( false ); } void KSyncPrefsDialog::addProfile ( KSyncProfile* temp ) { saveProfile(); mSyncProfiles.append( temp ); mSyncProfileNames << temp->getName(); insertProfiles(); int last = mProfileBox->count() -1; mProfileBox->blockSignals( true ); mProfileBox->setCurrentItem( last ); mProfileBox->blockSignals( false ); profileChanged(last); } void KSyncPrefsDialog::newProfile() { addProfile ( new KSyncProfile () ); } void KSyncPrefsDialog::cloneProfile() { if ( currentSelection >= 0 ) addProfile (mSyncProfiles.at(currentSelection)->clone()) ; else newProfile(); } void KSyncPrefsDialog::setLocalMachineName ( const QString& name ) { mMyMachineName->setText( name ); } QString KSyncPrefsDialog::getLocalMachineName ( ) { return mMyMachineName->text(); } QStringList KSyncPrefsDialog::getSyncProfileNames() { return mSyncProfileNames; } void KSyncPrefsDialog::usrReadConfig() { //KConfig *config = KOGlobals::config(); KConfig config ( locateLocal( "config","ksyncprofilesrc" ) ); config.setGroup("General"); mSyncProfileNames =config.readListEntry("SyncProfileNames"); mMyMachineName->setText(config.readEntry("LocalMachineName","undefined")); int i; KSyncProfile* temp ; mSyncProfiles.clear(); for ( i = 0; i < mSyncProfileNames.count();++i ) { temp = new KSyncProfile (); temp->setName( mSyncProfileNames[i] ); temp->readConfig( &config ); mSyncProfiles.append( temp ); } insertProfiles(); //mMyMachineName->setText(KOPrefs::instance()->mLocalMachineName ); } void KSyncPrefsDialog::usrWriteConfig() { saveProfile(); if ( currentSelection >= 0 ) profileChanged(currentSelection); //KConfig *config = KOGlobals::config(); KConfig config ( locateLocal( "config","ksyncprofilesrc" ) ); KSyncProfile* prof = mSyncProfiles.first(); QStringList externalSyncProfileNames; externalSyncProfileNames.append("Sharp_DTM");; while ( prof ) { prof->writeConfig(&config); if ( prof->getIsPhoneSync( ) ) externalSyncProfileNames.append(prof->getName( ) ); prof = mSyncProfiles.next(); } //KOPrefs::instance()->mSyncProfileNames = mSyncProfileNames; //KOPrefs::instance()->mLocalMachineName = mMyMachineName->text(); config.setGroup("General"); config.writeEntry("SyncProfileNames",mSyncProfileNames); config.writeEntry("ExternSyncProfiles",externalSyncProfileNames); config.writeEntry("LocalMachineName",mMyMachineName->text()); config.sync(); } void KSyncPrefsDialog::helpDevice() { QString hint = i18n("Insert device where\nphone is connected. E.g.:\n"); #ifdef _WIN32_ hint += "Leave empty for Irda.\n" "com1:\n(first serial port)\n" "usb not supported\n" "???\n(bluetooth device address)\n"; #else hint += "/dev/ircomm\n(Irda)\n" "/dev/ttyS0\n(first serial port)\n" "/dev/ttyUSB0\n(first device usb port)\n" "???\n(bluetooth device address)\n"; #endif KMessageBox::information(this,hint,i18n("KDE-Pim sync config")); } void KSyncPrefsDialog::helpModel() { - QString hint = i18n("Leave empty or\ninsert name of phone model:\n"); + QString hint = i18n("Recommended: Leave empty!\n(Such that model can\nbe auto detected)\nOr insert name of model:\n"); hint += "E.g. for Nokia 6310i:\n6310i\nAlso possible:\nobex\nfor Obex connection"; KMessageBox::information(this,hint,i18n("KDE-Pim sync config")); } void KSyncPrefsDialog::helpConnection() { QString hint = i18n("Insert kind of connection,e.g.:\n"); hint += "irda | Nokia FBUS over infrared\n" "irdaat | AT commands infrared\n(for Siemens/Sony-Erricsson)\n" "irdaobex | set also model as obex\n" "fbus | Nokia FBUS2 serial\n"; KMessageBox::information(this,hint,i18n("KDE-Pim sync config")); } |