forked from ali-rantakari/icalBuddy
-
Notifications
You must be signed in to change notification settings - Fork 13
/
icalBuddyFunctions.m
743 lines (619 loc) · 26.6 KB
/
icalBuddyFunctions.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
// icalBuddy
//
// http://hasseg.org/icalBuddy
//
/*
The MIT License
Copyright (c) 2008-2011 Ali Rantakari
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#import <Foundation/Foundation.h>
#import "calendarStoreImport.h"
#import "icalBuddyFunctions.h"
#import "icalBuddyDefines.h"
#import "HGCLIUtils.h"
#import "HGDateFunctions.h"
#import "icalBuddyL10N.h"
// todo: the right place for these?
NSDate *now;
NSDate *today;
BOOL areWePrintingEvents(AppOptions *opts)
{
return (opts->output_is_eventsToday || opts->output_is_eventsNow || opts->output_is_eventsFromTo);
}
BOOL areWePrintingTasks(AppOptions *opts)
{
return (opts->output_is_uncompletedTasks || opts->output_is_undatedUncompletedTasks || opts->output_is_tasksDueBefore);
}
BOOL areWePrintingItems(AppOptions *opts)
{
return (areWePrintingEvents(opts) || areWePrintingTasks(opts));
}
BOOL areWePrintingAlsoPastEvents(AppOptions *opts)
{
return (opts->output_is_eventsFromTo);
}
NSArray *getEvents(AppOptions *opts, NSArray *calendars)
{
NSDate *dateRangeStart = nil;
NSDate *dateRangeEnd = nil;
// get start and end dates for predicate
if (opts->output_is_eventsToday)
{
dateRangeStart = today;
dateRangeEnd = dateForEndOfDay(now);
}
else if (opts->output_is_eventsNow)
{
dateRangeStart = now;
dateRangeEnd = now;
}
else if (opts->output_is_eventsFromTo)
{
dateRangeStart = dateFromUserInput(opts->eventsFrom, @"start date", NO);
dateRangeEnd = dateFromUserInput(opts->eventsTo, @"end date", YES);
if (dateRangeStart == nil || dateRangeEnd == nil)
{
PrintfErr(@"\n");
printDateFormatInfo();
return nil;
}
if ([dateRangeStart compare:dateRangeEnd] == NSOrderedDescending)
{
// start date occurs before end date --> swap them
NSDate *tempSwapDate = dateRangeStart;
dateRangeStart = dateRangeEnd;
dateRangeEnd = tempSwapDate;
}
}
NSCAssert((dateRangeStart != nil && dateRangeEnd != nil), @"start or end date is nil");
// expand end date if NUM in "eventsToday+NUM" is specified
if (opts->output_is_eventsToday)
{
NSRange arg_output_plusSymbolRange = [opts->output rangeOfString:@"+"];
if (arg_output_plusSymbolRange.location != NSNotFound)
{
NSInteger daysToAddToRange = [[opts->output substringFromIndex:(arg_output_plusSymbolRange.location+arg_output_plusSymbolRange.length)] integerValue];
dateRangeEnd = dateByAddingDays(dateRangeEnd, daysToAddToRange);
}
}
opts->startDate = ((opts->includeOnlyEventsFromNowOn) ? now : dateRangeStart);
opts->endDate = dateRangeEnd;
DebugPrintf(@"effective query start date: %@\n", opts->startDate);
DebugPrintf(@"effective query end date: %@\n", opts->endDate);
// make predicate for getting all events between start and end dates + use it to get the events
NSPredicate *eventsPredicate = [CALENDAR_STORE
eventPredicateWithStartDate:opts->startDate
endDate:opts->endDate
calendars:calendars
];
NSArray *ret = [[CALENDAR_STORE defaultCalendarStore] eventsWithPredicate:eventsPredicate];
// filter results
if (opts->excludeAllDayEvents)
ret = [ret filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"isAllDay == NO"]];
return ret;
}
NSArray *getTasks(AppOptions *opts, NSArray *calendars)
{
NSPredicate *tasksPredicate = nil;
if (opts->output_is_tasksDueBefore)
{
NSDate *dueBeforeDate = nil;
NSString *dueBeforeDateStr = [opts->output substringFromIndex:15]; // "tasksDueBefore:" has 15 chars
dueBeforeDate = dateFromUserInput(dueBeforeDateStr, @"due date", NO);
if (dueBeforeDate == nil)
{
PrintfErr(@"\n");
printDateFormatInfo();
return nil;
}
opts->dueBeforeDate = dueBeforeDate;
DebugPrintf(@"effective query 'due before' date: %@\n", dueBeforeDate);
tasksPredicate = [CALENDAR_STORE taskPredicateWithUncompletedTasksDueBefore:dueBeforeDate calendars:calendars];
}
else if (opts->output_is_uncompletedTasks)
{
tasksPredicate = [CALENDAR_STORE taskPredicateWithUncompletedTasks:calendars];
}
else if (opts->output_is_undatedUncompletedTasks)
{
tasksPredicate = [CALENDAR_STORE taskPredicateWithCalendars:calendars];
NSArray *allTasks = [[CALENDAR_STORE defaultCalendarStore] tasksWithPredicate:tasksPredicate];
return [allTasks filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:
@"isCompleted == NO && dueDate == nil"]];
}
else
return nil;
return [[CALENDAR_STORE defaultCalendarStore] tasksWithPredicate:tasksPredicate];
}
NSArray *getCalItems(AppOptions *opts)
{
NSArray *calendars = getCalendars(opts);
if (calendars.count == 0)
{
PrintfErr(@"error: No calendars.\n");
return nil;
}
BOOL printingEvents = areWePrintingEvents(opts);
BOOL printingTasks = areWePrintingTasks(opts);
if (printingEvents)
return getEvents(opts, calendars);
else if (printingTasks)
return getTasks(opts, calendars);
return nil;
}
// sort function for sorting tasks:
// - sort numerically by priority except treat CalPriorityNone (0) as a special case
// - if priorities match, sort tasks that are late from their due date to be first and then
// order alphabetically by title
NSInteger prioritySort(CalTask *task1, CalTask *task2, void *context)
{
if ([task1 priority] < [task2 priority])
{
if ([task1 priority] == CalPriorityNone)
return NSOrderedDescending;
else
return NSOrderedAscending;
}
else if ([task1 priority] > [task2 priority])
if ([task2 priority] == CalPriorityNone)
return NSOrderedAscending;
else
return NSOrderedDescending;
else
{
// check if one task is late and the other is not
BOOL task1late = NO;
BOOL task2late = NO;
if ([task1 dueDate] != nil &&
[now compare:[task1 dueDate]] == NSOrderedDescending
)
task1late = YES;
if ([task2 dueDate] != nil &&
[now compare:[task2 dueDate]] == NSOrderedDescending
)
task2late = YES;
if (task1late && !task2late)
return NSOrderedAscending;
else if (task2late && !task1late)
return NSOrderedDescending;
// neither task is, or both tasks are late -> order alphabetically by title
return [[task1 title] compare:[task2 title]];
}
}
NSArray *sortCalItems(AppOptions *opts, NSArray *calItems)
{
NSArray *retCalItems = nil;
BOOL printingTasks = areWePrintingTasks(opts);
if (printingTasks)
{
if (opts->sortTasksByDueDate || opts->sortTasksByDueDateAscending)
{
retCalItems = [calItems
sortedArrayUsingDescriptors:[NSArray
arrayWithObjects:
[[[NSSortDescriptor alloc] initWithKey:@"dueDate" ascending:opts->sortTasksByDueDateAscending] autorelease],
nil
]
];
if (opts->sortTasksByDueDateAscending)
{
// put tasks with no due date last
NSArray *tasksWithNoDueDate = [retCalItems
filteredArrayUsingPredicate:[NSPredicate
predicateWithFormat:@"dueDate == nil"
]
];
retCalItems = [retCalItems
filteredArrayUsingPredicate:[NSPredicate
predicateWithFormat:@"dueDate != nil"
]
];
retCalItems = [retCalItems arrayByAddingObjectsFromArray:tasksWithNoDueDate];
}
}
else
retCalItems = [calItems sortedArrayUsingFunction:prioritySort context:NULL];
}
return (retCalItems == nil) ? calItems : retCalItems;
}
CalItemPrintOption getPrintOptions(AppOptions *opts)
{
BOOL printingEvents = areWePrintingEvents(opts);
BOOL printingTasks = areWePrintingTasks(opts);
CalItemPrintOption printOptions = {NO,NO,NO,NO,NO,0,0};
// set default print options
if (printingEvents)
{
printOptions.singleDay = YES;
if (opts->noCalendarNames)
printOptions.calendarAgnostic = YES;
if (opts->output_is_eventsFromTo)
printOptions.singleDay = NO;
else if (opts->output_is_eventsToday)
{
NSRange arg_output_plusSymbolRange = [opts->output rangeOfString:@"+"];
if (arg_output_plusSymbolRange.location != NSNotFound)
printOptions.singleDay = NO;
}
}
else if (printingTasks)
{
if (opts->noCalendarNames)
printOptions.calendarAgnostic = YES;
if (opts->separateByPriority)
printOptions.priorityAgnostic = YES;
}
if (opts->noPropNames)
printOptions.withoutPropNames = YES;
if (opts->separateByCalendar)
{
printOptions.calendarColorsForSectionTitles = YES;
printOptions.calendarAgnostic = YES;
}
else if (opts->separateByDate)
printOptions.singleDay = YES;
printOptions.maxNumPrintedAttendees = opts->maxNumPrintedAttendees;
printOptions.maxNumNoteCharacters = opts->maxNumNoteCharacters;
return printOptions;
}
NSArray *putItemsUnderSections(AppOptions *opts, NSArray *calItems)
{
NSMutableArray *sections = nil;
BOOL printingEvents = areWePrintingEvents(opts);
BOOL printingTasks = areWePrintingTasks(opts);
BOOL printingAlsoPastEvents = areWePrintingAlsoPastEvents(opts);
if (opts->separateByCalendar)
{
NSArray *calendars = getCalendars(opts);
sections = [NSMutableArray arrayWithCapacity:[calendars count]];
for (CalCalendar *cal in calendars)
{
NSMutableArray *thisCalendarItems = [NSMutableArray arrayWithCapacity:((printingEvents)?[calItems count]:[calItems count])];
if (printingEvents)
[thisCalendarItems addObjectsFromArray:calItems];
else if (printingTasks)
[thisCalendarItems addObjectsFromArray:calItems];
[thisCalendarItems filterUsingPredicate:[NSPredicate predicateWithFormat:@"calendar.uid == %@", [cal uid]]];
if (thisCalendarItems != nil && [thisCalendarItems count] > 0)
{
PrintSection section = {[cal title], thisCalendarItems, nil};
[sections addObject:SECTION_TO_NSVALUE(section)];
}
}
}
else if (opts->separateByDate)
{
// keys: NSDates (representing *days* to use as sections),
// values: NSArrays of CalCalendarItems that match those days
NSMutableDictionary *allDays = [NSMutableDictionary dictionaryWithCapacity:[calItems count]];
if (printingEvents)
{
// fill allDays using event start dates' days and all spanned days thereafter
// if the event spans multiple days
for (CalEvent *anEvent in calItems)
{
// calculate anEvent's days span and limit it to the range of days we
// want displayed
NSUInteger anEventDaysSpan = getDayDiff([anEvent startDate], [anEvent endDate]);
// the previous method call returns day spans that are one day too long for
// all-day events so in those cases we'll subtract one
if ([anEvent isAllDay] && anEventDaysSpan > 0)
anEventDaysSpan--;
NSUInteger eventsDateRangeDaysSpan = getDayDiff(opts->startDate, opts->endDate);
NSUInteger rangeStartToAnEventStartDaysSpan = getDayDiff(opts->startDate, [anEvent startDate]);
NSUInteger daySpanLeftInRange = eventsDateRangeDaysSpan - rangeStartToAnEventStartDaysSpan;
NSUInteger anEventDaysSpanToConsider = MIN(daySpanLeftInRange, anEventDaysSpan);
NSDate *thisEventStartDate = [anEvent startDate];
NSDate *fullDaysStartDate = dateForStartOfDay(opts->startDate);
NSDate *fullDaysEndDate = dateForEndOfDay(opts->endDate);
for (NSUInteger i = 0; i <= anEventDaysSpanToConsider; i++)
{
NSDate *dayToAdd = dateForStartOfDay(dateByAddingDays(thisEventStartDate, i));
NSComparisonResult dayToAddToEndComparisonResult = [dayToAdd compare:fullDaysEndDate];
if (dayToAddToEndComparisonResult == NSOrderedDescending
|| dayToAddToEndComparisonResult == NSOrderedSame
)
break;
if ([dayToAdd compare:fullDaysStartDate] == NSOrderedAscending)
continue;
NSComparisonResult dayToAddToNowComparisonResult = [dayToAdd compare:today];
if (printingAlsoPastEvents
|| dayToAddToNowComparisonResult == NSOrderedDescending
|| dayToAddToNowComparisonResult == NSOrderedSame
|| datesRepresentSameDay(now, dayToAdd)
)
{
if (![[allDays allKeys] containsObject:dayToAdd])
[allDays setObject:[NSMutableArray arrayWithCapacity:20] forKey:dayToAdd];
NSMutableArray *dayToAddEvents = [allDays objectForKey:dayToAdd];
NSCAssert((dayToAddEvents != nil), @"dayToAddEvents is nil");
[dayToAddEvents addObject:anEvent];
}
}
}
}
else if (printingTasks)
{
// fill allDays using task due dates' days
for (CalTask *aTask in calItems)
{
id thisDayKey = nil;
if ([aTask dueDate] != nil)
{
NSDate *thisTaskDueDate = [aTask dueDate];
NSDate *thisDueDay = dateForStartOfDay(thisTaskDueDate);
thisDayKey = thisDueDay;
}
else
thisDayKey = [NSNull null]; // represents "no due date"
if (![[allDays allKeys] containsObject:thisDayKey])
[allDays setObject:[NSMutableArray arrayWithCapacity:20] forKey:thisDayKey];
NSMutableArray *thisDayTasks = [allDays objectForKey:thisDayKey];
NSCAssert((thisDayTasks != nil), @"thisDayTasks is nil");
[thisDayTasks addObject:aTask];
}
}
sections = [NSMutableArray arrayWithCapacity:[calItems count]];
// add current date to list if needed
if (opts->alwaysShowTodaysSection && [allDays objectForKey:today] == nil)
[allDays setObject:[NSMutableArray array] forKey:today];
// remove NSNull ("no due date") if it exists and sort the dates
NSMutableArray *allDaysArr = [NSMutableArray arrayWithCapacity:[[allDays allKeys] count]];
[allDaysArr addObjectsFromArray:[allDays allKeys]];
[allDaysArr removeObjectIdenticalTo:[NSNull null]];
[allDaysArr sortUsingSelector:@selector(compare:)];
if (opts->sectionsForEachDayInSpan)
{
// fill the day span we have so that all days have an entry
NSDate *earliestDate = nil;
NSDate *latestDate = nil;
if (opts->output_is_eventsFromTo || opts->output_is_eventsToday || opts->output_is_eventsNow)
{
earliestDate = dateForStartOfDay(opts->startDate);
latestDate = dateForStartOfDay(opts->endDate);
}
else if (opts->output_is_tasksDueBefore)
{
earliestDate = [allDaysArr objectAtIndex:0];
latestDate = dateForStartOfDay(opts->dueBeforeDate);
}
else if (opts->output_is_uncompletedTasks || opts->output_is_undatedUncompletedTasks)
{
earliestDate = [allDaysArr objectAtIndex:0];
latestDate = [allDaysArr lastObject];
}
else
{
PrintfErr(@"No case defined for given output arg.\n");
exit(1);
}
NSDate *iterDate = earliestDate;
do
{
if (![allDaysArr containsObject:iterDate])
[allDaysArr addObject:iterDate];
iterDate = dateByAddingDays(iterDate, 1);
}
while ([iterDate compare:latestDate] != NSOrderedDescending);
[allDaysArr sortUsingSelector:@selector(compare:)];
}
// reinsert NSNull ("no due date") at the bottom if needed
if (printingTasks && [allDays objectForKey:[NSNull null]] != nil)
[allDaysArr addObject:[NSNull null]];
for (id aDayKey in allDaysArr)
{
NSArray *thisSectionItems = [allDays objectForKey:aDayKey];
if (thisSectionItems == nil)
thisSectionItems = [NSArray array];
NSDate *thisSectionContextDay = nil;
if (printingEvents && [aDayKey isKindOfClass:[NSDate class]])
thisSectionContextDay = aDayKey;
NSString *thisSectionTitle = nil;
if ([aDayKey isKindOfClass:[NSDate class]])
thisSectionTitle = dateStr(aDayKey, ONLY_DATE);
else if ([aDayKey isEqual:[NSNull null]])
thisSectionTitle = strConcat(@"(", localizedStr(kL10nKeyNoDueDate), @")", nil);
PrintSection section = {thisSectionTitle, thisSectionItems, thisSectionContextDay};
[sections addObject:SECTION_TO_NSVALUE(section)];
}
}
else if (opts->separateByPriority && printingTasks)
{
sections = [NSMutableArray arrayWithCapacity:4];
// None = 0, High = 1, Medium = 5, Low = 9
CalPriority priorities[] = {CalPriorityHigh, CalPriorityMedium, CalPriorityLow, CalPriorityNone};
int len_priorities = 4;
for (int i = 0; i < len_priorities; i++)
{
CalPriority priority = priorities[i];
NSMutableArray *thisCalendarItems = [NSMutableArray arrayWithCapacity:[calItems count]];
for (CalTask *aTask in calItems)
{
if ([aTask priority] == priority)
[thisCalendarItems addObject:aTask];
}
if (0 < [thisCalendarItems count])
{
PrintSection section = {localizedPriorityTitle(priority), thisCalendarItems, nil};
[sections addObject:SECTION_TO_NSVALUE(section)];
}
}
}
return sections;
}
void filterCalendarsByNameOrUID(NSMutableArray *cals, AppOptions *opts)
{
if (opts->includeCals != nil)
[cals filterUsingPredicate:[NSPredicate predicateWithFormat:@"(uid IN %@) OR (title IN %@)", opts->includeCals, opts->includeCals]];
if (opts->excludeCals != nil)
[cals filterUsingPredicate:[NSPredicate predicateWithFormat:@"(NOT(uid IN %@)) AND (NOT(title IN %@))", opts->excludeCals, opts->excludeCals]];
}
NSArray *getCalendarStoreCalTypeValuesForUserProvidedValues(NSArray *userProvidedCalTypes)
{
NSMutableArray *ret = [NSMutableArray arrayWithCapacity:[userProvidedCalTypes count]];
for (NSString *userProvidedType in userProvidedCalTypes)
{
if ([userProvidedType caseInsensitiveCompare:kCalendarTypeBirthday] == NSOrderedSame)
[ret addObject:CalCalendarTypeBirthday];
else if ([userProvidedType caseInsensitiveCompare:kCalendarTypeCalDAV] == NSOrderedSame)
[ret addObject:CalCalendarTypeCalDAV];
else if ([userProvidedType caseInsensitiveCompare:kCalendarTypeiCloud] == NSOrderedSame)
[ret addObject:CalCalendarTypeCalDAV];
else if ([userProvidedType caseInsensitiveCompare:kCalendarTypeExchange] == NSOrderedSame)
[ret addObject:CalCalendarTypeExchange];
else if ([userProvidedType caseInsensitiveCompare:kCalendarTypeIMAP] == NSOrderedSame)
[ret addObject:CalCalendarTypeIMAP];
else if ([userProvidedType caseInsensitiveCompare:kCalendarTypeLocal] == NSOrderedSame)
[ret addObject:CalCalendarTypeLocal];
else if ([userProvidedType caseInsensitiveCompare:kCalendarTypeSubscription] == NSOrderedSame)
[ret addObject:CalCalendarTypeSubscription];
}
return ret;
}
void filterCalendarsByType(NSMutableArray *cals, AppOptions *opts)
{
if (opts->includeCalTypes != nil)
{
NSArray *includeActualCalTypes = getCalendarStoreCalTypeValuesForUserProvidedValues(opts->includeCalTypes);
[cals filterUsingPredicate:[NSPredicate predicateWithFormat:@"type IN %@", includeActualCalTypes]];
}
if (opts->excludeCalTypes != nil)
{
NSArray *excludeActualCalTypes = getCalendarStoreCalTypeValuesForUserProvidedValues(opts->excludeCalTypes);
[cals filterUsingPredicate:[NSPredicate predicateWithFormat:@"NOT(type IN %@)", excludeActualCalTypes]];
}
}
void filterCalendars(NSMutableArray *cals, AppOptions *opts)
{
if (opts->specificCalFilterPrecedesCalTypeFilter)
{
filterCalendarsByNameOrUID(cals, opts);
filterCalendarsByType(cals, opts);
}
else
{
filterCalendarsByType(cals, opts);
filterCalendarsByNameOrUID(cals, opts);
}
}
NSArray *getCalendars(AppOptions *opts)
{
NSMutableArray *calendars = [[[[[[CALENDAR_STORE alloc] init] autorelease] calendars] mutableCopy] autorelease];
filterCalendars(calendars, opts);
return calendars;
}
void printAvailableStringEncodings()
{
Printf(@"\nAvailable String encodings (you can use one of these\nas an argument to the --strEncoding option):\n\n");
const NSStringEncoding *availableEncoding = [NSString availableStringEncodings];
while(*availableEncoding != 0)
{
Printf(@"%@\n", [NSString localizedNameOfStringEncoding: *availableEncoding]);
availableEncoding++;
}
Printf(@"\n");
}
void openConfigFileInEditor(NSString *configFilePath, BOOL openInCLIEditor)
{
NSString *path = configFilePath;
if (path == nil)
path = [kConfigFilePath stringByExpandingTildeInPath];
BOOL configFileIsDir;
BOOL configFileExists = [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&configFileIsDir];
if (!configFileExists)
{
[kConfigFileStub writeToFile:path atomically:YES];
Printf(@"Configuration file did not exist; it has now been created.\n");
}
if (configFileIsDir)
{
PrintfErr(
@"Error: There seems to be a directory where the configuration\nfile should be: %@\nCan not open configuration file.\n",
path
);
return;
}
if (openInCLIEditor)
{
NSString *foundEditorPath = nil;
NSMutableArray *preferredEditors = [NSMutableArray arrayWithObjects:@"vim", @"vi", @"nano", @"pico", @"emacs", @"ed", nil];
NSString *pathEnvironmentVariable = [[[NSProcessInfo processInfo] environment] objectForKey:@"PATH"];
NSString *editorEnvironmentVariable = [[[NSProcessInfo processInfo] environment] objectForKey:@"EDITOR"];
if (editorEnvironmentVariable != nil)
{
if ([[NSFileManager defaultManager] isExecutableFileAtPath:editorEnvironmentVariable])
foundEditorPath = editorEnvironmentVariable;
else
{
[preferredEditors removeObject:[editorEnvironmentVariable lastPathComponent]];
[preferredEditors insertObject:[editorEnvironmentVariable lastPathComponent] atIndex:0];
}
}
if (foundEditorPath == nil && pathEnvironmentVariable != nil)
{
NSArray *separatePaths = [pathEnvironmentVariable componentsSeparatedByString:@":"];
NSString *thisFullEditorPathCandidate;
NSString *thisEditor;
for (thisEditor in preferredEditors)
{
NSString *thisPath;
for (thisPath in separatePaths)
{
thisFullEditorPathCandidate = strConcat(thisPath, @"/", thisEditor, nil);
if ([[NSFileManager defaultManager] isExecutableFileAtPath:thisFullEditorPathCandidate])
{
foundEditorPath = thisFullEditorPathCandidate;
break;
}
}
if (foundEditorPath != nil)
break;
}
}
if (foundEditorPath != nil)
{
Printf(
@"Opening config file for editing with %@ -- press\nany key to continue or Ctrl-C to cancel.\n",
foundEditorPath
);
if (system("read") == 0)
system([strConcat(@"'", foundEditorPath, @"' '", path, @"'", nil) UTF8String]);
}
else
{
PrintfErr(
@"Error: Can not find or execute any of the following\neditors in your $PATH: %@\n",
[preferredEditors componentsJoinedByString:@", "]
);
}
}
else // GUI editor
{
if ([[NSWorkspace sharedWorkspace] fullPathForApplication:kPropertyListEditorAppName] != nil)
{
Printf(@"Opening configuration file with the Property List\nEditor application.\n");
[[NSWorkspace sharedWorkspace] openFile:path withApplication:kPropertyListEditorAppName];
}
else
{
Printf(@"Opening configuration file with the default application\nassociated with the property list type.\n");
[[NSWorkspace sharedWorkspace] openFile:path];
}
}
}