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