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