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