]> git.saurik.com Git - cydia.git/blame_incremental - MobileCydia.mm
Objective-C seriously didn't notice my mistake :/.
[cydia.git] / MobileCydia.mm
... / ...
CommitLineData
1/* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2015 Jay Freeman (saurik)
3*/
4
5/* GNU General Public License, Version 3 {{{ */
6/*
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
11 *
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
19**/
20/* }}} */
21
22// XXX: wtf/FastMalloc.h... wtf?
23#define USE_SYSTEM_MALLOC 1
24
25/* #include Directives {{{ */
26#include "CyteKit/UCPlatform.h"
27#include "CyteKit/Localize.h"
28
29#include <unicode/ustring.h>
30#include <unicode/utrans.h>
31
32#include <objc/objc.h>
33#include <objc/runtime.h>
34
35#include <CoreGraphics/CoreGraphics.h>
36#include <Foundation/Foundation.h>
37
38#if 0
39#define DEPLOYMENT_TARGET_MACOSX 1
40#define CF_BUILDING_CF 1
41#include <CoreFoundation/CFInternal.h>
42#endif
43
44#include <CoreFoundation/CFUniChar.h>
45
46#include <SystemConfiguration/SystemConfiguration.h>
47
48#include <UIKit/UIKit.h>
49#include "iPhonePrivate.h"
50
51#include <QuartzCore/CALayer.h>
52
53#include <WebCore/WebCoreThread.h>
54
55#include <algorithm>
56#include <fstream>
57#include <iomanip>
58#include <set>
59#include <sstream>
60#include <string>
61
62#include "fdstream.hpp"
63
64#undef ABS
65
66#include "apt.h"
67#include <apt-pkg/acquire.h>
68#include <apt-pkg/acquire-item.h>
69#include <apt-pkg/algorithms.h>
70#include <apt-pkg/cachefile.h>
71#include <apt-pkg/clean.h>
72#include <apt-pkg/configuration.h>
73#include <apt-pkg/debindexfile.h>
74#include <apt-pkg/debmetaindex.h>
75#include <apt-pkg/error.h>
76#include <apt-pkg/init.h>
77#include <apt-pkg/mmap.h>
78#include <apt-pkg/pkgrecords.h>
79#include <apt-pkg/sha1.h>
80#include <apt-pkg/sourcelist.h>
81#include <apt-pkg/sptr.h>
82#include <apt-pkg/strutl.h>
83#include <apt-pkg/tagfile.h>
84
85#include <sys/types.h>
86#include <sys/stat.h>
87#include <sys/sysctl.h>
88#include <sys/param.h>
89#include <sys/mount.h>
90#include <sys/reboot.h>
91
92#include <dirent.h>
93#include <fcntl.h>
94#include <notify.h>
95#include <dlfcn.h>
96
97extern "C" {
98#include <mach-o/nlist.h>
99}
100
101#include <cstdio>
102#include <cstdlib>
103#include <cstring>
104
105#include <errno.h>
106
107#include <Cytore.hpp>
108#include "Sources.h"
109
110#include "Substrate.hpp"
111#include "Menes/Menes.h"
112
113#include "CyteKit/CyteKit.h"
114#include "CyteKit/RegEx.hpp"
115
116#include "Cydia/MIMEAddress.h"
117#include "Cydia/LoadingViewController.h"
118#include "Cydia/ProgressEvent.h"
119/* }}} */
120
121/* Profiler {{{ */
122struct timeval _ltv;
123bool _itv;
124
125#define _timestamp ({ \
126 struct timeval tv; \
127 gettimeofday(&tv, NULL); \
128 tv.tv_sec * 1000000 + tv.tv_usec; \
129})
130
131typedef std::vector<class ProfileTime *> TimeList;
132TimeList times_;
133
134class ProfileTime {
135 private:
136 const char *name_;
137 uint64_t total_;
138 uint64_t count_;
139
140 public:
141 ProfileTime(const char *name) :
142 name_(name),
143 total_(0)
144 {
145 times_.push_back(this);
146 }
147
148 void AddTime(uint64_t time) {
149 total_ += time;
150 ++count_;
151 }
152
153 void Print() {
154 if (total_ != 0)
155 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
156 total_ = 0;
157 count_ = 0;
158 }
159};
160
161class ProfileTimer {
162 private:
163 ProfileTime &time_;
164 uint64_t start_;
165
166 public:
167 ProfileTimer(ProfileTime &time) :
168 time_(time),
169 start_(_timestamp)
170 {
171 }
172
173 ~ProfileTimer() {
174 time_.AddTime(_timestamp - start_);
175 }
176};
177
178void PrintTimes() {
179 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
180 (*i)->Print();
181 std::cerr << "========" << std::endl;
182}
183
184#define _profile(name) { \
185 static ProfileTime name(#name); \
186 ProfileTimer _ ## name(name);
187
188#define _end }
189/* }}} */
190
191extern NSString *Cydia_;
192
193#define lprintf(args...) fprintf(stderr, args)
194
195#define ForRelease 1
196#define TraceLogging (1 && !ForRelease)
197#define HistogramInsertionSort (0 && !ForRelease)
198#define ProfileTimes (0 && !ForRelease)
199#define ForSaurik (0 && !ForRelease)
200#define LogBrowser (0 && !ForRelease)
201#define TrackResize (0 && !ForRelease)
202#define ManualRefresh (1 && !ForRelease)
203#define ShowInternals (0 && !ForRelease)
204#define AlwaysReload (0 && !ForRelease)
205
206#if !TraceLogging
207#undef _trace
208#define _trace(args...)
209#endif
210
211#if !ProfileTimes
212#undef _profile
213#define _profile(name) {
214#undef _end
215#define _end }
216#define PrintTimes() do {} while (false)
217#endif
218
219// Hash Functions/Structures {{{
220extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
221
222union SplitHash {
223 uint32_t u32;
224 uint16_t u16[2];
225};
226// }}}
227
228static NSString *Colon_;
229NSString *Elision_;
230static NSString *Error_;
231static NSString *Warning_;
232
233static void (*$SBSSetInterceptsMenuButtonForever)(bool);
234static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
235
236static CFStringRef (*$MGCopyAnswer)(CFStringRef);
237
238static NSString *UniqueIdentifier(UIDevice *device = nil) {
239 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
240 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
241 else
242 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
243}
244
245static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
246
247static _finline NSString *CydiaURL(NSString *path) {
248 char page[26];
249 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
250 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
251 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
252 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
253 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
254 page[25] = '\0';
255 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
256}
257
258static NSString *ShellEscape(NSString *value) {
259 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
260}
261
262static _finline void UpdateExternalStatus(uint64_t newStatus) {
263 int notify_token;
264 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
265 notify_set_state(notify_token, newStatus);
266 notify_cancel(notify_token);
267 }
268 notify_post("com.saurik.Cydia.status");
269}
270
271/* NSForcedOrderingSearch doesn't work on the iPhone */
272static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
273static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
274static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
275
276/* Insertion Sort {{{ */
277
278template <typename Type_>
279size_t CFBSearch_(const Type_ &element, const void *list, size_t count, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
280 const char *ptr = (const char *)list;
281 while (0 < count) {
282 size_t half = count / 2;
283 const char *probe = ptr + sizeof(Type_) * half;
284 CFComparisonResult cr = comparator(element, * (const Type_ *) probe, context);
285 if (0 == cr) return (probe - (const char *)list) / sizeof(Type_);
286 ptr = (cr < 0) ? ptr : probe + sizeof(Type_);
287 count = (cr < 0) ? half : (half + (count & 1) - 1);
288 }
289 return (ptr - (const char *)list) / sizeof(Type_);
290}
291
292template <typename Type_>
293void CYArrayInsertionSortValues(Type_ *values, size_t length, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
294 if (length == 0)
295 return;
296
297#if HistogramInsertionSort > 0
298 uint32_t total(0), *offsets(new uint32_t[length]);
299#endif
300
301 for (size_t index(1); index != length; ++index) {
302 Type_ value(values[index]);
303#if 0
304 size_t correct(CFBSearch_(value, values, index, comparator, context));
305#else
306 size_t correct(index);
307 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
308#if HistogramInsertionSort > 1
309 NSLog(@"%@ < %@", value, values[correct - 1]);
310#endif
311 if (--correct == 0)
312 break;
313 if (index - correct >= 8) {
314 correct = CFBSearch_(value, values, correct, comparator, context);
315 break;
316 }
317 }
318#endif
319 if (correct != index) {
320 size_t offset(index - correct);
321#if HistogramInsertionSort
322 total += offset;
323 ++offsets[offset];
324 if (offset > 10)
325 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
326#endif
327 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
328 values[correct] = value;
329 }
330 }
331
332#if HistogramInsertionSort > 0
333 for (size_t index(0); index != range.length; ++index)
334 if (offsets[index] != 0)
335 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
336 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
337 delete [] offsets;
338#endif
339}
340
341/* }}} */
342
343/* Cydia NSString Additions {{{ */
344@interface NSString (Cydia)
345- (NSComparisonResult) compareByPath:(NSString *)other;
346- (NSString *) stringByAddingPercentEscapesIncludingReserved;
347@end
348
349@implementation NSString (Cydia)
350
351- (NSComparisonResult) compareByPath:(NSString *)other {
352 NSString *prefix = [self commonPrefixWithString:other options:0];
353 size_t length = [prefix length];
354
355 NSRange lrange = NSMakeRange(length, [self length] - length);
356 NSRange rrange = NSMakeRange(length, [other length] - length);
357
358 lrange = [self rangeOfString:@"/" options:0 range:lrange];
359 rrange = [other rangeOfString:@"/" options:0 range:rrange];
360
361 NSComparisonResult value;
362
363 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
364 value = NSOrderedSame;
365 else if (lrange.location == NSNotFound)
366 value = NSOrderedAscending;
367 else if (rrange.location == NSNotFound)
368 value = NSOrderedDescending;
369 else
370 value = NSOrderedSame;
371
372 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
373 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
374 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
375 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
376
377 NSComparisonResult result = [lpath compare:rpath];
378 return result == NSOrderedSame ? value : result;
379}
380
381- (NSString *) stringByAddingPercentEscapesIncludingReserved {
382 return [(id)CFURLCreateStringByAddingPercentEscapes(
383 kCFAllocatorDefault,
384 (CFStringRef) self,
385 NULL,
386 CFSTR(";/?:@&=+$,"),
387 kCFStringEncodingUTF8
388 ) autorelease];
389}
390
391@end
392/* }}} */
393
394/* C++ NSString Wrapper Cache {{{ */
395static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
396 return size == 0 ? NULL :
397 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
398 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
399}
400
401static _finline CFStringRef CYStringCreate(const std::string &data) {
402 return CYStringCreate(data.data(), data.size());
403}
404
405static _finline CFStringRef CYStringCreate(const char *data) {
406 return CYStringCreate(data, strlen(data));
407}
408
409class CYString {
410 private:
411 char *data_;
412 size_t size_;
413 CFStringRef cache_;
414
415 _finline void clear_() {
416 if (cache_ != NULL) {
417 CFRelease(cache_);
418 cache_ = NULL;
419 }
420 }
421
422 public:
423 _finline bool empty() const {
424 return size_ == 0;
425 }
426
427 _finline size_t size() const {
428 return size_;
429 }
430
431 _finline char *data() const {
432 return data_;
433 }
434
435 _finline void clear() {
436 size_ = 0;
437 clear_();
438 }
439
440 _finline CYString() :
441 data_(0),
442 size_(0),
443 cache_(NULL)
444 {
445 }
446
447 _finline ~CYString() {
448 clear_();
449 }
450
451 void operator =(const CYString &rhs) {
452 data_ = rhs.data_;
453 size_ = rhs.size_;
454
455 if (rhs.cache_ == nil)
456 cache_ = NULL;
457 else
458 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
459 }
460
461 void copy(CYPool *pool) {
462 char *temp(pool->malloc<char>(size_ + 1));
463 memcpy(temp, data_, size_);
464 temp[size_] = '\0';
465 data_ = temp;
466 }
467
468 void set(CYPool *pool, const char *data, size_t size) {
469 if (size == 0)
470 clear();
471 else {
472 clear_();
473
474 data_ = const_cast<char *>(data);
475 size_ = size;
476
477 if (pool != NULL)
478 copy(pool);
479 }
480 }
481
482 _finline void set(CYPool *pool, const char *data) {
483 set(pool, data, data == NULL ? 0 : strlen(data));
484 }
485
486 _finline void set(CYPool *pool, const std::string &rhs) {
487 set(pool, rhs.data(), rhs.size());
488 }
489
490 bool operator ==(const CYString &rhs) const {
491 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
492 }
493
494 _finline operator CFStringRef() {
495 if (cache_ == NULL)
496 cache_ = CYStringCreate(data_, size_);
497 return cache_;
498 }
499
500 _finline operator id() {
501 return (NSString *) static_cast<CFStringRef>(*this);
502 }
503
504 _finline operator const char *() {
505 return reinterpret_cast<const char *>(data_);
506 }
507};
508/* }}} */
509/* C++ NSString Algorithm Adapters {{{ */
510extern "C" {
511 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
512}
513
514struct NSStringMapHash :
515 std::unary_function<NSString *, size_t>
516{
517 _finline size_t operator ()(NSString *value) const {
518 return CFStringHashNSString((CFStringRef) value);
519 }
520};
521
522struct NSStringMapLess :
523 std::binary_function<NSString *, NSString *, bool>
524{
525 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
526 return [lhs compare:rhs] == NSOrderedAscending;
527 }
528};
529
530struct NSStringMapEqual :
531 std::binary_function<NSString *, NSString *, bool>
532{
533 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
534 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
535 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
536 //[lhs isEqualToString:rhs];
537 }
538};
539/* }}} */
540
541/* CoreGraphics Primitives {{{ */
542class CYColor {
543 private:
544 CGColorRef color_;
545
546 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
547 CGFloat color[] = {red, green, blue, alpha};
548 return CGColorCreate(space, color);
549 }
550
551 public:
552 CYColor() :
553 color_(NULL)
554 {
555 }
556
557 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
558 color_(Create_(space, red, green, blue, alpha))
559 {
560 Set(space, red, green, blue, alpha);
561 }
562
563 void Clear() {
564 if (color_ != NULL)
565 CGColorRelease(color_);
566 }
567
568 ~CYColor() {
569 Clear();
570 }
571
572 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
573 Clear();
574 color_ = Create_(space, red, green, blue, alpha);
575 }
576
577 operator CGColorRef() {
578 return color_;
579 }
580};
581/* }}} */
582
583/* Random Global Variables {{{ */
584static int PulseInterval_ = 500000;
585
586static const NSString *UI_;
587
588static int Finish_;
589static bool RestartSubstrate_;
590static NSArray *Finishes_;
591
592#define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
593#define NotifyConfig_ "/etc/notify.conf"
594
595static bool Queuing_;
596
597static CYColor Blue_;
598static CYColor Blueish_;
599static CYColor Black_;
600static CYColor Folder_;
601static CYColor Off_;
602static CYColor White_;
603static CYColor Gray_;
604static CYColor Green_;
605static CYColor Purple_;
606static CYColor Purplish_;
607
608static UIColor *InstallingColor_;
609static UIColor *RemovingColor_;
610
611static NSString *App_;
612
613static BOOL Advanced_;
614static BOOL Ignored_;
615
616static _H<UIFont> Font12_;
617static _H<UIFont> Font12Bold_;
618static _H<UIFont> Font14_;
619static _H<UIFont> Font18_;
620static _H<UIFont> Font18Bold_;
621static _H<UIFont> Font22Bold_;
622
623static _H<NSString> UniqueID_;
624
625static _H<NSLocale> CollationLocale_;
626static _H<NSArray> CollationThumbs_;
627static std::vector<NSInteger> CollationOffset_;
628static _H<NSArray> CollationTitles_;
629static _H<NSArray> CollationStarts_;
630static UTransliterator *CollationTransl_;
631//static Function<NSString *, NSString *> CollationModify_;
632
633typedef std::basic_string<UChar> ustring;
634static ustring CollationString_;
635
636#define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
637#define UC ustring &str(*reinterpret_cast<ustring *>(rep))
638static struct UReplaceableCallbacks CollationUCalls_ = {
639 .length = [](const UReplaceable *rep) -> int32_t { CUC;
640 return str.size();
641 },
642
643 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
644 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
645 if (offset >= str.size())
646 return 0xffff;
647 return str[offset];
648 },
649
650 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
651 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
652 if (offset >= str.size())
653 return 0xffff;
654 UChar32 c;
655 U16_GET(str.data(), 0, offset, str.size(), c);
656 return c;
657 },
658
659 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
660 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
661 str.replace(start, limit - start, text, length);
662 },
663
664 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
665 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
666 str.copy(dst, limit - start, start);
667 },
668
669 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
670 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
671 str.replace(dest, 0, str, start, limit - start);
672 },
673};
674
675static CFLocaleRef Locale_;
676static NSArray *Languages_;
677static CGColorSpaceRef space_;
678
679#define CacheState_ Cache("CacheState.plist")
680#define SavedState_ Cache("SavedState.plist")
681
682static NSDictionary *SectionMap_;
683static _H<NSDate> Backgrounded_;
684static _transient NSMutableDictionary *Values_;
685static _transient NSMutableDictionary *Sections_;
686_H<NSMutableDictionary> Sources_;
687static _transient NSNumber *Version_;
688static time_t now_;
689
690static _H<NSMutableDictionary> SessionData_;
691static _H<NSMutableSet> BridgedHosts_;
692static _H<NSMutableSet> InsecureHosts_;
693
694static NSString *kCydiaProgressEventTypeError = @"Error";
695static NSString *kCydiaProgressEventTypeInformation = @"Information";
696static NSString *kCydiaProgressEventTypeStatus = @"Status";
697static NSString *kCydiaProgressEventTypeWarning = @"Warning";
698/* }}} */
699
700/* Display Helpers {{{ */
701static _finline const char *StripVersion_(const char *version) {
702 const char *colon(strchr(version, ':'));
703 return colon == NULL ? version : colon + 1;
704}
705
706NSString *LocalizeSection(NSString *section) {
707 static RegEx title_r("(.*?) \\((.*)\\)");
708 if (title_r(section)) {
709 NSString *parent(title_r[1]);
710 NSString *child(title_r[2]);
711
712 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
713 LocalizeSection(parent),
714 LocalizeSection(child)
715 ];
716 }
717
718 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
719}
720
721NSString *Simplify(NSString *title) {
722 const char *data = [title UTF8String];
723 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
724
725 static RegEx square_r("\\[(.*)\\]");
726 if (square_r(data, size))
727 return Simplify(square_r[1]);
728
729 static RegEx paren_r("\\((.*)\\)");
730 if (paren_r(data, size))
731 return Simplify(paren_r[1]);
732
733 static RegEx title_r("(.*?) \\((.*)\\)");
734 if (title_r(data, size))
735 return Simplify(title_r[1]);
736
737 return title;
738}
739/* }}} */
740
741bool isSectionVisible(NSString *section) {
742 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
743 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
744 return hidden == nil || ![hidden boolValue];
745}
746
747static NSString *VerifySource(NSString *href) {
748 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
749 if (!href_r(href)) {
750 [[[[UIAlertView alloc]
751 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
752 message:UCLocalize("INVALID_URL_EX")
753 delegate:nil
754 cancelButtonTitle:UCLocalize("OK")
755 otherButtonTitles:nil
756 ] autorelease] show];
757
758 return nil;
759 }
760
761 if (![href hasSuffix:@"/"])
762 href = [href stringByAppendingString:@"/"];
763 return href;
764}
765
766@class Cydia;
767
768/* Delegate Prototypes {{{ */
769@class Package;
770@class Source;
771@class CydiaProgressEvent;
772
773@protocol DatabaseDelegate
774- (void) repairWithSelector:(SEL)selector;
775- (void) setConfigurationData:(NSString *)data;
776- (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
777@end
778
779@class CYPackageController;
780
781@protocol SourceDelegate
782- (void) setFetch:(NSNumber *)fetch;
783@end
784
785@protocol FetchDelegate
786- (bool) isSourceCancelled;
787- (void) startSourceFetch:(NSString *)uri;
788- (void) stopSourceFetch:(NSString *)uri;
789@end
790
791@protocol CydiaDelegate
792- (void) returnToCydia;
793- (void) saveState;
794- (void) retainNetworkActivityIndicator;
795- (void) releaseNetworkActivityIndicator;
796- (void) clearPackage:(Package *)package;
797- (void) installPackage:(Package *)package;
798- (void) installPackages:(NSArray *)packages;
799- (void) removePackage:(Package *)package;
800- (void) beginUpdate;
801- (BOOL) updating;
802- (bool) requestUpdate;
803- (void) distUpgrade;
804- (void) loadData;
805- (void) updateData;
806- (void) _saveConfig;
807- (void) syncData;
808- (void) addSource:(NSDictionary *)source;
809- (BOOL) addTrivialSource:(NSString *)href;
810- (UIProgressHUD *) addProgressHUD;
811- (void) removeProgressHUD:(UIProgressHUD *)hud;
812- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
813- (void) reloadDataWithInvocation:(NSInvocation *)invocation;
814@end
815/* }}} */
816
817/* CancelStatus {{{ */
818class CancelStatus :
819 public pkgAcquireStatus
820{
821 private:
822 bool cancelled_;
823
824 public:
825 CancelStatus() :
826 cancelled_(false)
827 {
828 }
829
830 virtual bool MediaChange(std::string media, std::string drive) {
831 return false;
832 }
833
834 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
835 Done(desc);
836 }
837
838 virtual bool Pulse_(pkgAcquire *Owner) = 0;
839
840 virtual bool Pulse(pkgAcquire *Owner) {
841 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
842 return true;
843 else {
844 cancelled_ = true;
845 return false;
846 }
847 }
848
849 _finline bool WasCancelled() const {
850 return cancelled_;
851 }
852};
853/* }}} */
854/* DelegateStatus {{{ */
855class CydiaStatus :
856 public CancelStatus
857{
858 private:
859 _transient NSObject<ProgressDelegate> *delegate_;
860
861 public:
862 CydiaStatus() :
863 delegate_(nil)
864 {
865 }
866
867 void setDelegate(NSObject<ProgressDelegate> *delegate) {
868 delegate_ = delegate;
869 }
870
871 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
872 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
873 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
874 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
875 }
876
877 virtual void Done(pkgAcquire::ItemDesc &desc) {
878 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
879 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
880 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
881 }
882
883 virtual void Fail(pkgAcquire::ItemDesc &desc) {
884 if (
885 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
886 desc.Owner->Status == pkgAcquire::Item::StatDone
887 )
888 return;
889
890 std::string &error(desc.Owner->ErrorText);
891 if (error.empty())
892 return;
893
894 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
895 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
896 }
897
898 virtual bool Pulse_(pkgAcquire *Owner) {
899 double percent(
900 double(CurrentBytes + CurrentItems) /
901 double(TotalBytes + TotalItems)
902 );
903
904 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
905 [NSNumber numberWithDouble:percent], @"Percent",
906
907 [NSNumber numberWithDouble:CurrentBytes], @"Current",
908 [NSNumber numberWithDouble:TotalBytes], @"Total",
909 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
910 nil] waitUntilDone:YES];
911
912 return ![delegate_ isProgressCancelled];
913 }
914
915 virtual void Start() {
916 pkgAcquireStatus::Start();
917 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
918 }
919
920 virtual void Stop() {
921 pkgAcquireStatus::Stop();
922 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
923 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
924 }
925};
926/* }}} */
927/* Database Interface {{{ */
928typedef std::map< unsigned long, _H<Source> > SourceMap;
929
930@interface Database : NSObject {
931 NSZone *zone_;
932 CYPool pool_;
933
934 unsigned era_;
935 _H<NSDate> delock_;
936
937 pkgCacheFile cache_;
938 pkgDepCache::Policy *policy_;
939 pkgRecords *records_;
940 pkgProblemResolver *resolver_;
941 pkgAcquire *fetcher_;
942 FileFd *lock_;
943 SPtr<pkgPackageManager> manager_;
944 pkgSourceList *list_;
945
946 SourceMap sourceMap_;
947 _H<NSMutableArray> sourceList_;
948
949 _H<NSArray> packages_;
950
951 _transient NSObject<DatabaseDelegate> *delegate_;
952 _transient NSObject<ProgressDelegate> *progress_;
953
954 CydiaStatus status_;
955
956 int cydiafd_;
957 int statusfd_;
958 FILE *input_;
959
960 std::map<const char *, _H<NSString> > sections_;
961}
962
963+ (Database *) sharedInstance;
964- (unsigned) era;
965- (bool) hasPackages;
966
967- (void) _readCydia:(NSNumber *)fd;
968- (void) _readStatus:(NSNumber *)fd;
969- (void) _readOutput:(NSNumber *)fd;
970
971- (FILE *) input;
972
973- (Package *) packageWithName:(NSString *)name;
974
975- (pkgCacheFile &) cache;
976- (pkgDepCache::Policy *) policy;
977- (pkgRecords *) records;
978- (pkgProblemResolver *) resolver;
979- (pkgAcquire &) fetcher;
980- (pkgSourceList &) list;
981- (NSArray *) packages;
982- (NSArray *) sources;
983- (Source *) sourceWithKey:(NSString *)key;
984- (void) reloadDataWithInvocation:(NSInvocation *)invocation;
985
986- (void) configure;
987- (bool) prepare;
988- (void) perform;
989- (bool) upgrade;
990- (void) update;
991
992- (void) updateWithStatus:(CancelStatus &)status;
993
994- (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
995
996- (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
997- (NSObject<ProgressDelegate> *) progressDelegate;
998
999- (Source *) getSource:(pkgCache::PkgFileIterator)file;
1000- (void) setFetch:(bool)fetch forURI:(const char *)uri;
1001- (void) resetFetch;
1002
1003- (NSString *) mappedSectionForPointer:(const char *)pointer;
1004
1005@end
1006/* }}} */
1007/* SourceStatus {{{ */
1008class SourceStatus :
1009 public CancelStatus
1010{
1011 private:
1012 _transient NSObject<FetchDelegate> *delegate_;
1013 _transient Database *database_;
1014 std::set<std::string> fetches_;
1015
1016 public:
1017 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1018 delegate_(delegate),
1019 database_(database)
1020 {
1021 }
1022
1023 void Set(bool fetch, const std::string &uri) {
1024 if (fetch) {
1025 if (!fetches_.insert(uri).second)
1026 return;
1027 } else {
1028 if (fetches_.erase(uri) == 0)
1029 return;
1030 }
1031
1032 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1033
1034 auto slash(uri.rfind('/'));
1035 if (slash != std::string::npos)
1036 [database_ setFetch:fetch forURI:uri.substr(0, slash).c_str()];
1037 }
1038
1039 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1040 /*unsigned long ID(fetch ? 1 : 0);
1041 if (item->ID == ID)
1042 return;
1043 item->ID = ID;*/
1044 Set(fetch, item->DescURI());
1045 }
1046
1047 void Log(const char *tag, pkgAcquire::Item *item) {
1048 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1049 }
1050
1051 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1052 Log("Fetch", desc.Owner);
1053 Set(true, desc.Owner);
1054 }
1055
1056 virtual void Done(pkgAcquire::ItemDesc &desc) {
1057 Log("Done", desc.Owner);
1058 Set(false, desc.Owner);
1059 }
1060
1061 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1062 Log("Fail", desc.Owner);
1063 Set(false, desc.Owner);
1064 }
1065
1066 virtual bool Pulse_(pkgAcquire *Owner) {
1067 std::set<std::string> fetches;
1068 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1069 bool fetch;
1070 if ((*item)->QueueCounter == 0)
1071 fetch = false;
1072 else switch ((*item)->Status) {
1073 case pkgAcquire::Item::StatFetching:
1074 fetches.insert((*item)->DescURI());
1075 fetch = true;
1076 break;
1077
1078 default:
1079 fetch = false;
1080 break;
1081 }
1082
1083 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1084 Set(fetch, *item);
1085 }
1086
1087 std::vector<std::string> stops;
1088 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1089 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1090 //printf("Stop(%s)\n", stop->c_str());
1091 Set(false, *stop);
1092 }
1093
1094 return ![delegate_ isSourceCancelled];
1095 }
1096
1097 virtual void Stop() {
1098 pkgAcquireStatus::Stop();
1099 [database_ resetFetch];
1100 }
1101};
1102/* }}} */
1103/* ProgressEvent Implementation {{{ */
1104@implementation CydiaProgressEvent
1105
1106+ (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1107 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1108}
1109
1110+ (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1111 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1112 [event setPackage:package];
1113 return event;
1114}
1115
1116+ (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1117 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1118
1119 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1120 NSArray *fields([description componentsSeparatedByString:@" "]);
1121 [event setItem:fields];
1122
1123 if ([fields count] > 3) {
1124 [event setPackage:[fields objectAtIndex:2]];
1125 [event setVersion:[fields objectAtIndex:3]];
1126 }
1127
1128 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1129
1130 return event;
1131}
1132
1133+ (NSArray *) _attributeKeys {
1134 return [NSArray arrayWithObjects:
1135 @"item",
1136 @"message",
1137 @"package",
1138 @"type",
1139 @"url",
1140 @"version",
1141 nil];
1142}
1143
1144- (NSArray *) attributeKeys {
1145 return [[self class] _attributeKeys];
1146}
1147
1148+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1149 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1150}
1151
1152- (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1153 if ((self = [super init]) != nil) {
1154 message_ = message;
1155 type_ = type;
1156 } return self;
1157}
1158
1159- (NSString *) message {
1160 return message_;
1161}
1162
1163- (NSString *) type {
1164 return type_;
1165}
1166
1167- (NSArray *) item {
1168 return (id) item_ ?: [NSNull null];
1169}
1170
1171- (void) setItem:(NSArray *)item {
1172 item_ = item;
1173}
1174
1175- (NSString *) package {
1176 return (id) package_ ?: [NSNull null];
1177}
1178
1179- (void) setPackage:(NSString *)package {
1180 package_ = package;
1181}
1182
1183- (NSString *) url {
1184 return (id) url_ ?: [NSNull null];
1185}
1186
1187- (void) setURL:(NSString *)url {
1188 url_ = url;
1189}
1190
1191- (void) setVersion:(NSString *)version {
1192 version_ = version;
1193}
1194
1195- (NSString *) version {
1196 return (id) version_ ?: [NSNull null];
1197}
1198
1199- (NSString *) compound:(NSString *)value {
1200 if (value != nil) {
1201 NSString *mode(nil); {
1202 NSString *type([self type]);
1203 if ([type isEqualToString:kCydiaProgressEventTypeError])
1204 mode = UCLocalize("ERROR");
1205 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1206 mode = UCLocalize("WARNING");
1207 }
1208
1209 if (mode != nil)
1210 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1211 }
1212
1213 return value;
1214}
1215
1216- (NSString *) compoundMessage {
1217 return [self compound:[self message]];
1218}
1219
1220- (NSString *) compoundTitle {
1221 NSString *title;
1222
1223 if (package_ == nil)
1224 title = nil;
1225 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1226 title = [package name];
1227 else
1228 title = package_;
1229
1230 return [self compound:title];
1231}
1232
1233@end
1234/* }}} */
1235
1236// Cytore Definitions {{{
1237struct PackageValue :
1238 Cytore::Block
1239{
1240 Cytore::Offset<PackageValue> next_;
1241
1242 uint32_t index_ : 23;
1243 uint32_t subscribed_ : 1;
1244 uint32_t : 8;
1245
1246 int32_t first_;
1247 int32_t last_;
1248
1249 uint16_t vhash_;
1250 uint16_t nhash_;
1251
1252 char version_[8];
1253 char name_[];
1254} _packed;
1255
1256struct MetaValue :
1257 Cytore::Block
1258{
1259 uint32_t active_;
1260 Cytore::Offset<PackageValue> packages_[1 << 16];
1261} _packed;
1262
1263static Cytore::File<MetaValue> MetaFile_;
1264// }}}
1265// Cytore Helper Functions {{{
1266static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1267 SplitHash nhash = { hashlittle(name, length) };
1268
1269 PackageValue *metadata;
1270
1271 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1272 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1273 *offset = MetaFile_.New<PackageValue>(length + 1);
1274 metadata = &MetaFile_.Get(*offset);
1275
1276 if (metadata == NULL) {
1277 if (fail != NULL)
1278 *fail = true;
1279
1280 metadata = new PackageValue();
1281 memset(metadata, 0, sizeof(*metadata));
1282 }
1283
1284 memcpy(metadata->name_, name, length);
1285 metadata->name_[length] = '\0';
1286 metadata->nhash_ = nhash.u16[1];
1287 } else {
1288 metadata = &MetaFile_.Get(*offset);
1289 if (metadata->nhash_ != nhash.u16[1])
1290 continue;
1291 if (strncmp(metadata->name_, name, length) != 0)
1292 continue;
1293 if (metadata->name_[length] != '\0')
1294 continue;
1295 } break; }
1296
1297 return metadata;
1298}
1299
1300static void PackageImport(const void *key, const void *value, void *context) {
1301 bool &fail(*reinterpret_cast<bool *>(context));
1302
1303 char buffer[1024];
1304 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1305 NSLog(@"failed to import package %@", key);
1306 return;
1307 }
1308
1309 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1310 NSDictionary *package((NSDictionary *) value);
1311
1312 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1313 if ([subscribed boolValue] && !metadata->subscribed_)
1314 metadata->subscribed_ = true;
1315
1316 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1317 time_t time([date timeIntervalSince1970]);
1318 if (metadata->first_ > time || metadata->first_ == 0)
1319 metadata->first_ = time;
1320 }
1321
1322 NSDate *date([package objectForKey:@"LastSeen"]);
1323 NSString *version([package objectForKey:@"LastVersion"]);
1324
1325 if (date != nil && version != nil) {
1326 time_t time([date timeIntervalSince1970]);
1327 if (metadata->last_ < time || metadata->last_ == 0)
1328 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1329 size_t length(strlen(buffer));
1330 uint16_t vhash(hashlittle(buffer, length));
1331
1332 size_t capped(std::min<size_t>(8, length));
1333 char *latest(buffer + length - capped);
1334
1335 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1336 metadata->vhash_ = vhash;
1337
1338 metadata->last_ = time;
1339 }
1340 }
1341}
1342// }}}
1343
1344static NSDate *GetStatusDate() {
1345 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1346}
1347
1348static void SaveConfig(NSObject *lock) {
1349 @synchronized (lock) {
1350 _trace();
1351 MetaFile_.Sync();
1352 _trace();
1353 }
1354
1355 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1356 Values_, @"CydiaValues",
1357 Sections_, @"CydiaSections",
1358 (id) Sources_, @"CydiaSources",
1359 Version_, @"CydiaVersion",
1360 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1361
1362 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1363 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1364
1365 CydiaWriteSources();
1366}
1367
1368/* Source Class {{{ */
1369@interface Source : NSObject {
1370 unsigned era_;
1371 Database *database_;
1372 metaIndex *index_;
1373
1374 CYString depiction_;
1375 CYString description_;
1376 CYString label_;
1377 CYString origin_;
1378 CYString support_;
1379
1380 CYString uri_;
1381 CYString distribution_;
1382 CYString type_;
1383 CYString base_;
1384 CYString version_;
1385
1386 _H<NSString> host_;
1387 _H<NSString> authority_;
1388
1389 CYString defaultIcon_;
1390
1391 _H<NSMutableDictionary> record_;
1392 BOOL trusted_;
1393
1394 std::set<std::string> fetches_;
1395 std::set<std::string> files_;
1396 _transient NSObject<SourceDelegate> *delegate_;
1397}
1398
1399- (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1400
1401- (NSComparisonResult) compareByName:(Source *)source;
1402
1403- (NSString *) depictionForPackage:(NSString *)package;
1404- (NSString *) supportForPackage:(NSString *)package;
1405
1406- (metaIndex *) metaIndex;
1407- (NSDictionary *) record;
1408- (BOOL) trusted;
1409
1410- (NSString *) rooturi;
1411- (NSString *) distribution;
1412- (NSString *) type;
1413
1414- (NSString *) key;
1415- (NSString *) host;
1416
1417- (NSString *) name;
1418- (NSString *) shortDescription;
1419- (NSString *) label;
1420- (NSString *) origin;
1421- (NSString *) version;
1422
1423- (NSString *) defaultIcon;
1424- (NSURL *) iconURL;
1425
1426- (void) setFetch:(bool)fetch forURI:(const char *)uri;
1427- (void) resetFetch;
1428
1429@end
1430
1431@implementation Source
1432
1433+ (NSString *) webScriptNameForSelector:(SEL)selector {
1434 if (false);
1435 else if (selector == @selector(addSection:))
1436 return @"addSection";
1437 else if (selector == @selector(getField:))
1438 return @"getField";
1439 else if (selector == @selector(removeSection:))
1440 return @"removeSection";
1441 else if (selector == @selector(remove))
1442 return @"remove";
1443 else
1444 return nil;
1445}
1446
1447+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1448 return [self webScriptNameForSelector:selector] == nil;
1449}
1450
1451+ (NSArray *) _attributeKeys {
1452 return [NSArray arrayWithObjects:
1453 @"baseuri",
1454 @"distribution",
1455 @"host",
1456 @"key",
1457 @"iconuri",
1458 @"label",
1459 @"name",
1460 @"origin",
1461 @"rooturi",
1462 @"sections",
1463 @"shortDescription",
1464 @"trusted",
1465 @"type",
1466 @"version",
1467 nil];
1468}
1469
1470- (NSArray *) attributeKeys {
1471 return [[self class] _attributeKeys];
1472}
1473
1474+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1475 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1476}
1477
1478- (metaIndex *) metaIndex {
1479 return index_;
1480}
1481
1482- (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1483 trusted_ = index->IsTrusted();
1484
1485 uri_.set(pool, index->GetURI());
1486 distribution_.set(pool, index->GetDist());
1487 type_.set(pool, index->GetType());
1488
1489 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1490 if (dindex != NULL) {
1491 std::string file(dindex->MetaIndexURI(""));
1492 base_.set(pool, file);
1493
1494 pkgAcquire acquire;
1495 _profile(Source$setMetaIndex$GetIndexes)
1496 dindex->GetIndexes(&acquire, true);
1497 _end
1498 _profile(Source$setMetaIndex$DescURI)
1499 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1500 std::string file((*item)->DescURI());
1501 auto slash(file.rfind('/'));
1502 if (slash == std::string::npos)
1503 continue;
1504 files_.insert(file.substr(0, slash));
1505 }
1506 _end
1507
1508 FileFd fd;
1509 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1510 _error->Discard();
1511 else {
1512 pkgTagFile tags(&fd);
1513
1514 pkgTagSection section;
1515 tags.Step(section);
1516
1517 struct {
1518 const char *name_;
1519 CYString *value_;
1520 } names[] = {
1521 {"default-icon", &defaultIcon_},
1522 {"depiction", &depiction_},
1523 {"description", &description_},
1524 {"label", &label_},
1525 {"origin", &origin_},
1526 {"support", &support_},
1527 {"version", &version_},
1528 };
1529
1530 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1531 const char *start, *end;
1532
1533 if (section.Find(names[i].name_, start, end)) {
1534 CYString &value(*names[i].value_);
1535 value.set(pool, start, end - start);
1536 }
1537 }
1538 }
1539 }
1540
1541 record_ = [Sources_ objectForKey:[self key]];
1542
1543 NSURL *url([NSURL URLWithString:uri_]);
1544
1545 host_ = [url host];
1546 if (host_ != nil)
1547 host_ = [host_ lowercaseString];
1548
1549 if (host_ != nil)
1550 authority_ = host_;
1551 else
1552 authority_ = [url path];
1553}
1554
1555- (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1556 if ((self = [super init]) != nil) {
1557 era_ = [database era];
1558 database_ = database;
1559 index_ = index;
1560
1561 _profile(Source$initWithMetaIndex$setMetaIndex)
1562 [self setMetaIndex:index inPool:pool];
1563 _end
1564 } return self;
1565}
1566
1567- (NSString *) getField:(NSString *)name {
1568@synchronized (database_) {
1569 if ([database_ era] != era_ || index_ == NULL)
1570 return nil;
1571
1572 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1573 if (dindex == NULL)
1574 return nil;
1575
1576 FileFd fd;
1577 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1578 _error->Discard();
1579 return nil;
1580 }
1581
1582 pkgTagFile tags(&fd);
1583
1584 pkgTagSection section;
1585 tags.Step(section);
1586
1587 const char *start, *end;
1588 if (!section.Find([name UTF8String], start, end))
1589 return (NSString *) [NSNull null];
1590
1591 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1592} }
1593
1594- (NSComparisonResult) compareByName:(Source *)source {
1595 NSString *lhs = [self name];
1596 NSString *rhs = [source name];
1597
1598 if ([lhs length] != 0 && [rhs length] != 0) {
1599 unichar lhc = [lhs characterAtIndex:0];
1600 unichar rhc = [rhs characterAtIndex:0];
1601
1602 if (isalpha(lhc) && !isalpha(rhc))
1603 return NSOrderedAscending;
1604 else if (!isalpha(lhc) && isalpha(rhc))
1605 return NSOrderedDescending;
1606 }
1607
1608 return [lhs compare:rhs options:LaxCompareOptions_];
1609}
1610
1611- (NSString *) depictionForPackage:(NSString *)package {
1612 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1613}
1614
1615- (NSString *) supportForPackage:(NSString *)package {
1616 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1617}
1618
1619- (NSArray *) sections {
1620 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1621}
1622
1623- (void) _addSection:(NSString *)section {
1624 if (record_ == nil)
1625 return;
1626 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1627 if (![sections containsObject:section])
1628 [sections addObject:section];
1629 } else
1630 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1631}
1632
1633- (bool) addSection:(NSString *)section {
1634 if (record_ == nil)
1635 return false;
1636
1637 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1638 return true;
1639}
1640
1641- (void) _removeSection:(NSString *)section {
1642 if (record_ == nil)
1643 return;
1644
1645 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1646 if ([sections containsObject:section])
1647 [sections removeObject:section];
1648}
1649
1650- (bool) removeSection:(NSString *)section {
1651 if (record_ == nil)
1652 return false;
1653
1654 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1655 return true;
1656}
1657
1658- (void) _remove {
1659 [Sources_ removeObjectForKey:[self key]];
1660}
1661
1662- (bool) remove {
1663 bool value(record_ != nil);
1664 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1665 return value;
1666}
1667
1668- (NSDictionary *) record {
1669 return record_;
1670}
1671
1672- (BOOL) trusted {
1673 return trusted_;
1674}
1675
1676- (NSString *) rooturi {
1677 return uri_;
1678}
1679
1680- (NSString *) distribution {
1681 return distribution_;
1682}
1683
1684- (NSString *) type {
1685 return type_;
1686}
1687
1688- (NSString *) baseuri {
1689 return base_.empty() ? nil : (id) base_;
1690}
1691
1692- (NSString *) iconuri {
1693 if (NSString *base = [self baseuri])
1694 return [base stringByAppendingString:@"CydiaIcon.png"];
1695
1696 return nil;
1697}
1698
1699- (NSURL *) iconURL {
1700 if (NSString *uri = [self iconuri])
1701 return [NSURL URLWithString:uri];
1702 return nil;
1703}
1704
1705- (NSString *) key {
1706 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1707}
1708
1709- (NSString *) host {
1710 return host_;
1711}
1712
1713- (NSString *) name {
1714 return origin_.empty() ? (id) authority_ : origin_;
1715}
1716
1717- (NSString *) shortDescription {
1718 return description_;
1719}
1720
1721- (NSString *) label {
1722 return label_.empty() ? (id) authority_ : label_;
1723}
1724
1725- (NSString *) origin {
1726 return origin_;
1727}
1728
1729- (NSString *) version {
1730 return version_;
1731}
1732
1733- (NSString *) defaultIcon {
1734 return defaultIcon_;
1735}
1736
1737- (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1738 delegate_ = delegate;
1739}
1740
1741- (bool) fetch {
1742 return !fetches_.empty();
1743}
1744
1745- (void) setFetch:(bool)fetch forURI:(const char *)uri {
1746 if (!fetch) {
1747 if (fetches_.erase(uri) == 0)
1748 return;
1749 } else if (files_.find(uri) == files_.end())
1750 return;
1751 else if (!fetches_.insert(uri).second)
1752 return;
1753
1754 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1755}
1756
1757- (void) resetFetch {
1758 fetches_.clear();
1759 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1760}
1761
1762@end
1763/* }}} */
1764/* CydiaOperation Class {{{ */
1765@interface CydiaOperation : NSObject {
1766 _H<NSString> operator_;
1767 _H<NSString> value_;
1768}
1769
1770- (NSString *) operator;
1771- (NSString *) value;
1772
1773@end
1774
1775@implementation CydiaOperation
1776
1777- (id) initWithOperator:(const char *)_operator value:(const char *)value {
1778 if ((self = [super init]) != nil) {
1779 operator_ = [NSString stringWithUTF8String:_operator];
1780 value_ = [NSString stringWithUTF8String:value];
1781 } return self;
1782}
1783
1784+ (NSArray *) _attributeKeys {
1785 return [NSArray arrayWithObjects:
1786 @"operator",
1787 @"value",
1788 nil];
1789}
1790
1791- (NSArray *) attributeKeys {
1792 return [[self class] _attributeKeys];
1793}
1794
1795+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1796 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1797}
1798
1799- (NSString *) operator {
1800 return operator_;
1801}
1802
1803- (NSString *) value {
1804 return value_;
1805}
1806
1807@end
1808/* }}} */
1809/* CydiaClause Class {{{ */
1810@interface CydiaClause : NSObject {
1811 _H<NSString> package_;
1812 _H<CydiaOperation> version_;
1813}
1814
1815- (NSString *) package;
1816- (CydiaOperation *) version;
1817
1818@end
1819
1820@implementation CydiaClause
1821
1822- (id) initWithIterator:(pkgCache::DepIterator &)dep {
1823 if ((self = [super init]) != nil) {
1824 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1825
1826 if (const char *version = dep.TargetVer())
1827 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1828 else
1829 version_ = (id) [NSNull null];
1830 } return self;
1831}
1832
1833+ (NSArray *) _attributeKeys {
1834 return [NSArray arrayWithObjects:
1835 @"package",
1836 @"version",
1837 nil];
1838}
1839
1840- (NSArray *) attributeKeys {
1841 return [[self class] _attributeKeys];
1842}
1843
1844+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1845 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1846}
1847
1848- (NSString *) package {
1849 return package_;
1850}
1851
1852- (CydiaOperation *) version {
1853 return version_;
1854}
1855
1856@end
1857/* }}} */
1858/* CydiaRelation Class {{{ */
1859@interface CydiaRelation : NSObject {
1860 _H<NSString> relationship_;
1861 _H<NSMutableArray> clauses_;
1862}
1863
1864- (NSString *) relationship;
1865- (NSArray *) clauses;
1866
1867@end
1868
1869@implementation CydiaRelation
1870
1871- (id) initWithIterator:(pkgCache::DepIterator &)dep {
1872 if ((self = [super init]) != nil) {
1873 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1874 clauses_ = [NSMutableArray arrayWithCapacity:8];
1875
1876 pkgCache::DepIterator start;
1877 pkgCache::DepIterator end;
1878 dep.GlobOr(start, end); // ++dep
1879
1880 _forever {
1881 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1882
1883 // yes, seriously. (wtf?)
1884 if (start == end)
1885 break;
1886 ++start;
1887 }
1888 } return self;
1889}
1890
1891+ (NSArray *) _attributeKeys {
1892 return [NSArray arrayWithObjects:
1893 @"clauses",
1894 @"relationship",
1895 nil];
1896}
1897
1898- (NSArray *) attributeKeys {
1899 return [[self class] _attributeKeys];
1900}
1901
1902+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1903 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1904}
1905
1906- (NSString *) relationship {
1907 return relationship_;
1908}
1909
1910- (NSArray *) clauses {
1911 return clauses_;
1912}
1913
1914- (void) addClause:(CydiaClause *)clause {
1915 [clauses_ addObject:clause];
1916}
1917
1918@end
1919/* }}} */
1920/* Package Class {{{ */
1921struct ParsedPackage {
1922 CYString md5sum_;
1923 CYString tagline_;
1924
1925 CYString architecture_;
1926 CYString icon_;
1927
1928 CYString depiction_;
1929 CYString homepage_;
1930 CYString author_;
1931
1932 CYString support_;
1933};
1934
1935@interface Package : NSObject {
1936 uint32_t era_ : 25;
1937 @public uint32_t role_ : 3;
1938 uint32_t essential_ : 1;
1939 uint32_t obsolete_ : 1;
1940 uint32_t ignored_ : 1;
1941 uint32_t pooled_ : 1;
1942
1943 CYPool *pool_;
1944
1945 uint32_t rank_;
1946
1947 _transient Database *database_;
1948
1949 pkgCache::VerIterator version_;
1950 pkgCache::PkgIterator iterator_;
1951 pkgCache::VerFileIterator file_;
1952
1953 CYString id_;
1954 CYString name_;
1955 CYString transform_;
1956
1957 CYString latest_;
1958 CYString installed_;
1959 time_t upgraded_;
1960
1961 const char *section_;
1962 _transient NSString *section$_;
1963
1964 _H<Source> source_;
1965
1966 PackageValue *metadata_;
1967 ParsedPackage *parsed_;
1968
1969 _H<NSMutableArray> tags_;
1970}
1971
1972- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
1973+ (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
1974
1975+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
1976
1977- (pkgCache::PkgIterator) iterator;
1978- (void) parse;
1979
1980- (NSString *) section;
1981- (NSString *) simpleSection;
1982
1983- (NSString *) longSection;
1984- (NSString *) shortSection;
1985
1986- (NSString *) uri;
1987
1988- (MIMEAddress *) maintainer;
1989- (size_t) size;
1990- (NSString *) longDescription;
1991- (NSString *) shortDescription;
1992- (unichar) index;
1993
1994- (PackageValue *) metadata;
1995- (time_t) seen;
1996
1997- (bool) subscribed;
1998- (bool) setSubscribed:(bool)subscribed;
1999
2000- (BOOL) ignored;
2001
2002- (NSString *) latest;
2003- (NSString *) installed;
2004- (BOOL) uninstalled;
2005
2006- (BOOL) upgradableAndEssential:(BOOL)essential;
2007- (BOOL) essential;
2008- (BOOL) broken;
2009- (BOOL) unfiltered;
2010- (BOOL) visible;
2011
2012- (BOOL) half;
2013- (BOOL) halfConfigured;
2014- (BOOL) halfInstalled;
2015- (BOOL) hasMode;
2016- (NSString *) mode;
2017
2018- (NSString *) id;
2019- (NSString *) name;
2020- (UIImage *) icon;
2021- (NSString *) homepage;
2022- (NSString *) depiction;
2023- (MIMEAddress *) author;
2024
2025- (NSString *) support;
2026
2027- (NSArray *) files;
2028- (NSArray *) warnings;
2029- (NSArray *) applications;
2030
2031- (Source *) source;
2032
2033- (uint32_t) rank;
2034- (BOOL) matches:(NSArray *)query;
2035
2036- (BOOL) hasTag:(NSString *)tag;
2037- (NSString *) primaryPurpose;
2038- (NSArray *) purposes;
2039- (bool) isCommercial;
2040
2041- (void) setIndex:(size_t)index;
2042
2043- (CYString &) cyname;
2044
2045- (uint32_t) compareBySection:(NSArray *)sections;
2046
2047- (void) install;
2048- (void) remove;
2049
2050@end
2051
2052uint32_t PackageChangesRadix(Package *self, void *) {
2053 union {
2054 uint32_t key;
2055
2056 struct {
2057 uint32_t timestamp : 30;
2058 uint32_t ignored : 1;
2059 uint32_t upgradable : 1;
2060 } bits;
2061 } value;
2062
2063 bool upgradable([self upgradableAndEssential:YES]);
2064 value.bits.upgradable = upgradable ? 1 : 0;
2065
2066 if (upgradable) {
2067 value.bits.timestamp = 0;
2068 value.bits.ignored = [self ignored] ? 0 : 1;
2069 value.bits.upgradable = 1;
2070 } else {
2071 value.bits.timestamp = [self seen] >> 2;
2072 value.bits.ignored = 0;
2073 value.bits.upgradable = 0;
2074 }
2075
2076 return _not(uint32_t) - value.key;
2077}
2078
2079CYString &(*PackageName)(Package *self, SEL sel);
2080
2081uint32_t PackagePrefixRadix(Package *self, void *context) {
2082 size_t offset(reinterpret_cast<size_t>(context));
2083 CYString &name(PackageName(self, @selector(cyname)));
2084
2085 size_t size(name.size());
2086 if (size == 0)
2087 return 0;
2088 char *text(name.data());
2089
2090 size_t zeros;
2091 if (!isdigit(text[0]))
2092 zeros = 0;
2093 else {
2094 size_t digits(1);
2095 while (size != digits && isdigit(text[digits]))
2096 if (++digits == 4)
2097 break;
2098 zeros = 4 - digits;
2099 }
2100
2101 uint8_t data[4];
2102
2103 if (offset == 0 && zeros != 0) {
2104 memset(data, '0', zeros);
2105 memcpy(data + zeros, text, 4 - zeros);
2106 } else {
2107 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2108 if (size <= offset - zeros)
2109 return 0;
2110
2111 text += offset - zeros;
2112 size -= offset - zeros;
2113
2114 if (size >= 4)
2115 memcpy(data, text, 4);
2116 else {
2117 memcpy(data, text, size);
2118 memset(data + size, 0, 4 - size);
2119 }
2120
2121 for (size_t i(0); i != 4; ++i)
2122 if (isalpha(data[i]))
2123 data[i] |= 0x20;
2124 }
2125
2126 if (offset == 0)
2127 if (data[0] == '@')
2128 data[0] = 0x7f;
2129 else
2130 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2131
2132 /* XXX: ntohl may be more honest */
2133 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2134}
2135
2136CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2137 _profile(PackageNameCompare)
2138 if (lhn == NULL)
2139 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2140 else if (rhn == NULL)
2141 return kCFCompareGreaterThan;
2142
2143 CFIndex length(CFStringGetLength(lhn));
2144
2145 _profile(PackageNameCompare$NumbersLast)
2146 if (length != 0 && CFStringGetLength(rhn) != 0) {
2147 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2148 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2149 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2150 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2151 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2152 }
2153 _end
2154
2155 _profile(PackageNameCompare$Compare)
2156 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2157 _end
2158 _end
2159}
2160
2161_finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2162 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2163}
2164
2165CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2166 CYString &lhn(PackageName(lhs, @selector(cyname)));
2167 NSString *rhn(PackageName(rhs, @selector(cyname)));
2168 return StringNameCompare(lhn, rhn, lhn.size());
2169}
2170
2171CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2172 return PackageNameCompare(*lhs, *rhs, arg);
2173}
2174
2175struct PackageNameOrdering :
2176 std::binary_function<Package *, Package *, bool>
2177{
2178 _finline bool operator ()(Package *lhs, Package *rhs) const {
2179 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2180 }
2181};
2182
2183@implementation Package
2184
2185- (NSString *) description {
2186 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2187}
2188
2189- (void) dealloc {
2190 if (!pooled_)
2191 delete pool_;
2192 if (parsed_ != NULL)
2193 delete parsed_;
2194 [super dealloc];
2195}
2196
2197+ (NSString *) webScriptNameForSelector:(SEL)selector {
2198 if (false);
2199 else if (selector == @selector(clear))
2200 return @"clear";
2201 else if (selector == @selector(getField:))
2202 return @"getField";
2203 else if (selector == @selector(getRecord))
2204 return @"getRecord";
2205 else if (selector == @selector(hasTag:))
2206 return @"hasTag";
2207 else if (selector == @selector(install))
2208 return @"install";
2209 else if (selector == @selector(remove))
2210 return @"remove";
2211 else
2212 return nil;
2213}
2214
2215+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2216 return [self webScriptNameForSelector:selector] == nil;
2217}
2218
2219+ (NSArray *) _attributeKeys {
2220 return [NSArray arrayWithObjects:
2221 @"applications",
2222 @"architecture",
2223 @"author",
2224 @"depiction",
2225 @"essential",
2226 @"homepage",
2227 @"icon",
2228 @"id",
2229 @"installed",
2230 @"latest",
2231 @"longDescription",
2232 @"longSection",
2233 @"maintainer",
2234 @"md5sum",
2235 @"mode",
2236 @"name",
2237 @"purposes",
2238 @"relations",
2239 @"section",
2240 @"selection",
2241 @"shortDescription",
2242 @"shortSection",
2243 @"simpleSection",
2244 @"size",
2245 @"source",
2246 @"state",
2247 @"support",
2248 @"tags",
2249 @"upgraded",
2250 @"warnings",
2251 nil];
2252}
2253
2254- (NSArray *) attributeKeys {
2255 return [[self class] _attributeKeys];
2256}
2257
2258+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2259 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2260}
2261
2262- (NSArray *) relations {
2263@synchronized (database_) {
2264 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2265 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2266 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2267 return relations;
2268} }
2269
2270- (NSString *) architecture {
2271 [self parse];
2272@synchronized (database_) {
2273 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2274} }
2275
2276- (NSString *) getField:(NSString *)name {
2277@synchronized (database_) {
2278 if ([database_ era] != era_ || file_.end())
2279 return nil;
2280
2281 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2282
2283 const char *start, *end;
2284 if (!parser.Find([name UTF8String], start, end))
2285 return (NSString *) [NSNull null];
2286
2287 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2288} }
2289
2290- (NSString *) getRecord {
2291@synchronized (database_) {
2292 if ([database_ era] != era_ || file_.end())
2293 return nil;
2294
2295 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2296
2297 const char *start, *end;
2298 parser.GetRec(start, end);
2299
2300 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2301} }
2302
2303- (void) parse {
2304 if (parsed_ != NULL)
2305 return;
2306@synchronized (database_) {
2307 if ([database_ era] != era_ || file_.end())
2308 return;
2309
2310 ParsedPackage *parsed(new ParsedPackage);
2311 parsed_ = parsed;
2312
2313 _profile(Package$parse)
2314 pkgRecords::Parser *parser;
2315
2316 _profile(Package$parse$Lookup)
2317 parser = &[database_ records]->Lookup(file_);
2318 _end
2319
2320 CYString bugs;
2321 CYString website;
2322
2323 _profile(Package$parse$Find)
2324 struct {
2325 const char *name_;
2326 CYString *value_;
2327 } names[] = {
2328 {"architecture", &parsed->architecture_},
2329 {"icon", &parsed->icon_},
2330 {"depiction", &parsed->depiction_},
2331 {"homepage", &parsed->homepage_},
2332 {"website", &website},
2333 {"bugs", &bugs},
2334 {"support", &parsed->support_},
2335 {"author", &parsed->author_},
2336 {"md5sum", &parsed->md5sum_},
2337 };
2338
2339 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2340 const char *start, *end;
2341
2342 if (parser->Find(names[i].name_, start, end)) {
2343 CYString &value(*names[i].value_);
2344 _profile(Package$parse$Value)
2345 value.set(pool_, start, end - start);
2346 _end
2347 }
2348 }
2349 _end
2350
2351 _profile(Package$parse$Tagline)
2352 parsed->tagline_.set(pool_, parser->ShortDesc());
2353 _end
2354
2355 _profile(Package$parse$Retain)
2356 if (parsed->homepage_.empty())
2357 parsed->homepage_ = website;
2358 if (parsed->homepage_ == parsed->depiction_)
2359 parsed->homepage_.clear();
2360 if (parsed->support_.empty())
2361 parsed->support_ = bugs;
2362 _end
2363 _end
2364} }
2365
2366- (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2367 if ((self = [super init]) != nil) {
2368 _profile(Package$initWithVersion)
2369 if (pool == NULL)
2370 pool_ = new CYPool();
2371 else {
2372 pool_ = pool;
2373 pooled_ = true;
2374 }
2375
2376 database_ = database;
2377 era_ = [database era];
2378
2379 version_ = version;
2380
2381 pkgCache::PkgIterator iterator(version_.ParentPkg());
2382 iterator_ = iterator;
2383
2384 _profile(Package$initWithVersion$Version)
2385 file_ = version_.FileList();
2386 _end
2387
2388 _profile(Package$initWithVersion$Cache)
2389 name_.set(NULL, version_.Display());
2390
2391 latest_.set(NULL, StripVersion_(version_.VerStr()));
2392
2393 pkgCache::VerIterator current(iterator.CurrentVer());
2394 if (!current.end())
2395 installed_.set(NULL, StripVersion_(current.VerStr()));
2396 _end
2397
2398 _profile(Package$initWithVersion$Transliterate) do {
2399 if (CollationTransl_ == NULL)
2400 break;
2401 if (name_.empty())
2402 break;
2403
2404 _profile(Package$initWithVersion$Transliterate$utf8)
2405 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2406 for (size_t i(0), e(name_.size()); i != e; ++i)
2407 if (data[i] >= 0x80)
2408 goto extended;
2409 break; extended:;
2410 _end
2411
2412 UErrorCode code(U_ZERO_ERROR);
2413 int32_t length;
2414
2415 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2416 CollationString_.resize(name_.size());
2417 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2418 if (!U_SUCCESS(code))
2419 break;
2420 CollationString_.resize(length);
2421 _end
2422
2423 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2424 length = CollationString_.size();
2425 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2426 if (!U_SUCCESS(code))
2427 break;
2428 _assert(CollationString_.size() == length);
2429 _end
2430
2431 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2432 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2433 if (code == U_BUFFER_OVERFLOW_ERROR)
2434 code = U_ZERO_ERROR;
2435 else if (!U_SUCCESS(code))
2436 break;
2437 _end
2438
2439 char *transform;
2440 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2441 transform = pool_->malloc<char>(length);
2442 _end
2443 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2444 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2445 if (!U_SUCCESS(code))
2446 break;
2447 _end
2448
2449 transform_.set(NULL, transform, length);
2450 } while (false); _end
2451
2452 _profile(Package$initWithVersion$Tags)
2453#ifndef __arm__
2454 pkgCache::TagIterator tag(version_.TagList());
2455#else
2456 pkgCache::TagIterator tag(iterator.TagList());
2457#endif
2458 if (!tag.end()) {
2459 tags_ = [NSMutableArray arrayWithCapacity:8];
2460
2461 goto tag; for (; !tag.end(); ++tag) tag: {
2462 const char *name(tag.Name());
2463 NSString *string((NSString *) CYStringCreate(name));
2464 if (string == nil)
2465 continue;
2466
2467 [tags_ addObject:[string autorelease]];
2468
2469 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2470 if (strcmp(name + 6, "enduser") == 0)
2471 role_ = 1;
2472 else if (strcmp(name + 6, "hacker") == 0)
2473 role_ = 2;
2474 else if (strcmp(name + 6, "developer") == 0)
2475 role_ = 3;
2476 else if (strcmp(name + 6, "cydia") == 0)
2477 role_ = 7;
2478 else
2479 role_ = 4;
2480 }
2481
2482 if (strncmp(name, "cydia::", 7) == 0) {
2483 if (strcmp(name + 7, "essential") == 0)
2484 essential_ = true;
2485 else if (strcmp(name + 7, "obsolete") == 0)
2486 obsolete_ = true;
2487 }
2488 }
2489 }
2490 _end
2491
2492 _profile(Package$initWithVersion$Metadata)
2493 const char *mixed(iterator.Name());
2494 size_t size(strlen(mixed));
2495 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2496 char lower[prefix + size + 5 + 1];
2497
2498 for (size_t i(0); i != size; ++i)
2499 lower[prefix + i] = mixed[i] | 0x20;
2500
2501 if (!installed_.empty()) {
2502 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2503 memcpy(lower + prefix + size, ".list", 6);
2504 struct stat info;
2505 if (stat(lower, &info) != -1)
2506 upgraded_ = info.st_birthtime;
2507 }
2508
2509 PackageValue *metadata(PackageFind(lower + prefix, size));
2510 metadata_ = metadata;
2511
2512 id_.set(NULL, metadata->name_, size);
2513
2514 const char *latest(version_.VerStr());
2515 size_t length(strlen(latest));
2516
2517 uint16_t vhash(hashlittle(latest, length));
2518
2519 size_t capped(std::min<size_t>(8, length));
2520 latest = latest + length - capped;
2521
2522 if (metadata->first_ == 0)
2523 metadata->first_ = now_;
2524
2525 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2526 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2527 metadata->vhash_ = vhash;
2528 metadata->last_ = now_;
2529 } else if (metadata->last_ == 0)
2530 metadata->last_ = metadata->first_;
2531 _end
2532
2533 _profile(Package$initWithVersion$Section)
2534 section_ = version_.Section();
2535 _end
2536
2537 _profile(Package$initWithVersion$Flags)
2538 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2539 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2540 _end
2541 _end } return self;
2542}
2543
2544+ (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2545 pkgCache::VerIterator version;
2546
2547 _profile(Package$packageWithIterator$GetCandidateVer)
2548 version = [database policy]->GetCandidateVer(iterator);
2549 _end
2550
2551 if (version.end())
2552 return nil;
2553
2554 Package *package;
2555
2556 _profile(Package$packageWithIterator$Allocate)
2557 package = [Package allocWithZone:zone];
2558 _end
2559
2560 _profile(Package$packageWithIterator$Initialize)
2561 package = [package
2562 initWithVersion:version
2563 withZone:zone
2564 inPool:pool
2565 database:database
2566 ];
2567 _end
2568
2569 return package;
2570}
2571
2572// XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2573+ (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2574 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2575}
2576
2577- (pkgCache::PkgIterator) iterator {
2578 return iterator_;
2579}
2580
2581- (NSArray *) downgrades {
2582 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2583
2584 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2585 if (version == version_)
2586 continue;
2587 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2588 if ([package source] == nil)
2589 continue;
2590 [versions addObject:package];
2591 }
2592
2593 return versions;
2594}
2595
2596- (NSString *) section {
2597 if (section$_ == nil) {
2598 if (section_ == NULL)
2599 return nil;
2600
2601 _profile(Package$section$mappedSectionForPointer)
2602 section$_ = [database_ mappedSectionForPointer:section_];
2603 _end
2604 } return section$_;
2605}
2606
2607- (NSString *) simpleSection {
2608 if (NSString *section = [self section])
2609 return Simplify(section);
2610 else
2611 return nil;
2612}
2613
2614- (NSString *) longSection {
2615 if (NSString *section = [self section])
2616 return LocalizeSection(section);
2617 else
2618 return nil;
2619}
2620
2621- (NSString *) shortSection {
2622 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2623}
2624
2625- (NSString *) uri {
2626 return nil;
2627#if 0
2628 pkgIndexFile *index;
2629 pkgCache::PkgFileIterator file(file_.File());
2630 if (![database_ list].FindIndex(file, index))
2631 return nil;
2632 return [NSString stringWithUTF8String:iterator_->Path];
2633 //return [NSString stringWithUTF8String:file.Site()];
2634 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2635#endif
2636}
2637
2638- (MIMEAddress *) maintainer {
2639@synchronized (database_) {
2640 if ([database_ era] != era_ || file_.end())
2641 return nil;
2642
2643 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2644 const std::string &maintainer(parser->Maintainer());
2645 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2646} }
2647
2648- (NSString *) md5sum {
2649 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2650}
2651
2652- (size_t) size {
2653@synchronized (database_) {
2654 if ([database_ era] != era_ || version_.end())
2655 return 0;
2656
2657 return version_->InstalledSize;
2658} }
2659
2660- (NSString *) longDescription {
2661@synchronized (database_) {
2662 if ([database_ era] != era_ || file_.end())
2663 return nil;
2664
2665 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2666 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2667
2668 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2669 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2670 if ([lines count] < 2)
2671 return nil;
2672
2673 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2674 for (size_t i(1), e([lines count]); i != e; ++i) {
2675 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2676 [trimmed addObject:trim];
2677 }
2678
2679 return [trimmed componentsJoinedByString:@"\n"];
2680} }
2681
2682- (NSString *) shortDescription {
2683 if (parsed_ != NULL)
2684 return static_cast<NSString *>(parsed_->tagline_);
2685
2686@synchronized (database_) {
2687 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2688 std::string value(parser.ShortDesc());
2689 if (value.empty())
2690 return nil;
2691 if (value.size() > 200)
2692 value.resize(200);
2693 return [(id) CYStringCreate(value) autorelease];
2694} }
2695
2696- (unichar) index {
2697 _profile(Package$index)
2698 CFStringRef name((CFStringRef) [self name]);
2699 if (CFStringGetLength(name) == 0)
2700 return '#';
2701 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2702 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2703 return '#';
2704 return toupper(character);
2705 _end
2706}
2707
2708- (PackageValue *) metadata {
2709 return metadata_;
2710}
2711
2712- (time_t) seen {
2713 PackageValue *metadata([self metadata]);
2714 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2715}
2716
2717- (bool) subscribed {
2718 return [self metadata]->subscribed_;
2719}
2720
2721- (bool) setSubscribed:(bool)subscribed {
2722 PackageValue *metadata([self metadata]);
2723 if (metadata->subscribed_ == subscribed)
2724 return false;
2725 metadata->subscribed_ = subscribed;
2726 return true;
2727}
2728
2729- (BOOL) ignored {
2730 return ignored_;
2731}
2732
2733- (NSString *) latest {
2734 return latest_;
2735}
2736
2737- (NSString *) installed {
2738 return installed_;
2739}
2740
2741- (BOOL) uninstalled {
2742 return installed_.empty();
2743}
2744
2745- (BOOL) upgradableAndEssential:(BOOL)essential {
2746 _profile(Package$upgradableAndEssential)
2747 pkgCache::VerIterator current(iterator_.CurrentVer());
2748 if (current.end())
2749 return essential && essential_;
2750 else
2751 return version_ != current;
2752 _end
2753}
2754
2755- (BOOL) essential {
2756 return essential_;
2757}
2758
2759- (BOOL) broken {
2760 return [database_ cache][iterator_].InstBroken();
2761}
2762
2763- (BOOL) unfiltered {
2764 _profile(Package$unfiltered$obsolete)
2765 if (_unlikely(obsolete_))
2766 return false;
2767 _end
2768
2769 _profile(Package$unfiltered$role)
2770 if (_unlikely(role_ > 3))
2771 return false;
2772 _end
2773
2774 return true;
2775}
2776
2777- (BOOL) visible {
2778 if (![self unfiltered])
2779 return false;
2780
2781 NSString *section;
2782
2783 _profile(Package$visible$section)
2784 section = [self section];
2785 _end
2786
2787 _profile(Package$visible$isSectionVisible)
2788 if (!isSectionVisible(section))
2789 return false;
2790 _end
2791
2792 return true;
2793}
2794
2795- (BOOL) half {
2796 unsigned char current(iterator_->CurrentState);
2797 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2798}
2799
2800- (BOOL) halfConfigured {
2801 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2802}
2803
2804- (BOOL) halfInstalled {
2805 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2806}
2807
2808- (BOOL) hasMode {
2809@synchronized (database_) {
2810 if ([database_ era] != era_ || iterator_.end())
2811 return NO;
2812
2813 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2814 return state.Mode != pkgDepCache::ModeKeep;
2815} }
2816
2817- (NSString *) mode {
2818@synchronized (database_) {
2819 if ([database_ era] != era_ || iterator_.end())
2820 return nil;
2821
2822 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2823
2824 switch (state.Mode) {
2825 case pkgDepCache::ModeDelete:
2826 if ((state.iFlags & pkgDepCache::Purge) != 0)
2827 return @"PURGE";
2828 else
2829 return @"REMOVE";
2830 case pkgDepCache::ModeKeep:
2831 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2832 return @"REINSTALL";
2833 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2834 return nil;*/
2835 else
2836 return nil;
2837 case pkgDepCache::ModeInstall:
2838 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2839 return @"REINSTALL";
2840 else*/ switch (state.Status) {
2841 case -1:
2842 return @"DOWNGRADE";
2843 case 0:
2844 return @"INSTALL";
2845 case 1:
2846 return @"UPGRADE";
2847 case 2:
2848 return @"NEW_INSTALL";
2849 _nodefault
2850 }
2851 _nodefault
2852 }
2853} }
2854
2855- (NSString *) id {
2856 return id_;
2857}
2858
2859- (NSString *) name {
2860 return name_.empty() ? id_ : name_;
2861}
2862
2863- (UIImage *) icon {
2864 NSString *section = [self simpleSection];
2865
2866 UIImage *icon(nil);
2867 if (parsed_ != NULL)
2868 if (NSString *href = parsed_->icon_)
2869 if ([href hasPrefix:@"file:///"])
2870 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2871 if (icon == nil) if (section != nil)
2872 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2873 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2874 if ([dicon hasPrefix:@"file:///"])
2875 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2876 if (icon == nil)
2877 icon = [UIImage imageNamed:@"unknown.png"];
2878 return icon;
2879}
2880
2881- (NSString *) homepage {
2882 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2883}
2884
2885- (NSString *) depiction {
2886 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2887}
2888
2889- (MIMEAddress *) author {
2890 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2891}
2892
2893- (NSString *) support {
2894 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2895}
2896
2897- (NSArray *) files {
2898 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2899 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2900
2901 std::ifstream fin;
2902 fin.open([path UTF8String]);
2903 if (!fin.is_open())
2904 return nil;
2905
2906 std::string line;
2907 while (std::getline(fin, line))
2908 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2909
2910 return files;
2911}
2912
2913- (NSString *) state {
2914@synchronized (database_) {
2915 if ([database_ era] != era_ || file_.end())
2916 return nil;
2917
2918 switch (iterator_->CurrentState) {
2919 case pkgCache::State::NotInstalled:
2920 return @"NotInstalled";
2921 case pkgCache::State::UnPacked:
2922 return @"UnPacked";
2923 case pkgCache::State::HalfConfigured:
2924 return @"HalfConfigured";
2925 case pkgCache::State::HalfInstalled:
2926 return @"HalfInstalled";
2927 case pkgCache::State::ConfigFiles:
2928 return @"ConfigFiles";
2929 case pkgCache::State::Installed:
2930 return @"Installed";
2931 case pkgCache::State::TriggersAwaited:
2932 return @"TriggersAwaited";
2933 case pkgCache::State::TriggersPending:
2934 return @"TriggersPending";
2935 }
2936
2937 return (NSString *) [NSNull null];
2938} }
2939
2940- (NSString *) selection {
2941@synchronized (database_) {
2942 if ([database_ era] != era_ || file_.end())
2943 return nil;
2944
2945 switch (iterator_->SelectedState) {
2946 case pkgCache::State::Unknown:
2947 return @"Unknown";
2948 case pkgCache::State::Install:
2949 return @"Install";
2950 case pkgCache::State::Hold:
2951 return @"Hold";
2952 case pkgCache::State::DeInstall:
2953 return @"DeInstall";
2954 case pkgCache::State::Purge:
2955 return @"Purge";
2956 }
2957
2958 return (NSString *) [NSNull null];
2959} }
2960
2961- (NSArray *) warnings {
2962@synchronized (database_) {
2963 if ([database_ era] != era_ || file_.end())
2964 return nil;
2965
2966 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2967 const char *name(iterator_.Name());
2968
2969 size_t length(strlen(name));
2970 if (length < 2) invalid:
2971 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2972 else for (size_t i(0); i != length; ++i)
2973 if (
2974 /* XXX: technically this is not allowed */
2975 (name[i] < 'A' || name[i] > 'Z') &&
2976 (name[i] < 'a' || name[i] > 'z') &&
2977 (name[i] < '0' || name[i] > '9') &&
2978 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2979 ) goto invalid;
2980
2981 if (strcmp(name, "cydia") != 0) {
2982 bool cydia = false;
2983 bool user = false;
2984 bool _private = false;
2985 bool stash = false;
2986 bool dbstash = false;
2987 bool dsstore = false;
2988
2989 bool repository = [[self section] isEqualToString:@"Repositories"];
2990
2991 if (NSArray *files = [self files])
2992 for (NSString *file in files)
2993 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2994 cydia = true;
2995 else if (!user && [file isEqualToString:@"/User"])
2996 user = true;
2997 else if (!_private && [file isEqualToString:@"/private"])
2998 _private = true;
2999 else if (!stash && [file isEqualToString:@"/var/stash"])
3000 stash = true;
3001 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3002 dbstash = true;
3003 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3004 dsstore = true;
3005
3006 /* XXX: this is not sensitive enough. only some folders are valid. */
3007 if (cydia && !repository)
3008 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3009 if (user)
3010 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3011 if (_private)
3012 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3013 if (stash)
3014 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3015 if (dbstash)
3016 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3017 if (dsstore)
3018 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3019 }
3020
3021 return [warnings count] == 0 ? nil : warnings;
3022} }
3023
3024- (NSArray *) applications {
3025 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3026
3027 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3028
3029 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3030 if (NSArray *files = [self files])
3031 for (NSString *file in files)
3032 if (application_r(file)) {
3033 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3034 if (info == nil)
3035 continue;
3036 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3037 if (id == nil || [id isEqualToString:me])
3038 continue;
3039
3040 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3041 if (display == nil)
3042 display = application_r[1];
3043
3044 NSString *bundle([file stringByDeletingLastPathComponent]);
3045 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3046 // XXX: maybe this should check if this is really a string, not just for length
3047 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3048 icon = @"icon.png";
3049 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3050
3051 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3052 [applications addObject:application];
3053
3054 [application addObject:id];
3055 [application addObject:display];
3056 [application addObject:url];
3057 }
3058
3059 return [applications count] == 0 ? nil : applications;
3060}
3061
3062- (Source *) source {
3063 if (source_ == nil) {
3064 @synchronized (database_) {
3065 if ([database_ era] != era_ || file_.end())
3066 source_ = (Source *) [NSNull null];
3067 else
3068 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3069 }
3070 }
3071
3072 return source_ == (Source *) [NSNull null] ? nil : source_;
3073}
3074
3075- (time_t) upgraded {
3076 return upgraded_;
3077}
3078
3079- (uint32_t) recent {
3080 return std::numeric_limits<uint32_t>::max() - upgraded_;
3081}
3082
3083- (uint32_t) rank {
3084 return rank_;
3085}
3086
3087- (BOOL) matches:(NSArray *)query {
3088 if (query == nil || [query count] == 0)
3089 return NO;
3090
3091 rank_ = 0;
3092
3093 NSString *string;
3094 NSRange range;
3095 NSUInteger length;
3096
3097 string = [self name];
3098 length = [string length];
3099
3100 if (length != 0)
3101 for (NSString *term in query) {
3102 range = [string rangeOfString:term options:MatchCompareOptions_];
3103 if (range.location != NSNotFound)
3104 rank_ -= 6 * 1000000 / length;
3105 }
3106
3107 if (rank_ == 0) {
3108 string = [self id];
3109 length = [string length];
3110
3111 if (length != 0)
3112 for (NSString *term in query) {
3113 range = [string rangeOfString:term options:MatchCompareOptions_];
3114 if (range.location != NSNotFound)
3115 rank_ -= 6 * 1000000 / length;
3116 }
3117 }
3118
3119 string = [self shortDescription];
3120 length = [string length];
3121 NSUInteger stop(std::min<NSUInteger>(length, 200));
3122
3123 if (length != 0)
3124 for (NSString *term in query) {
3125 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3126 if (range.location != NSNotFound)
3127 rank_ -= 2 * 100000;
3128 }
3129
3130 return rank_ != 0;
3131}
3132
3133- (NSArray *) tags {
3134 return tags_;
3135}
3136
3137- (BOOL) hasTag:(NSString *)tag {
3138 return tags_ == nil ? NO : [tags_ containsObject:tag];
3139}
3140
3141- (NSString *) primaryPurpose {
3142 for (NSString *tag in (NSArray *) tags_)
3143 if ([tag hasPrefix:@"purpose::"])
3144 return [tag substringFromIndex:9];
3145 return nil;
3146}
3147
3148- (NSArray *) purposes {
3149 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3150 for (NSString *tag in (NSArray *) tags_)
3151 if ([tag hasPrefix:@"purpose::"])
3152 [purposes addObject:[tag substringFromIndex:9]];
3153 return [purposes count] == 0 ? nil : purposes;
3154}
3155
3156- (bool) isCommercial {
3157 return [self hasTag:@"cydia::commercial"];
3158}
3159
3160- (void) setIndex:(size_t)index {
3161 if (metadata_->index_ != index + 1)
3162 metadata_->index_ = index + 1;
3163}
3164
3165- (CYString &) cyname {
3166 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3167}
3168
3169- (uint32_t) compareBySection:(NSArray *)sections {
3170 NSString *section([self section]);
3171 for (size_t i(0), e([sections count]); i != e; ++i) {
3172 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3173 return i;
3174 }
3175
3176 return _not(uint32_t);
3177}
3178
3179- (void) clear {
3180@synchronized (database_) {
3181 if ([database_ era] != era_ || file_.end())
3182 return;
3183
3184 pkgProblemResolver *resolver = [database_ resolver];
3185 resolver->Clear(iterator_);
3186
3187 pkgCacheFile &cache([database_ cache]);
3188 cache->SetReInstall(iterator_, false);
3189 cache->MarkKeep(iterator_, false);
3190} }
3191
3192- (void) install {
3193@synchronized (database_) {
3194 if ([database_ era] != era_ || file_.end())
3195 return;
3196
3197 pkgProblemResolver *resolver = [database_ resolver];
3198 resolver->Clear(iterator_);
3199 resolver->Protect(iterator_);
3200
3201 pkgCacheFile &cache([database_ cache]);
3202 cache->SetCandidateVersion(version_);
3203 cache->SetReInstall(iterator_, false);
3204 cache->MarkInstall(iterator_, false);
3205
3206 pkgDepCache::StateCache &state((*cache)[iterator_]);
3207 if (!state.Install())
3208 cache->SetReInstall(iterator_, true);
3209} }
3210
3211- (void) remove {
3212@synchronized (database_) {
3213 if ([database_ era] != era_ || file_.end())
3214 return;
3215
3216 pkgProblemResolver *resolver = [database_ resolver];
3217 resolver->Clear(iterator_);
3218 resolver->Remove(iterator_);
3219 resolver->Protect(iterator_);
3220
3221 pkgCacheFile &cache([database_ cache]);
3222 cache->SetReInstall(iterator_, false);
3223 cache->MarkDelete(iterator_, true);
3224} }
3225
3226@end
3227/* }}} */
3228/* Section Class {{{ */
3229@interface Section : NSObject {
3230 _H<NSString> name_;
3231 size_t row_;
3232 size_t count_;
3233 _H<NSString> localized_;
3234}
3235
3236- (NSComparisonResult) compareByLocalized:(Section *)section;
3237- (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3238- (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3239- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3240
3241- (NSString *) name;
3242- (void) setName:(NSString *)name;
3243
3244- (size_t) row;
3245- (size_t) count;
3246
3247- (void) addToRow;
3248- (void) addToCount;
3249
3250- (void) setCount:(size_t)count;
3251- (NSString *) localized;
3252
3253@end
3254
3255@implementation Section
3256
3257- (NSComparisonResult) compareByLocalized:(Section *)section {
3258 NSString *lhs(localized_);
3259 NSString *rhs([section localized]);
3260
3261 /*if ([lhs length] != 0 && [rhs length] != 0) {
3262 unichar lhc = [lhs characterAtIndex:0];
3263 unichar rhc = [rhs characterAtIndex:0];
3264
3265 if (isalpha(lhc) && !isalpha(rhc))
3266 return NSOrderedAscending;
3267 else if (!isalpha(lhc) && isalpha(rhc))
3268 return NSOrderedDescending;
3269 }*/
3270
3271 return [lhs compare:rhs options:LaxCompareOptions_];
3272}
3273
3274- (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3275 if ((self = [self initWithName:name localize:NO]) != nil) {
3276 if (localized != nil)
3277 localized_ = localized;
3278 } return self;
3279}
3280
3281- (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3282 return [self initWithName:name row:0 localize:localize];
3283}
3284
3285- (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3286 if ((self = [super init]) != nil) {
3287 name_ = name;
3288 row_ = row;
3289 if (localize)
3290 localized_ = LocalizeSection(name_);
3291 } return self;
3292}
3293
3294- (NSString *) name {
3295 return name_;
3296}
3297
3298- (void) setName:(NSString *)name {
3299 name_ = name;
3300}
3301
3302- (size_t) row {
3303 return row_;
3304}
3305
3306- (size_t) count {
3307 return count_;
3308}
3309
3310- (void) addToRow {
3311 ++row_;
3312}
3313
3314- (void) addToCount {
3315 ++count_;
3316}
3317
3318- (void) setCount:(size_t)count {
3319 count_ = count;
3320}
3321
3322- (NSString *) localized {
3323 return localized_;
3324}
3325
3326@end
3327/* }}} */
3328
3329class CydiaLogCleaner :
3330 public pkgArchiveCleaner
3331{
3332 protected:
3333 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3334 unlink(File);
3335 }
3336};
3337
3338/* Database Implementation {{{ */
3339@implementation Database
3340
3341+ (Database *) sharedInstance {
3342 static _H<Database> instance;
3343 if (instance == nil)
3344 instance = [[[Database alloc] init] autorelease];
3345 return instance;
3346}
3347
3348- (unsigned) era {
3349 return era_;
3350}
3351
3352- (void) releasePackages {
3353 packages_ = nil;
3354}
3355
3356- (bool) hasPackages {
3357 return [packages_ count] != 0;
3358}
3359
3360- (void) dealloc {
3361 // XXX: actually implement this thing
3362 _assert(false);
3363 [self releasePackages];
3364 NSRecycleZone(zone_);
3365 [super dealloc];
3366}
3367
3368- (void) _readCydia:(NSNumber *)fd {
3369 boost::fdistream is([fd intValue]);
3370 std::string line;
3371
3372 static RegEx finish_r("finish:([^:]*)");
3373
3374 while (std::getline(is, line)) {
3375 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3376
3377 const char *data(line.c_str());
3378 size_t size = line.size();
3379 lprintf("C:%s\n", data);
3380
3381 if (finish_r(data, size)) {
3382 NSString *finish = finish_r[1];
3383 int index = [Finishes_ indexOfObject:finish];
3384 if (index != INT_MAX && index > Finish_)
3385 Finish_ = index;
3386 }
3387
3388 [pool release];
3389 }
3390
3391 _assume(false);
3392}
3393
3394- (void) _readStatus:(NSNumber *)fd {
3395 boost::fdistream is([fd intValue]);
3396 std::string line;
3397
3398 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3399 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3400
3401 while (std::getline(is, line)) {
3402 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3403
3404 const char *data(line.c_str());
3405 size_t size(line.size());
3406 lprintf("S:%s\n", data);
3407
3408 if (conffile_r(data, size)) {
3409 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3410 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3411 } else if (strncmp(data, "status: ", 8) == 0) {
3412 // status: <package>: {unpacked,half-configured,installed}
3413 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3414 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3415 } else if (strncmp(data, "processing: ", 12) == 0) {
3416 // processing: configure: config-test
3417 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3418 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3419 } else if (pmstatus_r(data, size)) {
3420 std::string type([pmstatus_r[1] UTF8String]);
3421
3422 NSString *package = pmstatus_r[2];
3423 if ([package isEqualToString:@"dpkg-exec"])
3424 package = nil;
3425
3426 float percent([pmstatus_r[3] floatValue]);
3427 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3428
3429 NSString *string = pmstatus_r[4];
3430
3431 if (type == "pmerror") {
3432 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3433 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3434 } else if (type == "pmstatus") {
3435 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3436 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3437 } else if (type == "pmconffile")
3438 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3439 else
3440 lprintf("E:unknown pmstatus\n");
3441 } else
3442 lprintf("E:unknown status\n");
3443
3444 [pool release];
3445 }
3446
3447 _assume(false);
3448}
3449
3450- (void) _readOutput:(NSNumber *)fd {
3451 boost::fdistream is([fd intValue]);
3452 std::string line;
3453
3454 while (std::getline(is, line)) {
3455 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3456
3457 lprintf("O:%s\n", line.c_str());
3458
3459 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3460 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3461
3462 [pool release];
3463 }
3464
3465 _assume(false);
3466}
3467
3468- (FILE *) input {
3469 return input_;
3470}
3471
3472- (Package *) packageWithName:(NSString *)name {
3473 if (name == nil)
3474 return nil;
3475@synchronized (self) {
3476 if (static_cast<pkgDepCache *>(cache_) == NULL)
3477 return nil;
3478 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3479#ifndef __arm__
3480 , "any"
3481#endif
3482 ));
3483 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3484} }
3485
3486- (id) init {
3487 if ((self = [super init]) != nil) {
3488 policy_ = NULL;
3489 records_ = NULL;
3490 resolver_ = NULL;
3491 fetcher_ = NULL;
3492 lock_ = NULL;
3493
3494 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3495
3496 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3497
3498 int fds[2];
3499
3500 _assert(pipe(fds) != -1);
3501 cydiafd_ = fds[1];
3502
3503 _config->Set("APT::Keep-Fds::", cydiafd_);
3504 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3505
3506 [NSThread
3507 detachNewThreadSelector:@selector(_readCydia:)
3508 toTarget:self
3509 withObject:[NSNumber numberWithInt:fds[0]]
3510 ];
3511
3512 _assert(pipe(fds) != -1);
3513 statusfd_ = fds[1];
3514
3515 [NSThread
3516 detachNewThreadSelector:@selector(_readStatus:)
3517 toTarget:self
3518 withObject:[NSNumber numberWithInt:fds[0]]
3519 ];
3520
3521 _assert(pipe(fds) != -1);
3522 _assert(dup2(fds[0], 0) != -1);
3523 _assert(close(fds[0]) != -1);
3524
3525 input_ = fdopen(fds[1], "a");
3526
3527 _assert(pipe(fds) != -1);
3528 _assert(dup2(fds[1], 1) != -1);
3529 _assert(close(fds[1]) != -1);
3530
3531 [NSThread
3532 detachNewThreadSelector:@selector(_readOutput:)
3533 toTarget:self
3534 withObject:[NSNumber numberWithInt:fds[0]]
3535 ];
3536 } return self;
3537}
3538
3539- (pkgCacheFile &) cache {
3540 return cache_;
3541}
3542
3543- (pkgDepCache::Policy *) policy {
3544 return policy_;
3545}
3546
3547- (pkgRecords *) records {
3548 return records_;
3549}
3550
3551- (pkgProblemResolver *) resolver {
3552 return resolver_;
3553}
3554
3555- (pkgAcquire &) fetcher {
3556 return *fetcher_;
3557}
3558
3559- (pkgSourceList &) list {
3560 return *list_;
3561}
3562
3563- (NSArray *) packages {
3564 return packages_;
3565}
3566
3567- (NSArray *) sources {
3568 return sourceList_;
3569}
3570
3571- (Source *) sourceWithKey:(NSString *)key {
3572 for (Source *source in [self sources]) {
3573 if ([[source key] isEqualToString:key])
3574 return source;
3575 } return nil;
3576}
3577
3578- (bool) popErrorWithTitle:(NSString *)title {
3579 bool fatal(false);
3580
3581 while (!_error->empty()) {
3582 std::string error;
3583 bool warning(!_error->PopMessage(error));
3584 if (!warning)
3585 fatal = true;
3586
3587 for (;;) {
3588 size_t size(error.size());
3589 if (size == 0 || error[size - 1] != '\n')
3590 break;
3591 error.resize(size - 1);
3592 }
3593
3594 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3595
3596 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3597 if (warning && no_pubkey(error.c_str()))
3598 continue;
3599
3600 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3601 }
3602
3603 return fatal;
3604}
3605
3606- (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3607 return [self popErrorWithTitle:title] || !success;
3608}
3609
3610- (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3611 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3612 return true;
3613 return false;
3614
3615 list.Reset();
3616
3617 bool error(false);
3618
3619 if (access("/etc/apt/sources.list", F_OK) == 0)
3620 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3621
3622 std::string base("/etc/apt/sources.list.d");
3623 if (DIR *sources = opendir(base.c_str())) {
3624 while (dirent *source = readdir(sources))
3625 if (source->d_name[0] != '.' && source->d_namlen > 5 && strcmp(source->d_name + source->d_namlen - 5, ".list") == 0 && strcmp(source->d_name, "cydia.list") != 0)
3626 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3627 closedir(sources);
3628 }
3629
3630 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend([SOURCES_LIST UTF8String])];
3631
3632 return error;
3633}
3634
3635- (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3636@synchronized (self) {
3637 ++era_;
3638
3639 [self releasePackages];
3640
3641 sourceMap_.clear();
3642 [sourceList_ removeAllObjects];
3643
3644 _error->Discard();
3645
3646 delete list_;
3647 list_ = NULL;
3648 manager_ = NULL;
3649 delete lock_;
3650 lock_ = NULL;
3651 delete fetcher_;
3652 fetcher_ = NULL;
3653 delete resolver_;
3654 resolver_ = NULL;
3655 delete records_;
3656 records_ = NULL;
3657 delete policy_;
3658 policy_ = NULL;
3659
3660 cache_.Close();
3661
3662 pool_.~CYPool();
3663 new (&pool_) CYPool();
3664
3665 NSRecycleZone(zone_);
3666 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3667
3668 int chk(creat("/tmp/cydia.chk", 0644));
3669 if (chk != -1)
3670 close(chk);
3671
3672 if (invocation != nil)
3673 [invocation invoke];
3674
3675 NSString *title(UCLocalize("DATABASE"));
3676
3677 list_ = new pkgSourceList();
3678 _profile(reloadDataWithInvocation$ReadMainList)
3679 if ([self popErrorWithTitle:title forReadList:*list_])
3680 return;
3681 _end
3682
3683 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3684 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3685 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3686 [sourceList_ addObject:object];
3687 }
3688 _end
3689
3690 _trace();
3691 OpProgress progress;
3692 bool opened;
3693 open:
3694 delock_ = GetStatusDate();
3695 _profile(reloadDataWithInvocation$pkgCacheFile)
3696 opened = cache_.Open(progress, false);
3697 _end
3698 if (!opened) {
3699 // XXX: this block should probably be merged with popError: in some way
3700 while (!_error->empty()) {
3701 std::string error;
3702 bool warning(!_error->PopMessage(error));
3703
3704 lprintf("cache_.Open():[%s]\n", error.c_str());
3705
3706 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3707
3708 SEL repair(NULL);
3709 if (false);
3710 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3711 repair = @selector(configure);
3712 //else if (error == "The package lists or status file could not be parsed or opened.")
3713 // repair = @selector(update);
3714 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3715 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3716 // else if (error == "Malformed Status line")
3717 // else if (error == "The list of sources could not be read.")
3718
3719 if (repair != NULL) {
3720 _error->Discard();
3721 [delegate_ repairWithSelector:repair];
3722 goto open;
3723 }
3724 }
3725
3726 return;
3727 } else if ([self popErrorWithTitle:title forOperation:true])
3728 return;
3729 _trace();
3730
3731 unlink("/tmp/cydia.chk");
3732
3733 now_ = [[NSDate date] timeIntervalSince1970];
3734
3735 policy_ = new pkgDepCache::Policy();
3736 records_ = new pkgRecords(cache_);
3737 resolver_ = new pkgProblemResolver(cache_);
3738 fetcher_ = new pkgAcquire(&status_);
3739 lock_ = NULL;
3740
3741 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3742 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3743 return;
3744 }
3745
3746 _profile(reloadDataWithInvocation$pkgApplyStatus)
3747 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3748 return;
3749 _end
3750
3751 if (cache_->BrokenCount() != 0) {
3752 _profile(pkgApplyStatus$pkgFixBroken)
3753 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3754 return;
3755 _end
3756
3757 if (cache_->BrokenCount() != 0) {
3758 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3759 return;
3760 }
3761
3762 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3763 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3764 return;
3765 _end
3766 }
3767
3768 for (Source *object in (id) sourceList_) {
3769 metaIndex *source([object metaIndex]);
3770 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3771 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3772 // XXX: this could be more intelligent
3773 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3774 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3775 if (!cached.end())
3776 sourceMap_[cached->ID] = object;
3777 }
3778 }
3779
3780 {
3781 size_t capacity(MetaFile_->active_);
3782 if (capacity == 0)
3783 capacity = 128*1024;
3784 else
3785 capacity += 1024;
3786
3787 std::vector<Package *> packages;
3788 packages.reserve(capacity);
3789 size_t lost(0);
3790
3791 size_t last(0);
3792 _profile(reloadDataWithInvocation$packageWithIterator)
3793 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3794 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3795 if (unsigned index = package.metadata->index_) {
3796 --index;
3797 if (packages.size() == index) {
3798 packages.push_back(package);
3799 } else if (packages.size() <= index) {
3800 packages.resize(index + 1, nil);
3801 packages[index] = package;
3802 continue;
3803 } else {
3804 std::swap(package, packages[index]);
3805 if (package != nil) {
3806 if (package.metadata->index_ == index + 1)
3807 ++lost;
3808 goto lost;
3809 }
3810 if (last != index)
3811 continue;
3812 }
3813 } else {
3814 ++lost;
3815 lost: if (last == packages.size())
3816 packages.push_back(package);
3817 else
3818 packages[last] = package;
3819 ++last;
3820 }
3821
3822 for (; last != packages.size(); ++last)
3823 if (packages[last] == nil)
3824 break;
3825 }
3826 _end
3827
3828 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
3829 while (true) {
3830 if (next == packages.size())
3831 goto done;
3832 if (packages[next] != nil)
3833 break;
3834 ++next;
3835 }
3836
3837 std::swap(packages[last], packages[next]);
3838 } done:;
3839
3840 packages.resize(last);
3841
3842 if (lost > 128) {
3843 NSLog(@"lost = %zu", lost);
3844
3845 _profile(reloadDataWithInvocation$radix$8)
3846 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(8));
3847 _end
3848
3849 _profile(reloadDataWithInvocation$radix$4)
3850 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(4));
3851 _end
3852
3853 _profile(reloadDataWithInvocation$radix$0)
3854 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(0));
3855 _end
3856 }
3857
3858 _profile(reloadDataWithInvocation$insertion)
3859 CYArrayInsertionSortValues(packages.data(), packages.size(), &PackageNameCompare, NULL);
3860 _end
3861
3862 packages_ = [[[NSArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
3863
3864 /*_profile(reloadDataWithInvocation$CFQSortArray)
3865 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3866 _end*/
3867
3868 /*_profile(reloadDataWithInvocation$stdsort)
3869 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3870 _end*/
3871
3872 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3873 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3874 _end*/
3875
3876 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3877 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3878 _end*/
3879
3880 MetaFile_->active_ = packages.size();
3881 for (size_t index(0), count(packages.size()); index != count; ++index) {
3882 auto package(packages[index]);
3883 [package setIndex:index];
3884 [package release];
3885 }
3886 }
3887} }
3888
3889- (void) clear {
3890@synchronized (self) {
3891 delete resolver_;
3892 resolver_ = new pkgProblemResolver(cache_);
3893
3894 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3895 if (!cache_[iterator].Keep())
3896 cache_->MarkKeep(iterator, false);
3897 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3898 cache_->SetReInstall(iterator, false);
3899} }
3900
3901- (void) configure {
3902 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
3903 _trace();
3904 system([dpkg UTF8String]);
3905 _trace();
3906}
3907
3908- (bool) clean {
3909@synchronized (self) {
3910 // XXX: I don't remember this condition
3911 if (lock_ != NULL)
3912 return false;
3913
3914 FileFd Lock;
3915 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3916
3917 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3918
3919 if ([self popErrorWithTitle:title])
3920 return false;
3921
3922 pkgAcquire fetcher;
3923 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3924
3925 CydiaLogCleaner cleaner;
3926 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3927 return false;
3928
3929 return true;
3930} }
3931
3932- (bool) prepare {
3933 fetcher_->Shutdown();
3934
3935 pkgRecords records(cache_);
3936
3937 lock_ = new FileFd();
3938 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3939
3940 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3941
3942 if ([self popErrorWithTitle:title])
3943 return false;
3944
3945 pkgSourceList list;
3946 if ([self popErrorWithTitle:title forReadList:list])
3947 return false;
3948
3949 manager_ = (_system->CreatePM(cache_));
3950 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3951 return false;
3952
3953 return true;
3954}
3955
3956- (void) perform {
3957 bool substrate(RestartSubstrate_);
3958 RestartSubstrate_ = false;
3959
3960 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3961
3962 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3963 pkgSourceList list;
3964 if ([self popErrorWithTitle:title forReadList:list])
3965 return;
3966 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3967 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3968 }
3969
3970 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3971
3972 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3973 _trace();
3974 [self popErrorWithTitle:title];
3975 return;
3976 }
3977
3978 bool failed = false;
3979 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3980 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3981 continue;
3982 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3983 continue;
3984
3985 std::string uri = (*item)->DescURI();
3986 std::string error = (*item)->ErrorText;
3987
3988 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3989 failed = true;
3990
3991 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3992 [delegate_ addProgressEventOnMainThread:event forTask:title];
3993 }
3994
3995 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3996
3997 if (failed) {
3998 _trace();
3999 return;
4000 }
4001
4002 if (substrate)
4003 RestartSubstrate_ = true;
4004
4005 if (![delock_ isEqual:GetStatusDate()]) {
4006 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4007 return;
4008 }
4009
4010 delock_ = nil;
4011
4012 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4013
4014 NSString *oextended(@"/var/lib/apt/extended_states");
4015 NSString *nextended(Cache("extended_states"));
4016
4017 struct stat info;
4018 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4019 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4020
4021 unlink([nextended UTF8String]);
4022 symlink([oextended UTF8String], [nextended UTF8String]);
4023
4024 if ([self popErrorWithTitle:title])
4025 return;
4026
4027 if (result == pkgPackageManager::Failed) {
4028 _trace();
4029 return;
4030 }
4031
4032 if (result != pkgPackageManager::Completed) {
4033 _trace();
4034 return;
4035 }
4036
4037 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4038 pkgSourceList list;
4039 if ([self popErrorWithTitle:title forReadList:list])
4040 return;
4041 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4042 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4043 }
4044
4045 if (![before isEqualToArray:after])
4046 [self update];
4047}
4048
4049- (bool) delocked {
4050 return ![delock_ isEqual:GetStatusDate()];
4051}
4052
4053- (bool) upgrade {
4054 NSString *title(UCLocalize("UPGRADE"));
4055 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4056 return false;
4057 return true;
4058}
4059
4060- (void) update {
4061 [self updateWithStatus:status_];
4062}
4063
4064- (void) updateWithStatus:(CancelStatus &)status {
4065 NSString *title(UCLocalize("REFRESHING_DATA"));
4066
4067 pkgSourceList list;
4068 if ([self popErrorWithTitle:title forReadList:list])
4069 return;
4070
4071 FileFd lock;
4072 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4073 if ([self popErrorWithTitle:title])
4074 return;
4075
4076 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4077
4078 bool success(ListUpdate(status, list, PulseInterval_));
4079 if (status.WasCancelled())
4080 _error->Discard();
4081 else {
4082 [self popErrorWithTitle:title forOperation:success];
4083
4084 [[NSDictionary dictionaryWithObjectsAndKeys:
4085 [NSDate date], @"LastUpdate",
4086 nil] writeToFile:CacheState_ atomically:YES];
4087 }
4088
4089 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4090}
4091
4092- (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4093 delegate_ = delegate;
4094}
4095
4096- (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4097 progress_ = delegate;
4098 status_.setDelegate(delegate);
4099}
4100
4101- (NSObject<ProgressDelegate> *) progressDelegate {
4102 return progress_;
4103}
4104
4105- (Source *) getSource:(pkgCache::PkgFileIterator)file {
4106 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4107 return i == sourceMap_.end() ? nil : i->second;
4108}
4109
4110- (void) setFetch:(bool)fetch forURI:(const char *)uri {
4111 for (Source *source in (id) sourceList_)
4112 [source setFetch:fetch forURI:uri];
4113}
4114
4115- (void) resetFetch {
4116 for (Source *source in (id) sourceList_)
4117 [source resetFetch];
4118}
4119
4120- (NSString *) mappedSectionForPointer:(const char *)section {
4121 _H<NSString> *mapped;
4122
4123 _profile(Database$mappedSectionForPointer$Cache)
4124 mapped = &sections_[section];
4125 _end
4126
4127 if (*mapped == NULL) {
4128 size_t length(strlen(section));
4129 char spaced[length + 1];
4130
4131 _profile(Database$mappedSectionForPointer$Replace)
4132 for (size_t index(0); index != length; ++index)
4133 spaced[index] = section[index] == '_' ? ' ' : section[index];
4134 spaced[length] = '\0';
4135 _end
4136
4137 NSString *string;
4138
4139 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4140 string = [NSString stringWithUTF8String:spaced];
4141 _end
4142
4143 _profile(Database$mappedSectionForPointer$Map)
4144 string = [SectionMap_ objectForKey:string] ?: string;
4145 _end
4146
4147 *mapped = string;
4148 } return *mapped;
4149}
4150
4151@end
4152/* }}} */
4153
4154@interface CydiaObject : CyteObject {
4155 _transient id delegate_;
4156}
4157
4158@end
4159
4160@interface CydiaWebViewController : CyteWebViewController {
4161 _H<CydiaObject> cydia_;
4162}
4163
4164+ (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4165+ (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4166- (void) setDelegate:(id)delegate;
4167
4168@end
4169
4170/* Web Scripting {{{ */
4171@implementation CydiaObject
4172
4173- (void) setDelegate:(id)delegate {
4174 delegate_ = delegate;
4175}
4176
4177- (NSArray *) attributeKeys {
4178 return [[NSArray arrayWithObjects:
4179 @"cells",
4180 @"device",
4181 @"mcc",
4182 @"mnc",
4183 @"operator",
4184 @"role",
4185 @"version",
4186 nil] arrayByAddingObjectsFromArray:[super attributeKeys]];
4187}
4188
4189- (NSString *) version {
4190 return Cydia_;
4191}
4192
4193- (NSString *) device {
4194 return UniqueIdentifier();
4195}
4196
4197- (NSArray *) cells {
4198 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4199 if ($_CTServerConnectionCreate == NULL)
4200 return nil;
4201
4202 struct CTResult { int flag; int error; };
4203 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4204 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4205 return nil;
4206
4207 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4208 if (connection == nil)
4209 return nil;
4210
4211 int count(0);
4212 CFArrayRef cells(NULL);
4213 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4214 if (result.flag != 0)
4215 return nil;
4216
4217 return [(NSArray *) cells autorelease];
4218}
4219
4220- (NSString *) mcc {
4221 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4222 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4223 return nil;
4224}
4225
4226- (NSString *) mnc {
4227 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4228 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4229 return nil;
4230}
4231
4232- (NSString *) operator {
4233 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4234 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4235 return nil;
4236}
4237
4238- (NSString *) role {
4239 return (id) [NSNull null];
4240}
4241
4242+ (NSString *) webScriptNameForSelector:(SEL)selector {
4243 if (false);
4244 else if (selector == @selector(addBridgedHost:))
4245 return @"addBridgedHost";
4246 else if (selector == @selector(addInsecureHost:))
4247 return @"addInsecureHost";
4248 else if (selector == @selector(addSource:::))
4249 return @"addSource";
4250 else if (selector == @selector(addTrivialSource:))
4251 return @"addTrivialSource";
4252 else if (selector == @selector(du:))
4253 return @"du";
4254 else if (selector == @selector(getAllSources))
4255 return @"getAllSources";
4256 else if (selector == @selector(getApplicationInfo:value:))
4257 return @"getApplicationInfoValue";
4258 else if (selector == @selector(getDisplayIdentifiers))
4259 return @"getDisplayIdentifiers";
4260 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4261 return @"getLocalizedNameForDisplayIdentifier";
4262 else if (selector == @selector(getInstalledPackages))
4263 return @"getInstalledPackages";
4264 else if (selector == @selector(getPackageById:))
4265 return @"getPackageById";
4266 else if (selector == @selector(getMetadataKeys))
4267 return @"getMetadataKeys";
4268 else if (selector == @selector(getMetadataValue:))
4269 return @"getMetadataValue";
4270 else if (selector == @selector(getSessionValue:))
4271 return @"getSessionValue";
4272 else if (selector == @selector(installPackages:))
4273 return @"installPackages";
4274 else if (selector == @selector(refreshSources))
4275 return @"refreshSources";
4276 else if (selector == @selector(saveConfig))
4277 return @"saveConfig";
4278 else if (selector == @selector(setMetadataValue::))
4279 return @"setMetadataValue";
4280 else if (selector == @selector(setSessionValue::))
4281 return @"setSessionValue";
4282 else if (selector == @selector(substitutePackageNames:))
4283 return @"substitutePackageNames";
4284 else if (selector == @selector(setToken:))
4285 return @"setToken";
4286 else
4287 return nil;
4288}
4289
4290+ (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4291 return [self webScriptNameForSelector:selector] == nil;
4292}
4293
4294- (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4295 char path[1024];
4296 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4297 return (id) [NSNull null];
4298 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4299 if (info == nil)
4300 return (id) [NSNull null];
4301 return [info objectForKey:key];
4302}
4303
4304- (NSArray *) getDisplayIdentifiers {
4305 return SBSCopyApplicationDisplayIdentifiers(false, false);
4306}
4307
4308- (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4309 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4310}
4311
4312- (NSNumber *) getKernelNumber:(NSString *)name {
4313 const char *string([name UTF8String]);
4314
4315 size_t size;
4316 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4317 return (id) [NSNull null];
4318
4319 if (size != sizeof(int))
4320 return (id) [NSNull null];
4321
4322 int value;
4323 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4324 return (id) [NSNull null];
4325
4326 return [NSNumber numberWithInt:value];
4327}
4328
4329- (NSArray *) getMetadataKeys {
4330@synchronized (Values_) {
4331 return [Values_ allKeys];
4332} }
4333
4334- (id) getMetadataValue:(NSString *)key {
4335@synchronized (Values_) {
4336 return [Values_ objectForKey:key];
4337} }
4338
4339- (void) setMetadataValue:(NSString *)key :(NSString *)value {
4340@synchronized (Values_) {
4341 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4342 [Values_ removeObjectForKey:key];
4343 else
4344 [Values_ setObject:value forKey:key];
4345} }
4346
4347- (id) getSessionValue:(NSString *)key {
4348@synchronized (SessionData_) {
4349 return [SessionData_ objectForKey:key];
4350} }
4351
4352- (void) setSessionValue:(NSString *)key :(NSString *)value {
4353@synchronized (SessionData_) {
4354 if (value == (id) [WebUndefined undefined])
4355 [SessionData_ removeObjectForKey:key];
4356 else
4357 [SessionData_ setObject:value forKey:key];
4358} }
4359
4360- (void) addBridgedHost:(NSString *)host {
4361@synchronized (BridgedHosts_) {
4362 [BridgedHosts_ addObject:host];
4363} }
4364
4365- (void) addInsecureHost:(NSString *)host {
4366@synchronized (InsecureHosts_) {
4367 [InsecureHosts_ addObject:host];
4368} }
4369
4370- (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4371 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4372
4373 for (NSString *section in sections)
4374 [array addObject:section];
4375
4376 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4377 @"deb", @"Type",
4378 href, @"URI",
4379 distribution, @"Distribution",
4380 array, @"Sections",
4381 nil] waitUntilDone:NO];
4382}
4383
4384- (BOOL) addTrivialSource:(NSString *)href {
4385 href = VerifySource(href);
4386 if (href == nil)
4387 return NO;
4388 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4389 return YES;
4390}
4391
4392- (void) refreshSources {
4393 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4394}
4395
4396- (void) saveConfig {
4397 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4398}
4399
4400- (NSArray *) getAllSources {
4401 return [[Database sharedInstance] sources];
4402}
4403
4404- (NSArray *) getInstalledPackages {
4405 Database *database([Database sharedInstance]);
4406@synchronized (database) {
4407 NSArray *packages([database packages]);
4408 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4409 for (Package *package in packages)
4410 if (![package uninstalled])
4411 [installed addObject:package];
4412 return installed;
4413} }
4414
4415- (Package *) getPackageById:(NSString *)id {
4416 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4417 [package parse];
4418 return package;
4419 } else
4420 return (Package *) [NSNull null];
4421}
4422
4423- (NSNumber *) du:(NSString *)path {
4424 NSNumber *value(nil);
4425
4426 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4427 if (du != NULL) {
4428 char line[1024];
4429 while (fgets(line, sizeof(line), du) != NULL) {
4430 size_t length(strlen(line));
4431 while (length != 0 && line[length - 1] == '\n')
4432 line[--length] = '\0';
4433 if (char *tab = strchr(line, '\t')) {
4434 *tab = '\0';
4435 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4436 }
4437 }
4438 pclose(du);
4439 }
4440
4441 return value;
4442}
4443
4444- (void) installPackages:(NSArray *)packages {
4445 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4446}
4447
4448- (NSString *) substitutePackageNames:(NSString *)message {
4449 auto database([Database sharedInstance]);
4450
4451 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4452 if (![database hasPackages])
4453 return message;
4454
4455 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4456 for (size_t i(0), e([words count]); i != e; ++i) {
4457 NSString *word([words objectAtIndex:i]);
4458 if (Package *package = [database packageWithName:word])
4459 [words replaceObjectAtIndex:i withObject:[package name]];
4460 }
4461
4462 return [words componentsJoinedByString:@" "];
4463}
4464
4465- (void) setToken:(NSString *)token {
4466 // XXX: the website expects this :/
4467}
4468
4469@end
4470/* }}} */
4471
4472@interface NSURL (CydiaSecure)
4473@end
4474
4475@implementation NSURL (CydiaSecure)
4476
4477- (bool) isCydiaSecure {
4478 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4479 return true;
4480
4481 @synchronized (InsecureHosts_) {
4482 if ([InsecureHosts_ containsObject:[self host]])
4483 return true;
4484 }
4485
4486 return false;
4487}
4488
4489@end
4490
4491/* Cydia Browser Controller {{{ */
4492@implementation CydiaWebViewController
4493
4494- (NSURL *) navigationURL {
4495 if (NSURLRequest *request = self.request)
4496 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
4497 else
4498 return nil;
4499}
4500
4501- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4502 [super webView:view didClearWindowObject:window forFrame:frame];
4503 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4504}
4505
4506+ (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4507 WebDataSource *source([frame dataSource]);
4508 NSURLResponse *response([source response]);
4509 NSURL *url([response URL]);
4510 NSString *scheme([[url scheme] lowercaseString]);
4511
4512 bool bridged(false);
4513
4514 @synchronized (BridgedHosts_) {
4515 if ([scheme isEqualToString:@"file"])
4516 bridged = true;
4517 else if ([scheme isEqualToString:@"https"])
4518 if ([BridgedHosts_ containsObject:[url host]])
4519 bridged = true;
4520 }
4521
4522 if (bridged)
4523 [window setValue:cydia forKey:@"cydia"];
4524}
4525
4526- (void) _setupMail:(MFMailComposeViewController *)controller {
4527 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4528
4529 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4530 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4531}
4532
4533- (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4534 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4535}
4536
4537- (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4538 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4539}
4540
4541+ (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4542 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4543
4544 NSURL *url([copy URL]);
4545 NSString *href([url absoluteString]);
4546 NSString *host([url host]);
4547
4548 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4549 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4550 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4551 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4552 }
4553
4554 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4555 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4556
4557 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4558 return copy;
4559 }
4560
4561 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4562 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4563 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4564 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4565
4566 bool bridged; @synchronized (BridgedHosts_) {
4567 bridged = [BridgedHosts_ containsObject:host];
4568 }
4569
4570 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4571 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4572
4573 return copy;
4574}
4575
4576- (void) setDelegate:(id)delegate {
4577 [super setDelegate:delegate];
4578 [cydia_ setDelegate:delegate];
4579}
4580
4581- (id) init {
4582 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4583 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
4584 } return self;
4585}
4586
4587@end
4588
4589@interface AppCacheController : CydiaWebViewController {
4590}
4591
4592@end
4593
4594@implementation AppCacheController
4595
4596- (void) didReceiveMemoryWarning {
4597 // XXX: this doesn't work
4598}
4599
4600- (bool) retainsNetworkActivityIndicator {
4601 return false;
4602}
4603
4604@end
4605/* }}} */
4606
4607/* Confirmation Controller {{{ */
4608bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4609 if (!iterator.end())
4610 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4611 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4612 continue;
4613 pkgCache::PkgIterator package(dep.TargetPkg());
4614 if (package.end())
4615 continue;
4616 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4617 return true;
4618 }
4619
4620 return false;
4621}
4622
4623@protocol ConfirmationControllerDelegate
4624- (void) cancelAndClear:(bool)clear;
4625- (void) confirmWithNavigationController:(UINavigationController *)navigation;
4626- (void) queue;
4627@end
4628
4629@interface ConfirmationController : CydiaWebViewController {
4630 _transient Database *database_;
4631
4632 _H<UIAlertView> essential_;
4633
4634 _H<NSDictionary> changes_;
4635 _H<NSMutableArray> issues_;
4636 _H<NSDictionary> sizes_;
4637
4638 BOOL substrate_;
4639}
4640
4641- (id) initWithDatabase:(Database *)database;
4642
4643@end
4644
4645@implementation ConfirmationController
4646
4647- (void) complete {
4648 if (substrate_)
4649 RestartSubstrate_ = true;
4650 [self.delegate confirmWithNavigationController:[self navigationController]];
4651}
4652
4653- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4654 NSString *context([alert context]);
4655
4656 if ([context isEqualToString:@"remove"]) {
4657 if (button == [alert cancelButtonIndex])
4658 [self _doContinue];
4659 else if (button == [alert firstOtherButtonIndex]) {
4660 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4661 }
4662
4663 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4664 } else if ([context isEqualToString:@"unable"]) {
4665 [self dismissModalViewControllerAnimated:YES];
4666 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4667 } else {
4668 [super alertView:alert clickedButtonAtIndex:button];
4669 }
4670}
4671
4672- (void) _doContinue {
4673 [self.delegate cancelAndClear:NO];
4674 [self dismissModalViewControllerAnimated:YES];
4675}
4676
4677- (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4678 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4679 return nil;
4680}
4681
4682- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4683 [super webView:view didClearWindowObject:window forFrame:frame];
4684
4685 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4686 (id) changes_, @"changes",
4687 (id) issues_, @"issues",
4688 (id) sizes_, @"sizes",
4689 self, @"queue",
4690 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4691}
4692
4693- (id) initWithDatabase:(Database *)database {
4694 if ((self = [super init]) != nil) {
4695 database_ = database;
4696
4697 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4698 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4699 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4700 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4701 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4702
4703 bool remove(false);
4704
4705 pkgCacheFile &cache([database_ cache]);
4706 NSArray *packages([database_ packages]);
4707 pkgDepCache::Policy *policy([database_ policy]);
4708
4709 issues_ = [NSMutableArray arrayWithCapacity:4];
4710
4711 for (Package *package in packages) {
4712 pkgCache::PkgIterator iterator([package iterator]);
4713 NSString *name([package id]);
4714
4715 if ([package broken]) {
4716 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4717
4718 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4719 name, @"package",
4720 reasons, @"reasons",
4721 nil]];
4722
4723 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4724 if (ver.end())
4725 continue;
4726
4727 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4728 pkgCache::DepIterator start;
4729 pkgCache::DepIterator end;
4730 dep.GlobOr(start, end); // ++dep
4731
4732 if (!cache->IsImportantDep(end))
4733 continue;
4734 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4735 continue;
4736
4737 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4738
4739 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4740 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4741 clauses, @"clauses",
4742 nil]];
4743
4744 _forever {
4745 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4746
4747 pkgCache::PkgIterator target(start.TargetPkg());
4748 if (target->ProvidesList != 0)
4749 reason = @"missing";
4750 else {
4751 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4752 if (!ver.end()) {
4753 reason = @"installed";
4754 installed = [NSString stringWithUTF8String:ver.VerStr()];
4755 } else if (!cache[target].CandidateVerIter(cache).end())
4756 reason = @"uninstalled";
4757 else if (target->ProvidesList == 0)
4758 reason = @"uninstallable";
4759 else
4760 reason = @"virtual";
4761 }
4762
4763 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4764 [NSString stringWithUTF8String:start.CompType()], @"operator",
4765 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4766 nil]);
4767
4768 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4769 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4770 version, @"version",
4771 reason, @"reason",
4772 installed, @"installed",
4773 nil]];
4774
4775 // yes, seriously. (wtf?)
4776 if (start == end)
4777 break;
4778 ++start;
4779 }
4780 }
4781 }
4782
4783 pkgDepCache::StateCache &state(cache[iterator]);
4784
4785 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
4786
4787 if (state.NewInstall())
4788 [installs addObject:name];
4789 // XXX: else if (state.Install())
4790 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4791 [reinstalls addObject:name];
4792 // XXX: move before previous if
4793 else if (state.Upgrade())
4794 [upgrades addObject:name];
4795 else if (state.Downgrade())
4796 [downgrades addObject:name];
4797 else if (!state.Delete())
4798 // XXX: _assert(state.Keep());
4799 continue;
4800 else if (special_r(name))
4801 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4802 [NSNull null], @"package",
4803 [NSArray arrayWithObjects:
4804 [NSDictionary dictionaryWithObjectsAndKeys:
4805 @"Conflicts", @"relationship",
4806 [NSArray arrayWithObjects:
4807 [NSDictionary dictionaryWithObjectsAndKeys:
4808 name, @"package",
4809 [NSNull null], @"version",
4810 @"installed", @"reason",
4811 nil],
4812 nil], @"clauses",
4813 nil],
4814 nil], @"reasons",
4815 nil]];
4816 else {
4817 if ([package essential])
4818 remove = true;
4819 [removes addObject:name];
4820 }
4821
4822 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4823 substrate_ |= DepSubstrate(iterator.CurrentVer());
4824 }
4825
4826 if (!remove)
4827 essential_ = nil;
4828 else if (Advanced_) {
4829 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4830
4831 essential_ = [[[UIAlertView alloc]
4832 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4833 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4834 delegate:self
4835 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4836 otherButtonTitles:
4837 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4838 nil
4839 ] autorelease];
4840
4841 [essential_ setContext:@"remove"];
4842 [essential_ setNumberOfRows:2];
4843 } else {
4844 essential_ = [[[UIAlertView alloc]
4845 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4846 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4847 delegate:self
4848 cancelButtonTitle:UCLocalize("OKAY")
4849 otherButtonTitles:nil
4850 ] autorelease];
4851
4852 [essential_ setContext:@"unable"];
4853 }
4854
4855 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4856 installs, @"installs",
4857 reinstalls, @"reinstalls",
4858 upgrades, @"upgrades",
4859 downgrades, @"downgrades",
4860 removes, @"removes",
4861 nil];
4862
4863 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4864 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4865 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4866 nil];
4867
4868 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4869 } return self;
4870}
4871
4872- (UIBarButtonItem *) leftButton {
4873 return [[[UIBarButtonItem alloc]
4874 initWithTitle:UCLocalize("CANCEL")
4875 style:UIBarButtonItemStylePlain
4876 target:self
4877 action:@selector(cancelButtonClicked)
4878 ] autorelease];
4879}
4880
4881#if !AlwaysReload
4882- (void) applyRightButton {
4883 if ([issues_ count] == 0 && ![self isLoading])
4884 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4885 initWithTitle:UCLocalize("CONFIRM")
4886 style:UIBarButtonItemStyleDone
4887 target:self
4888 action:@selector(confirmButtonClicked)
4889 ] autorelease]];
4890 else
4891 [[self navigationItem] setRightBarButtonItem:nil];
4892}
4893#endif
4894
4895- (void) cancelButtonClicked {
4896 [self.delegate cancelAndClear:YES];
4897 [self dismissModalViewControllerAnimated:YES];
4898}
4899
4900#if !AlwaysReload
4901- (void) confirmButtonClicked {
4902 if (essential_ != nil)
4903 [essential_ show];
4904 else
4905 [self complete];
4906}
4907#endif
4908
4909@end
4910/* }}} */
4911
4912/* Progress Data {{{ */
4913@interface CydiaProgressData : NSObject {
4914 _transient id delegate_;
4915
4916 bool running_;
4917 float percent_;
4918
4919 float current_;
4920 float total_;
4921 float speed_;
4922
4923 _H<NSMutableArray> events_;
4924 _H<NSString> title_;
4925
4926 _H<NSString> status_;
4927 _H<NSString> finish_;
4928}
4929
4930@end
4931
4932@implementation CydiaProgressData
4933
4934+ (NSArray *) _attributeKeys {
4935 return [NSArray arrayWithObjects:
4936 @"current",
4937 @"events",
4938 @"finish",
4939 @"percent",
4940 @"running",
4941 @"speed",
4942 @"title",
4943 @"total",
4944 nil];
4945}
4946
4947- (NSArray *) attributeKeys {
4948 return [[self class] _attributeKeys];
4949}
4950
4951+ (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4952 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4953}
4954
4955- (id) init {
4956 if ((self = [super init]) != nil) {
4957 events_ = [NSMutableArray arrayWithCapacity:32];
4958 } return self;
4959}
4960
4961- (id) delegate {
4962 return delegate_;
4963}
4964
4965- (void) setDelegate:(id)delegate {
4966 delegate_ = delegate;
4967}
4968
4969- (void) setPercent:(float)value {
4970 percent_ = value;
4971}
4972
4973- (NSNumber *) percent {
4974 return [NSNumber numberWithFloat:percent_];
4975}
4976
4977- (void) setCurrent:(float)value {
4978 current_ = value;
4979}
4980
4981- (NSNumber *) current {
4982 return [NSNumber numberWithFloat:current_];
4983}
4984
4985- (void) setTotal:(float)value {
4986 total_ = value;
4987}
4988
4989- (NSNumber *) total {
4990 return [NSNumber numberWithFloat:total_];
4991}
4992
4993- (void) setSpeed:(float)value {
4994 speed_ = value;
4995}
4996
4997- (NSNumber *) speed {
4998 return [NSNumber numberWithFloat:speed_];
4999}
5000
5001- (NSArray *) events {
5002 return events_;
5003}
5004
5005- (void) removeAllEvents {
5006 [events_ removeAllObjects];
5007}
5008
5009- (void) addEvent:(CydiaProgressEvent *)event {
5010 [events_ addObject:event];
5011}
5012
5013- (void) setTitle:(NSString *)text {
5014 title_ = text;
5015}
5016
5017- (NSString *) title {
5018 return title_;
5019}
5020
5021- (void) setFinish:(NSString *)text {
5022 finish_ = text;
5023}
5024
5025- (NSString *) finish {
5026 return (id) finish_ ?: [NSNull null];
5027}
5028
5029- (void) setRunning:(bool)running {
5030 running_ = running;
5031}
5032
5033- (NSNumber *) running {
5034 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5035}
5036
5037@end
5038/* }}} */
5039/* Progress Controller {{{ */
5040@interface ProgressController : CydiaWebViewController <
5041 ProgressDelegate
5042> {
5043 _transient Database *database_;
5044 _H<CydiaProgressData, 1> progress_;
5045 unsigned cancel_;
5046}
5047
5048- (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5049
5050- (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5051
5052- (void) setTitle:(NSString *)title;
5053- (void) setCancellable:(bool)cancellable;
5054
5055@end
5056
5057@implementation ProgressController
5058
5059- (void) dealloc {
5060 [database_ setProgressDelegate:nil];
5061 [super dealloc];
5062}
5063
5064- (UIBarButtonItem *) leftButton {
5065 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5066 initWithTitle:UCLocalize("CANCEL")
5067 style:UIBarButtonItemStylePlain
5068 target:self
5069 action:@selector(cancel)
5070 ] autorelease] : nil;
5071}
5072
5073- (void) updateCancel {
5074 [super applyLeftButton];
5075}
5076
5077- (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5078 if ((self = [super init]) != nil) {
5079 database_ = database;
5080 self.delegate = delegate;
5081
5082 [database_ setProgressDelegate:self];
5083
5084 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5085 [progress_ setDelegate:self];
5086
5087 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5088
5089 [self setPageColor:[UIColor blackColor]];
5090
5091 [[self navigationItem] setHidesBackButton:YES];
5092
5093 [self updateCancel];
5094 } return self;
5095}
5096
5097- (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5098 [super webView:view didClearWindowObject:window forFrame:frame];
5099 [window setValue:progress_ forKey:@"cydiaProgress"];
5100}
5101
5102- (void) updateProgress {
5103 [self dispatchEvent:@"CydiaProgressUpdate"];
5104}
5105
5106- (void) viewWillAppear:(BOOL)animated {
5107 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5108 [super viewWillAppear:animated];
5109}
5110
5111- (void) close {
5112 UpdateExternalStatus(0);
5113
5114 if (Finish_ > 1)
5115 [self.delegate saveState];
5116
5117 switch (Finish_) {
5118 case 0:
5119 [self.delegate returnToCydia];
5120 break;
5121
5122 case 1:
5123 [self.delegate terminateWithSuccess];
5124 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5125 [self.delegate suspendWithAnimation:YES];
5126 else
5127 [self.delegate suspend];*/
5128 break;
5129
5130 case 2:
5131 _trace();
5132 goto reload;
5133
5134 case 3:
5135 _trace();
5136 goto reload;
5137
5138 reload: {
5139 UIProgressHUD *hud([self.delegate addProgressHUD]);
5140 [hud setText:UCLocalize("LOADING")];
5141 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5142 return;
5143 }
5144
5145 case 4:
5146 _trace();
5147 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5148 SBReboot(SBSSpringBoardServerPort());
5149 else
5150 reboot2(RB_AUTOBOOT);
5151 break;
5152 }
5153
5154 [super close];
5155}
5156
5157- (void) setTitle:(NSString *)title {
5158 [progress_ setTitle:title];
5159 [self updateProgress];
5160}
5161
5162- (UIBarButtonItem *) rightButton {
5163 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5164 initWithTitle:UCLocalize("CLOSE")
5165 style:UIBarButtonItemStylePlain
5166 target:self
5167 action:@selector(close)
5168 ] autorelease];
5169}
5170
5171- (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5172 UpdateExternalStatus(1);
5173
5174 [progress_ setRunning:true];
5175 [self setTitle:title];
5176 // implicit updateProgress
5177
5178 SHA1SumValue notifyconf; {
5179 FileFd file;
5180 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5181 _error->Discard();
5182 else {
5183 MMap mmap(file, MMap::ReadOnly);
5184 SHA1Summation sha1;
5185 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5186 notifyconf = sha1.Result();
5187 }
5188 }
5189
5190 SHA1SumValue springlist; {
5191 FileFd file;
5192 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5193 _error->Discard();
5194 else {
5195 MMap mmap(file, MMap::ReadOnly);
5196 SHA1Summation sha1;
5197 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5198 springlist = sha1.Result();
5199 }
5200 }
5201
5202 if (invocation != nil) {
5203 [invocation yieldToSelector:@selector(invoke)];
5204 [self setTitle:@"COMPLETE"];
5205 }
5206
5207 if (Finish_ < 4) {
5208 FileFd file;
5209 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5210 _error->Discard();
5211 else {
5212 MMap mmap(file, MMap::ReadOnly);
5213 SHA1Summation sha1;
5214 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5215 if (!(notifyconf == sha1.Result()))
5216 Finish_ = 4;
5217 }
5218 }
5219
5220 if (Finish_ < 3) {
5221 FileFd file;
5222 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5223 _error->Discard();
5224 else {
5225 MMap mmap(file, MMap::ReadOnly);
5226 SHA1Summation sha1;
5227 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5228 if (!(springlist == sha1.Result()))
5229 Finish_ = 3;
5230 }
5231 }
5232
5233 if (Finish_ < 2) {
5234 if (RestartSubstrate_)
5235 Finish_ = 2;
5236 }
5237
5238 RestartSubstrate_ = false;
5239
5240 switch (Finish_) {
5241 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5242 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5243 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5244 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5245 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5246 }
5247
5248 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5249
5250 [progress_ setRunning:false];
5251 [self updateProgress];
5252
5253 [self applyRightButton];
5254}
5255
5256- (void) addProgressEvent:(CydiaProgressEvent *)event {
5257 [progress_ addEvent:event];
5258 [self updateProgress];
5259}
5260
5261- (bool) isProgressCancelled {
5262 return cancel_ == 2;
5263}
5264
5265- (void) cancel {
5266 cancel_ = 2;
5267 [self updateCancel];
5268}
5269
5270- (void) setCancellable:(bool)cancellable {
5271 unsigned cancel(cancel_);
5272
5273 if (!cancellable)
5274 cancel_ = 0;
5275 else if (cancel_ == 0)
5276 cancel_ = 1;
5277
5278 if (cancel != cancel_)
5279 [self updateCancel];
5280}
5281
5282- (void) setProgressCancellable:(NSNumber *)cancellable {
5283 [self setCancellable:[cancellable boolValue]];
5284}
5285
5286- (void) setProgressPercent:(NSNumber *)percent {
5287 [progress_ setPercent:[percent floatValue]];
5288 [self updateProgress];
5289}
5290
5291- (void) setProgressStatus:(NSDictionary *)status {
5292 if (status == nil) {
5293 [progress_ setCurrent:0];
5294 [progress_ setTotal:0];
5295 [progress_ setSpeed:0];
5296 } else {
5297 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5298
5299 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5300 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5301 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5302 }
5303
5304 [self updateProgress];
5305}
5306
5307@end
5308/* }}} */
5309
5310/* Package Cell {{{ */
5311@interface PackageCell : CyteTableViewCell <
5312 CyteTableViewCellDelegate
5313> {
5314 _H<UIImage> icon_;
5315 _H<NSString> name_;
5316 _H<NSString> description_;
5317 bool commercial_;
5318 _H<NSString> source_;
5319 _H<UIImage> badge_;
5320 _H<UIImage> placard_;
5321 bool summarized_;
5322}
5323
5324- (PackageCell *) init;
5325- (void) setPackage:(Package *)package asSummary:(bool)summary;
5326
5327- (void) drawContentRect:(CGRect)rect;
5328
5329@end
5330
5331@implementation PackageCell
5332
5333- (PackageCell *) init {
5334 CGRect frame(CGRectMake(0, 0, 320, 74));
5335 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5336 [self.content setOpaque:YES];
5337 } return self;
5338}
5339
5340- (NSString *) accessibilityLabel {
5341 return name_;
5342}
5343
5344- (void) setPackage:(Package *)package asSummary:(bool)summary {
5345 summarized_ = summary;
5346
5347 icon_ = nil;
5348 name_ = nil;
5349 description_ = nil;
5350 source_ = nil;
5351 badge_ = nil;
5352 placard_ = nil;
5353
5354 if (package == nil)
5355 [self.content setBackgroundColor:[UIColor whiteColor]];
5356 else {
5357 [package parse];
5358
5359 Source *source = [package source];
5360
5361 icon_ = [package icon];
5362
5363 if (NSString *name = [package name])
5364 name_ = [NSString stringWithString:name];
5365
5366 if (NSString *description = [package shortDescription])
5367 description_ = [NSString stringWithString:description];
5368
5369 commercial_ = [package isCommercial];
5370
5371 NSString *label = nil;
5372 bool trusted = false;
5373
5374 if (source != nil) {
5375 label = [source label];
5376 trusted = [source trusted];
5377 } else if ([[package id] isEqualToString:@"firmware"])
5378 label = UCLocalize("APPLE");
5379 else
5380 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5381
5382 NSString *from(label);
5383
5384 NSString *section = [package simpleSection];
5385 if (section != nil && ![section isEqualToString:label]) {
5386 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5387 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5388 }
5389
5390 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5391
5392 if (NSString *purpose = [package primaryPurpose])
5393 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5394
5395 UIColor *color;
5396 NSString *placard;
5397
5398 if (NSString *mode = [package mode]) {
5399 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5400 color = RemovingColor_;
5401 placard = @"removing";
5402 } else {
5403 color = InstallingColor_;
5404 placard = @"installing";
5405 }
5406 } else {
5407 color = [UIColor whiteColor];
5408
5409 if ([package installed] != nil)
5410 placard = @"installed";
5411 else
5412 placard = nil;
5413 }
5414
5415 [self.content setBackgroundColor:color];
5416
5417 if (placard != nil)
5418 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5419 }
5420
5421 [self setNeedsDisplay];
5422 [self.content setNeedsDisplay];
5423}
5424
5425- (void) drawSummaryContentRect:(CGRect)rect {
5426 bool highlighted(self.highlighted);
5427 float width([self bounds].size.width);
5428
5429 if (icon_ != nil) {
5430 CGRect rect;
5431 rect.size = [(UIImage *) icon_ size];
5432
5433 while (rect.size.width > 16 || rect.size.height > 16) {
5434 rect.size.width /= 2;
5435 rect.size.height /= 2;
5436 }
5437
5438 rect.origin.x = 19 - rect.size.width / 2;
5439 rect.origin.y = 19 - rect.size.height / 2;
5440
5441 [icon_ drawInRect:Retina(rect)];
5442 }
5443
5444 if (badge_ != nil) {
5445 CGRect rect;
5446 rect.size = [(UIImage *) badge_ size];
5447
5448 rect.size.width /= 4;
5449 rect.size.height /= 4;
5450
5451 rect.origin.x = 25 - rect.size.width / 2;
5452 rect.origin.y = 25 - rect.size.height / 2;
5453
5454 [badge_ drawInRect:Retina(rect)];
5455 }
5456
5457 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5458 UISetColor(White_);
5459
5460 if (!highlighted)
5461 UISetColor(commercial_ ? Purple_ : Black_);
5462 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5463
5464 if (placard_ != nil)
5465 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5466}
5467
5468- (void) drawNormalContentRect:(CGRect)rect {
5469 bool highlighted(self.highlighted);
5470 float width([self bounds].size.width);
5471
5472 if (icon_ != nil) {
5473 CGRect rect;
5474 rect.size = [(UIImage *) icon_ size];
5475
5476 while (rect.size.width > 32 || rect.size.height > 32) {
5477 rect.size.width /= 2;
5478 rect.size.height /= 2;
5479 }
5480
5481 rect.origin.x = 25 - rect.size.width / 2;
5482 rect.origin.y = 25 - rect.size.height / 2;
5483
5484 [icon_ drawInRect:Retina(rect)];
5485 }
5486
5487 if (badge_ != nil) {
5488 CGRect rect;
5489 rect.size = [(UIImage *) badge_ size];
5490
5491 rect.size.width /= 2;
5492 rect.size.height /= 2;
5493
5494 rect.origin.x = 36 - rect.size.width / 2;
5495 rect.origin.y = 36 - rect.size.height / 2;
5496
5497 [badge_ drawInRect:Retina(rect)];
5498 }
5499
5500 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5501 UISetColor(White_);
5502
5503 if (!highlighted)
5504 UISetColor(commercial_ ? Purple_ : Black_);
5505 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5506 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5507
5508 if (!highlighted)
5509 UISetColor(commercial_ ? Purplish_ : Gray_);
5510 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5511
5512 if (placard_ != nil)
5513 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5514}
5515
5516- (void) drawContentRect:(CGRect)rect {
5517 if (summarized_)
5518 [self drawSummaryContentRect:rect];
5519 else
5520 [self drawNormalContentRect:rect];
5521}
5522
5523@end
5524/* }}} */
5525/* Section Cell {{{ */
5526@interface SectionCell : CyteTableViewCell <
5527 CyteTableViewCellDelegate
5528> {
5529 _H<NSString> basic_;
5530 _H<NSString> section_;
5531 _H<NSString> name_;
5532 _H<NSString> count_;
5533 _H<UIImage> icon_;
5534 _H<UISwitch> switch_;
5535 BOOL editing_;
5536}
5537
5538- (void) setSection:(Section *)section editing:(BOOL)editing;
5539
5540@end
5541
5542@implementation SectionCell
5543
5544- (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5545 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5546 icon_ = [UIImage imageNamed:@"folder.png"];
5547 // XXX: this initial frame is wrong, but is fixed later
5548 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5549 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5550
5551 [self.content setBackgroundColor:[UIColor whiteColor]];
5552 } return self;
5553}
5554
5555- (void) onSwitch:(id)sender {
5556 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5557 if (metadata == nil) {
5558 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5559 [Sections_ setObject:metadata forKey:basic_];
5560 }
5561
5562 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5563}
5564
5565- (void) setSection:(Section *)section editing:(BOOL)editing {
5566 if (editing != editing_) {
5567 if (editing_)
5568 [switch_ removeFromSuperview];
5569 else
5570 [self addSubview:switch_];
5571 editing_ = editing;
5572 }
5573
5574 basic_ = nil;
5575 section_ = nil;
5576 name_ = nil;
5577 count_ = nil;
5578
5579 if (section == nil) {
5580 name_ = UCLocalize("ALL_PACKAGES");
5581 count_ = nil;
5582 } else {
5583 basic_ = [section name];
5584 section_ = [section localized];
5585
5586 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5587 count_ = [NSString stringWithFormat:@"%zd", [section count]];
5588
5589 if (editing_)
5590 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5591 }
5592
5593 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5594 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5595
5596 [self.content setNeedsDisplay];
5597}
5598
5599- (void) setFrame:(CGRect)frame {
5600 [super setFrame:frame];
5601
5602 CGRect rect([switch_ frame]);
5603 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5604}
5605
5606- (NSString *) accessibilityLabel {
5607 return name_;
5608}
5609
5610- (void) drawContentRect:(CGRect)rect {
5611 bool highlighted(self.highlighted && !editing_);
5612
5613 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5614
5615 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5616 UISetColor(White_);
5617
5618 float width(rect.size.width);
5619 if (editing_)
5620 width -= 9 + [switch_ frame].size.width;
5621
5622 if (!highlighted)
5623 UISetColor(Black_);
5624 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
5625
5626 CGSize size = [count_ sizeWithFont:Font14_];
5627
5628 UISetColor(Folder_);
5629 if (count_ != nil)
5630 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
5631}
5632
5633@end
5634/* }}} */
5635
5636/* File Table {{{ */
5637@interface FileTable : CyteListController <
5638 UITableViewDataSource,
5639 UITableViewDelegate
5640> {
5641 _transient Database *database_;
5642 _H<Package> package_;
5643 _H<NSString> name_;
5644 _H<NSMutableArray> files_;
5645}
5646
5647- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5648
5649@end
5650
5651@implementation FileTable
5652
5653- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5654 return files_ == nil ? 0 : [files_ count];
5655}
5656
5657/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5658 return 24.0f;
5659}*/
5660
5661- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5662 static NSString *reuseIdentifier = @"Cell";
5663
5664 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5665 if (cell == nil) {
5666 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5667 [cell setFont:[UIFont systemFontOfSize:16]];
5668 }
5669 [cell setText:[files_ objectAtIndex:indexPath.row]];
5670 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5671
5672 return cell;
5673}
5674
5675- (NSURL *) navigationURL {
5676 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5677}
5678
5679- (CGFloat) rowHeight {
5680 return 24;
5681}
5682
5683- (void) releaseSubviews {
5684 package_ = nil;
5685 files_ = nil;
5686
5687 [super releaseSubviews];
5688}
5689
5690- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5691 if ((self = [super initWithTitle:UCLocalize("INSTALLED_FILES")]) != nil) {
5692 database_ = database;
5693 name_ = name;
5694 } return self;
5695}
5696
5697- (bool) shouldYield {
5698 return false;
5699}
5700
5701- (void) _reloadData {
5702 files_ = nil;
5703
5704 package_ = [database_ packageWithName:name_];
5705 if (package_ != nil) {
5706 files_ = [NSMutableArray arrayWithCapacity:32];
5707
5708 if (NSArray *files = [package_ files])
5709 [files_ addObjectsFromArray:files];
5710
5711 if ([files_ count] != 0) {
5712 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5713 [files_ removeObjectAtIndex:0];
5714 [files_ sortUsingSelector:@selector(compareByPath:)];
5715
5716 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5717 [stack addObject:@"/"];
5718
5719 for (int i(0), e([files_ count]); i != e; ++i) {
5720 NSString *file = [files_ objectAtIndex:i];
5721 while (![file hasPrefix:[stack lastObject]])
5722 [stack removeLastObject];
5723 NSString *directory = [stack lastObject];
5724 [stack addObject:[file stringByAppendingString:@"/"]];
5725 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5726 int(([stack count] - 2) * 3), "",
5727 [file substringFromIndex:[directory length]]
5728 ]];
5729 }
5730 }
5731 }
5732
5733 [super _reloadData];
5734}
5735
5736@end
5737/* }}} */
5738/* Package Controller {{{ */
5739@interface CYPackageController : CydiaWebViewController <
5740 UIActionSheetDelegate
5741> {
5742 _transient Database *database_;
5743 _H<Package> package_;
5744 _H<NSString> name_;
5745 bool commercial_;
5746 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
5747 _H<UIActionSheet> sheet_;
5748 _H<UIBarButtonItem> button_;
5749 _H<NSArray> versions_;
5750}
5751
5752- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5753
5754@end
5755
5756@implementation CYPackageController
5757
5758- (NSURL *) navigationURL {
5759 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5760}
5761
5762- (void) _clickButtonWithPackage:(Package *)package {
5763 [self.delegate installPackage:package];
5764}
5765
5766- (void) _clickButtonWithName:(NSString *)name {
5767 if ([name isEqualToString:@"CLEAR"])
5768 return [self.delegate clearPackage:package_];
5769 else if ([name isEqualToString:@"REMOVE"])
5770 return [self.delegate removePackage:package_];
5771 else if ([name isEqualToString:@"DOWNGRADE"]) {
5772 sheet_ = [[[UIActionSheet alloc]
5773 initWithTitle:nil
5774 delegate:self
5775 cancelButtonTitle:nil
5776 destructiveButtonTitle:nil
5777 otherButtonTitles:nil
5778 ] autorelease];
5779
5780 for (Package *version in (id) versions_)
5781 [sheet_ addButtonWithTitle:[version latest]];
5782 [sheet_ setContext:@"version"];
5783
5784 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
5785 return;
5786 }
5787
5788 else if ([name isEqualToString:@"INSTALL"]);
5789 else if ([name isEqualToString:@"REINSTALL"]);
5790 else if ([name isEqualToString:@"UPGRADE"]);
5791 else _assert(false);
5792
5793 [self.delegate installPackage:package_];
5794}
5795
5796- (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5797 NSString *context([sheet context]);
5798 if (sheet_ == sheet)
5799 sheet_ = nil;
5800
5801 if ([context isEqualToString:@"modify"]) {
5802 if (button != [sheet cancelButtonIndex]) {
5803 if (IsWildcat_)
5804 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
5805 else
5806 [self _clickButtonWithName:buttons_[button].first];
5807 }
5808
5809 [sheet dismissWithClickedButtonIndex:button animated:YES];
5810 } else if ([context isEqualToString:@"version"]) {
5811 if (button != [sheet cancelButtonIndex]) {
5812 Package *version([versions_ objectAtIndex:button]);
5813 if (IsWildcat_)
5814 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
5815 else
5816 [self _clickButtonWithPackage:version];
5817 }
5818
5819 [sheet dismissWithClickedButtonIndex:button animated:YES];
5820 }
5821}
5822
5823- (bool) _allowJavaScriptPanel {
5824 return commercial_;
5825}
5826
5827#if !AlwaysReload
5828- (void) _customButtonClicked {
5829 if (commercial_ && self.isLoading && [package_ uninstalled])
5830 return [self reloadURLWithCache:NO];
5831
5832 size_t count(buttons_.size());
5833 if (count == 0)
5834 return;
5835
5836 if (count == 1)
5837 [self _clickButtonWithName:buttons_[0].first];
5838 else {
5839 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5840 for (const auto &button : buttons_)
5841 [buttons addObject:button.second];
5842
5843 sheet_ = [[[UIActionSheet alloc]
5844 initWithTitle:nil
5845 delegate:self
5846 cancelButtonTitle:nil
5847 destructiveButtonTitle:nil
5848 otherButtonTitles:nil
5849 ] autorelease];
5850
5851 for (NSString *button in buttons)
5852 [sheet_ addButtonWithTitle:button];
5853 [sheet_ setContext:@"modify"];
5854
5855 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
5856 }
5857}
5858
5859- (void) applyLoadingTitle {
5860 // Don't show "Loading" as the title. Ever.
5861}
5862
5863- (UIBarButtonItem *) rightButton {
5864 return button_;
5865}
5866#endif
5867
5868- (void) setPageColor:(UIColor *)color {
5869 return [super setPageColor:nil];
5870}
5871
5872- (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
5873 if ((self = [super init]) != nil) {
5874 database_ = database;
5875 name_ = name == nil ? @"" : [NSString stringWithString:name];
5876 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
5877 } return self;
5878}
5879
5880- (void) reloadData {
5881 [super reloadData];
5882
5883 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
5884 sheet_ = nil;
5885
5886 package_ = [database_ packageWithName:name_];
5887 versions_ = [package_ downgrades];
5888
5889 buttons_.clear();
5890
5891 if (package_ != nil) {
5892 [(Package *) package_ parse];
5893
5894 commercial_ = [package_ isCommercial];
5895
5896 if ([package_ mode] != nil)
5897 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
5898 if ([package_ source] == nil);
5899 else if ([package_ upgradableAndEssential:NO])
5900 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
5901 else if ([package_ uninstalled])
5902 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
5903 else
5904 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
5905 if (![package_ uninstalled])
5906 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
5907 if ([versions_ count] != 0)
5908 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
5909 }
5910
5911 NSString *title;
5912 switch (buttons_.size()) {
5913 case 0: title = nil; break;
5914 case 1: title = buttons_[0].second; break;
5915 default: title = UCLocalize("MODIFY"); break;
5916 }
5917
5918 button_ = [[[UIBarButtonItem alloc]
5919 initWithTitle:title
5920 style:UIBarButtonItemStylePlain
5921 target:self
5922 action:@selector(customButtonClicked)
5923 ] autorelease];
5924}
5925
5926- (bool) isLoading {
5927 return commercial_ ? [super isLoading] : false;
5928}
5929
5930@end
5931/* }}} */
5932
5933/* Package List Controller {{{ */
5934@interface PackageListController : CyteListController <
5935 UITableViewDataSource,
5936 UITableViewDelegate
5937> {
5938 _transient Database *database_;
5939 unsigned era_;
5940 _H<NSArray> packages_;
5941 _H<NSArray> sections_;
5942
5943 _H<NSArray> thumbs_;
5944 std::vector<NSInteger> offset_;
5945
5946 unsigned reloading_;
5947}
5948
5949- (id) initWithDatabase:(Database *)database title:(NSString *)title;
5950
5951- (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
5952
5953@end
5954
5955@implementation PackageListController
5956
5957- (NSURL *) referrerURL {
5958 return [self navigationURL];
5959}
5960
5961- (bool) isSummarized {
5962 return false;
5963}
5964
5965- (bool) showsSections {
5966 return true;
5967}
5968
5969- (void) didSelectPackage:(Package *)package {
5970 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
5971 [view setDelegate:self.delegate];
5972 [[self navigationController] pushViewController:view animated:YES];
5973}
5974
5975- (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5976 NSInteger count([sections_ count]);
5977 return count == 0 ? 1 : count;
5978}
5979
5980- (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5981 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5982 return nil;
5983 return [[sections_ objectAtIndex:section] name];
5984}
5985
5986- (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5987 if ([sections_ count] == 0)
5988 return 0;
5989 return [[sections_ objectAtIndex:section] count];
5990}
5991
5992- (Package *) packageAtIndexPath:(NSIndexPath *)path {
5993@synchronized (database_) {
5994 if ([database_ era] != era_)
5995 return nil;
5996
5997 Section *section([sections_ objectAtIndex:[path section]]);
5998 NSInteger row([path row]);
5999 Package *package([packages_ objectAtIndex:([section row] + row)]);
6000 return [[package retain] autorelease];
6001} }
6002
6003- (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6004 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6005 if (cell == nil)
6006 cell = [[[PackageCell alloc] init] autorelease];
6007
6008 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6009 [cell setPackage:package asSummary:[self isSummarized]];
6010 return cell;
6011}
6012
6013- (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6014 Package *package([self packageAtIndexPath:path]);
6015 package = [database_ packageWithName:[package id]];
6016 [self didSelectPackage:package];
6017}
6018
6019- (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6020 return thumbs_;
6021}
6022
6023- (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6024 return offset_[index];
6025}
6026
6027- (CGFloat) rowHeight {
6028 return [self isSummarized] ? 38 : 73;
6029}
6030
6031- (id) initWithDatabase:(Database *)database title:(NSString *)title {
6032 if ((self = [super initWithTitle:title]) != nil) {
6033 database_ = database;
6034 } return self;
6035}
6036
6037- (void) releaseSubviews {
6038 packages_ = nil;
6039 sections_ = nil;
6040
6041 thumbs_ = nil;
6042 offset_.clear();
6043
6044 [super releaseSubviews];
6045}
6046
6047- (bool) shouldBlock {
6048 return false;
6049}
6050
6051- (NSMutableArray *) _reloadPackages {
6052@synchronized (database_) {
6053 era_ = [database_ era];
6054 NSArray *packages([database_ packages]);
6055
6056 return [NSMutableArray arrayWithArray:packages];
6057} }
6058
6059- (void) _reloadData {
6060 if (reloading_ != 0) {
6061 reloading_ = 2;
6062 return;
6063 }
6064
6065 NSMutableArray *packages;
6066
6067 reload:
6068 if ([self shouldYield]) {
6069 do {
6070 UIProgressHUD *hud;
6071
6072 if (![self shouldBlock])
6073 hud = nil;
6074 else {
6075 hud = [self.delegate addProgressHUD];
6076 [hud setText:UCLocalize("LOADING")];
6077 }
6078
6079 reloading_ = 1;
6080 packages = [self yieldToSelector:@selector(_reloadPackages)];
6081
6082 if (hud != nil)
6083 [self.delegate removeProgressHUD:hud];
6084 } while (reloading_ == 2);
6085 } else {
6086 packages = [self _reloadPackages];
6087 }
6088
6089@synchronized (database_) {
6090 if (era_ != [database_ era])
6091 goto reload;
6092 reloading_ = 0;
6093
6094 thumbs_ = nil;
6095 offset_.clear();
6096
6097 packages_ = packages;
6098
6099 if ([self showsSections])
6100 sections_ = [self sectionsForPackages:packages];
6101 else {
6102 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6103 [section setCount:[packages_ count]];
6104 sections_ = [NSArray arrayWithObject:section];
6105 }
6106
6107 [super _reloadData];
6108}
6109
6110 PrintTimes();
6111}
6112
6113- (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6114 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6115 size_t end([packages count]);
6116
6117 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6118 Section *section(prefix);
6119
6120 thumbs_ = CollationThumbs_;
6121 offset_ = CollationOffset_;
6122
6123 size_t offset(0);
6124 size_t offsets([CollationStarts_ count]);
6125
6126 NSString *start([CollationStarts_ objectAtIndex:offset]);
6127 size_t length([start length]);
6128
6129 for (size_t index(0); index != end; ++index) {
6130 if (start != nil) {
6131 Package *package([packages objectAtIndex:index]);
6132 NSString *name(PackageName(package, @selector(cyname)));
6133
6134 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6135 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6136 NSString *title([CollationTitles_ objectAtIndex:offset]);
6137 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6138 [sections addObject:section];
6139
6140 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6141 if (start == nil)
6142 break;
6143 length = [start length];
6144 }
6145 }
6146
6147 [section addToCount];
6148 }
6149
6150 for (; offset != offsets; ++offset) {
6151 NSString *title([CollationTitles_ objectAtIndex:offset]);
6152 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6153 [sections addObject:section];
6154 }
6155
6156 if ([prefix count] != 0) {
6157 Section *suffix([sections lastObject]);
6158 [prefix setName:[suffix name]];
6159 [suffix setName:nil];
6160 [sections insertObject:prefix atIndex:(offsets - 1)];
6161 }
6162
6163 return sections;
6164}
6165
6166@end
6167/* }}} */
6168/* Filtered Package List Controller {{{ */
6169typedef Function<bool, Package *> PackageFilter;
6170typedef Function<void, NSMutableArray *> PackageSorter;
6171@interface FilteredPackageListController : PackageListController {
6172 PackageFilter filter_;
6173 PackageSorter sorter_;
6174}
6175
6176- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6177
6178- (void) setFilter:(PackageFilter)filter;
6179- (void) setSorter:(PackageSorter)sorter;
6180
6181@end
6182
6183@implementation FilteredPackageListController
6184
6185- (void) setFilter:(PackageFilter)filter {
6186@synchronized (self) {
6187 filter_ = filter;
6188} }
6189
6190- (void) setSorter:(PackageSorter)sorter {
6191@synchronized (self) {
6192 sorter_ = sorter;
6193} }
6194
6195- (NSMutableArray *) _reloadPackages {
6196@synchronized (database_) {
6197 era_ = [database_ era];
6198
6199 NSArray *packages([database_ packages]);
6200 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6201
6202 PackageFilter filter;
6203 PackageSorter sorter;
6204
6205 @synchronized (self) {
6206 filter = filter_;
6207 sorter = sorter_;
6208 }
6209
6210 _profile(PackageTable$reloadData$Filter)
6211 for (Package *package in packages)
6212 if (filter(package))
6213 [filtered addObject:package];
6214 _end
6215
6216 if (sorter)
6217 sorter(filtered);
6218 return filtered;
6219} }
6220
6221- (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6222 if ((self = [super initWithDatabase:database title:title]) != nil) {
6223 [self setFilter:filter];
6224 } return self;
6225}
6226
6227@end
6228/* }}} */
6229
6230/* Home Controller {{{ */
6231@interface HomeController : CydiaWebViewController {
6232 CFRunLoopRef runloop_;
6233 SCNetworkReachabilityRef reachability_;
6234}
6235
6236@end
6237
6238@implementation HomeController
6239
6240static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6241 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6242}
6243
6244- (id) init {
6245 if ((self = [super init]) != nil) {
6246 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6247 [self reloadData];
6248
6249 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6250 if (reachability_ != NULL) {
6251 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6252 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6253
6254 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6255 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6256 runloop_ = runloop;
6257 }
6258 } return self;
6259}
6260
6261- (void) dealloc {
6262 if (reachability_ != NULL && runloop_ != NULL)
6263 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6264 [super dealloc];
6265}
6266
6267- (NSURL *) navigationURL {
6268 return [NSURL URLWithString:@"cydia://home"];
6269}
6270
6271- (void) aboutButtonClicked {
6272 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6273
6274 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6275 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6276 [alert setCancelButtonIndex:0];
6277
6278 [alert setMessage:
6279 @"Copyright \u00a9 2008-2015\n"
6280 "SaurikIT, LLC\n"
6281 "\n"
6282 "Jay Freeman (saurik)\n"
6283 "saurik@saurik.com\n"
6284 "http://www.saurik.com/"
6285 ];
6286
6287 [alert show];
6288}
6289
6290- (UIBarButtonItem *) leftButton {
6291 return [[[UIBarButtonItem alloc]
6292 initWithTitle:UCLocalize("ABOUT")
6293 style:UIBarButtonItemStylePlain
6294 target:self
6295 action:@selector(aboutButtonClicked)
6296 ] autorelease];
6297}
6298
6299@end
6300/* }}} */
6301
6302/* Cydia Tab Bar Controller {{{ */
6303@interface CydiaTabBarController : CyteTabBarController <
6304 UITabBarControllerDelegate,
6305 FetchDelegate
6306> {
6307 _transient Database *database_;
6308
6309 _H<UIActivityIndicatorView> indicator_;
6310
6311 bool updating_;
6312 // XXX: ok, "updatedelegate_"?...
6313 _transient NSObject<CydiaDelegate> *updatedelegate_;
6314}
6315
6316- (void) beginUpdate;
6317- (BOOL) updating;
6318
6319@end
6320
6321@implementation CydiaTabBarController
6322
6323- (id) initWithDatabase:(Database *)database {
6324 if ((self = [super init]) != nil) {
6325 database_ = database;
6326 [self setDelegate:self];
6327
6328 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6329 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6330
6331 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6332 } return self;
6333}
6334
6335- (void) beginUpdate {
6336 if (updating_)
6337 return;
6338
6339 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6340 UITabBarItem *item([controller tabBarItem]);
6341
6342 [item setBadgeValue:@""];
6343 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6344
6345 [indicator_ startAnimating];
6346 [badge addSubview:indicator_];
6347
6348 [updatedelegate_ retainNetworkActivityIndicator];
6349 updating_ = true;
6350
6351 [NSThread
6352 detachNewThreadSelector:@selector(performUpdate)
6353 toTarget:self
6354 withObject:nil
6355 ];
6356}
6357
6358- (void) performUpdate {
6359 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6360
6361 SourceStatus status(self, database_);
6362 [database_ updateWithStatus:status];
6363
6364 [self
6365 performSelectorOnMainThread:@selector(completeUpdate)
6366 withObject:nil
6367 waitUntilDone:NO
6368 ];
6369
6370 [pool release];
6371}
6372
6373- (void) stopUpdateWithSelector:(SEL)selector {
6374 updating_ = false;
6375 [updatedelegate_ releaseNetworkActivityIndicator];
6376
6377 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6378 [[controller tabBarItem] setBadgeValue:nil];
6379
6380 [indicator_ removeFromSuperview];
6381 [indicator_ stopAnimating];
6382
6383 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6384}
6385
6386- (void) completeUpdate {
6387 if (!updating_)
6388 return;
6389 [self stopUpdateWithSelector:@selector(reloadData)];
6390}
6391
6392- (void) cancelUpdate {
6393 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6394}
6395
6396- (void) cancelPressed {
6397 [self cancelUpdate];
6398}
6399
6400- (BOOL) updating {
6401 return updating_;
6402}
6403
6404- (bool) isSourceCancelled {
6405 return !updating_;
6406}
6407
6408- (void) startSourceFetch:(NSString *)uri {
6409}
6410
6411- (void) stopSourceFetch:(NSString *)uri {
6412}
6413
6414- (void) setUpdateDelegate:(id)delegate {
6415 updatedelegate_ = delegate;
6416}
6417
6418@end
6419/* }}} */
6420
6421/* Cydia:// Protocol {{{ */
6422@interface CydiaURLProtocol : CyteURLProtocol {
6423}
6424
6425@end
6426
6427@implementation CydiaURLProtocol
6428
6429+ (NSString *) scheme {
6430 return @"cydia";
6431}
6432
6433- (bool) loadForPath:(NSString *)path ofRequest:(NSURLRequest *)request {
6434 NSRange slash([path rangeOfString:@"/"]);
6435
6436 NSString *command;
6437 if (slash.location == NSNotFound) {
6438 command = path;
6439 path = nil;
6440 } else {
6441 command = [path substringToIndex:slash.location];
6442 path = [path substringFromIndex:(slash.location + 1)];
6443 }
6444
6445 Database *database([Database sharedInstance]);
6446
6447 if (false);
6448 else if ([command isEqualToString:@"application-icon"]) {
6449 if (path == nil)
6450 goto fail;
6451 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6452
6453 UIImage *icon(nil);
6454
6455 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
6456 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
6457 icon = [UIImage imageWithData:data];
6458 }
6459
6460 if (icon == nil)
6461 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
6462 icon = [UIImage imageAtPath:file];
6463
6464 if (icon == nil)
6465 icon = [UIImage imageNamed:@"unknown.png"];
6466
6467 [self _returnPNGWithImage:icon forRequest:request];
6468 } else if ([command isEqualToString:@"package-icon"]) {
6469 if (path == nil)
6470 goto fail;
6471 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6472 Package *package([database packageWithName:path]);
6473 if (package == nil)
6474 goto fail;
6475 [package parse];
6476 UIImage *icon([package icon]);
6477 [self _returnPNGWithImage:icon forRequest:request];
6478 } else if ([command isEqualToString:@"uikit-image"]) {
6479 if (path == nil)
6480 goto fail;
6481 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6482 UIImage *icon(_UIImageWithName(path));
6483 [self _returnPNGWithImage:icon forRequest:request];
6484 } else if ([command isEqualToString:@"section-icon"]) {
6485 if (path == nil)
6486 goto fail;
6487 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6488 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6489 if (icon == nil)
6490 icon = [UIImage imageNamed:@"unknown.png"];
6491 [self _returnPNGWithImage:icon forRequest:request];
6492 } else fail: {
6493 return [super loadForPath:path ofRequest:request];
6494 }
6495
6496 return true;
6497}
6498
6499@end
6500/* }}} */
6501
6502/* Section Controller {{{ */
6503@interface SectionController : FilteredPackageListController {
6504 _H<NSString> key_;
6505 _H<NSString> section_;
6506}
6507
6508- (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
6509
6510@end
6511
6512@implementation SectionController
6513
6514- (NSURL *) referrerURL {
6515 NSString *name(section_);
6516 name = name ?: @"*";
6517 NSString *key(key_);
6518 key = key ?: @"*";
6519 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
6520}
6521
6522- (NSURL *) navigationURL {
6523 NSString *name(section_);
6524 name = name ?: @"*";
6525 NSString *key(key_);
6526 key = key ?: @"*";
6527 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
6528}
6529
6530- (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
6531 NSString *title;
6532 if (section == nil)
6533 title = UCLocalize("ALL_PACKAGES");
6534 else if (![section isEqual:@""])
6535 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
6536 else
6537 title = UCLocalize("NO_SECTION");
6538
6539 if ((self = [super initWithDatabase:database title:title]) != nil) {
6540 key_ = [source key];
6541 section_ = section;
6542 } return self;
6543}
6544
6545- (void) reloadData {
6546 Source *source([database_ sourceWithKey:key_]);
6547 _H<NSString> name(section_);
6548
6549 [self setFilter:[=](Package *package) {
6550 NSString *section([package section]);
6551
6552 return (
6553 name == nil ||
6554 section == nil && [name length] == 0 ||
6555 [name isEqualToString:section]
6556 ) && (
6557 source == nil ||
6558 [package source] == source
6559 ) && [package visible];
6560 }];
6561
6562 [super reloadData];
6563}
6564
6565@end
6566/* }}} */
6567/* Sections Controller {{{ */
6568@interface SectionsController : CyteViewController <
6569 UITableViewDataSource,
6570 UITableViewDelegate
6571> {
6572 _transient Database *database_;
6573 _H<NSString> key_;
6574 _H<NSMutableArray> sections_;
6575 _H<NSMutableArray> filtered_;
6576 _H<UITableView, 2> list_;
6577}
6578
6579- (id) initWithDatabase:(Database *)database source:(Source *)source;
6580- (void) editButtonClicked;
6581
6582@end
6583
6584@implementation SectionsController
6585
6586- (NSURL *) navigationURL {
6587 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
6588}
6589
6590- (Source *) source {
6591 if (key_ == nil)
6592 return nil;
6593 return [database_ sourceWithKey:key_];
6594}
6595
6596- (void) updateNavigationItem {
6597 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6598 if ([sections_ count] == 0) {
6599 [[self navigationItem] setRightBarButtonItem:nil];
6600 } else {
6601 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6602 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6603 target:self
6604 action:@selector(editButtonClicked)
6605 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6606 }
6607}
6608
6609- (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6610 [super setEditing:editing animated:animated];
6611
6612 if (editing)
6613 [list_ reloadData];
6614 else
6615 [self.delegate updateData];
6616
6617 [self updateNavigationItem];
6618}
6619
6620- (void) viewDidAppear:(BOOL)animated {
6621 [super viewDidAppear:animated];
6622 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6623}
6624
6625- (void) viewWillDisappear:(BOOL)animated {
6626 [super viewWillDisappear:animated];
6627 [self setEditing:NO];
6628}
6629
6630- (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6631 Section *section = nil;
6632 int index = [indexPath row];
6633 if (![self isEditing]) {
6634 index -= 1;
6635 if (index >= 0)
6636 section = [filtered_ objectAtIndex:index];
6637 } else {
6638 section = [sections_ objectAtIndex:index];
6639 }
6640 return section;
6641}
6642
6643- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6644 if ([self isEditing])
6645 return [sections_ count];
6646 else
6647 return [filtered_ count] + 1;
6648}
6649
6650/*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6651 return 45.0f;
6652}*/
6653
6654- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6655 static NSString *reuseIdentifier = @"SectionCell";
6656
6657 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6658 if (cell == nil)
6659 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6660
6661 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6662
6663 return cell;
6664}
6665
6666- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6667 if ([self isEditing])
6668 return;
6669
6670 Section *section = [self sectionAtIndexPath:indexPath];
6671
6672 SectionController *controller = [[[SectionController alloc]
6673 initWithDatabase:database_
6674 source:[self source]
6675 section:[section name]
6676 ] autorelease];
6677 [controller setDelegate:self.delegate];
6678
6679 [[self navigationController] pushViewController:controller animated:YES];
6680}
6681
6682- (void) loadView {
6683 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6684 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6685 [list_ setRowHeight:46];
6686 [(UITableView *) list_ setDataSource:self];
6687 [list_ setDelegate:self];
6688 [self setView:list_];
6689}
6690
6691- (void) viewDidLoad {
6692 [super viewDidLoad];
6693
6694 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6695}
6696
6697- (void) releaseSubviews {
6698 list_ = nil;
6699
6700 sections_ = nil;
6701 filtered_ = nil;
6702
6703 [super releaseSubviews];
6704}
6705
6706- (id) initWithDatabase:(Database *)database source:(Source *)source {
6707 if ((self = [super init]) != nil) {
6708 database_ = database;
6709 key_ = [source key];
6710 } return self;
6711}
6712
6713- (void) reloadData {
6714 [super reloadData];
6715
6716 NSArray *packages = [database_ packages];
6717
6718 sections_ = [NSMutableArray arrayWithCapacity:16];
6719 filtered_ = [NSMutableArray arrayWithCapacity:16];
6720
6721 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6722
6723 Source *source([self source]);
6724
6725 _trace();
6726 for (Package *package in packages) {
6727 if (source != nil && [package source] != source)
6728 continue;
6729
6730 NSString *name([package section]);
6731 NSString *key(name == nil ? @"" : name);
6732
6733 Section *section;
6734
6735 _profile(SectionsView$reloadData$Section)
6736 section = [sections objectForKey:key];
6737 if (section == nil) {
6738 _profile(SectionsView$reloadData$Section$Allocate)
6739 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6740 [sections setObject:section forKey:key];
6741 _end
6742 }
6743 _end
6744
6745 [section addToCount];
6746
6747 _profile(SectionsView$reloadData$Filter)
6748 if (![package visible])
6749 continue;
6750 _end
6751
6752 [section addToRow];
6753 }
6754 _trace();
6755
6756 [sections_ addObjectsFromArray:[sections allValues]];
6757
6758 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6759
6760 for (Section *section in (id) sections_) {
6761 size_t count([section row]);
6762 if (count == 0)
6763 continue;
6764
6765 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6766 [section setCount:count];
6767 [filtered_ addObject:section];
6768 }
6769
6770 [self updateNavigationItem];
6771 [list_ reloadData];
6772 _trace();
6773}
6774
6775- (void) editButtonClicked {
6776 [self setEditing:![self isEditing] animated:YES];
6777}
6778
6779@end
6780/* }}} */
6781
6782/* Changes Controller {{{ */
6783@interface ChangesController : FilteredPackageListController {
6784 unsigned upgrades_;
6785}
6786
6787- (id) initWithDatabase:(Database *)database;
6788
6789@end
6790
6791@implementation ChangesController
6792
6793- (NSURL *) referrerURL {
6794 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
6795}
6796
6797- (NSURL *) navigationURL {
6798 return [NSURL URLWithString:@"cydia://changes"];
6799}
6800
6801- (Package *) packageAtIndexPath:(NSIndexPath *)path {
6802@synchronized (database_) {
6803 if ([database_ era] != era_)
6804 return nil;
6805
6806 NSUInteger sectionIndex([path section]);
6807 if (sectionIndex >= [sections_ count])
6808 return nil;
6809 Section *section([sections_ objectAtIndex:sectionIndex]);
6810 NSInteger row([path row]);
6811 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
6812} }
6813
6814- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6815 NSString *context([alert context]);
6816
6817 if ([context isEqualToString:@"norefresh"])
6818 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6819}
6820
6821- (void) setLeftBarButtonItem {
6822 if ([self.delegate updating])
6823 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6824 initWithTitle:UCLocalize("CANCEL")
6825 style:UIBarButtonItemStyleDone
6826 target:self
6827 action:@selector(cancelButtonClicked)
6828 ] autorelease] animated:YES];
6829 else
6830 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6831 initWithTitle:UCLocalize("REFRESH")
6832 style:UIBarButtonItemStylePlain
6833 target:self
6834 action:@selector(refreshButtonClicked)
6835 ] autorelease] animated:YES];
6836}
6837
6838- (void) refreshButtonClicked {
6839 if ([self.delegate requestUpdate])
6840 [self setLeftBarButtonItem];
6841}
6842
6843- (void) cancelButtonClicked {
6844 [self.delegate cancelUpdate];
6845}
6846
6847- (void) upgradeButtonClicked {
6848 [self.delegate distUpgrade];
6849 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
6850}
6851
6852- (bool) shouldYield {
6853 return true;
6854}
6855
6856- (bool) shouldBlock {
6857 return true;
6858}
6859
6860- (void) useFilter {
6861@synchronized (self) {
6862 [self setFilter:[](Package *package) {
6863 return [package upgradableAndEssential:YES] || [package visible];
6864 }];
6865
6866 [self setSorter:[](NSMutableArray *packages) {
6867 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
6868 }];
6869} }
6870
6871- (id) initWithDatabase:(Database *)database {
6872 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
6873 [self useFilter];
6874 } return self;
6875}
6876
6877- (void) viewDidLoad {
6878 [super viewDidLoad];
6879 [self setLeftBarButtonItem];
6880}
6881
6882- (void) viewWillAppear:(BOOL)animated {
6883 [super viewWillAppear:animated];
6884 [self setLeftBarButtonItem];
6885}
6886
6887- (void) reloadData {
6888 [self setLeftBarButtonItem];
6889 [super reloadData];
6890}
6891
6892- (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6893 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6894
6895 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6896 Section *ignored = nil;
6897 Section *section = nil;
6898 time_t last = 0;
6899
6900 upgrades_ = 0;
6901 bool unseens = false;
6902
6903 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6904
6905 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
6906 Package *package = [packages objectAtIndex:offset];
6907
6908 BOOL uae = [package upgradableAndEssential:YES];
6909
6910 if (!uae) {
6911 unseens = true;
6912 time_t seen([package seen]);
6913
6914 if (section == nil || last != seen) {
6915 last = seen;
6916
6917 NSString *name;
6918 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
6919 [name autorelease];
6920
6921 _profile(ChangesController$reloadData$Allocate)
6922 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6923 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6924 [sections addObject:section];
6925 _end
6926 }
6927
6928 [section addToCount];
6929 } else if ([package ignored]) {
6930 if (ignored == nil) {
6931 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
6932 }
6933 [ignored addToCount];
6934 } else {
6935 ++upgrades_;
6936 [upgradable addToCount];
6937 }
6938 }
6939 _trace();
6940
6941 CFRelease(formatter);
6942
6943 if (unseens) {
6944 Section *last = [sections lastObject];
6945 size_t count = [last count];
6946 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
6947 [sections removeLastObject];
6948 }
6949
6950 if ([ignored count] != 0)
6951 [sections insertObject:ignored atIndex:0];
6952 if (upgrades_ != 0)
6953 [sections insertObject:upgradable atIndex:0];
6954
6955 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
6956 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
6957 style:UIBarButtonItemStylePlain
6958 target:self
6959 action:@selector(upgradeButtonClicked)
6960 ] autorelease]) animated:YES];
6961
6962 return sections;
6963}
6964
6965@end
6966/* }}} */
6967/* Search Controller {{{ */
6968@interface SearchController : FilteredPackageListController <
6969 UISearchBarDelegate
6970> {
6971 _H<UISearchBar, 1> search_;
6972 BOOL searchloaded_;
6973 bool summary_;
6974}
6975
6976- (id) initWithDatabase:(Database *)database query:(NSString *)query;
6977- (void) reloadData;
6978
6979@end
6980
6981@implementation SearchController
6982
6983- (NSURL *) referrerURL {
6984 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
6985}
6986
6987- (NSURL *) navigationURL {
6988 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
6989 return [NSURL URLWithString:@"cydia://search"];
6990 else
6991 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
6992}
6993
6994- (NSArray *) termsForQuery:(NSString *)query {
6995 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
6996 for (NSString *component in [query componentsSeparatedByString:@" "])
6997 if ([component length] != 0)
6998 [terms addObject:component];
6999
7000 return terms;
7001}
7002
7003- (void) useSearch {
7004 _H<NSArray> query([self termsForQuery:[search_ text]]);
7005 summary_ = false;
7006
7007@synchronized (self) {
7008 [self setFilter:[=](Package *package) {
7009 if (![package unfiltered])
7010 return false;
7011 if (![package matches:query])
7012 return false;
7013 return true;
7014 }];
7015
7016 [self setSorter:[](NSMutableArray *packages) {
7017 [packages radixSortUsingSelector:@selector(rank)];
7018 }];
7019}
7020
7021 [self clearData];
7022 [self reloadData];
7023}
7024
7025- (void) usePrefix:(NSString *)prefix {
7026 _H<NSString> query(prefix);
7027 summary_ = true;
7028
7029@synchronized (self) {
7030 [self setFilter:[=](Package *package) {
7031 if ([query length] == 0)
7032 return false;
7033 if (![package unfiltered])
7034 return false;
7035 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7036 return false;
7037 return true;
7038 }];
7039
7040 [self setSorter:nullptr];
7041}
7042
7043 [self reloadData];
7044}
7045
7046- (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7047 [self clearData];
7048 [self usePrefix:[search_ text]];
7049}
7050
7051- (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7052 [search_ resignFirstResponder];
7053 [self useSearch];
7054}
7055
7056- (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7057 [search_ setText:@""];
7058 [self searchBarButtonClicked:searchBar];
7059}
7060
7061- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7062 [self searchBarButtonClicked:searchBar];
7063}
7064
7065- (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7066 [self usePrefix:text];
7067}
7068
7069- (bool) shouldYield {
7070 return YES;
7071}
7072
7073- (bool) shouldBlock {
7074 return !summary_;
7075}
7076
7077- (bool) isSummarized {
7078 return summary_;
7079}
7080
7081- (bool) showsSections {
7082 return false;
7083}
7084
7085- (id) initWithDatabase:(Database *)database query:(NSString *)query {
7086 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7087 search_ = [[[UISearchBar alloc] init] autorelease];
7088 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7089 [search_ setDelegate:self];
7090
7091 UITextField *textField;
7092 if ([search_ respondsToSelector:@selector(searchField)])
7093 textField = [search_ searchField];
7094 else
7095 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7096
7097 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7098 [textField setEnablesReturnKeyAutomatically:NO];
7099 [[self navigationItem] setTitleView:textField];
7100
7101 if (query != nil)
7102 [search_ setText:query];
7103 [self useSearch];
7104 } return self;
7105}
7106
7107- (void) viewDidAppear:(BOOL)animated {
7108 [super viewDidAppear:animated];
7109
7110 if (!searchloaded_) {
7111 searchloaded_ = YES;
7112 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7113 [search_ layoutSubviews];
7114 }
7115
7116 if ([self isSummarized])
7117 [search_ becomeFirstResponder];
7118}
7119
7120- (void) reloadData {
7121 [self resetCursor];
7122 [super reloadData];
7123}
7124
7125- (void) didSelectPackage:(Package *)package {
7126 [search_ resignFirstResponder];
7127 [super didSelectPackage:package];
7128}
7129
7130@end
7131/* }}} */
7132/* Package Settings Controller {{{ */
7133@interface PackageSettingsController : CyteViewController <
7134 UITableViewDataSource,
7135 UITableViewDelegate
7136> {
7137 _transient Database *database_;
7138 _H<NSString> name_;
7139 _H<Package> package_;
7140 _H<UITableView, 2> table_;
7141 _H<UISwitch> subscribedSwitch_;
7142 _H<UISwitch> ignoredSwitch_;
7143 _H<UITableViewCell> subscribedCell_;
7144 _H<UITableViewCell> ignoredCell_;
7145}
7146
7147- (id) initWithDatabase:(Database *)database package:(NSString *)package;
7148
7149@end
7150
7151@implementation PackageSettingsController
7152
7153- (NSURL *) navigationURL {
7154 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7155}
7156
7157- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7158 if (package_ == nil)
7159 return 0;
7160
7161 if ([package_ installed] == nil)
7162 return 1;
7163 else
7164 return 2;
7165}
7166
7167- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7168 if (package_ == nil)
7169 return 0;
7170
7171 // both sections contain just one item right now.
7172 return 1;
7173}
7174
7175- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7176 return nil;
7177}
7178
7179- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7180 if (section == 0)
7181 return UCLocalize("SHOW_ALL_CHANGES_EX");
7182 else
7183 return UCLocalize("IGNORE_UPGRADES_EX");
7184}
7185
7186- (void) onSubscribed:(id)control {
7187 bool value([control isOn]);
7188 if (package_ == nil)
7189 return;
7190 if ([package_ setSubscribed:value])
7191 [self.delegate updateData];
7192}
7193
7194- (void) _updateIgnored {
7195 const char *package([name_ UTF8String]);
7196 bool on([ignoredSwitch_ isOn]);
7197
7198 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7199 fwrite(package, strlen(package), 1, dpkg);
7200
7201 if (on)
7202 fwrite(" hold\n", 6, 1, dpkg);
7203 else
7204 fwrite(" install\n", 9, 1, dpkg);
7205
7206 pclose(dpkg);
7207}
7208
7209- (void) onIgnored:(id)control {
7210 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7211 [invocation setTarget:self];
7212 [invocation setSelector:@selector(_updateIgnored)];
7213
7214 [self.delegate reloadDataWithInvocation:invocation];
7215}
7216
7217- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7218 if (package_ == nil)
7219 return nil;
7220
7221 switch ([indexPath section]) {
7222 case 0: return subscribedCell_;
7223 case 1: return ignoredCell_;
7224
7225 _nodefault
7226 }
7227
7228 return nil;
7229}
7230
7231- (void) loadView {
7232 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7233 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7234 [self setView:view];
7235
7236 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7237 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7238 [(UITableView *) table_ setDataSource:self];
7239 [table_ setDelegate:self];
7240 [view addSubview:table_];
7241
7242 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7243 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7244 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7245
7246 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7247 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7248 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7249
7250 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7251 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7252 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7253 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7254
7255 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7256 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7257 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7258 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7259}
7260
7261- (void) viewDidLoad {
7262 [super viewDidLoad];
7263
7264 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7265}
7266
7267- (void) releaseSubviews {
7268 ignoredCell_ = nil;
7269 subscribedCell_ = nil;
7270 table_ = nil;
7271 ignoredSwitch_ = nil;
7272 subscribedSwitch_ = nil;
7273
7274 [super releaseSubviews];
7275}
7276
7277- (id) initWithDatabase:(Database *)database package:(NSString *)package {
7278 if ((self = [super init]) != nil) {
7279 database_ = database;
7280 name_ = package;
7281 } return self;
7282}
7283
7284- (void) reloadData {
7285 [super reloadData];
7286
7287 package_ = [database_ packageWithName:name_];
7288
7289 if (package_ != nil) {
7290 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7291 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7292 } // XXX: what now, G?
7293
7294 [table_ reloadData];
7295}
7296
7297@end
7298/* }}} */
7299
7300/* Installed Controller {{{ */
7301@interface InstalledController : FilteredPackageListController {
7302 bool sectioned_;
7303}
7304
7305- (id) initWithDatabase:(Database *)database;
7306- (void) queueStatusDidChange;
7307
7308@end
7309
7310@implementation InstalledController
7311
7312- (NSURL *) referrerURL {
7313 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7314}
7315
7316- (NSURL *) navigationURL {
7317 return [NSURL URLWithString:@"cydia://installed"];
7318}
7319
7320- (void) useRecent {
7321 sectioned_ = false;
7322
7323@synchronized (self) {
7324 [self setFilter:[](Package *package) {
7325 return ![package uninstalled] && package->role_ < 7;
7326 }];
7327
7328 [self setSorter:[](NSMutableArray *packages) {
7329 [packages radixSortUsingSelector:@selector(recent)];
7330 }];
7331} }
7332
7333- (void) useFilter:(UISegmentedControl *)segmented {
7334 NSInteger selected([segmented selectedSegmentIndex]);
7335 if (selected == 2)
7336 return [self useRecent];
7337 bool simple(selected == 0);
7338 sectioned_ = true;
7339
7340@synchronized (self) {
7341 [self setFilter:[=](Package *package) {
7342 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7343 }];
7344
7345 [self setSorter:nullptr];
7346} }
7347
7348- (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7349 if (sectioned_)
7350 return [super sectionsForPackages:packages];
7351
7352 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
7353
7354 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7355 Section *section(nil);
7356 time_t last(0);
7357
7358 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
7359 Package *package([packages objectAtIndex:offset]);
7360
7361 time_t upgraded([package upgraded]);
7362 if (upgraded < 1168364520)
7363 upgraded = 0;
7364 else
7365 upgraded -= upgraded % (60 * 60 * 24);
7366
7367 if (section == nil || upgraded != last) {
7368 last = upgraded;
7369
7370 NSString *name;
7371 if (upgraded == 0)
7372 continue; // XXX: name = UCLocalize("...");
7373 else {
7374 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
7375 [name autorelease];
7376 }
7377
7378 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7379 [sections addObject:section];
7380 }
7381
7382 [section addToCount];
7383 }
7384
7385 CFRelease(formatter);
7386 return sections;
7387}
7388
7389- (id) initWithDatabase:(Database *)database {
7390 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
7391 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
7392 [segmented setSelectedSegmentIndex:0];
7393 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7394 [[self navigationItem] setTitleView:segmented];
7395
7396 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7397 [self useFilter:segmented];
7398
7399 [self queueStatusDidChange];
7400 } return self;
7401}
7402
7403#if !AlwaysReload
7404- (void) queueButtonClicked {
7405 [self.delegate queue];
7406}
7407#endif
7408
7409- (void) queueStatusDidChange {
7410#if !AlwaysReload
7411 if (Queuing_) {
7412 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7413 initWithTitle:UCLocalize("QUEUE")
7414 style:UIBarButtonItemStyleDone
7415 target:self
7416 action:@selector(queueButtonClicked)
7417 ] autorelease]];
7418 } else {
7419 [[self navigationItem] setRightBarButtonItem:nil];
7420 }
7421#endif
7422}
7423
7424- (void) modeChanged:(UISegmentedControl *)segmented {
7425 [self useFilter:segmented];
7426 [self reloadData];
7427}
7428
7429@end
7430/* }}} */
7431
7432/* Source Cell {{{ */
7433@interface SourceCell : CyteTableViewCell <
7434 CyteTableViewCellDelegate,
7435 SourceDelegate
7436> {
7437 _H<Source, 1> source_;
7438 _H<NSURL> url_;
7439 _H<UIImage> icon_;
7440 _H<NSString> origin_;
7441 _H<NSString> label_;
7442 _H<UIActivityIndicatorView> indicator_;
7443}
7444
7445- (void) setSource:(Source *)source;
7446- (void) setFetch:(NSNumber *)fetch;
7447
7448@end
7449
7450@implementation SourceCell
7451
7452- (void) _setImage:(NSArray *)data {
7453 if ([url_ isEqual:[data objectAtIndex:0]]) {
7454 icon_ = [data objectAtIndex:1];
7455 [self.content setNeedsDisplay];
7456 }
7457}
7458
7459- (void) _setSource:(NSURL *) url {
7460 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7461
7462 if (NSData *data = [NSURLConnection
7463 sendSynchronousRequest:[NSURLRequest
7464 requestWithURL:url
7465 cachePolicy:NSURLRequestUseProtocolCachePolicy
7466 timeoutInterval:10
7467 ]
7468
7469 returningResponse:NULL
7470 error:NULL
7471 ])
7472 if (UIImage *image = [UIImage imageWithData:data])
7473 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
7474
7475 [pool release];
7476}
7477
7478- (void) setSource:(Source *)source {
7479 source_ = source;
7480 [source_ setDelegate:self];
7481
7482 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
7483
7484 icon_ = [UIImage imageNamed:@"unknown.png"];
7485
7486 origin_ = [source name];
7487 label_ = [source rooturi];
7488
7489 [self.content setNeedsDisplay];
7490
7491 url_ = [source iconURL];
7492 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
7493}
7494
7495- (void) setAllSource {
7496 source_ = nil;
7497 [indicator_ stopAnimating];
7498
7499 icon_ = [UIImage imageNamed:@"folder.png"];
7500 origin_ = UCLocalize("ALL_SOURCES");
7501 label_ = UCLocalize("ALL_SOURCES_EX");
7502 [self.content setNeedsDisplay];
7503}
7504
7505- (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7506 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7507 [self.content setBackgroundColor:[UIColor whiteColor]];
7508 [self.content setOpaque:YES];
7509
7510 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
7511 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
7512 [[self contentView] addSubview:indicator_];
7513
7514 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
7515 } return self;
7516}
7517
7518- (void) layoutSubviews {
7519 [super layoutSubviews];
7520
7521 UIView *content([self contentView]);
7522 CGRect bounds([content bounds]);
7523
7524 CGRect frame([indicator_ frame]);
7525 frame.origin.x = bounds.size.width - frame.size.width;
7526 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
7527
7528 if (kCFCoreFoundationVersionNumber < 800)
7529 frame.origin.x -= 8;
7530 [indicator_ setFrame:frame];
7531}
7532
7533- (NSString *) accessibilityLabel {
7534 return origin_;
7535}
7536
7537- (void) drawContentRect:(CGRect)rect {
7538 bool highlighted(self.highlighted);
7539 float width(rect.size.width);
7540
7541 if (icon_ != nil) {
7542 CGRect rect;
7543 rect.size = [(UIImage *) icon_ size];
7544
7545 while (rect.size.width > 32 || rect.size.height > 32) {
7546 rect.size.width /= 2;
7547 rect.size.height /= 2;
7548 }
7549
7550 rect.origin.x = 26 - rect.size.width / 2;
7551 rect.origin.y = 26 - rect.size.height / 2;
7552
7553 [icon_ drawInRect:Retina(rect)];
7554 }
7555
7556 if (highlighted && kCFCoreFoundationVersionNumber < 800)
7557 UISetColor(White_);
7558
7559 if (!highlighted)
7560 UISetColor(Black_);
7561 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
7562
7563 if (!highlighted)
7564 UISetColor(Gray_);
7565 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
7566}
7567
7568- (void) setFetch:(NSNumber *)fetch {
7569 if ([fetch boolValue])
7570 [indicator_ startAnimating];
7571 else
7572 [indicator_ stopAnimating];
7573}
7574
7575@end
7576/* }}} */
7577/* Sources Controller {{{ */
7578@interface SourcesController : CyteViewController <
7579 UITableViewDataSource,
7580 UITableViewDelegate
7581> {
7582 _transient Database *database_;
7583 unsigned era_;
7584
7585 _H<UITableView, 2> list_;
7586 _H<NSMutableArray> sources_;
7587 int offset_;
7588
7589 _H<NSString> href_;
7590 _H<UIProgressHUD> hud_;
7591 _H<NSError> error_;
7592
7593 NSURLConnection *trivial_bz2_;
7594 NSURLConnection *trivial_gz_;
7595
7596 BOOL cydia_;
7597}
7598
7599- (id) initWithDatabase:(Database *)database;
7600- (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
7601
7602@end
7603
7604@implementation SourcesController
7605
7606- (void) _releaseConnection:(NSURLConnection *)connection {
7607 if (connection != nil) {
7608 [connection cancel];
7609 //[connection setDelegate:nil];
7610 [connection release];
7611 }
7612}
7613
7614- (void) dealloc {
7615 [self _releaseConnection:trivial_gz_];
7616 [self _releaseConnection:trivial_bz2_];
7617
7618 [super dealloc];
7619}
7620
7621- (NSURL *) navigationURL {
7622 return [NSURL URLWithString:@"cydia://sources"];
7623}
7624
7625- (void) viewDidAppear:(BOOL)animated {
7626 [super viewDidAppear:animated];
7627 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7628}
7629
7630- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7631 return 2;
7632}
7633
7634- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7635 if (section == 1)
7636 return UCLocalize("INDIVIDUAL_SOURCES");
7637 return nil;
7638}
7639
7640- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7641 switch (section) {
7642 case 0: return 1;
7643 case 1: return [sources_ count];
7644 default: return 0;
7645 }
7646}
7647
7648- (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7649@synchronized (database_) {
7650 if ([database_ era] != era_)
7651 return nil;
7652 if ([indexPath section] != 1)
7653 return nil;
7654 NSUInteger index([indexPath row]);
7655 if (index >= [sources_ count])
7656 return nil;
7657 return [sources_ objectAtIndex:index];
7658} }
7659
7660- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7661 static NSString *cellIdentifier = @"SourceCell";
7662
7663 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7664 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7665 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7666
7667 Source *source([self sourceAtIndexPath:indexPath]);
7668 if (source == nil)
7669 [cell setAllSource];
7670 else
7671 [cell setSource:source];
7672
7673 return cell;
7674}
7675
7676- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7677 SectionsController *controller([[[SectionsController alloc]
7678 initWithDatabase:database_
7679 source:[self sourceAtIndexPath:indexPath]
7680 ] autorelease]);
7681
7682 [controller setDelegate:self.delegate];
7683 [[self navigationController] pushViewController:controller animated:YES];
7684}
7685
7686- (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7687 if ([indexPath section] != 1)
7688 return false;
7689 Source *source = [self sourceAtIndexPath:indexPath];
7690 return [source record] != nil;
7691}
7692
7693- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7694 _assert([indexPath section] == 1);
7695 if (editingStyle == UITableViewCellEditingStyleDelete) {
7696 Source *source = [self sourceAtIndexPath:indexPath];
7697 if (source == nil) return;
7698
7699 [Sources_ removeObjectForKey:[source key]];
7700
7701 [self.delegate syncData];
7702 }
7703}
7704
7705- (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
7706 [self updateButtonsForEditingStatusAnimated:YES];
7707}
7708
7709- (void) complete {
7710 [self.delegate addTrivialSource:href_];
7711 href_ = nil;
7712
7713 [self.delegate syncData];
7714}
7715
7716- (NSString *) getWarning {
7717 NSString *href(href_);
7718 NSRange colon([href rangeOfString:@"://"]);
7719 if (colon.location != NSNotFound)
7720 href = [href substringFromIndex:(colon.location + 3)];
7721 href = [href stringByAddingPercentEscapes];
7722 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7723
7724 NSURL *url([NSURL URLWithString:href]);
7725
7726 NSStringEncoding encoding;
7727 NSError *error(nil);
7728
7729 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7730 return [warning length] == 0 ? nil : warning;
7731 return nil;
7732}
7733
7734- (void) _endConnection:(NSURLConnection *)connection {
7735 // XXX: the memory management in this method is horribly awkward
7736
7737 NSURLConnection **field = NULL;
7738 if (connection == trivial_bz2_)
7739 field = &trivial_bz2_;
7740 else if (connection == trivial_gz_)
7741 field = &trivial_gz_;
7742 _assert(field != NULL);
7743 [connection release];
7744 *field = nil;
7745
7746 if (
7747 trivial_bz2_ == nil &&
7748 trivial_gz_ == nil
7749 ) {
7750 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
7751
7752 [self.delegate releaseNetworkActivityIndicator];
7753
7754 [self.delegate removeProgressHUD:hud_];
7755 hud_ = nil;
7756
7757 if (cydia_) {
7758 if (warning != nil) {
7759 UIAlertView *alert = [[[UIAlertView alloc]
7760 initWithTitle:UCLocalize("SOURCE_WARNING")
7761 message:warning
7762 delegate:self
7763 cancelButtonTitle:UCLocalize("CANCEL")
7764 otherButtonTitles:
7765 UCLocalize("ADD_ANYWAY"),
7766 nil
7767 ] autorelease];
7768
7769 [alert setContext:@"warning"];
7770 [alert setNumberOfRows:1];
7771 [alert show];
7772
7773 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
7774 error_ = nil;
7775 return;
7776 }
7777
7778 [self complete];
7779 } else if (error_ != nil) {
7780 UIAlertView *alert = [[[UIAlertView alloc]
7781 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7782 message:[error_ localizedDescription]
7783 delegate:self
7784 cancelButtonTitle:UCLocalize("OK")
7785 otherButtonTitles:nil
7786 ] autorelease];
7787
7788 [alert setContext:@"urlerror"];
7789 [alert show];
7790
7791 href_ = nil;
7792 } else {
7793 UIAlertView *alert = [[[UIAlertView alloc]
7794 initWithTitle:UCLocalize("NOT_REPOSITORY")
7795 message:UCLocalize("NOT_REPOSITORY_EX")
7796 delegate:self
7797 cancelButtonTitle:UCLocalize("OK")
7798 otherButtonTitles:nil
7799 ] autorelease];
7800
7801 [alert setContext:@"trivial"];
7802 [alert show];
7803
7804 href_ = nil;
7805 }
7806
7807 error_ = nil;
7808 }
7809}
7810
7811- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7812 switch ([response statusCode]) {
7813 case 200:
7814 cydia_ = YES;
7815 }
7816}
7817
7818- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7819 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7820 error_ = error;
7821 [self _endConnection:connection];
7822}
7823
7824- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7825 [self _endConnection:connection];
7826}
7827
7828- (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7829 NSURL *url([NSURL URLWithString:href]);
7830
7831 NSMutableURLRequest *request = [NSMutableURLRequest
7832 requestWithURL:url
7833 cachePolicy:NSURLRequestUseProtocolCachePolicy
7834 timeoutInterval:10
7835 ];
7836
7837 [request setHTTPMethod:method];
7838
7839 if (Machine_ != NULL)
7840 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7841
7842 if (UniqueID_ != nil)
7843 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7844
7845 if ([url isCydiaSecure]) {
7846 if (UniqueID_ != nil)
7847 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
7848 }
7849
7850 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7851}
7852
7853- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7854 NSString *context([alert context]);
7855
7856 if ([context isEqualToString:@"source"]) {
7857 switch (button) {
7858 case 1: {
7859 NSString *href = [[alert textField] text];
7860 href = VerifySource(href);
7861 if (href == nil)
7862 break;
7863 href_ = href;
7864
7865 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7866 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7867
7868 cydia_ = false;
7869
7870 // XXX: this is stupid
7871 hud_ = [self.delegate addProgressHUD];
7872 [hud_ setText:UCLocalize("VERIFYING_URL")];
7873 [self.delegate retainNetworkActivityIndicator];
7874 } break;
7875
7876 case 0:
7877 break;
7878
7879 _nodefault
7880 }
7881
7882 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7883 } else if ([context isEqualToString:@"trivial"])
7884 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7885 else if ([context isEqualToString:@"urlerror"])
7886 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7887 else if ([context isEqualToString:@"warning"]) {
7888 switch (button) {
7889 case 1:
7890 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
7891 break;
7892
7893 case 0:
7894 break;
7895
7896 _nodefault
7897 }
7898
7899 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7900 }
7901}
7902
7903- (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
7904 BOOL editing([list_ isEditing]);
7905
7906 if (editing)
7907 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7908 initWithTitle:UCLocalize("ADD")
7909 style:UIBarButtonItemStylePlain
7910 target:self
7911 action:@selector(addButtonClicked)
7912 ] autorelease] animated:animated];
7913 else if ([self.delegate updating])
7914 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7915 initWithTitle:UCLocalize("CANCEL")
7916 style:UIBarButtonItemStyleDone
7917 target:self
7918 action:@selector(cancelButtonClicked)
7919 ] autorelease] animated:animated];
7920 else
7921 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7922 initWithTitle:UCLocalize("REFRESH")
7923 style:UIBarButtonItemStylePlain
7924 target:self
7925 action:@selector(refreshButtonClicked)
7926 ] autorelease] animated:animated];
7927
7928 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7929 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
7930 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7931 target:self
7932 action:@selector(editButtonClicked)
7933 ] autorelease] animated:animated];
7934}
7935
7936- (void) loadView {
7937 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
7938 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7939 [list_ setRowHeight:53];
7940 [(UITableView *) list_ setDataSource:self];
7941 [list_ setDelegate:self];
7942 [self setView:list_];
7943}
7944
7945- (void) viewDidLoad {
7946 [super viewDidLoad];
7947
7948 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
7949 [self updateButtonsForEditingStatusAnimated:NO];
7950}
7951
7952- (void) viewWillAppear:(BOOL)animated {
7953 [super viewWillAppear:animated];
7954
7955 [list_ setEditing:NO];
7956 [self updateButtonsForEditingStatusAnimated:NO];
7957}
7958
7959- (void) releaseSubviews {
7960 list_ = nil;
7961
7962 sources_ = nil;
7963
7964 [super releaseSubviews];
7965}
7966
7967- (id) initWithDatabase:(Database *)database {
7968 if ((self = [super init]) != nil) {
7969 database_ = database;
7970 } return self;
7971}
7972
7973- (void) reloadData {
7974 [super reloadData];
7975 [self updateButtonsForEditingStatusAnimated:YES];
7976
7977@synchronized (database_) {
7978 era_ = [database_ era];
7979
7980 sources_ = [NSMutableArray arrayWithCapacity:16];
7981 [sources_ addObjectsFromArray:[database_ sources]];
7982 _trace();
7983 [sources_ sortUsingSelector:@selector(compareByName:)];
7984 _trace();
7985
7986 int count([sources_ count]);
7987 offset_ = 0;
7988 for (int i = 0; i != count; i++) {
7989 if ([[sources_ objectAtIndex:i] record] == nil)
7990 break;
7991 offset_++;
7992 }
7993
7994 [list_ reloadData];
7995} }
7996
7997- (void) showAddSourcePrompt {
7998 UIAlertView *alert = [[[UIAlertView alloc]
7999 initWithTitle:UCLocalize("ENTER_APT_URL")
8000 message:nil
8001 delegate:self
8002 cancelButtonTitle:UCLocalize("CANCEL")
8003 otherButtonTitles:
8004 UCLocalize("ADD_SOURCE"),
8005 nil
8006 ] autorelease];
8007
8008 [alert setContext:@"source"];
8009
8010 [alert setNumberOfRows:1];
8011 [alert addTextFieldWithValue:@"http://" label:@""];
8012
8013 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8014 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8015 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8016 [traits setKeyboardType:UIKeyboardTypeURL];
8017 // XXX: UIReturnKeyDone
8018 [traits setReturnKeyType:UIReturnKeyNext];
8019
8020 [alert show];
8021}
8022
8023- (void) addButtonClicked {
8024 [self showAddSourcePrompt];
8025}
8026
8027- (void) refreshButtonClicked {
8028 if ([self.delegate requestUpdate])
8029 [self updateButtonsForEditingStatusAnimated:YES];
8030}
8031
8032- (void) cancelButtonClicked {
8033 [self.delegate cancelUpdate];
8034}
8035
8036- (void) editButtonClicked {
8037 [list_ setEditing:![list_ isEditing] animated:YES];
8038 [self updateButtonsForEditingStatusAnimated:YES];
8039}
8040
8041@end
8042/* }}} */
8043
8044/* Stash Controller {{{ */
8045@interface StashController : CyteViewController {
8046 _H<UIActivityIndicatorView> spinner_;
8047 _H<UILabel> status_;
8048 _H<UILabel> caption_;
8049}
8050
8051@end
8052
8053@implementation StashController
8054
8055- (void) loadView {
8056 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8057 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8058 [self setView:view];
8059
8060 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8061
8062 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8063 CGRect spinrect = [spinner_ frame];
8064 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8065 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8066 [spinner_ setFrame:spinrect];
8067 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8068 [view addSubview:spinner_];
8069 [spinner_ startAnimating];
8070
8071 CGRect captrect;
8072 captrect.size.width = [[self view] frame].size.width;
8073 captrect.size.height = 40.0f;
8074 captrect.origin.x = 0;
8075 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8076 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8077 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8078 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8079 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8080 [caption_ setTextColor:[UIColor whiteColor]];
8081 [caption_ setBackgroundColor:[UIColor clearColor]];
8082 [caption_ setShadowColor:[UIColor blackColor]];
8083 [caption_ setTextAlignment:NSTextAlignmentCenter];
8084 [view addSubview:caption_];
8085
8086 CGRect statusrect;
8087 statusrect.size.width = [[self view] frame].size.width;
8088 statusrect.size.height = 30.0f;
8089 statusrect.origin.x = 0;
8090 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8091 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8092 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8093 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8094 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8095 [status_ setTextColor:[UIColor whiteColor]];
8096 [status_ setBackgroundColor:[UIColor clearColor]];
8097 [status_ setShadowColor:[UIColor blackColor]];
8098 [status_ setTextAlignment:NSTextAlignmentCenter];
8099 [view addSubview:status_];
8100}
8101
8102- (void) releaseSubviews {
8103 spinner_ = nil;
8104 status_ = nil;
8105 caption_ = nil;
8106
8107 [super releaseSubviews];
8108}
8109
8110@end
8111/* }}} */
8112
8113@interface Cydia : CyteApplication <
8114 ConfirmationControllerDelegate,
8115 DatabaseDelegate,
8116 CydiaDelegate
8117> {
8118 _H<CyteWindow> window_;
8119 _H<CydiaTabBarController> tabbar_;
8120 _H<CyteTabBarController> emulated_;
8121 _H<AppCacheController> appcache_;
8122
8123 _H<NSMutableArray> essential_;
8124 _H<NSMutableArray> broken_;
8125
8126 Database *database_;
8127
8128 _H<NSURL> starturl_;
8129
8130 unsigned locked_;
8131
8132 _H<StashController> stash_;
8133
8134 bool loaded_;
8135}
8136
8137- (void) loadData;
8138
8139@end
8140
8141@implementation Cydia
8142
8143- (void) lockSuspend {
8144 if (locked_++ == 0) {
8145 if ($SBSSetInterceptsMenuButtonForever != NULL)
8146 (*$SBSSetInterceptsMenuButtonForever)(true);
8147
8148 [self setIdleTimerDisabled:YES];
8149 }
8150}
8151
8152- (void) unlockSuspend {
8153 if (--locked_ == 0) {
8154 [self setIdleTimerDisabled:NO];
8155
8156 if ($SBSSetInterceptsMenuButtonForever != NULL)
8157 (*$SBSSetInterceptsMenuButtonForever)(false);
8158 }
8159}
8160
8161- (void) beginUpdate {
8162 [tabbar_ beginUpdate];
8163}
8164
8165- (void) cancelUpdate {
8166 [tabbar_ cancelUpdate];
8167}
8168
8169- (bool) requestUpdate {
8170 if (CyteIsReachable("cydia.saurik.com")) {
8171 [self beginUpdate];
8172 return true;
8173 } else {
8174 UIAlertView *alert = [[[UIAlertView alloc]
8175 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8176 message:@"Host Unreachable" // XXX: Localize
8177 delegate:self
8178 cancelButtonTitle:UCLocalize("OK")
8179 otherButtonTitles:nil
8180 ] autorelease];
8181
8182 [alert setContext:@"norefresh"];
8183 [alert show];
8184
8185 return false;
8186 }
8187}
8188
8189- (BOOL) updating {
8190 return [tabbar_ updating];
8191}
8192
8193- (void) _loaded {
8194 if ([broken_ count] != 0) {
8195 int count = [broken_ count];
8196
8197 UIAlertView *alert = [[[UIAlertView alloc]
8198 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8199 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8200 delegate:self
8201 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8202 otherButtonTitles:
8203 UCLocalize("TEMPORARY_IGNORE"),
8204 nil
8205 ] autorelease];
8206
8207 [alert setContext:@"fixhalf"];
8208 [alert setNumberOfRows:2];
8209 [alert show];
8210 } else if (!Ignored_ && [essential_ count] != 0) {
8211 int count = [essential_ count];
8212
8213 UIAlertView *alert = [[[UIAlertView alloc]
8214 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8215 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8216 delegate:self
8217 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8218 otherButtonTitles:
8219 UCLocalize("UPGRADE_ESSENTIAL"),
8220 UCLocalize("COMPLETE_UPGRADE"),
8221 nil
8222 ] autorelease];
8223
8224 [alert setContext:@"upgrade"];
8225 [alert show];
8226 }
8227}
8228
8229- (void) returnToCydia {
8230 [self _loaded];
8231}
8232
8233- (void) reloadSpringBoard {
8234 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
8235 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
8236 else
8237 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
8238 sleep(15);
8239 system("/usr/bin/killall backboardd SpringBoard");
8240}
8241
8242- (void) _saveConfig {
8243 SaveConfig(database_);
8244}
8245
8246// Navigation controller for the queuing badge.
8247- (UINavigationController *) queueNavigationController {
8248 NSArray *controllers = [tabbar_ viewControllers];
8249 return [controllers objectAtIndex:3];
8250}
8251
8252- (void) _updateData {
8253 [self _saveConfig];
8254 [window_ unloadData];
8255
8256 UINavigationController *navigation = [self queueNavigationController];
8257
8258 id queuedelegate = nil;
8259 if ([[navigation viewControllers] count] > 0)
8260 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8261
8262 [queuedelegate queueStatusDidChange];
8263 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8264}
8265
8266- (void) _refreshIfPossible {
8267 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8268
8269 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:CacheState_] objectForKey:@"LastUpdate"]);
8270
8271 bool recently = false;
8272 if (update != nil) {
8273 NSTimeInterval interval([update timeIntervalSinceNow]);
8274 if (interval > -(15*60))
8275 recently = true;
8276 }
8277
8278 // Don't automatic refresh if:
8279 // - We already refreshed recently.
8280 // - We already auto-refreshed this launch.
8281 // - Auto-refresh is disabled.
8282 // - Cydia's server is not reachable
8283 if (recently || loaded_ || ManualRefresh || !CyteIsReachable("cydia.saurik.com")) {
8284 // If we are cancelling, we need to make sure it knows it's already loaded.
8285 loaded_ = true;
8286
8287 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8288 } else {
8289 // We are going to load, so remember that.
8290 loaded_ = true;
8291
8292 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
8293 }
8294
8295 [pool release];
8296}
8297
8298- (void) refreshIfPossible {
8299 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8300}
8301
8302- (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8303_profile(reloadDataWithInvocation)
8304@synchronized (self) {
8305 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8306 if (hud != nil)
8307 [hud setText:UCLocalize("RELOADING_DATA")];
8308
8309 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8310
8311 size_t changes(0);
8312
8313 [essential_ removeAllObjects];
8314 [broken_ removeAllObjects];
8315
8316 _profile(reloadDataWithInvocation$Essential)
8317 NSArray *packages([database_ packages]);
8318 for (Package *package in packages) {
8319 if ([package half])
8320 [broken_ addObject:package];
8321 if ([package upgradableAndEssential:YES] && ![package ignored]) {
8322 if ([package essential] && [package installed] != nil)
8323 [essential_ addObject:package];
8324 ++changes;
8325 }
8326 }
8327 _end
8328
8329 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8330 if (changes != 0) {
8331 _trace();
8332 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8333 [changesItem setBadgeValue:badge];
8334 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8335 [self setApplicationIconBadgeNumber:changes];
8336 } else {
8337 _trace();
8338 [changesItem setBadgeValue:nil];
8339 [changesItem setAnimatedBadge:NO];
8340 [self setApplicationIconBadgeNumber:0];
8341 }
8342
8343 Queuing_ = false;
8344 [self _updateData];
8345
8346 if (hud != nil)
8347 [self removeProgressHUD:hud];
8348}
8349_end
8350
8351 PrintTimes();
8352}
8353
8354- (void) updateData {
8355 [self _updateData];
8356}
8357
8358- (void) updateDataAndLoad {
8359 [self _updateData];
8360 if ([database_ progressDelegate] == nil)
8361 [self _loaded];
8362}
8363
8364- (void) update_ {
8365 [database_ update];
8366 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8367}
8368
8369- (void) disemulate {
8370 if (emulated_ == nil)
8371 return;
8372
8373 [window_ setRootViewController:tabbar_];
8374 emulated_ = nil;
8375
8376 [window_ setUserInteractionEnabled:YES];
8377}
8378
8379- (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8380 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8381
8382 UIViewController *parent;
8383 if (emulated_ == nil)
8384 parent = tabbar_;
8385 else if (!force)
8386 parent = emulated_;
8387 else {
8388 [self disemulate];
8389 parent = tabbar_;
8390 }
8391
8392 if (IsWildcat_)
8393 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8394 [parent presentModalViewController:navigation animated:YES];
8395}
8396
8397- (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8398 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8399
8400 if (navigation != nil)
8401 [navigation pushViewController:progress animated:YES];
8402 else
8403 [self presentModalViewController:progress force:YES];
8404
8405 [progress invoke:invocation withTitle:title];
8406 return progress;
8407}
8408
8409- (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8410 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8411}
8412
8413- (void) repairWithInvocation:(NSInvocation *)invocation {
8414 _trace();
8415 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8416 _trace();
8417}
8418
8419- (void) repairWithSelector:(SEL)selector {
8420 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8421}
8422
8423- (void) reloadData {
8424 [self reloadDataWithInvocation:nil];
8425 if ([database_ progressDelegate] == nil)
8426 [self _loaded];
8427}
8428
8429- (void) syncData {
8430 [self _saveConfig];
8431 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8432}
8433
8434- (void) addSource:(NSDictionary *) source {
8435 CydiaAddSource(source);
8436}
8437
8438- (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
8439 CydiaAddSource(href, distribution, sections);
8440}
8441
8442// XXX: this method should not return anything
8443- (BOOL) addTrivialSource:(NSString *)href {
8444 CydiaAddSource(href, @"./");
8445 return YES;
8446}
8447
8448- (void) resolve {
8449 pkgProblemResolver *resolver = [database_ resolver];
8450
8451 resolver->InstallProtect();
8452 if (!resolver->Resolve(true))
8453 _error->Discard();
8454}
8455
8456- (bool) perform {
8457 // XXX: this is a really crappy way of doing this.
8458 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8459 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8460 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8461 if ([tabbar_ updating])
8462 [tabbar_ cancelUpdate];
8463
8464 if (![database_ prepare])
8465 return false;
8466
8467 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8468 [page setDelegate:self];
8469 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8470
8471 if (IsWildcat_)
8472 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8473 [tabbar_ presentModalViewController:confirm_ animated:YES];
8474
8475 return true;
8476}
8477
8478- (void) queue {
8479 @synchronized (self) {
8480 [self perform];
8481 }
8482}
8483
8484- (void) clearPackage:(Package *)package {
8485 @synchronized (self) {
8486 [package clear];
8487 [self resolve];
8488 [self perform];
8489 }
8490}
8491
8492- (void) installPackages:(NSArray *)packages {
8493 @synchronized (self) {
8494 for (Package *package in packages)
8495 [package install];
8496 [self resolve];
8497 [self perform];
8498 }
8499}
8500
8501- (void) installPackage:(Package *)package {
8502 @synchronized (self) {
8503 [package install];
8504 [self resolve];
8505 [self perform];
8506 }
8507}
8508
8509- (void) removePackage:(Package *)package {
8510 @synchronized (self) {
8511 [package remove];
8512 [self resolve];
8513 [self perform];
8514 }
8515}
8516
8517- (void) distUpgrade {
8518 @synchronized (self) {
8519 if (![database_ upgrade])
8520 return;
8521 [self perform];
8522 }
8523}
8524
8525- (void) _uicache {
8526 _trace();
8527 system("/usr/bin/uicache");
8528 _trace();
8529}
8530
8531- (void) uicache {
8532 UIProgressHUD *hud([self addProgressHUD]);
8533 [hud setText:UCLocalize("LOADING")];
8534 [self yieldToSelector:@selector(_uicache)];
8535 [self removeProgressHUD:hud];
8536}
8537
8538- (void) perform_ {
8539 [database_ perform];
8540 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8541 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
8542}
8543
8544- (void) confirmWithNavigationController:(UINavigationController *)navigation {
8545 Queuing_ = false;
8546 [self lockSuspend];
8547 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
8548 [self unlockSuspend];
8549}
8550
8551- (void) cancelAndClear:(bool)clear {
8552 @synchronized (self) {
8553 if (clear) {
8554 [database_ clear];
8555 Queuing_ = false;
8556 } else {
8557 Queuing_ = true;
8558 }
8559
8560 [self _updateData];
8561 }
8562}
8563
8564- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8565 NSString *context([alert context]);
8566
8567 if ([context isEqualToString:@"conffile"]) {
8568 FILE *input = [database_ input];
8569 if (button == [alert cancelButtonIndex])
8570 fprintf(input, "N\n");
8571 else if (button == [alert firstOtherButtonIndex])
8572 fprintf(input, "Y\n");
8573 fflush(input);
8574
8575 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8576 } else if ([context isEqualToString:@"fixhalf"]) {
8577 if (button == [alert cancelButtonIndex]) {
8578 @synchronized (self) {
8579 for (Package *broken in (id) broken_) {
8580 [broken remove];
8581 NSString *id(ShellEscape([broken id]));
8582 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
8583 " /var/lib/dpkg/info/%@.prerm"
8584 " /var/lib/dpkg/info/%@.postrm"
8585 " /var/lib/dpkg/info/%@.preinst"
8586 " /var/lib/dpkg/info/%@.postinst"
8587 " /var/lib/dpkg/info/%@.extrainst_"
8588 "", id, id, id, id, id] UTF8String]);
8589 }
8590
8591 [self resolve];
8592 [self perform];
8593 }
8594 } else if (button == [alert firstOtherButtonIndex]) {
8595 [broken_ removeAllObjects];
8596 [self _loaded];
8597 }
8598
8599 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8600 } else if ([context isEqualToString:@"upgrade"]) {
8601 if (button == [alert firstOtherButtonIndex]) {
8602 @synchronized (self) {
8603 for (Package *essential in (id) essential_)
8604 [essential install];
8605
8606 [self resolve];
8607 [self perform];
8608 }
8609 } else if (button == [alert firstOtherButtonIndex] + 1) {
8610 [self distUpgrade];
8611 } else if (button == [alert cancelButtonIndex]) {
8612 Ignored_ = YES;
8613 }
8614
8615 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8616 }
8617}
8618
8619- (void) system:(NSString *)command {
8620 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8621
8622 _trace();
8623 system([command UTF8String]);
8624 _trace();
8625
8626 [pool release];
8627}
8628
8629- (void) applicationWillSuspend {
8630 [database_ clean];
8631 [super applicationWillSuspend];
8632}
8633
8634- (BOOL) isSafeToSuspend {
8635 if (locked_ != 0) {
8636#if !ForRelease
8637 NSLog(@"isSafeToSuspend: locked_ != 0");
8638#endif
8639 return false;
8640 }
8641
8642 if ([tabbar_ modalViewController] != nil)
8643 return false;
8644
8645 // Use external process status API internally.
8646 // This is probably a really bad idea.
8647 // XXX: what is the point of this? does this solve anything at all?
8648 uint64_t status = 0;
8649 int notify_token;
8650 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
8651 notify_get_state(notify_token, &status);
8652 notify_cancel(notify_token);
8653 }
8654
8655 if (status != 0) {
8656#if !ForRelease
8657 NSLog(@"isSafeToSuspend: status != 0");
8658#endif
8659 return false;
8660 }
8661
8662#if !ForRelease
8663 NSLog(@"isSafeToSuspend: -> true");
8664#endif
8665 return true;
8666}
8667
8668- (void) suspendReturningToLastApp:(BOOL)returning {
8669 if ([self isSafeToSuspend])
8670 [super suspendReturningToLastApp:returning];
8671}
8672
8673- (void) suspend {
8674 if ([self isSafeToSuspend])
8675 [super suspend];
8676}
8677
8678- (void) applicationSuspend {
8679 if ([self isSafeToSuspend])
8680 [super applicationSuspend];
8681}
8682
8683- (void) applicationSuspend:(GSEventRef)event {
8684 if ([self isSafeToSuspend])
8685 [super applicationSuspend:event];
8686}
8687
8688- (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8689 if ([self isSafeToSuspend])
8690 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8691}
8692
8693- (void) _setSuspended:(BOOL)value {
8694 if ([self isSafeToSuspend])
8695 [super _setSuspended:value];
8696}
8697
8698- (UIProgressHUD *) addProgressHUD {
8699 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
8700 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8701
8702 [window_ setUserInteractionEnabled:NO];
8703
8704 UIViewController *target(tabbar_);
8705 if (UIViewController *modal = [target modalViewController])
8706 target = modal;
8707
8708 [hud showInView:[target view]];
8709
8710 [self lockSuspend];
8711 return hud;
8712}
8713
8714- (void) removeProgressHUD:(UIProgressHUD *)hud {
8715 [self unlockSuspend];
8716 [hud hide];
8717 [hud removeFromSuperview];
8718 [window_ setUserInteractionEnabled:YES];
8719}
8720
8721- (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
8722 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
8723}
8724
8725- (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
8726 NSString *scheme([[url scheme] lowercaseString]);
8727 if ([[url absoluteString] length] <= [scheme length] + 3)
8728 return nil;
8729 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8730 NSArray *components([path componentsSeparatedByString:@"/"]);
8731
8732 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
8733 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
8734 if (controller != nil)
8735 [controller setDelegate:self];
8736 return controller;
8737 }
8738
8739 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8740 return nil;
8741
8742 NSString *base([components objectAtIndex:0]);
8743
8744 CyteViewController *controller = nil;
8745
8746 if ([base isEqualToString:@"url"]) {
8747 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8748 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8749 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
8750 } else if (!external && [components count] == 1) {
8751 if ([base isEqualToString:@"sources"]) {
8752 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8753 }
8754
8755 if ([base isEqualToString:@"home"]) {
8756 controller = [[[HomeController alloc] init] autorelease];
8757 }
8758
8759 if ([base isEqualToString:@"sections"]) {
8760 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
8761 }
8762
8763 if ([base isEqualToString:@"search"]) {
8764 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
8765 }
8766
8767 if ([base isEqualToString:@"changes"]) {
8768 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8769 }
8770
8771 if ([base isEqualToString:@"installed"]) {
8772 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8773 }
8774 } else if ([components count] == 2) {
8775 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
8776
8777 if ([base isEqualToString:@"package"]) {
8778 controller = [self pageForPackage:argument withReferrer:referrer];
8779 }
8780
8781 if (!external && [base isEqualToString:@"search"]) {
8782 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
8783 }
8784
8785 if (!external && [base isEqualToString:@"sections"]) {
8786 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
8787 argument = nil;
8788 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
8789 }
8790
8791 if ([base isEqualToString:@"sources"]) {
8792 if ([argument isEqualToString:@"add"]) {
8793 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8794 [(SourcesController *)controller showAddSourcePrompt];
8795 } else {
8796 Source *source([database_ sourceWithKey:argument]);
8797 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
8798 }
8799 }
8800
8801 if (!external && [base isEqualToString:@"launch"]) {
8802 [self launchApplicationWithIdentifier:argument suspended:NO];
8803 return nil;
8804 }
8805 } else if (!external && [components count] == 3) {
8806 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
8807 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
8808
8809 if ([base isEqualToString:@"package"]) {
8810 if ([arg2 isEqualToString:@"settings"]) {
8811 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8812 } else if ([arg2 isEqualToString:@"files"]) {
8813 controller = [[[FileTable alloc] initWithDatabase:database_ forPackage:arg1] autorelease];
8814 }
8815 }
8816
8817 if ([base isEqualToString:@"sections"]) {
8818 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
8819 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
8820 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
8821 }
8822 }
8823
8824 [controller setDelegate:self];
8825 return controller;
8826}
8827
8828- (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
8829 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
8830
8831 if (page != nil)
8832 [tabbar_ setUnselectedViewController:page];
8833
8834 return page != nil;
8835}
8836
8837- (void) applicationOpenURL:(NSURL *)url {
8838 [super applicationOpenURL:url];
8839
8840 if (!loaded_)
8841 starturl_ = url;
8842 else
8843 [self openCydiaURL:url forExternal:YES];
8844}
8845
8846- (void) applicationWillResignActive:(UIApplication *)application {
8847 // Stop refreshing if you get a phone call or lock the device.
8848 if ([tabbar_ updating])
8849 [tabbar_ cancelUpdate];
8850
8851 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8852 [super applicationWillResignActive:application];
8853}
8854
8855- (void) saveState {
8856 [[NSDictionary dictionaryWithObjectsAndKeys:
8857 @"InterfaceState", [tabbar_ navigationURLCollection],
8858 @"LastClosed", [NSDate date],
8859 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
8860 nil] writeToFile:SavedState_ atomically:YES];
8861
8862 [self _saveConfig];
8863}
8864
8865- (void) applicationWillTerminate:(UIApplication *)application {
8866 [self saveState];
8867}
8868
8869- (void) applicationDidEnterBackground:(UIApplication *)application {
8870 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
8871 return [self terminateWithSuccess];
8872 Backgrounded_ = [NSDate date];
8873 [self saveState];
8874}
8875
8876- (void) applicationWillEnterForeground:(UIApplication *)application {
8877 if (Backgrounded_ == nil)
8878 return;
8879
8880 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
8881
8882 if (interval <= -(30*60)) {
8883 [tabbar_ setSelectedIndex:0];
8884 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
8885 }
8886
8887 if (interval <= -(15*60)) {
8888 if (CyteIsReachable("cydia.saurik.com")) {
8889 [tabbar_ beginUpdate];
8890 [appcache_ reloadURLWithCache:YES];
8891 }
8892 }
8893
8894 if ([database_ delocked])
8895 [self reloadData];
8896}
8897
8898- (void) setConfigurationData:(NSString *)data {
8899 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
8900
8901 if (!conffile_r(data)) {
8902 lprintf("E:invalid conffile\n");
8903 return;
8904 }
8905
8906 NSString *ofile = conffile_r[1];
8907 //NSString *nfile = conffile_r[2];
8908
8909 UIAlertView *alert = [[[UIAlertView alloc]
8910 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
8911 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
8912 delegate:self
8913 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
8914 otherButtonTitles:
8915 UCLocalize("ACCEPT_NEW_COPY"),
8916 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
8917 nil
8918 ] autorelease];
8919
8920 [alert setContext:@"conffile"];
8921 [alert setNumberOfRows:2];
8922 [alert show];
8923}
8924
8925- (void) addStashController {
8926 [self lockSuspend];
8927 stash_ = [[[StashController alloc] init] autorelease];
8928 [window_ addSubview:[stash_ view]];
8929}
8930
8931- (void) removeStashController {
8932 [[stash_ view] removeFromSuperview];
8933 stash_ = nil;
8934 [self unlockSuspend];
8935}
8936
8937- (void) stash {
8938 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8939 UpdateExternalStatus(1);
8940 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
8941 UpdateExternalStatus(0);
8942
8943 [self removeStashController];
8944 [self reloadSpringBoard];
8945}
8946
8947- (void) applicationDidFinishLaunching:(id)unused {
8948 [super applicationDidFinishLaunching:unused];
8949 [CyteWebViewController _initialize];
8950
8951 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
8952
8953 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8954
8955 // this would disallow http{,s} URLs from accessing this data
8956 //[WebView registerURLSchemeAsLocal:@"cydia"];
8957
8958 Font12_ = [UIFont systemFontOfSize:12];
8959 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
8960 Font14_ = [UIFont systemFontOfSize:14];
8961 Font18_ = [UIFont systemFontOfSize:18];
8962 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
8963 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
8964
8965 essential_ = [NSMutableArray arrayWithCapacity:4];
8966 broken_ = [NSMutableArray arrayWithCapacity:4];
8967
8968 // XXX: I really need this thing... like, seriously... I'm sorry
8969 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
8970 [appcache_ reloadData];
8971
8972 window_ = [[[CyteWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
8973 [window_ orderFront:self];
8974 [window_ makeKey:self];
8975 [window_ setHidden:NO];
8976
8977 if (access("/.cydia_no_stash", F_OK) == 0);
8978 else {
8979
8980 if (false) stash: {
8981 [self addStashController];
8982 // XXX: this would be much cleaner as a yieldToSelector:
8983 // that way the removeStashController could happen right here inline
8984 // we also could no longer require the useless stash_ field anymore
8985 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8986 return;
8987 }
8988
8989 struct stat root;
8990 int error(stat("/", &root));
8991 _assert(error != -1);
8992
8993 #define Stash_(path) do { \
8994 struct stat folder; \
8995 int error(lstat((path), &folder)); \
8996 if (error != -1 && ( \
8997 folder.st_dev == root.st_dev && \
8998 S_ISDIR(folder.st_mode) \
8999 ) || error == -1 && ( \
9000 errno == ENOENT || \
9001 errno == ENOTDIR \
9002 )) goto stash; \
9003 } while (false)
9004
9005 Stash_("/Applications");
9006 Stash_("/Library/Ringtones");
9007 Stash_("/Library/Wallpaper");
9008 //Stash_("/usr/bin");
9009 Stash_("/usr/include");
9010 Stash_("/usr/share");
9011 //Stash_("/var/lib");
9012
9013 }
9014
9015 database_ = [Database sharedInstance];
9016 [database_ setDelegate:self];
9017
9018 [window_ setUserInteractionEnabled:NO];
9019
9020 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9021
9022 [tabbar_ addViewControllers:nil,
9023 @"Cydia", @"home.png", @"home7.png", @"home7s.png",
9024 UCLocalize("SOURCES"), @"install.png", @"install7.png", @"install7s.png",
9025 UCLocalize("CHANGES"), @"changes.png", @"changes7.png", @"changes7s.png",
9026 UCLocalize("INSTALLED"), @"manage.png", @"manage7.png", @"manage7s.png",
9027 UCLocalize("SEARCH"), @"search.png", @"search7.png", @"search7s.png",
9028 nil];
9029
9030 [tabbar_ setUpdateDelegate:self];
9031
9032 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9033 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9034 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9035
9036 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9037 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9038 [emulated_ setSelectedIndex:0];
9039
9040 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9041 [emulated_ concealTabBarSelection];
9042
9043 [window_ setRootViewController:emulated_];
9044
9045 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9046_trace();
9047}
9048
9049- (NSArray *) defaultStartPages {
9050 NSMutableArray *standard = [NSMutableArray array];
9051 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9052 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9053 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9054 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9055 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9056 return standard;
9057}
9058
9059- (void) loadData {
9060_trace();
9061 if ([emulated_ modalViewController] != nil)
9062 [emulated_ dismissModalViewControllerAnimated:YES];
9063 [window_ setUserInteractionEnabled:NO];
9064
9065 [self reloadDataWithInvocation:nil];
9066 [self refreshIfPossible];
9067 [self disemulate];
9068
9069 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:SavedState_]);
9070
9071 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9072 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9073 int standardIndex = 0;
9074 NSArray *standard = [self defaultStartPages];
9075
9076 BOOL valid = YES;
9077
9078 if (saved == nil)
9079 valid = NO;
9080
9081 NSDate *closed = [state objectForKey:@"LastClosed"];
9082 if (valid && closed != nil) {
9083 NSTimeInterval interval([closed timeIntervalSinceNow]);
9084 if (interval <= -(30*60))
9085 valid = NO;
9086 }
9087
9088 if (valid && [saved count] != [standard count])
9089 valid = NO;
9090
9091 if (valid) {
9092 for (unsigned int i = 0; i < [standard count]; i++) {
9093 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9094 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9095 // but it's good enough for now.
9096 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9097 valid = NO;
9098 break;
9099 }
9100 }
9101 }
9102
9103 NSArray *items = nil;
9104 if (valid) {
9105 [tabbar_ setSelectedIndex:savedIndex];
9106 items = saved;
9107 } else {
9108 [tabbar_ setSelectedIndex:standardIndex];
9109 items = standard;
9110 }
9111
9112 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9113 NSArray *stack = [items objectAtIndex:tab];
9114 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9115 NSMutableArray *current = [NSMutableArray array];
9116
9117 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9118 NSString *addr = [stack objectAtIndex:nav];
9119 NSURL *url = [NSURL URLWithString:addr];
9120 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9121 if (page != nil)
9122 [current addObject:page];
9123 }
9124
9125 [navigation setViewControllers:current];
9126 }
9127
9128 // (Try to) show the startup URL.
9129 if (starturl_ != nil) {
9130 [self openCydiaURL:starturl_ forExternal:YES];
9131 starturl_ = nil;
9132 }
9133}
9134
9135- (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9136 if (!IsWildcat_) {
9137 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
9138 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
9139 }
9140
9141 if (item != nil && IsWildcat_) {
9142 [sheet showFromBarButtonItem:item animated:YES];
9143 } else {
9144 [sheet showInView:window_];
9145 }
9146}
9147
9148- (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9149 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9150 [progress setTitle:task];
9151 [progress addProgressEvent:event];
9152}
9153
9154- (void) addProgressEventForTask:(NSArray *)data {
9155 CydiaProgressEvent *event([data objectAtIndex:0]);
9156 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9157 [self addProgressEvent:event forTask:task];
9158}
9159
9160- (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9161 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9162}
9163
9164@end
9165
9166/*IMP alloc_;
9167id Alloc_(id self, SEL selector) {
9168 id object = alloc_(self, selector);
9169 lprintf("[%s]A-%p\n", self->isa->name, object);
9170 return object;
9171}*/
9172
9173/*IMP dealloc_;
9174id Dealloc_(id self, SEL selector) {
9175 id object = dealloc_(self, selector);
9176 lprintf("[%s]D-%p\n", self->isa->name, object);
9177 return object;
9178}*/
9179
9180static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
9181 if (type == NULL)
9182 return nil;
9183 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
9184 return nil;
9185 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
9186 CFRelease(type);
9187 return [(NSMutableDictionary *) copy autorelease];
9188}
9189
9190int main_copy();
9191int main_file();
9192int main_gpgv();
9193int main_rred(int, char *argv[]);
9194
9195int main_gzip(int, char *argv[]);
9196
9197int main_store(int, char *argv[]);
9198
9199int main_http();
9200
9201int main(int argc, char *argv[]) {
9202 const char *argv0(argv[0]);
9203 if (const char *slash = strrchr(argv0, '/'))
9204 argv0 = slash + 1;
9205 if (false);
9206 else if (!strcmp(argv0, "copy"))
9207 return main_copy();
9208 else if (!strcmp(argv0, "file"))
9209 return main_file();
9210 else if (!strcmp(argv0, "gpgv"))
9211 return main_gpgv();
9212 else if (!strcmp(argv0, "rred"))
9213 return main_rred(argc, argv);
9214#ifdef __arm__
9215 else if (!strcmp(argv0, "bzip2"))
9216 return main_gzip(argc, argv);
9217 else if (!strcmp(argv0, "gzip"))
9218 return main_gzip(argc, argv);
9219 else if (!strcmp(argv0, "lzma"))
9220 return main_gzip(argc, argv);
9221#endif
9222#ifndef __arm__
9223 else if (!strcmp(argv0, "store"))
9224 return main_store(argc, argv);
9225#endif
9226 else if (!strcmp(argv0, "http"))
9227 return main_http();
9228 else if (!strcmp(argv0, "https"))
9229 return main_http();
9230 else {}
9231
9232 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
9233 dup2(fd, 2);
9234 close(fd);
9235
9236 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9237
9238 _trace();
9239
9240 CyteInitialize([NSString stringWithFormat:@"Cydia/%@", Cydia_]);
9241 UpdateExternalStatus(0);
9242
9243 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9244 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9245 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9246
9247 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@/1.1", IsWildcat_ ? @"ipad" : @"iphone"]);
9248 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9249
9250 /* Set Locale {{{ */
9251 Locale_ = CFLocaleCopyCurrent();
9252 Languages_ = [NSLocale preferredLanguages];
9253
9254 std::string languages;
9255 const char *translation(NULL);
9256
9257 // XXX: this isn't really a language, but this is compatible with older Cydia builds
9258 if (Locale_ != NULL)
9259 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
9260 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
9261 if (pattern(language)) {
9262 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
9263 languages += translation;
9264 languages += ",";
9265 }
9266 }
9267
9268 if (Languages_ != nil)
9269 for (NSString *locale : Languages_) {
9270 auto components([NSLocale componentsFromLocaleIdentifier:locale]);
9271 NSString *language([components objectForKey:(id)kCFLocaleLanguageCode]);
9272 if (NSString *script = [components objectForKey:(id)kCFLocaleScriptCode])
9273 language = [NSString stringWithFormat:@"%@-%@", language, script];
9274 languages += [language UTF8String];
9275 languages += ",";
9276 }
9277
9278 languages += "en";
9279 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
9280 /* }}} */
9281 /* Index Collation {{{ */
9282 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
9283 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
9284 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
9285 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
9286 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
9287 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
9288
9289 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
9290
9291 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
9292 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
9293 for (NSInteger offset : (NSInteger[]) {0,1,3,4,6,7,9,10,12,13,15,16,18,25,26,29,30,33,34,37,38,42,43,46,47,50,51})
9294 CollationOffset_.push_back(offset);
9295 CollationTitles_ = [NSArray arrayWithObjects:@"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 畫以上",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
9296 CollationStarts_ = [NSArray arrayWithObjects:@"一",@"丁",@"丈",@"不",@"且",@"丞",@"串",@"並",@"亭",@"乘",@"乾",@"傀",@"亂",@"僎",@"僵",@"儐",@"償",@"叢",@"儳",@"嚴",@"儷",@"儻",@"囌",@"囑",@"廳",@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"ʒ",nil];
9297 } else {
9298
9299 CollationThumbs_ = [collation sectionIndexTitles];
9300 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
9301 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
9302
9303 CollationTitles_ = [collation sectionTitles];
9304 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
9305
9306 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
9307 if (&transform != NULL && transform != nil) {
9308 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
9309 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
9310 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
9311 UErrorCode code(U_ZERO_ERROR);
9312 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
9313 if (!U_SUCCESS(code))
9314 NSLog(@"%s", u_errorName(code));
9315 }
9316
9317 }
9318 } @catch (NSException *e) {
9319 NSLog(@"%@", e);
9320 goto hard;
9321 } } else hard: {
9322 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
9323
9324 CollationThumbs_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
9325 for (NSInteger offset(0); offset != 28; ++offset)
9326 CollationOffset_.push_back(offset);
9327
9328 CollationTitles_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
9329 CollationStarts_ = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"ʒ",nil];
9330 }
9331 /* }}} */
9332
9333 App_ = [[NSBundle mainBundle] bundlePath];
9334 Advanced_ = YES;
9335
9336 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
9337 mkdir([Cache_ UTF8String], 0755);
9338
9339 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9340 alloc_ = alloc->method_imp;
9341 alloc->method_imp = (IMP) &Alloc_;*/
9342
9343 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9344 dealloc_ = dealloc->method_imp;
9345 dealloc->method_imp = (IMP) &Dealloc_;*/
9346
9347 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
9348 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
9349 UniqueID_ = UniqueIdentifier([UIDevice currentDevice]);
9350
9351 /* System Information {{{ */
9352 size_t size;
9353
9354 int maxproc;
9355 size = sizeof(maxproc);
9356 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9357 perror("sysctlbyname(\"kern.maxproc\", ?)");
9358 else if (maxproc < 64) {
9359 maxproc = 64;
9360 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9361 perror("sysctlbyname(\"kern.maxproc\", #)");
9362 }
9363 /* }}} */
9364 /* Load Database {{{ */
9365 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9366
9367 _trace();
9368 mkdir("/var/mobile/Library/Cydia", 0755);
9369 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
9370 _trace();
9371
9372 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
9373 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
9374 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
9375 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
9376
9377 _trace();
9378 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
9379
9380 if (Values_ == nil)
9381 Values_ = [metadata objectForKey:@"Values"];
9382 if (Values_ == nil)
9383 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
9384
9385 if (Sections_ == nil)
9386 Sections_ = [metadata objectForKey:@"Sections"];
9387 if (Sections_ == nil)
9388 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9389
9390 if (Sources_ == nil)
9391 Sources_ = [metadata objectForKey:@"Sources"];
9392 if (Sources_ == nil)
9393 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9394
9395 // XXX: this wrong, but in a way that doesn't matter :/
9396 if (Version_ == nil)
9397 Version_ = [metadata objectForKey:@"Version"];
9398 if (Version_ == nil)
9399 Version_ = [NSNumber numberWithUnsignedInt:0];
9400
9401 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
9402 bool fail(false);
9403 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
9404 _trace();
9405 if (fail)
9406 NSLog(@"unable to import package preferences... from 2010? oh well :/");
9407 }
9408
9409 if ([Version_ unsignedIntValue] == 0) {
9410 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9411 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9412 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9413
9414 Version_ = [NSNumber numberWithUnsignedInt:1];
9415
9416 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:CacheState_]) {
9417 [cache removeObjectForKey:@"LastUpdate"];
9418 [cache writeToFile:CacheState_ atomically:YES];
9419 }
9420 }
9421
9422 _H<NSMutableArray> broken([NSMutableArray array]);
9423 for (NSString *key in (id) Sources_)
9424 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
9425 [broken addObject:key];
9426 if ([broken count] != 0)
9427 for (NSString *key in (id) broken)
9428 [Sources_ removeObjectForKey:key];
9429 broken = nil;
9430
9431 SaveConfig(nil);
9432 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
9433 /* }}} */
9434
9435 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9436
9437 if (kCFCoreFoundationVersionNumber > 1000)
9438 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
9439
9440 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9441
9442 if (access("/User", F_OK) != 0 || version != 6) {
9443 _trace();
9444 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
9445 _trace();
9446 }
9447
9448 if (access("/tmp/cydia.chk", F_OK) == 0) {
9449 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
9450 _assert(errno == ENOENT);
9451 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
9452 _assert(errno == ENOENT);
9453 }
9454
9455 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/ln -sf %@ /etc/apt/sources.list.d/cydia.list", Cache("sources.list")] UTF8String]);
9456
9457 /* APT Initialization {{{ */
9458 _assert(pkgInitConfig(*_config));
9459 _assert(pkgInitSystem(*_config, _system));
9460
9461 _config->Set("Acquire::AllowInsecureRepositories", true);
9462 _config->Set("Acquire::Check-Valid-Until", false);
9463
9464 _config->Set("Dir::Bin::Methods", "/Applications/Cydia.app");
9465
9466 _config->Set("pkgCacheGen::ForceEssential", "");
9467
9468 if (translation != NULL)
9469 _config->Set("APT::Acquire::Translation", translation);
9470 _config->Set("Acquire::Languages", languages);
9471
9472 // XXX: this timeout might be important :(
9473 //_config->Set("Acquire::http::Timeout", 15);
9474
9475 int64_t usermem(0);
9476 size = sizeof(usermem);
9477 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
9478 usermem = 0;
9479 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
9480
9481 mkdir([Cache("archives") UTF8String], 0755);
9482 mkdir([Cache("archives/partial") UTF8String], 0755);
9483 _config->Set("Dir::Cache", [Cache_ UTF8String]);
9484
9485 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
9486 _config->Set("Dir::State", [Cache_ UTF8String]);
9487
9488 mkdir([Cache("lists") UTF8String], 0755);
9489 mkdir([Cache("lists/partial") UTF8String], 0755);
9490 mkdir([Cache("periodic") UTF8String], 0755);
9491 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
9492
9493 std::string logs("/var/mobile/Library/Logs/Cydia");
9494 mkdir(logs.c_str(), 0755);
9495 _config->Set("Dir::Log", logs);
9496
9497 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
9498 /* }}} */
9499 /* Color Choices {{{ */
9500 space_ = CGColorSpaceCreateDeviceRGB();
9501
9502 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9503 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9504 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9505 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
9506 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9507 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9508 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9509 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9510 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9511 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9512
9513 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9514 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9515 /* }}}*/
9516 /* UIKit Configuration {{{ */
9517 // XXX: I have a feeling this was important
9518 //UIKeyboardDisableAutomaticAppearance();
9519 /* }}} */
9520
9521 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
9522 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
9523
9524 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
9525 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
9526 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
9527
9528 PulseInterval_ = fast ? 50000 : 500000;
9529
9530 Colon_ = UCLocalize("COLON_DELIMITED");
9531 Elision_ = UCLocalize("ELISION");
9532 Error_ = UCLocalize("ERROR");
9533 Warning_ = UCLocalize("WARNING");
9534
9535 _trace();
9536 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9537
9538 CGColorSpaceRelease(space_);
9539 CFRelease(Locale_);
9540
9541 [pool release];
9542 return value;
9543}