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