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