-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathabc.m
1081 lines (943 loc) · 30.4 KB
/
abc.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Simple Contacts (AddressBook) query CLI
* Copyright 2012-2014 Mike Carlton
*
* Released under terms of the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* build:
clang -framework Foundation -framework AddressBook -framework AppKit \
-Wall -Werror -Weverything -Wno-format-nonliteral -Wno-missing-field-initializers -Wno-shadow \
-o abc abc.m
* Field names defined in
* /System/Library/Frameworks/AddressBook.framework/Versions/A/Headers/ABGlobals.h
*
* Structures in
* /System/Library/Frameworks/AddressBook.framework/Versions/A/Headers/AddressBook.h
* /System/Library/Frameworks/AddressBook.framework/Versions/A/Headers/ABPerson.h
* /System/Library/Frameworks/AddressBook.framework/Versions/A/Headers/ABGroup.h
* /System/Library/Frameworks/AddressBook.framework/Versions/A/Headers/ABAddressBook.h
*
* TODO:
* - sort results according to AB preference (if not specified):
* defaultNameOrdering
* - additional properties: social media, related dates
* kABInstantMessageProperty.
* kABOtherDatesProperty, kABMultiDateProperty
* - handle related names (use record label as display label)
* - ability to set primary email and address
* - search dates
* - search organization as part of name
* - group search:
* kABGroupNameProperty
* - display as vcard
* - escape urls via (NSString *)
* stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
* - use person flags (e.g. display as company), see
* https://developer.apple.com/library/mac/#samplecode/ABPresence/Listings/ABPersonDisplayNameAdditions_m.html
*/
#import <Foundation/Foundation.h>
#import <AddressBook/AddressBook.h>
#import <Appkit/NSWorkspace.h>
#include <getopt.h>
#define numElts(array) (sizeof(array)/sizeof(*array))
#define plural(n) ((n) == 1 ? "" : "s")
#define eplural(n) ((n) == 1 ? "" : "es")
typedef enum {
labelNone,
labelHome,
labelWork,
} Preferred;
typedef enum
{
plainDisplay,
standardDisplay,
briefDisplay,
longDisplay,
rawDisplay,
} DisplayForm;
typedef enum
{
searchNames,
searchGroups,
searchAll,
} SearchFields;
static Boolean urlGui = false; // open browser gui with URL?
static Boolean emailGui = false; // open gui email?
static Boolean googleMapsGui = false; // open gui google maps?
static Boolean mapsGui = false; // open gui maps?
static Boolean contactsGui = false; // open gui address book?
static Boolean dial = false; // call on iphone?
static const char *phoneLabel = NULL; // label of phone number to dial
static Boolean edit = false; // gui address book in edit mode?
static int listGroups = false; // list all groups?
static Boolean uid = false; // display/search records with uid?
static const char *uidStr = NULL; // uid to search for
static Preferred label = labelNone; // use which label?
static DisplayForm displayForm = standardDisplay; // default type of display
static SearchFields searchFields = searchAll; // default type of search
typedef struct
{
const char *label;
NSString *property;
int abType;
int labelWidth;
// int valueWidth;
union
{
id generic;
NSString *string;
ABMultiValue *multi;
NSDate *date;
} value;
} Field;
enum
{
firstname,
middlename,
lastname,
nickname,
maidenname,
finalname = maidenname, // mark final name
organization,
address,
phone,
email,
jobtitle,
url,
birthday,
related,
social,
note,
numFields,
};
static Field field[numFields];
enum
{
addressStreet,
addressCity,
addressState,
addressZIP,
addressCountry,
addressCountryCode,
numAddressKeys,
};
static NSString *addressKey[numAddressKeys];
/*
* Initialize the fields
*/
static void
init(Field *field, NSString **addressKey)
{
Field fieldInit[] =
{
{ "First Name", kABFirstNameProperty, kABStringProperty },
{ "Middle Name", kABMiddleNameProperty, kABStringProperty },
{ "Last Name", kABLastNameProperty, kABStringProperty },
{ "Nickname", kABNicknameProperty, kABStringProperty },
{ "Maiden Name", kABMaidenNameProperty, kABStringProperty },
{ "Organization", kABOrganizationProperty, kABStringProperty },
{ "Address", kABAddressProperty, kABMultiDictionaryProperty },
{ "Phone", kABPhoneProperty, kABMultiStringProperty },
{ "Email", kABEmailProperty, kABMultiStringProperty },
{ "Job Title", kABJobTitleProperty, kABStringProperty },
{ "URL", kABURLsProperty, kABMultiStringProperty },
{ "Birthday", kABBirthdayProperty, kABDateProperty },
{ "Related", kABRelatedNamesProperty, kABMultiStringProperty },
{ "Social", kABSocialProfileProperty, kABMultiDictionaryProperty },
{ "Note", kABNoteProperty, kABStringProperty },
};
for (unsigned int i=0; i<numElts(fieldInit); i++, field++)
{
*field = fieldInit[i];
field->labelWidth = (int)strlen(field->label);
}
NSString *addressInit[] =
{
kABAddressStreetKey,
kABAddressCityKey,
kABAddressStateKey,
kABAddressZIPKey,
kABAddressCountryKey,
kABAddressCountryCodeKey,
};
for (unsigned int i=0; i<numElts(addressInit); i++, addressKey++)
{
*addressKey = addressInit[i];
}
}
static const char *
str(NSString *ns)
{
const char *s = NULL;
if (ns)
{
s = [ns UTF8String];
}
return (s) ? s : "";
}
/*
* Allocate and return a cleaned up label
* Standard (Apple defined) labels come out of AB like this: _$!<Work>!$_
* User-defined labels are unadorned, e.g. Account
*/
static char *
cleanLabel(const char *label)
{
char *kind;
const char *start = index(label, '<');
const char *end = rindex(label, '>');
if (start && end && end > start)
{
kind = strndup(start+1, (size_t)(end-start-1));
} else {
kind = strdup(label);
}
return kind;
}
/*
* returns first value with matching label
*/
static id
getValueWithLabel(ABMultiValue *multi, NSString *labelWanted)
{
id result = nil;
unsigned long count = [multi count];
for (unsigned int i = 0; i < count; i++)
{
if ([labelWanted isEqualToString:[multi labelAtIndex:i]] == true)
{
result = [multi valueAtIndex:i];
break;
}
}
return result;
}
/*
* returns value of first entry whose label contains case-insensitive substring
*/
static id
getValueWithLabelSubstring(ABMultiValue *multi, NSString *labelWanted)
{
id result = nil;
unsigned long count = [multi count];
for (unsigned int i = 0; i < count; i++)
{
if ([[multi labelAtIndex:i]
rangeOfString: labelWanted
options: NSCaseInsensitiveSearch].location != NSNotFound)
{
result = [multi valueAtIndex:i];
break;
}
}
return result;
}
/*
* Format and return a formatted address
* FIXME: use formattedAddressFromDictionary
*/
static NSString *
formattedAddress(NSDictionary *value, bool url)
{
static char buffer[1024];
snprintf(buffer, sizeof(buffer), "%s, %s %s %s",
str([value objectForKey: kABAddressStreetKey]),
str([value objectForKey: kABAddressCityKey]),
str([value objectForKey: kABAddressStateKey]),
str([value objectForKey: kABAddressZIPKey]));
if (url) /* escape any spaces */
{
char *s = buffer;
while ((s = index(s, ' ')))
{
*s='+';
}
}
return [NSString stringWithUTF8String: buffer];
}
/*
* returns identifier for preferred label of property
*
* if preferred is none, return first match of primary, home, work
* else return first match of home or work as requested
*/
static id
getPreferredProperty(ABPerson *person, NSString *property, Preferred label)
{
ABMultiValue *multi = [person valueForProperty:property];
NSString *identifier = nil;
id value = nil;
switch (label)
{
case labelNone:
identifier = [multi primaryIdentifier];
if (identifier)
{
value = [multi valueForIdentifier:identifier];
break;
} // else fall through to home next
case labelHome:
value = getValueWithLabel(multi, kABHomeLabel);
// try "HomePage" also if property is URLs
if (!value && [property isEqualToString:kABURLsProperty])
{
value = getValueWithLabel(multi, kABHomePageLabel );
}
if (value)
{
break;
} // else fall through to work
case labelWork:
value = getValueWithLabel(multi, kABWorkLabel);
break;
}
return value;
}
/*
* Open the specified URL
*/
static void
openURL(NSString *url)
{
NSURL *nsurl = [NSURL URLWithString:url];
// stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
[[NSWorkspace sharedWorkspace] openURL:nsurl];
}
/*
* Call phone number with case-insenstive substring label on connected phone
*/
static void
callOnConnectedPhone(ABPerson *person, const char *label)
{
ABMultiValue *multi = [person valueForProperty:kABPhoneProperty];
NSString *phone = getValueWithLabelSubstring(multi,
[NSString stringWithCString:label
encoding: NSUTF8StringEncoding]);
if (phone)
{
openURL([NSString stringWithFormat:@"tel:%@", phone]);
}
else
{
fprintf(stderr, "Could not find a phone with label '%s'\n", label);
}
}
/*
* Open up a browser with the person's URL
*/
static void
openInBrowser(ABPerson *person, Preferred label)
{
NSString *url = getPreferredProperty(person, kABURLsProperty, label);
if (url)
{
openURL(url);
}
}
/*
* Open given mapping url
*/
static void
openInMappingProvider(ABPerson *person, Preferred label, const char *provider)
{
NSDictionary *address = getPreferredProperty(person, kABAddressProperty,
label);
if (address)
{
NSString *url = [NSString stringWithFormat:
@"http://maps.%@.com/maps?q=%@",
[NSString stringWithUTF8String: provider],
formattedAddress(address, true)];
openURL(url);
}
}
/*
* Open up a browser with the person's address in Google Maps
*/
static void
openInGoogleMapping(ABPerson *person, Preferred label)
{
openInMappingProvider(person, label, "google");
}
/*
* Open Maps application with the person's address mapped
*/
static void
openInMapping(ABPerson *person, Preferred label)
{
openInMappingProvider(person, label, "apple");
}
/*
* Open up the email application with a new message for person
*/
static void
openInEmail(ABPerson *person, Preferred label)
{
NSString *email = getPreferredProperty(person, kABEmailProperty, label);
if (email)
{
NSString *url = [NSString stringWithFormat:@"mailto:%@", email];
openURL(url);
}
}
/*
* Open up the Contacts application with the person displayed
* and optionally in edit mode
* Reference:
* /System/Library/Frameworks/AddressBook.framework/Versions/A/Headers/ABAddressBook.h
*/
static void
openInContacts(ABPerson *person, Boolean edit)
{
NSString *param = [NSString stringWithUTF8String: edit ? "?edit" : ""];
NSString *url = [NSString stringWithFormat:@"addressbook://%@%@",
[person uniqueId], param];
openURL(url);
}
/*
* Print a multi-line value, label for first line is already printed
*/
static void
printNote(int labelWidth, const char *note)
{
Boolean first = true;
size_t length, offset;
const char *end = note + strlen(note);
while (note < end)
{
if (!first)
{
printf("%*s: ", labelWidth, "");
}
length = strlen(note);
offset = strcspn(note, "\r\n");
printf("%.*s\n", (int)offset, note);
note += offset;
note++;
first = false;
}
}
static void
printField(Field *field, const char *label, int width, char *terminator,
bool abbrev)
{
unsigned long count;
switch (field->abType)
{
case kABStringProperty:
if (label) // if requested, label on 1st line only
{
printf("%*s: ", width, label);
}
if (field->property == kABNoteProperty) // multi-line string
{
printNote(width, str(field->value.string));
} else { // simple string
printf("%s%s", str(field->value.string), terminator);
}
break;
case kABDateProperty:
if (label) // if requested, label on 1st line only
{
printf("%*s: ", width, label);
}
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"EEEE, MMMM d, y"];
printf("%s%s", str([formatter stringFromDate:field->value.date]),
terminator);
break;
case kABMultiStringProperty:
count = [field->value.multi count];
for (unsigned int j = 0; j < count; j++)
{
const char *value = str([field->value.multi valueAtIndex:j]);
char const *kind = str([field->value.multi labelAtIndex:j]);
char *kind2 = cleanLabel(kind); // returns a dup
if (label) // if requested, label on 1st line only
{
printf("%*s: ", width, (j == 0) ? label : "");
}
printf("%s (%.*s)%s", value, abbrev ? 1 : -1, kind2, terminator);
free((void *)kind2);
}
break;
case kABMultiDictionaryProperty:
count = [field->value.multi count];
if (field->property == kABAddressProperty)
{
for (unsigned int j = 0; j < count; j++)
{
NSDictionary *value = [field->value.multi valueAtIndex:j];
const char *kind = str([field->value.multi labelAtIndex:j]);
char *kind2 = cleanLabel(kind); // returns a dup
if (label) // if requested, label on 1st line only
{
printf("%*s: ", width, (j == 0) ? label : "");
}
printf("%s, %s %s %s (%.*s)%s",
str([value objectForKey: kABAddressStreetKey]),
str([value objectForKey: kABAddressCityKey]),
str([value objectForKey: kABAddressStateKey]),
str([value objectForKey: kABAddressZIPKey]),
abbrev ? 1 : -1, kind2, terminator);
free((void *)kind2);
}
}
else if (field->property == kABSocialProfileProperty)
{
for (unsigned int j = 0; j < count; j++)
{
NSDictionary *value = [field->value.multi valueAtIndex:j];
if (label) // multiple values
{
printf("%*s: ", width,
str([value objectForKey: kABSocialProfileServiceKey]));
}
printf("%s%s",
str([value objectForKey: kABSocialProfileUsernameKey]),
terminator);
}
}
break;
default:
break;
}
}
/*
* Allocate and print a formatted name
* Uses nickname (if present) instead of first name
* Uses organization (if present) if none of nickname, first and last are present
*/
static void
printFormattedName(char *terminator)
{
int first = firstname;
if (field[nickname].value.generic)
{
first = nickname;
}
if (field[first].value.generic || field[lastname].value.generic)
{
printField(&field[first], NULL, 0, " ", true);
printField(&field[lastname], NULL, 0, terminator, true);
} else if (field[organization].value.generic)
{
printField(&field[organization], NULL, 0, terminator, true);
}
}
/*
* Display person in brief format
*/
static void
displayBrief(void)
{
NSString *phoneLabels[] =
{
kABPhoneMobileLabel,
kABPhoneHomeLabel,
kABPhoneWorkLabel
};
NSString *emailLabels[] =
{
kABEmailHomeLabel,
kABEmailWorkLabel
};
printFormattedName(" ");
// first of each phone type
for (unsigned int i=0; i<numElts(phoneLabels); i++)
{
NSString *s = getValueWithLabel(field[phone].value.multi,
phoneLabels[i]);
if (s)
{
const char *kind = cleanLabel(str(phoneLabels[i]));
printf("%s (%.1s) ", str(s), kind);
}
}
// first of each email type
for (unsigned int i=0; i<numElts(emailLabels); i++)
{
NSString *s = getValueWithLabel(field[email].value.multi,
emailLabels[i]);
if (s)
{
const char *kind = cleanLabel(str(emailLabels[i]));
printf("%s (%.1s) ", str(s), kind);
}
}
printf("\n");
}
static void
displayRaw(ABRecord *record)
{
printf("%s\n", str([record description]));
}
/*
* Display one group record
*/
static void
displayGroup(ABGroup *group, DisplayForm form)
{
if (form == rawDisplay)
{
displayRaw(group);
return;
}
NSString *name = [group valueForProperty:kABGroupNameProperty];
printf("%s", str(name));
if (form == briefDisplay)
{
printf("\n");
return;
}
NSArray *members = [group members];
unsigned long length = [members count];
printf(" (%lu member%s)\n", length, plural(length));
if (form == longDisplay)
{
NSEnumerator *membersEnum = [members objectEnumerator];
ABPerson *person;
while ((person = (ABPerson *)[membersEnum nextObject]))
{
for (unsigned int i=0; i<finalname; i++)
{
field[i].value.string = [person
valueForProperty:field[i].property];
}
printf("\t");
printFormattedName("\n");
}
return;
}
}
/*
* Display one person record
*/
static void
display(ABPerson *person, DisplayForm form)
{
if (form == rawDisplay)
{
displayRaw(person);
return;
}
/* retrieve all values and find widest label of non-null values */
int labelWidth = 0;
for (unsigned int i=0; i<numFields; i++)
{
if (form <= standardDisplay && i > email) // stop here for standard
{
break;
}
field[i].value.generic = [person valueForProperty:field[i].property];
int width = (form == standardDisplay && i <= finalname ) ?
strlen("Name") : field[i].labelWidth;
if (field[i].value.generic && width > labelWidth)
{
labelWidth = width;
}
}
/* if brief requested, print it and return */
if (form == briefDisplay)
{
displayBrief();
return;
}
/* print non-null fields */
for (unsigned int i=0; i<numFields; i++)
{
if (!field[i].value.generic) // skip if empty
{
continue;
}
if (form <= standardDisplay && i > email) // stop here for standard
{
break;
}
if (form <= standardDisplay && i <= finalname) // print formatted name
{
if (form != plainDisplay)
{
printf("%*s: ", labelWidth, "Name");
}
printFormattedName("\n");
i = finalname; // skip other name fields
}
else
{
printField(&field[i], form == plainDisplay ? NULL : field[i].label,
labelWidth, "\n", false);
}
}
if (uid)
{
const char *uidStr = str([person valueForProperty:kABUIDProperty]);
printf("%*s: %.*s\n", labelWidth, "UID",
(int)(rindex(uidStr, ':') - uidStr), uidStr);
}
printf("\n");
}
static NSArray *
search(ABAddressBook *book, int numTerms, char * const term[])
{
NSMutableArray *searchTerms = [NSMutableArray new];
// FIXME: add search for group
int fieldLimit = (searchFields == searchNames) ? finalname : numFields;
for (int i=0; i<numTerms; i++)
{
NSString *key = [NSString stringWithCString:term[i]
encoding: NSUTF8StringEncoding];
NSMutableArray *searchRecord = [NSMutableArray new];
/* look for term in name or all fields */
for (int j=0; j<fieldLimit; j++)
{
#if 1
[searchRecord addObject:
[ABPerson searchElementForProperty:field[j].property
label:nil /* use this to filter Home v. Work */
//label:kABAddressHomeLabel
key:nil
value:key
comparison:kABContainsSubStringCaseInsensitive]];
#else
switch (field[j].abType)
{
case kABStringProperty:
case kABMultiStringProperty: /* may differ for filtering */
[searchRecord addObject:
[ABPerson searchElementForProperty:field[j].property
label:nil /* use this to filter Home v. Work */
key:nil
value:key
comparison:kABContainsSubStringCaseInsensitive]];
break;
case kABDateProperty:
break;
case kABMultiDictionaryProperty:
// FIXME: assume MultiDictionary is Address (currently true)
// search on indiviual keys
break;
}
#endif
}
[searchTerms addObject: [ABSearchElement
searchElementForConjunction:kABSearchOr
children:searchRecord]];
}
/* if a UID is given, require it to match also */
if (uidStr)
{
[searchTerms addObject:
[ABPerson searchElementForProperty:kABUIDProperty
label:nil
key:nil
value: [NSString stringWithCString:uidStr
encoding: NSUTF8StringEncoding]
comparison:kABContainsSubStringCaseInsensitive]];
}
/* search all records for each term */
ABSearchElement *search = [ABSearchElement
searchElementForConjunction:kABSearchAnd
children:searchTerms];
return [book recordsMatchingSearchElement:search];
}
/*
* Returns a new array sorted by keys
*/
static NSArray *
sortBy(NSArray *unsorted, unsigned int numKeys, NSString *keys[])
{
NSMutableArray *descriptors = [NSMutableArray new];
for (unsigned int i=0; i<numKeys; i++)
{
[descriptors addObject: [[NSSortDescriptor alloc]
initWithKey:keys[i]
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)]];
}
return [unsorted sortedArrayUsingDescriptors:descriptors];
}
/*
search filters:
first F
first L
notes N
email M
city C
street S
limit n <arg>
interactive i
*/
/*
* Summarize program usage
*/
static const char *options = ":spblrnaghuCD:EGMUHW";
static struct option longopts[] =
{
{ "std", no_argument, NULL, 's' },
{ "brief", no_argument, NULL, 'b' },
{ "plain", no_argument, NULL, 'p' },
{ "long", no_argument, NULL, 'l' },
{ "raw", no_argument, NULL, 'r' },
{ "name", no_argument, NULL, 'n' },
{ "all", no_argument, NULL, 'a' },
// FIXME { "group", no_argument, NULL, 'g' },
{ "help", no_argument, NULL, 'h' },
{ "uid", optional_argument, NULL, 'u' },
{ "groups", no_argument, &listGroups, 1 },
{ "contacts", no_argument, NULL, 'C' },
{ "dial", required_argument, NULL, 'D' },
{ "email", no_argument, NULL, 'E' },
{ "google", no_argument, NULL, 'G' },
{ "maps", no_argument, NULL, 'M' },
{ "url", no_argument, NULL, 'U' },
{ "home", no_argument, NULL, 'H' },
{ "work", no_argument, NULL, 'W' },
{ NULL, 0, NULL, 0 }
};
static void __attribute__ ((noreturn))
usage(char *name)
{
static char *help[] = {
" -s, --std display records in standard form (default)",
" -p, --plain display records in plain (no labels) form",
" -b, --brief display records in brief form",
" -l, --long display records in long form",
" -r, --raw display records in raw form",
"",
" -a, --all search all Person fields (default)",
" -n, --name search name fields only",
// FIXME " -g, --group search group name only",
"",
" -h, --help this help",
" -u, --uid[=id] display unique ids; search for id if given",
"",
" --groups list all groups",
"",
" -C, --contacts open Contacts with person",
" -D, --dial=LABEL dial number with substring LABEL on connected phone",
" -E, --email open email application with message for person",
" -G, --google open google maps in browser to address of person",
" -M, --maps open Maps with address of person",
" -U, --url open browser with URL of person",
" -H, --home use 'home' values for gui",
" -W, --work use 'work' values for gui",
};
fprintf(stderr, "usage: %s [options] search term(s)\n", name);
for (unsigned i=0; i<numElts(help); i++)
{
fprintf(stderr, "%s\n", help[i]);
}
exit(0);
}
int main(int argc, char * const argv[])
{
@autoreleasepool
{
char *programName = argv[0];
int opt;
while ((opt = getopt_long(argc, argv, options, longopts, NULL)) >= 0)
{
if (opt == 0)
{
continue; // long opt only
}
switch (opt)
{
case 's': displayForm = standardDisplay; break;
case 'p': displayForm = plainDisplay; break;
case 'b': displayForm = briefDisplay; break;
case 'l': displayForm = longDisplay; break;
case 'r': displayForm = rawDisplay; break;
case 'n': searchFields = searchNames; break;
case 'g': searchFields = searchGroups; break;
case 'a': searchFields = searchAll; break;
case 'C': contactsGui = true; edit = false; break;
case 'D': dial = true; phoneLabel = optarg; break;
case 'E': emailGui = true; break;
case 'M': mapsGui = true; break;
case 'G': googleMapsGui = true; break;
case 'U': urlGui = true; break;
case 'H': label = labelHome; break;
case 'W': label = labelWork; break;
case 'u': uid = true; uidStr = optarg; break;
case 'h':
default:
usage(programName);
}
}
argc -= optind;
argv += optind;
if (argc < 1 && !uidStr && !listGroups)
{
usage(programName);
}