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