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