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