]>
Commit | Line | Data |
---|---|---|
1 | /* Cydia - iPhone UIKit Front-End for Debian APT | |
2 | * Copyright (C) 2008-2013 Jay Freeman (saurik) | |
3 | */ | |
4 | ||
5 | /* GNU General Public License, Version 3 {{{ */ | |
6 | /* | |
7 | * Cydia is free software: you can redistribute it and/or modify | |
8 | * it under the terms of the GNU General Public License as published | |
9 | * by the Free Software Foundation, either version 3 of the License, | |
10 | * or (at your option) any later version. | |
11 | * | |
12 | * Cydia is distributed in the hope that it will be useful, but | |
13 | * WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
15 | * GNU General Public License for more details. | |
16 | * | |
17 | * You should have received a copy of the GNU General Public License | |
18 | * along with Cydia. If not, see <http://www.gnu.org/licenses/>. | |
19 | **/ | |
20 | /* }}} */ | |
21 | ||
22 | // XXX: wtf/FastMalloc.h... wtf? | |
23 | #define USE_SYSTEM_MALLOC 1 | |
24 | ||
25 | /* #include Directives {{{ */ | |
26 | #include "CyteKit/UCPlatform.h" | |
27 | #include "CyteKit/Localize.h" | |
28 | ||
29 | #include <unicode/ustring.h> | |
30 | #include <unicode/utrans.h> | |
31 | ||
32 | #include <objc/objc.h> | |
33 | #include <objc/runtime.h> | |
34 | ||
35 | #include <CoreGraphics/CoreGraphics.h> | |
36 | #include <Foundation/Foundation.h> | |
37 | ||
38 | #if 0 | |
39 | #define DEPLOYMENT_TARGET_MACOSX 1 | |
40 | #define CF_BUILDING_CF 1 | |
41 | #include <CoreFoundation/CFInternal.h> | |
42 | #endif | |
43 | ||
44 | #include <CoreFoundation/CFUniChar.h> | |
45 | ||
46 | #include <SystemConfiguration/SystemConfiguration.h> | |
47 | ||
48 | #include <UIKit/UIKit.h> | |
49 | #include "iPhonePrivate.h" | |
50 | ||
51 | #include <IOKit/IOKitLib.h> | |
52 | ||
53 | #include <QuartzCore/CALayer.h> | |
54 | ||
55 | #include <WebCore/WebCoreThread.h> | |
56 | #include <WebKit/DOMHTMLIFrameElement.h> | |
57 | ||
58 | #include <algorithm> | |
59 | #include <iomanip> | |
60 | #include <set> | |
61 | #include <sstream> | |
62 | #include <string> | |
63 | ||
64 | #include <ext/stdio_filebuf.h> | |
65 | ||
66 | #undef ABS | |
67 | ||
68 | #include <apt-pkg/acquire.h> | |
69 | #include <apt-pkg/acquire-item.h> | |
70 | #include <apt-pkg/algorithms.h> | |
71 | #include <apt-pkg/cachefile.h> | |
72 | #include <apt-pkg/clean.h> | |
73 | #include <apt-pkg/configuration.h> | |
74 | #include <apt-pkg/debindexfile.h> | |
75 | #include <apt-pkg/debmetaindex.h> | |
76 | #include <apt-pkg/error.h> | |
77 | #include <apt-pkg/init.h> | |
78 | #include <apt-pkg/mmap.h> | |
79 | #include <apt-pkg/pkgrecords.h> | |
80 | #include <apt-pkg/sha1.h> | |
81 | #include <apt-pkg/sourcelist.h> | |
82 | #include <apt-pkg/sptr.h> | |
83 | #include <apt-pkg/strutl.h> | |
84 | #include <apt-pkg/tagfile.h> | |
85 | ||
86 | #include <apr-1/apr_pools.h> | |
87 | ||
88 | #include <sys/types.h> | |
89 | #include <sys/stat.h> | |
90 | #include <sys/sysctl.h> | |
91 | #include <sys/param.h> | |
92 | #include <sys/mount.h> | |
93 | #include <sys/reboot.h> | |
94 | ||
95 | #include <fcntl.h> | |
96 | #include <notify.h> | |
97 | #include <dlfcn.h> | |
98 | ||
99 | extern "C" { | |
100 | #include <mach-o/nlist.h> | |
101 | } | |
102 | ||
103 | #include <cstdio> | |
104 | #include <cstdlib> | |
105 | #include <cstring> | |
106 | ||
107 | #include <errno.h> | |
108 | ||
109 | #include <Cytore.hpp> | |
110 | #include "Sources.h" | |
111 | ||
112 | #include <CydiaSubstrate/CydiaSubstrate.h> | |
113 | #include "Menes/Menes.h" | |
114 | ||
115 | #include "CyteKit/IndirectDelegate.h" | |
116 | #include "CyteKit/PerlCompatibleRegEx.hpp" | |
117 | #include "CyteKit/TableViewCell.h" | |
118 | #include "CyteKit/TabBarController.h" | |
119 | #include "CyteKit/WebScriptObject-Cyte.h" | |
120 | #include "CyteKit/WebViewController.h" | |
121 | #include "CyteKit/WebViewTableViewCell.h" | |
122 | #include "CyteKit/stringWithUTF8Bytes.h" | |
123 | ||
124 | #include "Cydia/MIMEAddress.h" | |
125 | #include "Cydia/LoadingViewController.h" | |
126 | #include "Cydia/ProgressEvent.h" | |
127 | ||
128 | #include "SDURLCache/SDURLCache.h" | |
129 | /* }}} */ | |
130 | ||
131 | /* Profiler {{{ */ | |
132 | struct timeval _ltv; | |
133 | bool _itv; | |
134 | ||
135 | #define _timestamp ({ \ | |
136 | struct timeval tv; \ | |
137 | gettimeofday(&tv, NULL); \ | |
138 | tv.tv_sec * 1000000 + tv.tv_usec; \ | |
139 | }) | |
140 | ||
141 | typedef std::vector<class ProfileTime *> TimeList; | |
142 | TimeList times_; | |
143 | ||
144 | class ProfileTime { | |
145 | private: | |
146 | const char *name_; | |
147 | uint64_t total_; | |
148 | uint64_t count_; | |
149 | ||
150 | public: | |
151 | ProfileTime(const char *name) : | |
152 | name_(name), | |
153 | total_(0) | |
154 | { | |
155 | times_.push_back(this); | |
156 | } | |
157 | ||
158 | void AddTime(uint64_t time) { | |
159 | total_ += time; | |
160 | ++count_; | |
161 | } | |
162 | ||
163 | void Print() { | |
164 | if (total_ != 0) | |
165 | std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl; | |
166 | total_ = 0; | |
167 | count_ = 0; | |
168 | } | |
169 | }; | |
170 | ||
171 | class ProfileTimer { | |
172 | private: | |
173 | ProfileTime &time_; | |
174 | uint64_t start_; | |
175 | ||
176 | public: | |
177 | ProfileTimer(ProfileTime &time) : | |
178 | time_(time), | |
179 | start_(_timestamp) | |
180 | { | |
181 | } | |
182 | ||
183 | ~ProfileTimer() { | |
184 | time_.AddTime(_timestamp - start_); | |
185 | } | |
186 | }; | |
187 | ||
188 | void PrintTimes() { | |
189 | for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i) | |
190 | (*i)->Print(); | |
191 | std::cerr << "========" << std::endl; | |
192 | } | |
193 | ||
194 | #define _profile(name) { \ | |
195 | static ProfileTime name(#name); \ | |
196 | ProfileTimer _ ## name(name); | |
197 | ||
198 | #define _end } | |
199 | /* }}} */ | |
200 | ||
201 | // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork | |
202 | #define synchronized(lock) \ | |
203 | synchronized(static_cast<NSObject *>(lock)) | |
204 | ||
205 | extern NSString *Cydia_; | |
206 | ||
207 | #define lprintf(args...) fprintf(stderr, args) | |
208 | ||
209 | #define ForRelease 1 | |
210 | #define TraceLogging (1 && !ForRelease) | |
211 | #define HistogramInsertionSort (0 && !ForRelease) | |
212 | #define ProfileTimes (0 && !ForRelease) | |
213 | #define ForSaurik (0 && !ForRelease) | |
214 | #define LogBrowser (0 && !ForRelease) | |
215 | #define TrackResize (0 && !ForRelease) | |
216 | #define ManualRefresh (1 && !ForRelease) | |
217 | #define ShowInternals (0 && !ForRelease) | |
218 | #define AlwaysReload (0 && !ForRelease) | |
219 | ||
220 | #if !TraceLogging | |
221 | #undef _trace | |
222 | #define _trace(args...) | |
223 | #endif | |
224 | ||
225 | #if !ProfileTimes | |
226 | #undef _profile | |
227 | #define _profile(name) { | |
228 | #undef _end | |
229 | #define _end } | |
230 | #define PrintTimes() do {} while (false) | |
231 | #endif | |
232 | ||
233 | // Hash Functions/Structures {{{ | |
234 | extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0); | |
235 | ||
236 | union SplitHash { | |
237 | uint32_t u32; | |
238 | uint16_t u16[2]; | |
239 | }; | |
240 | // }}} | |
241 | ||
242 | static NSString *Colon_; | |
243 | NSString *Elision_; | |
244 | static NSString *Error_; | |
245 | static NSString *Warning_; | |
246 | ||
247 | static NSString *Cache_; | |
248 | ||
249 | static void (*$SBSSetInterceptsMenuButtonForever)(bool); | |
250 | ||
251 | static CFStringRef (*$MGCopyAnswer)(CFStringRef); | |
252 | ||
253 | static NSString *UniqueIdentifier(UIDevice *device = nil) { | |
254 | if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x | |
255 | return [device ?: [UIDevice currentDevice] uniqueIdentifier]; | |
256 | else | |
257 | return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease]; | |
258 | } | |
259 | ||
260 | static bool IsReachable(const char *name) { | |
261 | SCNetworkReachabilityFlags flags; { | |
262 | SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name)); | |
263 | SCNetworkReachabilityGetFlags(reachability, &flags); | |
264 | CFRelease(reachability); | |
265 | } | |
266 | ||
267 | // XXX: this elaborate mess is what Apple is using to determine this? :( | |
268 | // XXX: do we care if the user has to intervene? maybe that's ok? | |
269 | return | |
270 | (flags & kSCNetworkReachabilityFlagsReachable) != 0 && ( | |
271 | (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || ( | |
272 | (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 || | |
273 | (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0 | |
274 | ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 || | |
275 | (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0 | |
276 | ) | |
277 | ; | |
278 | } | |
279 | ||
280 | static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); | |
281 | ||
282 | static _finline NSString *CydiaURL(NSString *path) { | |
283 | char page[26]; | |
284 | page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's'; | |
285 | page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y'; | |
286 | page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's'; | |
287 | page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k'; | |
288 | page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/'; | |
289 | page[25] = '\0'; | |
290 | return [[NSString stringWithUTF8String:page] stringByAppendingString:path]; | |
291 | } | |
292 | ||
293 | static void ReapZombie(pid_t pid) { | |
294 | int status; | |
295 | wait: | |
296 | if (waitpid(pid, &status, 0) == -1) | |
297 | if (errno == EINTR) | |
298 | goto wait; | |
299 | else _assert(false); | |
300 | } | |
301 | ||
302 | static _finline void UpdateExternalStatus(uint64_t newStatus) { | |
303 | int notify_token; | |
304 | if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) { | |
305 | notify_set_state(notify_token, newStatus); | |
306 | notify_cancel(notify_token); | |
307 | } | |
308 | notify_post("com.saurik.Cydia.status"); | |
309 | } | |
310 | ||
311 | static CGFloat CYStatusBarHeight() { | |
312 | CGSize size([[UIApplication sharedApplication] statusBarFrame].size); | |
313 | return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width; | |
314 | } | |
315 | ||
316 | /* NSForcedOrderingSearch doesn't work on the iPhone */ | |
317 | static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch; | |
318 | static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch; | |
319 | static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering; | |
320 | ||
321 | /* Insertion Sort {{{ */ | |
322 | ||
323 | CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) { | |
324 | const char *ptr = (const char *)list; | |
325 | while (0 < count) { | |
326 | CFIndex half = count / 2; | |
327 | const char *probe = ptr + elementSize * half; | |
328 | CFComparisonResult cr = comparator(element, probe, context); | |
329 | if (0 == cr) return (probe - (const char *)list) / elementSize; | |
330 | ptr = (cr < 0) ? ptr : probe + elementSize; | |
331 | count = (cr < 0) ? half : (half + (count & 1) - 1); | |
332 | } | |
333 | return (ptr - (const char *)list) / elementSize; | |
334 | } | |
335 | ||
336 | CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) { | |
337 | const char *ptr = (const char *)list; | |
338 | while (0 < count) { | |
339 | CFIndex half = count / 2; | |
340 | const char *probe = ptr + elementSize * half; | |
341 | CFComparisonResult cr = comparator(element, probe, context); | |
342 | if (0 == cr) return (probe - (const char *)list) / elementSize; | |
343 | ptr = (cr < 0) ? ptr : probe + elementSize; | |
344 | count = (cr < 0) ? half : (half + (count & 1) - 1); | |
345 | } | |
346 | return (ptr - (const char *)list) / elementSize; | |
347 | } | |
348 | ||
349 | void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) { | |
350 | if (range.length == 0) | |
351 | return; | |
352 | const void **values(new const void *[range.length]); | |
353 | CFArrayGetValues(array, range, values); | |
354 | ||
355 | #if HistogramInsertionSort > 0 | |
356 | uint32_t total(0), *offsets(new uint32_t[range.length]); | |
357 | #endif | |
358 | ||
359 | for (CFIndex index(1); index != range.length; ++index) { | |
360 | const void *value(values[index]); | |
361 | //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context)); | |
362 | CFIndex correct(index); | |
363 | while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) { | |
364 | #if HistogramInsertionSort > 1 | |
365 | NSLog(@"%@ < %@", value, values[correct - 1]); | |
366 | #endif | |
367 | if (--correct == 0) | |
368 | break; | |
369 | } | |
370 | if (correct != index) { | |
371 | size_t offset(index - correct); | |
372 | #if HistogramInsertionSort | |
373 | total += offset; | |
374 | ++offsets[offset]; | |
375 | if (offset > 10) | |
376 | NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value); | |
377 | #endif | |
378 | memmove(values + correct + 1, values + correct, sizeof(const void *) * offset); | |
379 | values[correct] = value; | |
380 | } | |
381 | } | |
382 | ||
383 | CFArrayReplaceValues(array, range, values, range.length); | |
384 | delete [] values; | |
385 | ||
386 | #if HistogramInsertionSort > 0 | |
387 | for (CFIndex index(0); index != range.length; ++index) | |
388 | if (offsets[index] != 0) | |
389 | NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]); | |
390 | NSLog(@"Average Insertion Displacement: %f", double(total) / range.length); | |
391 | delete [] offsets; | |
392 | #endif | |
393 | } | |
394 | ||
395 | /* }}} */ | |
396 | ||
397 | /* Apple Bug Fixes {{{ */ | |
398 | @implementation UIWebDocumentView (Cydia) | |
399 | ||
400 | - (void) _setScrollerOffset:(CGPoint)offset { | |
401 | UIScroller *scroller([self _scroller]); | |
402 | ||
403 | CGSize size([scroller contentSize]); | |
404 | CGSize bounds([scroller bounds].size); | |
405 | ||
406 | CGPoint max; | |
407 | max.x = size.width - bounds.width; | |
408 | max.y = size.height - bounds.height; | |
409 | ||
410 | // wtf Apple?! | |
411 | if (max.x < 0) | |
412 | max.x = 0; | |
413 | if (max.y < 0) | |
414 | max.y = 0; | |
415 | ||
416 | offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x; | |
417 | offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y; | |
418 | ||
419 | [scroller setOffset:offset]; | |
420 | } | |
421 | ||
422 | @end | |
423 | /* }}} */ | |
424 | ||
425 | NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) { | |
426 | size_t length([self length] - state->state); | |
427 | if (length <= 0) | |
428 | return 0; | |
429 | else if (length > count) | |
430 | length = count; | |
431 | for (size_t i(0); i != length; ++i) | |
432 | objects[i] = [self item:state->state++]; | |
433 | state->itemsPtr = objects; | |
434 | state->mutationsPtr = (unsigned long *) self; | |
435 | return length; | |
436 | } | |
437 | ||
438 | /* Cydia NSString Additions {{{ */ | |
439 | @interface NSString (Cydia) | |
440 | - (NSComparisonResult) compareByPath:(NSString *)other; | |
441 | - (NSString *) stringByAddingPercentEscapesIncludingReserved; | |
442 | @end | |
443 | ||
444 | @implementation NSString (Cydia) | |
445 | ||
446 | - (NSComparisonResult) compareByPath:(NSString *)other { | |
447 | NSString *prefix = [self commonPrefixWithString:other options:0]; | |
448 | size_t length = [prefix length]; | |
449 | ||
450 | NSRange lrange = NSMakeRange(length, [self length] - length); | |
451 | NSRange rrange = NSMakeRange(length, [other length] - length); | |
452 | ||
453 | lrange = [self rangeOfString:@"/" options:0 range:lrange]; | |
454 | rrange = [other rangeOfString:@"/" options:0 range:rrange]; | |
455 | ||
456 | NSComparisonResult value; | |
457 | ||
458 | if (lrange.location == NSNotFound && rrange.location == NSNotFound) | |
459 | value = NSOrderedSame; | |
460 | else if (lrange.location == NSNotFound) | |
461 | value = NSOrderedAscending; | |
462 | else if (rrange.location == NSNotFound) | |
463 | value = NSOrderedDescending; | |
464 | else | |
465 | value = NSOrderedSame; | |
466 | ||
467 | NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] : | |
468 | [self substringWithRange:NSMakeRange(length, lrange.location - length)]; | |
469 | NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] : | |
470 | [other substringWithRange:NSMakeRange(length, rrange.location - length)]; | |
471 | ||
472 | NSComparisonResult result = [lpath compare:rpath]; | |
473 | return result == NSOrderedSame ? value : result; | |
474 | } | |
475 | ||
476 | - (NSString *) stringByAddingPercentEscapesIncludingReserved { | |
477 | return [(id)CFURLCreateStringByAddingPercentEscapes( | |
478 | kCFAllocatorDefault, | |
479 | (CFStringRef) self, | |
480 | NULL, | |
481 | CFSTR(";/?:@&=+$,"), | |
482 | kCFStringEncodingUTF8 | |
483 | ) autorelease]; | |
484 | } | |
485 | ||
486 | @end | |
487 | /* }}} */ | |
488 | ||
489 | /* C++ NSString Wrapper Cache {{{ */ | |
490 | static _finline CFStringRef CYStringCreate(const char *data, size_t size) { | |
491 | return size == 0 ? NULL : | |
492 | CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?: | |
493 | CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull); | |
494 | } | |
495 | ||
496 | static _finline CFStringRef CYStringCreate(const char *data) { | |
497 | return CYStringCreate(data, strlen(data)); | |
498 | } | |
499 | ||
500 | class CYString { | |
501 | private: | |
502 | char *data_; | |
503 | size_t size_; | |
504 | CFStringRef cache_; | |
505 | ||
506 | _finline void clear_() { | |
507 | if (cache_ != NULL) { | |
508 | CFRelease(cache_); | |
509 | cache_ = NULL; | |
510 | } | |
511 | } | |
512 | ||
513 | public: | |
514 | _finline bool empty() const { | |
515 | return size_ == 0; | |
516 | } | |
517 | ||
518 | _finline size_t size() const { | |
519 | return size_; | |
520 | } | |
521 | ||
522 | _finline char *data() const { | |
523 | return data_; | |
524 | } | |
525 | ||
526 | _finline void clear() { | |
527 | size_ = 0; | |
528 | clear_(); | |
529 | } | |
530 | ||
531 | _finline CYString() : | |
532 | data_(0), | |
533 | size_(0), | |
534 | cache_(NULL) | |
535 | { | |
536 | } | |
537 | ||
538 | _finline ~CYString() { | |
539 | clear_(); | |
540 | } | |
541 | ||
542 | void operator =(const CYString &rhs) { | |
543 | data_ = rhs.data_; | |
544 | size_ = rhs.size_; | |
545 | ||
546 | if (rhs.cache_ == nil) | |
547 | cache_ = NULL; | |
548 | else | |
549 | cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_)); | |
550 | } | |
551 | ||
552 | void copy(apr_pool_t *pool) { | |
553 | char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1))); | |
554 | memcpy(temp, data_, size_); | |
555 | temp[size_] = '\0'; | |
556 | data_ = temp; | |
557 | } | |
558 | ||
559 | void set(apr_pool_t *pool, const char *data, size_t size) { | |
560 | if (size == 0) | |
561 | clear(); | |
562 | else { | |
563 | clear_(); | |
564 | ||
565 | data_ = const_cast<char *>(data); | |
566 | size_ = size; | |
567 | ||
568 | if (pool != NULL) | |
569 | copy(pool); | |
570 | } | |
571 | } | |
572 | ||
573 | _finline void set(apr_pool_t *pool, const char *data) { | |
574 | set(pool, data, data == NULL ? 0 : strlen(data)); | |
575 | } | |
576 | ||
577 | _finline void set(apr_pool_t *pool, const std::string &rhs) { | |
578 | set(pool, rhs.data(), rhs.size()); | |
579 | } | |
580 | ||
581 | bool operator ==(const CYString &rhs) const { | |
582 | return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0; | |
583 | } | |
584 | ||
585 | _finline operator CFStringRef() { | |
586 | if (cache_ == NULL) | |
587 | cache_ = CYStringCreate(data_, size_); | |
588 | return cache_; | |
589 | } | |
590 | ||
591 | _finline operator id() { | |
592 | return (NSString *) static_cast<CFStringRef>(*this); | |
593 | } | |
594 | ||
595 | _finline operator const char *() { | |
596 | return reinterpret_cast<const char *>(data_); | |
597 | } | |
598 | }; | |
599 | /* }}} */ | |
600 | /* C++ NSString Algorithm Adapters {{{ */ | |
601 | extern "C" { | |
602 | CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str); | |
603 | } | |
604 | ||
605 | struct NSStringMapHash : | |
606 | std::unary_function<NSString *, size_t> | |
607 | { | |
608 | _finline size_t operator ()(NSString *value) const { | |
609 | return CFStringHashNSString((CFStringRef) value); | |
610 | } | |
611 | }; | |
612 | ||
613 | struct NSStringMapLess : | |
614 | std::binary_function<NSString *, NSString *, bool> | |
615 | { | |
616 | _finline bool operator ()(NSString *lhs, NSString *rhs) const { | |
617 | return [lhs compare:rhs] == NSOrderedAscending; | |
618 | } | |
619 | }; | |
620 | ||
621 | struct NSStringMapEqual : | |
622 | std::binary_function<NSString *, NSString *, bool> | |
623 | { | |
624 | _finline bool operator ()(NSString *lhs, NSString *rhs) const { | |
625 | return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo; | |
626 | //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs); | |
627 | //[lhs isEqualToString:rhs]; | |
628 | } | |
629 | }; | |
630 | /* }}} */ | |
631 | ||
632 | /* CoreGraphics Primitives {{{ */ | |
633 | class CYColor { | |
634 | private: | |
635 | CGColorRef color_; | |
636 | ||
637 | static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) { | |
638 | CGFloat color[] = {red, green, blue, alpha}; | |
639 | return CGColorCreate(space, color); | |
640 | } | |
641 | ||
642 | public: | |
643 | CYColor() : | |
644 | color_(NULL) | |
645 | { | |
646 | } | |
647 | ||
648 | CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) : | |
649 | color_(Create_(space, red, green, blue, alpha)) | |
650 | { | |
651 | Set(space, red, green, blue, alpha); | |
652 | } | |
653 | ||
654 | void Clear() { | |
655 | if (color_ != NULL) | |
656 | CGColorRelease(color_); | |
657 | } | |
658 | ||
659 | ~CYColor() { | |
660 | Clear(); | |
661 | } | |
662 | ||
663 | void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) { | |
664 | Clear(); | |
665 | color_ = Create_(space, red, green, blue, alpha); | |
666 | } | |
667 | ||
668 | operator CGColorRef() { | |
669 | return color_; | |
670 | } | |
671 | }; | |
672 | /* }}} */ | |
673 | ||
674 | /* Random Global Variables {{{ */ | |
675 | static int PulseInterval_ = 500000; | |
676 | ||
677 | static const NSString *UI_; | |
678 | ||
679 | static int Finish_; | |
680 | static bool RestartSubstrate_; | |
681 | static NSArray *Finishes_; | |
682 | ||
683 | #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist" | |
684 | #define NotifyConfig_ "/etc/notify.conf" | |
685 | ||
686 | static bool Queuing_; | |
687 | ||
688 | static CYColor Blue_; | |
689 | static CYColor Blueish_; | |
690 | static CYColor Black_; | |
691 | static CYColor Folder_; | |
692 | static CYColor Off_; | |
693 | static CYColor White_; | |
694 | static CYColor Gray_; | |
695 | static CYColor Green_; | |
696 | static CYColor Purple_; | |
697 | static CYColor Purplish_; | |
698 | ||
699 | static UIColor *InstallingColor_; | |
700 | static UIColor *RemovingColor_; | |
701 | ||
702 | static NSString *App_; | |
703 | ||
704 | static BOOL Advanced_; | |
705 | static BOOL Ignored_; | |
706 | ||
707 | static _H<UIFont> Font12_; | |
708 | static _H<UIFont> Font12Bold_; | |
709 | static _H<UIFont> Font14_; | |
710 | static _H<UIFont> Font18_; | |
711 | static _H<UIFont> Font18Bold_; | |
712 | static _H<UIFont> Font22Bold_; | |
713 | ||
714 | static const char *Machine_ = NULL; | |
715 | static _H<NSString> System_; | |
716 | static NSString *SerialNumber_ = nil; | |
717 | static NSString *ChipID_ = nil; | |
718 | static NSString *BBSNum_ = nil; | |
719 | static _H<NSString> Token_; | |
720 | static _H<NSString> UniqueID_; | |
721 | static _H<NSString> UserAgent_; | |
722 | static _H<NSString> Product_; | |
723 | static _H<NSString> Safari_; | |
724 | ||
725 | static _H<NSLocale> CollationLocale_; | |
726 | static _H<NSArray> CollationThumbs_; | |
727 | static std::vector<NSInteger> CollationOffset_; | |
728 | static _H<NSArray> CollationTitles_; | |
729 | static _H<NSArray> CollationStarts_; | |
730 | static UTransliterator *CollationTransl_; | |
731 | //static Function<NSString *, NSString *> CollationModify_; | |
732 | ||
733 | typedef std::basic_string<UChar> ustring; | |
734 | static ustring CollationString_; | |
735 | ||
736 | #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep)) | |
737 | #define UC ustring &str(*reinterpret_cast<ustring *>(rep)) | |
738 | static struct UReplaceableCallbacks CollationUCalls_ = { | |
739 | .length = [](const UReplaceable *rep) -> int32_t { CUC; | |
740 | return str.size(); | |
741 | }, | |
742 | ||
743 | .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC; | |
744 | //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size()); | |
745 | if (offset >= str.size()) | |
746 | return 0xffff; | |
747 | return str[offset]; | |
748 | }, | |
749 | ||
750 | .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC; | |
751 | //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size()); | |
752 | if (offset >= str.size()) | |
753 | return 0xffff; | |
754 | UChar32 c; | |
755 | U16_GET(str.data(), 0, offset, str.size(), c); | |
756 | return c; | |
757 | }, | |
758 | ||
759 | .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC; | |
760 | //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size()); | |
761 | str.replace(start, limit - start, text, length); | |
762 | }, | |
763 | ||
764 | .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC; | |
765 | //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size()); | |
766 | str.copy(dst, limit - start, start); | |
767 | }, | |
768 | ||
769 | .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC; | |
770 | //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size()); | |
771 | str.replace(dest, 0, str, start, limit - start); | |
772 | }, | |
773 | }; | |
774 | ||
775 | static CFLocaleRef Locale_; | |
776 | static NSArray *Languages_; | |
777 | static CGColorSpaceRef space_; | |
778 | ||
779 | static NSDictionary *SectionMap_; | |
780 | static NSMutableDictionary *Metadata_; | |
781 | static _transient NSMutableDictionary *Settings_; | |
782 | static _transient NSMutableDictionary *Packages_; | |
783 | static _transient NSMutableDictionary *Values_; | |
784 | static _transient NSMutableDictionary *Sections_; | |
785 | _H<NSMutableDictionary> Sources_; | |
786 | static _transient NSNumber *Version_; | |
787 | bool Changed_; | |
788 | static time_t now_; | |
789 | ||
790 | bool IsWildcat_; | |
791 | static CGFloat ScreenScale_; | |
792 | static NSString *Idiom_; | |
793 | static _H<NSString> Firmware_; | |
794 | static NSString *Major_; | |
795 | ||
796 | static _H<NSMutableDictionary> SessionData_; | |
797 | static _H<NSObject> HostConfig_; | |
798 | static _H<NSMutableSet> BridgedHosts_; | |
799 | static _H<NSMutableSet> TokenHosts_; | |
800 | static _H<NSMutableSet> InsecureHosts_; | |
801 | static _H<NSMutableSet> PipelinedHosts_; | |
802 | static _H<NSMutableSet> CachedURLs_; | |
803 | ||
804 | static NSString *kCydiaProgressEventTypeError = @"Error"; | |
805 | static NSString *kCydiaProgressEventTypeInformation = @"Information"; | |
806 | static NSString *kCydiaProgressEventTypeStatus = @"Status"; | |
807 | static NSString *kCydiaProgressEventTypeWarning = @"Warning"; | |
808 | /* }}} */ | |
809 | ||
810 | /* Display Helpers {{{ */ | |
811 | inline float Interpolate(float begin, float end, float fraction) { | |
812 | return (end - begin) * fraction + begin; | |
813 | } | |
814 | ||
815 | static _finline const char *StripVersion_(const char *version) { | |
816 | const char *colon(strchr(version, ':')); | |
817 | return colon == NULL ? version : colon + 1; | |
818 | } | |
819 | ||
820 | NSString *LocalizeSection(NSString *section) { | |
821 | static Pcre title_r("^(.*?) \\((.*)\\)$"); | |
822 | if (title_r(section)) { | |
823 | NSString *parent(title_r[1]); | |
824 | NSString *child(title_r[2]); | |
825 | ||
826 | return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), | |
827 | LocalizeSection(parent), | |
828 | LocalizeSection(child) | |
829 | ]; | |
830 | } | |
831 | ||
832 | return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"]; | |
833 | } | |
834 | ||
835 | NSString *Simplify(NSString *title) { | |
836 | const char *data = [title UTF8String]; | |
837 | size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; | |
838 | ||
839 | static Pcre square_r("^\\[(.*)\\]$"); | |
840 | if (square_r(data, size)) | |
841 | return Simplify(square_r[1]); | |
842 | ||
843 | static Pcre paren_r("^\\((.*)\\)$"); | |
844 | if (paren_r(data, size)) | |
845 | return Simplify(paren_r[1]); | |
846 | ||
847 | static Pcre title_r("^(.*?) \\((.*)\\)$"); | |
848 | if (title_r(data, size)) | |
849 | return Simplify(title_r[1]); | |
850 | ||
851 | return title; | |
852 | } | |
853 | /* }}} */ | |
854 | ||
855 | NSString *GetLastUpdate() { | |
856 | NSDate *update = [Metadata_ objectForKey:@"LastUpdate"]; | |
857 | ||
858 | if (update == nil) | |
859 | return UCLocalize("NEVER_OR_UNKNOWN"); | |
860 | ||
861 | CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle); | |
862 | CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update); | |
863 | ||
864 | CFRelease(formatter); | |
865 | ||
866 | return [(NSString *) formatted autorelease]; | |
867 | } | |
868 | ||
869 | bool isSectionVisible(NSString *section) { | |
870 | NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]); | |
871 | NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]); | |
872 | return hidden == nil || ![hidden boolValue]; | |
873 | } | |
874 | ||
875 | static NSObject *CYIOGetValue(const char *path, NSString *property) { | |
876 | io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path)); | |
877 | if (entry == MACH_PORT_NULL) | |
878 | return nil; | |
879 | ||
880 | CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0)); | |
881 | IOObjectRelease(entry); | |
882 | ||
883 | if (value == NULL) | |
884 | return nil; | |
885 | return [(id) value autorelease]; | |
886 | } | |
887 | ||
888 | static NSString *CYHex(NSData *data, bool reverse = false) { | |
889 | if (data == nil) | |
890 | return nil; | |
891 | ||
892 | size_t length([data length]); | |
893 | uint8_t bytes[length]; | |
894 | [data getBytes:bytes]; | |
895 | ||
896 | char string[length * 2 + 1]; | |
897 | for (size_t i(0); i != length; ++i) | |
898 | sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]); | |
899 | ||
900 | return [NSString stringWithUTF8String:string]; | |
901 | } | |
902 | ||
903 | @class Cydia; | |
904 | ||
905 | /* Delegate Prototypes {{{ */ | |
906 | @class Package; | |
907 | @class Source; | |
908 | @class CydiaProgressEvent; | |
909 | ||
910 | @protocol DatabaseDelegate | |
911 | - (void) repairWithSelector:(SEL)selector; | |
912 | - (void) setConfigurationData:(NSString *)data; | |
913 | - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task; | |
914 | @end | |
915 | ||
916 | @class CYPackageController; | |
917 | ||
918 | @protocol SourceDelegate | |
919 | - (void) setFetch:(NSNumber *)fetch; | |
920 | @end | |
921 | ||
922 | @protocol FetchDelegate | |
923 | - (bool) isSourceCancelled; | |
924 | - (void) startSourceFetch:(NSString *)uri; | |
925 | - (void) stopSourceFetch:(NSString *)uri; | |
926 | @end | |
927 | ||
928 | @protocol CydiaDelegate | |
929 | - (void) returnToCydia; | |
930 | - (void) saveState; | |
931 | - (void) retainNetworkActivityIndicator; | |
932 | - (void) releaseNetworkActivityIndicator; | |
933 | - (void) clearPackage:(Package *)package; | |
934 | - (void) installPackage:(Package *)package; | |
935 | - (void) installPackages:(NSArray *)packages; | |
936 | - (void) removePackage:(Package *)package; | |
937 | - (void) beginUpdate; | |
938 | - (BOOL) updating; | |
939 | - (bool) requestUpdate; | |
940 | - (void) distUpgrade; | |
941 | - (void) loadData; | |
942 | - (void) updateData; | |
943 | - (void) _saveConfig; | |
944 | - (void) syncData; | |
945 | - (void) addSource:(NSDictionary *)source; | |
946 | - (void) addTrivialSource:(NSString *)href; | |
947 | - (UIProgressHUD *) addProgressHUD; | |
948 | - (void) removeProgressHUD:(UIProgressHUD *)hud; | |
949 | - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item; | |
950 | - (void) reloadDataWithInvocation:(NSInvocation *)invocation; | |
951 | @end | |
952 | /* }}} */ | |
953 | ||
954 | /* CancelStatus {{{ */ | |
955 | class CancelStatus : | |
956 | public pkgAcquireStatus | |
957 | { | |
958 | private: | |
959 | bool cancelled_; | |
960 | ||
961 | public: | |
962 | CancelStatus() : | |
963 | cancelled_(false) | |
964 | { | |
965 | } | |
966 | ||
967 | virtual bool MediaChange(std::string media, std::string drive) { | |
968 | return false; | |
969 | } | |
970 | ||
971 | virtual void IMSHit(pkgAcquire::ItemDesc &item) { | |
972 | Done(item); | |
973 | } | |
974 | ||
975 | virtual bool Pulse_(pkgAcquire *Owner) = 0; | |
976 | ||
977 | virtual bool Pulse(pkgAcquire *Owner) { | |
978 | if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner)) | |
979 | return true; | |
980 | else { | |
981 | cancelled_ = true; | |
982 | return false; | |
983 | } | |
984 | } | |
985 | ||
986 | _finline bool WasCancelled() const { | |
987 | return cancelled_; | |
988 | } | |
989 | }; | |
990 | /* }}} */ | |
991 | /* DelegateStatus {{{ */ | |
992 | class CydiaStatus : | |
993 | public CancelStatus | |
994 | { | |
995 | private: | |
996 | _transient NSObject<ProgressDelegate> *delegate_; | |
997 | ||
998 | public: | |
999 | CydiaStatus() : | |
1000 | delegate_(nil) | |
1001 | { | |
1002 | } | |
1003 | ||
1004 | void setDelegate(NSObject<ProgressDelegate> *delegate) { | |
1005 | delegate_ = delegate; | |
1006 | } | |
1007 | ||
1008 | virtual void Fetch(pkgAcquire::ItemDesc &item) { | |
1009 | NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]); | |
1010 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]); | |
1011 | [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
1012 | } | |
1013 | ||
1014 | virtual void Done(pkgAcquire::ItemDesc &item) { | |
1015 | NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]); | |
1016 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]); | |
1017 | [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
1018 | } | |
1019 | ||
1020 | virtual void Fail(pkgAcquire::ItemDesc &item) { | |
1021 | if ( | |
1022 | item.Owner->Status == pkgAcquire::Item::StatIdle || | |
1023 | item.Owner->Status == pkgAcquire::Item::StatDone | |
1024 | ) | |
1025 | return; | |
1026 | ||
1027 | std::string &error(item.Owner->ErrorText); | |
1028 | if (error.empty()) | |
1029 | return; | |
1030 | ||
1031 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]); | |
1032 | [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
1033 | } | |
1034 | ||
1035 | virtual bool Pulse_(pkgAcquire *Owner) { | |
1036 | double percent( | |
1037 | double(CurrentBytes + CurrentItems) / | |
1038 | double(TotalBytes + TotalItems) | |
1039 | ); | |
1040 | ||
1041 | [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys: | |
1042 | [NSNumber numberWithDouble:percent], @"Percent", | |
1043 | ||
1044 | [NSNumber numberWithDouble:CurrentBytes], @"Current", | |
1045 | [NSNumber numberWithDouble:TotalBytes], @"Total", | |
1046 | [NSNumber numberWithDouble:CurrentCPS], @"Speed", | |
1047 | nil] waitUntilDone:YES]; | |
1048 | ||
1049 | return ![delegate_ isProgressCancelled]; | |
1050 | } | |
1051 | ||
1052 | virtual void Start() { | |
1053 | pkgAcquireStatus::Start(); | |
1054 | [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES]; | |
1055 | } | |
1056 | ||
1057 | virtual void Stop() { | |
1058 | pkgAcquireStatus::Stop(); | |
1059 | [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES]; | |
1060 | [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES]; | |
1061 | } | |
1062 | }; | |
1063 | /* }}} */ | |
1064 | /* Database Interface {{{ */ | |
1065 | typedef std::map< unsigned long, _H<Source> > SourceMap; | |
1066 | ||
1067 | @interface Database : NSObject { | |
1068 | NSZone *zone_; | |
1069 | apr_pool_t *pool_; | |
1070 | ||
1071 | unsigned era_; | |
1072 | ||
1073 | pkgCacheFile cache_; | |
1074 | pkgDepCache::Policy *policy_; | |
1075 | pkgRecords *records_; | |
1076 | pkgProblemResolver *resolver_; | |
1077 | pkgAcquire *fetcher_; | |
1078 | FileFd *lock_; | |
1079 | SPtr<pkgPackageManager> manager_; | |
1080 | pkgSourceList *list_; | |
1081 | ||
1082 | SourceMap sourceMap_; | |
1083 | _H<NSMutableArray> sourceList_; | |
1084 | ||
1085 | CFMutableArrayRef packages_; | |
1086 | ||
1087 | _transient NSObject<DatabaseDelegate> *delegate_; | |
1088 | _transient NSObject<ProgressDelegate> *progress_; | |
1089 | ||
1090 | CydiaStatus status_; | |
1091 | ||
1092 | int cydiafd_; | |
1093 | int statusfd_; | |
1094 | FILE *input_; | |
1095 | ||
1096 | std::map<const char *, _H<NSString> > sections_; | |
1097 | } | |
1098 | ||
1099 | + (Database *) sharedInstance; | |
1100 | - (unsigned) era; | |
1101 | ||
1102 | - (void) _readCydia:(NSNumber *)fd; | |
1103 | - (void) _readStatus:(NSNumber *)fd; | |
1104 | - (void) _readOutput:(NSNumber *)fd; | |
1105 | ||
1106 | - (FILE *) input; | |
1107 | ||
1108 | - (Package *) packageWithName:(NSString *)name; | |
1109 | ||
1110 | - (pkgCacheFile &) cache; | |
1111 | - (pkgDepCache::Policy *) policy; | |
1112 | - (pkgRecords *) records; | |
1113 | - (pkgProblemResolver *) resolver; | |
1114 | - (pkgAcquire &) fetcher; | |
1115 | - (pkgSourceList &) list; | |
1116 | - (NSArray *) packages; | |
1117 | - (NSArray *) sources; | |
1118 | - (Source *) sourceWithKey:(NSString *)key; | |
1119 | - (void) reloadDataWithInvocation:(NSInvocation *)invocation; | |
1120 | ||
1121 | - (void) configure; | |
1122 | - (bool) prepare; | |
1123 | - (void) perform; | |
1124 | - (bool) upgrade; | |
1125 | - (void) update; | |
1126 | ||
1127 | - (void) updateWithStatus:(CancelStatus &)status; | |
1128 | ||
1129 | - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate; | |
1130 | ||
1131 | - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate; | |
1132 | - (NSObject<ProgressDelegate> *) progressDelegate; | |
1133 | ||
1134 | - (Source *) getSource:(pkgCache::PkgFileIterator)file; | |
1135 | - (void) setFetch:(bool)fetch forURI:(const char *)uri; | |
1136 | - (void) resetFetch; | |
1137 | ||
1138 | - (NSString *) mappedSectionForPointer:(const char *)pointer; | |
1139 | ||
1140 | @end | |
1141 | /* }}} */ | |
1142 | /* SourceStatus {{{ */ | |
1143 | class SourceStatus : | |
1144 | public CancelStatus | |
1145 | { | |
1146 | private: | |
1147 | _transient NSObject<FetchDelegate> *delegate_; | |
1148 | _transient Database *database_; | |
1149 | ||
1150 | public: | |
1151 | SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) : | |
1152 | delegate_(delegate), | |
1153 | database_(database) | |
1154 | { | |
1155 | } | |
1156 | ||
1157 | void Set(bool fetch, pkgAcquire::ItemDesc &desc) { | |
1158 | desc.Owner->ID = 0; | |
1159 | [database_ setFetch:fetch forURI:desc.Owner->DescURI().c_str()]; | |
1160 | } | |
1161 | ||
1162 | virtual void Fetch(pkgAcquire::ItemDesc &desc) { | |
1163 | Set(true, desc); | |
1164 | } | |
1165 | ||
1166 | virtual void Done(pkgAcquire::ItemDesc &desc) { | |
1167 | Set(false, desc); | |
1168 | } | |
1169 | ||
1170 | virtual void Fail(pkgAcquire::ItemDesc &desc) { | |
1171 | Set(false, desc); | |
1172 | } | |
1173 | ||
1174 | virtual bool Pulse_(pkgAcquire *Owner) { | |
1175 | for (pkgAcquire::ItemCIterator item = Owner->ItemsBegin(); item != Owner->ItemsEnd(); ++item) | |
1176 | if ((*item)->ID != 0); | |
1177 | else if ((*item)->Status == pkgAcquire::Item::StatIdle) { | |
1178 | (*item)->ID = 1; | |
1179 | [database_ setFetch:true forURI:(*item)->DescURI().c_str()]; | |
1180 | } else (*item)->ID = 0; | |
1181 | return ![delegate_ isSourceCancelled]; | |
1182 | } | |
1183 | ||
1184 | virtual void Stop() { | |
1185 | pkgAcquireStatus::Stop(); | |
1186 | [database_ resetFetch]; | |
1187 | } | |
1188 | }; | |
1189 | /* }}} */ | |
1190 | /* ProgressEvent Implementation {{{ */ | |
1191 | @implementation CydiaProgressEvent | |
1192 | ||
1193 | + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type { | |
1194 | return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease]; | |
1195 | } | |
1196 | ||
1197 | + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package { | |
1198 | CydiaProgressEvent *event([self eventWithMessage:message ofType:type]); | |
1199 | [event setPackage:package]; | |
1200 | return event; | |
1201 | } | |
1202 | ||
1203 | + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item { | |
1204 | CydiaProgressEvent *event([self eventWithMessage:message ofType:type]); | |
1205 | ||
1206 | NSString *description([NSString stringWithUTF8String:item.Description.c_str()]); | |
1207 | NSArray *fields([description componentsSeparatedByString:@" "]); | |
1208 | [event setItem:fields]; | |
1209 | ||
1210 | if ([fields count] > 3) { | |
1211 | [event setPackage:[fields objectAtIndex:2]]; | |
1212 | [event setVersion:[fields objectAtIndex:3]]; | |
1213 | } | |
1214 | ||
1215 | [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]]; | |
1216 | ||
1217 | return event; | |
1218 | } | |
1219 | ||
1220 | + (NSArray *) _attributeKeys { | |
1221 | return [NSArray arrayWithObjects: | |
1222 | @"item", | |
1223 | @"message", | |
1224 | @"package", | |
1225 | @"type", | |
1226 | @"url", | |
1227 | @"version", | |
1228 | nil]; | |
1229 | } | |
1230 | ||
1231 | - (NSArray *) attributeKeys { | |
1232 | return [[self class] _attributeKeys]; | |
1233 | } | |
1234 | ||
1235 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
1236 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
1237 | } | |
1238 | ||
1239 | - (id) initWithMessage:(NSString *)message ofType:(NSString *)type { | |
1240 | if ((self = [super init]) != nil) { | |
1241 | message_ = message; | |
1242 | type_ = type; | |
1243 | } return self; | |
1244 | } | |
1245 | ||
1246 | - (NSString *) message { | |
1247 | return message_; | |
1248 | } | |
1249 | ||
1250 | - (NSString *) type { | |
1251 | return type_; | |
1252 | } | |
1253 | ||
1254 | - (NSArray *) item { | |
1255 | return (id) item_ ?: [NSNull null]; | |
1256 | } | |
1257 | ||
1258 | - (void) setItem:(NSArray *)item { | |
1259 | item_ = item; | |
1260 | } | |
1261 | ||
1262 | - (NSString *) package { | |
1263 | return (id) package_ ?: [NSNull null]; | |
1264 | } | |
1265 | ||
1266 | - (void) setPackage:(NSString *)package { | |
1267 | package_ = package; | |
1268 | } | |
1269 | ||
1270 | - (NSString *) url { | |
1271 | return (id) url_ ?: [NSNull null]; | |
1272 | } | |
1273 | ||
1274 | - (void) setURL:(NSString *)url { | |
1275 | url_ = url; | |
1276 | } | |
1277 | ||
1278 | - (void) setVersion:(NSString *)version { | |
1279 | version_ = version; | |
1280 | } | |
1281 | ||
1282 | - (NSString *) version { | |
1283 | return (id) version_ ?: [NSNull null]; | |
1284 | } | |
1285 | ||
1286 | - (NSString *) compound:(NSString *)value { | |
1287 | if (value != nil) { | |
1288 | NSString *mode(nil); { | |
1289 | NSString *type([self type]); | |
1290 | if ([type isEqualToString:kCydiaProgressEventTypeError]) | |
1291 | mode = UCLocalize("ERROR"); | |
1292 | else if ([type isEqualToString:kCydiaProgressEventTypeWarning]) | |
1293 | mode = UCLocalize("WARNING"); | |
1294 | } | |
1295 | ||
1296 | if (mode != nil) | |
1297 | value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value]; | |
1298 | } | |
1299 | ||
1300 | return value; | |
1301 | } | |
1302 | ||
1303 | - (NSString *) compoundMessage { | |
1304 | return [self compound:[self message]]; | |
1305 | } | |
1306 | ||
1307 | - (NSString *) compoundTitle { | |
1308 | NSString *title; | |
1309 | ||
1310 | if (package_ == nil) | |
1311 | title = nil; | |
1312 | else if (Package *package = [[Database sharedInstance] packageWithName:package_]) | |
1313 | title = [package name]; | |
1314 | else | |
1315 | title = package_; | |
1316 | ||
1317 | return [self compound:title]; | |
1318 | } | |
1319 | ||
1320 | @end | |
1321 | /* }}} */ | |
1322 | ||
1323 | // Cytore Definitions {{{ | |
1324 | struct PackageValue : | |
1325 | Cytore::Block | |
1326 | { | |
1327 | Cytore::Offset<PackageValue> next_; | |
1328 | ||
1329 | uint32_t index_ : 23; | |
1330 | uint32_t subscribed_ : 1; | |
1331 | uint32_t : 8; | |
1332 | ||
1333 | int32_t first_; | |
1334 | int32_t last_; | |
1335 | ||
1336 | uint16_t vhash_; | |
1337 | uint16_t nhash_; | |
1338 | ||
1339 | char version_[8]; | |
1340 | char name_[]; | |
1341 | }; | |
1342 | ||
1343 | struct MetaValue : | |
1344 | Cytore::Block | |
1345 | { | |
1346 | uint32_t active_; | |
1347 | Cytore::Offset<PackageValue> packages_[1 << 16]; | |
1348 | }; | |
1349 | ||
1350 | static Cytore::File<MetaValue> MetaFile_; | |
1351 | // }}} | |
1352 | // Cytore Helper Functions {{{ | |
1353 | static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) { | |
1354 | SplitHash nhash = { hashlittle(name, length) }; | |
1355 | ||
1356 | PackageValue *metadata; | |
1357 | ||
1358 | Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]); | |
1359 | for (;; offset = &metadata->next_) { if (offset->IsNull()) { | |
1360 | *offset = MetaFile_.New<PackageValue>(length + 1); | |
1361 | metadata = &MetaFile_.Get(*offset); | |
1362 | ||
1363 | if (metadata == NULL) { | |
1364 | if (fail != NULL) | |
1365 | *fail = true; | |
1366 | ||
1367 | metadata = new PackageValue(); | |
1368 | memset(metadata, 0, sizeof(*metadata)); | |
1369 | } | |
1370 | ||
1371 | memcpy(metadata->name_, name, length); | |
1372 | metadata->name_[length] = '\0'; | |
1373 | metadata->nhash_ = nhash.u16[1]; | |
1374 | } else { | |
1375 | metadata = &MetaFile_.Get(*offset); | |
1376 | if (metadata->nhash_ != nhash.u16[1]) | |
1377 | continue; | |
1378 | if (strncmp(metadata->name_, name, length) != 0) | |
1379 | continue; | |
1380 | if (metadata->name_[length] != '\0') | |
1381 | continue; | |
1382 | } break; } | |
1383 | ||
1384 | return metadata; | |
1385 | } | |
1386 | ||
1387 | static void PackageImport(const void *key, const void *value, void *context) { | |
1388 | bool &fail(*reinterpret_cast<bool *>(context)); | |
1389 | ||
1390 | char buffer[1024]; | |
1391 | if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) { | |
1392 | NSLog(@"failed to import package %@", key); | |
1393 | return; | |
1394 | } | |
1395 | ||
1396 | PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail)); | |
1397 | NSDictionary *package((NSDictionary *) value); | |
1398 | ||
1399 | if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"]) | |
1400 | if ([subscribed boolValue] && !metadata->subscribed_) | |
1401 | metadata->subscribed_ = true; | |
1402 | ||
1403 | if (NSDate *date = [package objectForKey:@"FirstSeen"]) { | |
1404 | time_t time([date timeIntervalSince1970]); | |
1405 | if (metadata->first_ > time || metadata->first_ == 0) | |
1406 | metadata->first_ = time; | |
1407 | } | |
1408 | ||
1409 | NSDate *date([package objectForKey:@"LastSeen"]); | |
1410 | NSString *version([package objectForKey:@"LastVersion"]); | |
1411 | ||
1412 | if (date != nil && version != nil) { | |
1413 | time_t time([date timeIntervalSince1970]); | |
1414 | if (metadata->last_ < time || metadata->last_ == 0) | |
1415 | if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) { | |
1416 | size_t length(strlen(buffer)); | |
1417 | uint16_t vhash(hashlittle(buffer, length)); | |
1418 | ||
1419 | size_t capped(std::min<size_t>(8, length)); | |
1420 | char *latest(buffer + length - capped); | |
1421 | ||
1422 | strncpy(metadata->version_, latest, sizeof(metadata->version_)); | |
1423 | metadata->vhash_ = vhash; | |
1424 | ||
1425 | metadata->last_ = time; | |
1426 | } | |
1427 | } | |
1428 | } | |
1429 | // }}} | |
1430 | ||
1431 | /* Source Class {{{ */ | |
1432 | @interface Source : NSObject { | |
1433 | unsigned era_; | |
1434 | Database *database_; | |
1435 | metaIndex *index_; | |
1436 | ||
1437 | CYString depiction_; | |
1438 | CYString description_; | |
1439 | CYString label_; | |
1440 | CYString origin_; | |
1441 | CYString support_; | |
1442 | ||
1443 | CYString uri_; | |
1444 | CYString distribution_; | |
1445 | CYString type_; | |
1446 | CYString base_; | |
1447 | CYString version_; | |
1448 | ||
1449 | _H<NSString> host_; | |
1450 | _H<NSString> authority_; | |
1451 | ||
1452 | CYString defaultIcon_; | |
1453 | ||
1454 | _H<NSMutableDictionary> record_; | |
1455 | BOOL trusted_; | |
1456 | ||
1457 | std::set<std::string> fetches_; | |
1458 | std::set<std::string> files_; | |
1459 | _transient NSObject<SourceDelegate> *delegate_; | |
1460 | } | |
1461 | ||
1462 | - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool; | |
1463 | ||
1464 | - (NSComparisonResult) compareByName:(Source *)source; | |
1465 | ||
1466 | - (NSString *) depictionForPackage:(NSString *)package; | |
1467 | - (NSString *) supportForPackage:(NSString *)package; | |
1468 | ||
1469 | - (metaIndex *) metaIndex; | |
1470 | - (NSDictionary *) record; | |
1471 | - (BOOL) trusted; | |
1472 | ||
1473 | - (NSString *) rooturi; | |
1474 | - (NSString *) distribution; | |
1475 | - (NSString *) type; | |
1476 | ||
1477 | - (NSString *) key; | |
1478 | - (NSString *) host; | |
1479 | ||
1480 | - (NSString *) name; | |
1481 | - (NSString *) shortDescription; | |
1482 | - (NSString *) label; | |
1483 | - (NSString *) origin; | |
1484 | - (NSString *) version; | |
1485 | ||
1486 | - (NSString *) defaultIcon; | |
1487 | - (NSURL *) iconURL; | |
1488 | ||
1489 | - (void) setFetch:(bool)fetch forURI:(const char *)uri; | |
1490 | - (void) resetFetch; | |
1491 | ||
1492 | @end | |
1493 | ||
1494 | @implementation Source | |
1495 | ||
1496 | + (NSString *) webScriptNameForSelector:(SEL)selector { | |
1497 | if (false); | |
1498 | else if (selector == @selector(addSection:)) | |
1499 | return @"addSection"; | |
1500 | else if (selector == @selector(getField:)) | |
1501 | return @"getField"; | |
1502 | else if (selector == @selector(removeSection:)) | |
1503 | return @"removeSection"; | |
1504 | else if (selector == @selector(remove)) | |
1505 | return @"remove"; | |
1506 | else | |
1507 | return nil; | |
1508 | } | |
1509 | ||
1510 | + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector { | |
1511 | return [self webScriptNameForSelector:selector] == nil; | |
1512 | } | |
1513 | ||
1514 | + (NSArray *) _attributeKeys { | |
1515 | return [NSArray arrayWithObjects: | |
1516 | @"baseuri", | |
1517 | @"distribution", | |
1518 | @"host", | |
1519 | @"key", | |
1520 | @"iconuri", | |
1521 | @"label", | |
1522 | @"name", | |
1523 | @"origin", | |
1524 | @"rooturi", | |
1525 | @"sections", | |
1526 | @"shortDescription", | |
1527 | @"trusted", | |
1528 | @"type", | |
1529 | @"version", | |
1530 | nil]; | |
1531 | } | |
1532 | ||
1533 | - (NSArray *) attributeKeys { | |
1534 | return [[self class] _attributeKeys]; | |
1535 | } | |
1536 | ||
1537 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
1538 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
1539 | } | |
1540 | ||
1541 | - (metaIndex *) metaIndex { | |
1542 | return index_; | |
1543 | } | |
1544 | ||
1545 | - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool { | |
1546 | trusted_ = index->IsTrusted(); | |
1547 | ||
1548 | uri_.set(pool, index->GetURI()); | |
1549 | distribution_.set(pool, index->GetDist()); | |
1550 | type_.set(pool, index->GetType()); | |
1551 | ||
1552 | debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index)); | |
1553 | if (dindex != NULL) { | |
1554 | std::string file(dindex->MetaIndexURI("")); | |
1555 | base_.set(pool, file); | |
1556 | ||
1557 | pkgAcquire acquire; | |
1558 | _profile(Source$setMetaIndex$GetIndexes) | |
1559 | dindex->GetIndexes(&acquire, true); | |
1560 | _end | |
1561 | _profile(Source$setMetaIndex$DescURI) | |
1562 | for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) { | |
1563 | std::string file((*item)->DescURI()); | |
1564 | files_.insert(file); | |
1565 | if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2") | |
1566 | continue; | |
1567 | file = file.substr(0, file.length() - 4); | |
1568 | files_.insert(file); | |
1569 | files_.insert(file + ".gz"); | |
1570 | files_.insert(file + "Index"); | |
1571 | } | |
1572 | _end | |
1573 | ||
1574 | FileFd fd; | |
1575 | if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) | |
1576 | _error->Discard(); | |
1577 | else { | |
1578 | pkgTagFile tags(&fd); | |
1579 | ||
1580 | pkgTagSection section; | |
1581 | tags.Step(section); | |
1582 | ||
1583 | struct { | |
1584 | const char *name_; | |
1585 | CYString *value_; | |
1586 | } names[] = { | |
1587 | {"default-icon", &defaultIcon_}, | |
1588 | {"depiction", &depiction_}, | |
1589 | {"description", &description_}, | |
1590 | {"label", &label_}, | |
1591 | {"origin", &origin_}, | |
1592 | {"support", &support_}, | |
1593 | {"version", &version_}, | |
1594 | }; | |
1595 | ||
1596 | for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) { | |
1597 | const char *start, *end; | |
1598 | ||
1599 | if (section.Find(names[i].name_, start, end)) { | |
1600 | CYString &value(*names[i].value_); | |
1601 | value.set(pool, start, end - start); | |
1602 | } | |
1603 | } | |
1604 | } | |
1605 | } | |
1606 | ||
1607 | record_ = [Sources_ objectForKey:[self key]]; | |
1608 | ||
1609 | NSURL *url([NSURL URLWithString:uri_]); | |
1610 | ||
1611 | host_ = [url host]; | |
1612 | if (host_ != nil) | |
1613 | host_ = [host_ lowercaseString]; | |
1614 | ||
1615 | if (host_ != nil) | |
1616 | authority_ = host_; | |
1617 | else | |
1618 | authority_ = [url path]; | |
1619 | } | |
1620 | ||
1621 | - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool { | |
1622 | if ((self = [super init]) != nil) { | |
1623 | era_ = [database era]; | |
1624 | database_ = database; | |
1625 | index_ = index; | |
1626 | ||
1627 | _profile(Source$initWithMetaIndex$setMetaIndex) | |
1628 | [self setMetaIndex:index inPool:pool]; | |
1629 | _end | |
1630 | } return self; | |
1631 | } | |
1632 | ||
1633 | - (NSString *) getField:(NSString *)name { | |
1634 | @synchronized (database_) { | |
1635 | if ([database_ era] != era_ || index_ == NULL) | |
1636 | return nil; | |
1637 | ||
1638 | debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_)); | |
1639 | if (dindex == NULL) | |
1640 | return nil; | |
1641 | ||
1642 | FileFd fd; | |
1643 | if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) { | |
1644 | _error->Discard(); | |
1645 | return nil; | |
1646 | } | |
1647 | ||
1648 | pkgTagFile tags(&fd); | |
1649 | ||
1650 | pkgTagSection section; | |
1651 | tags.Step(section); | |
1652 | ||
1653 | const char *start, *end; | |
1654 | if (!section.Find([name UTF8String], start, end)) | |
1655 | return (NSString *) [NSNull null]; | |
1656 | ||
1657 | return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]]; | |
1658 | } } | |
1659 | ||
1660 | - (NSComparisonResult) compareByName:(Source *)source { | |
1661 | NSString *lhs = [self name]; | |
1662 | NSString *rhs = [source name]; | |
1663 | ||
1664 | if ([lhs length] != 0 && [rhs length] != 0) { | |
1665 | unichar lhc = [lhs characterAtIndex:0]; | |
1666 | unichar rhc = [rhs characterAtIndex:0]; | |
1667 | ||
1668 | if (isalpha(lhc) && !isalpha(rhc)) | |
1669 | return NSOrderedAscending; | |
1670 | else if (!isalpha(lhc) && isalpha(rhc)) | |
1671 | return NSOrderedDescending; | |
1672 | } | |
1673 | ||
1674 | return [lhs compare:rhs options:LaxCompareOptions_]; | |
1675 | } | |
1676 | ||
1677 | - (NSString *) depictionForPackage:(NSString *)package { | |
1678 | return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package]; | |
1679 | } | |
1680 | ||
1681 | - (NSString *) supportForPackage:(NSString *)package { | |
1682 | return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package]; | |
1683 | } | |
1684 | ||
1685 | - (NSArray *) sections { | |
1686 | return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array]; | |
1687 | } | |
1688 | ||
1689 | - (void) _addSection:(NSString *)section { | |
1690 | if (record_ == nil) | |
1691 | return; | |
1692 | else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) { | |
1693 | if (![sections containsObject:section]) { | |
1694 | [sections addObject:section]; | |
1695 | Changed_ = true; | |
1696 | } | |
1697 | } else { | |
1698 | [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"]; | |
1699 | Changed_ = true; | |
1700 | } | |
1701 | } | |
1702 | ||
1703 | - (bool) addSection:(NSString *)section { | |
1704 | if (record_ == nil) | |
1705 | return false; | |
1706 | ||
1707 | [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO]; | |
1708 | return true; | |
1709 | } | |
1710 | ||
1711 | - (void) _removeSection:(NSString *)section { | |
1712 | if (record_ == nil) | |
1713 | return; | |
1714 | ||
1715 | if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) | |
1716 | if ([sections containsObject:section]) { | |
1717 | [sections removeObject:section]; | |
1718 | Changed_ = true; | |
1719 | } | |
1720 | } | |
1721 | ||
1722 | - (bool) removeSection:(NSString *)section { | |
1723 | if (record_ == nil) | |
1724 | return false; | |
1725 | ||
1726 | [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO]; | |
1727 | return true; | |
1728 | } | |
1729 | ||
1730 | - (void) _remove { | |
1731 | [Sources_ removeObjectForKey:[self key]]; | |
1732 | Changed_ = true; | |
1733 | } | |
1734 | ||
1735 | - (bool) remove { | |
1736 | bool value(record_ != nil); | |
1737 | [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO]; | |
1738 | return value; | |
1739 | } | |
1740 | ||
1741 | - (NSDictionary *) record { | |
1742 | return record_; | |
1743 | } | |
1744 | ||
1745 | - (BOOL) trusted { | |
1746 | return trusted_; | |
1747 | } | |
1748 | ||
1749 | - (NSString *) rooturi { | |
1750 | return uri_; | |
1751 | } | |
1752 | ||
1753 | - (NSString *) distribution { | |
1754 | return distribution_; | |
1755 | } | |
1756 | ||
1757 | - (NSString *) type { | |
1758 | return type_; | |
1759 | } | |
1760 | ||
1761 | - (NSString *) baseuri { | |
1762 | return base_.empty() ? nil : (id) base_; | |
1763 | } | |
1764 | ||
1765 | - (NSString *) iconuri { | |
1766 | if (NSString *base = [self baseuri]) | |
1767 | return [base stringByAppendingString:@"CydiaIcon.png"]; | |
1768 | ||
1769 | return nil; | |
1770 | } | |
1771 | ||
1772 | - (NSURL *) iconURL { | |
1773 | if (NSString *uri = [self iconuri]) | |
1774 | return [NSURL URLWithString:uri]; | |
1775 | return nil; | |
1776 | } | |
1777 | ||
1778 | - (NSString *) key { | |
1779 | return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_]; | |
1780 | } | |
1781 | ||
1782 | - (NSString *) host { | |
1783 | return host_; | |
1784 | } | |
1785 | ||
1786 | - (NSString *) name { | |
1787 | return origin_.empty() ? (id) authority_ : origin_; | |
1788 | } | |
1789 | ||
1790 | - (NSString *) shortDescription { | |
1791 | return description_; | |
1792 | } | |
1793 | ||
1794 | - (NSString *) label { | |
1795 | return label_.empty() ? (id) authority_ : label_; | |
1796 | } | |
1797 | ||
1798 | - (NSString *) origin { | |
1799 | return origin_; | |
1800 | } | |
1801 | ||
1802 | - (NSString *) version { | |
1803 | return version_; | |
1804 | } | |
1805 | ||
1806 | - (NSString *) defaultIcon { | |
1807 | return defaultIcon_; | |
1808 | } | |
1809 | ||
1810 | - (void) setDelegate:(NSObject<SourceDelegate> *)delegate { | |
1811 | delegate_ = delegate; | |
1812 | } | |
1813 | ||
1814 | - (bool) fetch { | |
1815 | return !fetches_.empty(); | |
1816 | } | |
1817 | ||
1818 | - (void) setFetch:(bool)fetch forURI:(const char *)uri { | |
1819 | if (!fetch) { | |
1820 | if (fetches_.erase(uri) == 0) | |
1821 | return; | |
1822 | } else if (files_.find(uri) == files_.end()) | |
1823 | return; | |
1824 | else if (!fetches_.insert(uri).second) | |
1825 | return; | |
1826 | ||
1827 | [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO]; | |
1828 | } | |
1829 | ||
1830 | - (void) resetFetch { | |
1831 | fetches_.clear(); | |
1832 | [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO]; | |
1833 | } | |
1834 | ||
1835 | @end | |
1836 | /* }}} */ | |
1837 | /* CydiaOperation Class {{{ */ | |
1838 | @interface CydiaOperation : NSObject { | |
1839 | _H<NSString> operator_; | |
1840 | _H<NSString> value_; | |
1841 | } | |
1842 | ||
1843 | - (NSString *) operator; | |
1844 | - (NSString *) value; | |
1845 | ||
1846 | @end | |
1847 | ||
1848 | @implementation CydiaOperation | |
1849 | ||
1850 | - (id) initWithOperator:(const char *)_operator value:(const char *)value { | |
1851 | if ((self = [super init]) != nil) { | |
1852 | operator_ = [NSString stringWithUTF8String:_operator]; | |
1853 | value_ = [NSString stringWithUTF8String:value]; | |
1854 | } return self; | |
1855 | } | |
1856 | ||
1857 | + (NSArray *) _attributeKeys { | |
1858 | return [NSArray arrayWithObjects: | |
1859 | @"operator", | |
1860 | @"value", | |
1861 | nil]; | |
1862 | } | |
1863 | ||
1864 | - (NSArray *) attributeKeys { | |
1865 | return [[self class] _attributeKeys]; | |
1866 | } | |
1867 | ||
1868 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
1869 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
1870 | } | |
1871 | ||
1872 | - (NSString *) operator { | |
1873 | return operator_; | |
1874 | } | |
1875 | ||
1876 | - (NSString *) value { | |
1877 | return value_; | |
1878 | } | |
1879 | ||
1880 | @end | |
1881 | /* }}} */ | |
1882 | /* CydiaClause Class {{{ */ | |
1883 | @interface CydiaClause : NSObject { | |
1884 | _H<NSString> package_; | |
1885 | _H<CydiaOperation> version_; | |
1886 | } | |
1887 | ||
1888 | - (NSString *) package; | |
1889 | - (CydiaOperation *) version; | |
1890 | ||
1891 | @end | |
1892 | ||
1893 | @implementation CydiaClause | |
1894 | ||
1895 | - (id) initWithIterator:(pkgCache::DepIterator &)dep { | |
1896 | if ((self = [super init]) != nil) { | |
1897 | package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()]; | |
1898 | ||
1899 | if (const char *version = dep.TargetVer()) | |
1900 | version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease]; | |
1901 | else | |
1902 | version_ = (id) [NSNull null]; | |
1903 | } return self; | |
1904 | } | |
1905 | ||
1906 | + (NSArray *) _attributeKeys { | |
1907 | return [NSArray arrayWithObjects: | |
1908 | @"package", | |
1909 | @"version", | |
1910 | nil]; | |
1911 | } | |
1912 | ||
1913 | - (NSArray *) attributeKeys { | |
1914 | return [[self class] _attributeKeys]; | |
1915 | } | |
1916 | ||
1917 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
1918 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
1919 | } | |
1920 | ||
1921 | - (NSString *) package { | |
1922 | return package_; | |
1923 | } | |
1924 | ||
1925 | - (CydiaOperation *) version { | |
1926 | return version_; | |
1927 | } | |
1928 | ||
1929 | @end | |
1930 | /* }}} */ | |
1931 | /* CydiaRelation Class {{{ */ | |
1932 | @interface CydiaRelation : NSObject { | |
1933 | _H<NSString> relationship_; | |
1934 | _H<NSMutableArray> clauses_; | |
1935 | } | |
1936 | ||
1937 | - (NSString *) relationship; | |
1938 | - (NSArray *) clauses; | |
1939 | ||
1940 | @end | |
1941 | ||
1942 | @implementation CydiaRelation | |
1943 | ||
1944 | - (id) initWithIterator:(pkgCache::DepIterator &)dep { | |
1945 | if ((self = [super init]) != nil) { | |
1946 | relationship_ = [NSString stringWithUTF8String:dep.DepType()]; | |
1947 | clauses_ = [NSMutableArray arrayWithCapacity:8]; | |
1948 | ||
1949 | pkgCache::DepIterator start; | |
1950 | pkgCache::DepIterator end; | |
1951 | dep.GlobOr(start, end); // ++dep | |
1952 | ||
1953 | _forever { | |
1954 | [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]]; | |
1955 | ||
1956 | // yes, seriously. (wtf?) | |
1957 | if (start == end) | |
1958 | break; | |
1959 | ++start; | |
1960 | } | |
1961 | } return self; | |
1962 | } | |
1963 | ||
1964 | + (NSArray *) _attributeKeys { | |
1965 | return [NSArray arrayWithObjects: | |
1966 | @"clauses", | |
1967 | @"relationship", | |
1968 | nil]; | |
1969 | } | |
1970 | ||
1971 | - (NSArray *) attributeKeys { | |
1972 | return [[self class] _attributeKeys]; | |
1973 | } | |
1974 | ||
1975 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
1976 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
1977 | } | |
1978 | ||
1979 | - (NSString *) relationship { | |
1980 | return relationship_; | |
1981 | } | |
1982 | ||
1983 | - (NSArray *) clauses { | |
1984 | return clauses_; | |
1985 | } | |
1986 | ||
1987 | - (void) addClause:(CydiaClause *)clause { | |
1988 | [clauses_ addObject:clause]; | |
1989 | } | |
1990 | ||
1991 | @end | |
1992 | /* }}} */ | |
1993 | /* Package Class {{{ */ | |
1994 | struct ParsedPackage { | |
1995 | CYString md5sum_; | |
1996 | CYString tagline_; | |
1997 | ||
1998 | CYString architecture_; | |
1999 | CYString icon_; | |
2000 | ||
2001 | CYString depiction_; | |
2002 | CYString homepage_; | |
2003 | CYString author_; | |
2004 | ||
2005 | CYString support_; | |
2006 | }; | |
2007 | ||
2008 | @interface Package : NSObject { | |
2009 | uint32_t era_ : 25; | |
2010 | @public uint32_t role_ : 3; | |
2011 | uint32_t essential_ : 1; | |
2012 | uint32_t obsolete_ : 1; | |
2013 | uint32_t ignored_ : 1; | |
2014 | uint32_t pooled_ : 1; | |
2015 | ||
2016 | apr_pool_t *pool_; | |
2017 | ||
2018 | uint32_t rank_; | |
2019 | ||
2020 | _transient Database *database_; | |
2021 | ||
2022 | pkgCache::VerIterator version_; | |
2023 | pkgCache::PkgIterator iterator_; | |
2024 | pkgCache::VerFileIterator file_; | |
2025 | ||
2026 | CYString id_; | |
2027 | CYString name_; | |
2028 | CYString transform_; | |
2029 | ||
2030 | CYString latest_; | |
2031 | CYString installed_; | |
2032 | time_t upgraded_; | |
2033 | ||
2034 | const char *section_; | |
2035 | _transient NSString *section$_; | |
2036 | ||
2037 | _H<Source> source_; | |
2038 | ||
2039 | PackageValue *metadata_; | |
2040 | ParsedPackage *parsed_; | |
2041 | ||
2042 | _H<NSMutableArray> tags_; | |
2043 | } | |
2044 | ||
2045 | - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database; | |
2046 | + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database; | |
2047 | ||
2048 | - (pkgCache::PkgIterator) iterator; | |
2049 | - (void) parse; | |
2050 | ||
2051 | - (NSString *) section; | |
2052 | - (NSString *) simpleSection; | |
2053 | ||
2054 | - (NSString *) longSection; | |
2055 | - (NSString *) shortSection; | |
2056 | ||
2057 | - (NSString *) uri; | |
2058 | ||
2059 | - (MIMEAddress *) maintainer; | |
2060 | - (size_t) size; | |
2061 | - (NSString *) longDescription; | |
2062 | - (NSString *) shortDescription; | |
2063 | - (unichar) index; | |
2064 | ||
2065 | - (PackageValue *) metadata; | |
2066 | - (time_t) seen; | |
2067 | ||
2068 | - (bool) subscribed; | |
2069 | - (bool) setSubscribed:(bool)subscribed; | |
2070 | ||
2071 | - (BOOL) ignored; | |
2072 | ||
2073 | - (NSString *) latest; | |
2074 | - (NSString *) installed; | |
2075 | - (BOOL) uninstalled; | |
2076 | ||
2077 | - (BOOL) valid; | |
2078 | - (BOOL) upgradableAndEssential:(BOOL)essential; | |
2079 | - (BOOL) essential; | |
2080 | - (BOOL) broken; | |
2081 | - (BOOL) unfiltered; | |
2082 | - (BOOL) visible; | |
2083 | ||
2084 | - (BOOL) half; | |
2085 | - (BOOL) halfConfigured; | |
2086 | - (BOOL) halfInstalled; | |
2087 | - (BOOL) hasMode; | |
2088 | - (NSString *) mode; | |
2089 | ||
2090 | - (NSString *) id; | |
2091 | - (NSString *) name; | |
2092 | - (UIImage *) icon; | |
2093 | - (NSString *) homepage; | |
2094 | - (NSString *) depiction; | |
2095 | - (MIMEAddress *) author; | |
2096 | ||
2097 | - (NSString *) support; | |
2098 | ||
2099 | - (NSArray *) files; | |
2100 | - (NSArray *) warnings; | |
2101 | - (NSArray *) applications; | |
2102 | ||
2103 | - (Source *) source; | |
2104 | ||
2105 | - (uint32_t) rank; | |
2106 | - (BOOL) matches:(NSArray *)query; | |
2107 | ||
2108 | - (BOOL) hasTag:(NSString *)tag; | |
2109 | - (NSString *) primaryPurpose; | |
2110 | - (NSArray *) purposes; | |
2111 | - (bool) isCommercial; | |
2112 | ||
2113 | - (void) setIndex:(size_t)index; | |
2114 | ||
2115 | - (CYString &) cyname; | |
2116 | ||
2117 | - (uint32_t) compareBySection:(NSArray *)sections; | |
2118 | ||
2119 | - (void) install; | |
2120 | - (void) remove; | |
2121 | ||
2122 | @end | |
2123 | ||
2124 | uint32_t PackageChangesRadix(Package *self, void *) { | |
2125 | union { | |
2126 | uint32_t key; | |
2127 | ||
2128 | struct { | |
2129 | uint32_t timestamp : 30; | |
2130 | uint32_t ignored : 1; | |
2131 | uint32_t upgradable : 1; | |
2132 | } bits; | |
2133 | } value; | |
2134 | ||
2135 | bool upgradable([self upgradableAndEssential:YES]); | |
2136 | value.bits.upgradable = upgradable ? 1 : 0; | |
2137 | ||
2138 | if (upgradable) { | |
2139 | value.bits.timestamp = 0; | |
2140 | value.bits.ignored = [self ignored] ? 0 : 1; | |
2141 | value.bits.upgradable = 1; | |
2142 | } else { | |
2143 | value.bits.timestamp = [self seen] >> 2; | |
2144 | value.bits.ignored = 0; | |
2145 | value.bits.upgradable = 0; | |
2146 | } | |
2147 | ||
2148 | return _not(uint32_t) - value.key; | |
2149 | } | |
2150 | ||
2151 | CYString &(*PackageName)(Package *self, SEL sel); | |
2152 | ||
2153 | uint32_t PackagePrefixRadix(Package *self, void *context) { | |
2154 | size_t offset(reinterpret_cast<size_t>(context)); | |
2155 | CYString &name(PackageName(self, @selector(cyname))); | |
2156 | ||
2157 | size_t size(name.size()); | |
2158 | if (size == 0) | |
2159 | return 0; | |
2160 | char *text(name.data()); | |
2161 | ||
2162 | size_t zeros; | |
2163 | if (!isdigit(text[0])) | |
2164 | zeros = 0; | |
2165 | else { | |
2166 | size_t digits(1); | |
2167 | while (size != digits && isdigit(text[digits])) | |
2168 | if (++digits == 4) | |
2169 | break; | |
2170 | zeros = 4 - digits; | |
2171 | } | |
2172 | ||
2173 | uint8_t data[4]; | |
2174 | ||
2175 | if (offset == 0 && zeros != 0) { | |
2176 | memset(data, '0', zeros); | |
2177 | memcpy(data + zeros, text, 4 - zeros); | |
2178 | } else { | |
2179 | /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */ | |
2180 | if (size <= offset - zeros) | |
2181 | return 0; | |
2182 | ||
2183 | text += offset - zeros; | |
2184 | size -= offset - zeros; | |
2185 | ||
2186 | if (size >= 4) | |
2187 | memcpy(data, text, 4); | |
2188 | else { | |
2189 | memcpy(data, text, size); | |
2190 | memset(data + size, 0, 4 - size); | |
2191 | } | |
2192 | ||
2193 | for (size_t i(0); i != 4; ++i) | |
2194 | if (isalpha(data[i])) | |
2195 | data[i] |= 0x20; | |
2196 | } | |
2197 | ||
2198 | if (offset == 0) | |
2199 | if (data[0] == '@') | |
2200 | data[0] = 0x7f; | |
2201 | else | |
2202 | data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6]; | |
2203 | ||
2204 | /* XXX: ntohl may be more honest */ | |
2205 | return OSSwapInt32(*reinterpret_cast<uint32_t *>(data)); | |
2206 | } | |
2207 | ||
2208 | CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) { | |
2209 | _profile(PackageNameCompare) | |
2210 | if (lhn == NULL) | |
2211 | return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan; | |
2212 | else if (rhn == NULL) | |
2213 | return kCFCompareGreaterThan; | |
2214 | ||
2215 | CFIndex length(CFStringGetLength(lhn)); | |
2216 | ||
2217 | _profile(PackageNameCompare$NumbersLast) | |
2218 | if (length != 0 && CFStringGetLength(rhn) != 0) { | |
2219 | UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0)); | |
2220 | UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0)); | |
2221 | bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet)); | |
2222 | if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet)) | |
2223 | return lha ? kCFCompareLessThan : kCFCompareGreaterThan; | |
2224 | } | |
2225 | _end | |
2226 | ||
2227 | _profile(PackageNameCompare$Compare) | |
2228 | return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_); | |
2229 | _end | |
2230 | _end | |
2231 | } | |
2232 | ||
2233 | _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) { | |
2234 | return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length); | |
2235 | } | |
2236 | ||
2237 | CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) { | |
2238 | CYString &lhn(PackageName(lhs, @selector(cyname))); | |
2239 | NSString *rhn(PackageName(rhs, @selector(cyname))); | |
2240 | return StringNameCompare(lhn, rhn, lhn.size()); | |
2241 | } | |
2242 | ||
2243 | CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) { | |
2244 | return PackageNameCompare(*lhs, *rhs, arg); | |
2245 | } | |
2246 | ||
2247 | struct PackageNameOrdering : | |
2248 | std::binary_function<Package *, Package *, bool> | |
2249 | { | |
2250 | _finline bool operator ()(Package *lhs, Package *rhs) const { | |
2251 | return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan; | |
2252 | } | |
2253 | }; | |
2254 | ||
2255 | @implementation Package | |
2256 | ||
2257 | - (NSString *) description { | |
2258 | return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)]; | |
2259 | } | |
2260 | ||
2261 | - (void) dealloc { | |
2262 | if (!pooled_) | |
2263 | apr_pool_destroy(pool_); | |
2264 | if (parsed_ != NULL) | |
2265 | delete parsed_; | |
2266 | [super dealloc]; | |
2267 | } | |
2268 | ||
2269 | + (NSString *) webScriptNameForSelector:(SEL)selector { | |
2270 | if (false); | |
2271 | else if (selector == @selector(clear)) | |
2272 | return @"clear"; | |
2273 | else if (selector == @selector(getField:)) | |
2274 | return @"getField"; | |
2275 | else if (selector == @selector(getRecord)) | |
2276 | return @"getRecord"; | |
2277 | else if (selector == @selector(hasTag:)) | |
2278 | return @"hasTag"; | |
2279 | else if (selector == @selector(install)) | |
2280 | return @"install"; | |
2281 | else if (selector == @selector(remove)) | |
2282 | return @"remove"; | |
2283 | else | |
2284 | return nil; | |
2285 | } | |
2286 | ||
2287 | + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector { | |
2288 | return [self webScriptNameForSelector:selector] == nil; | |
2289 | } | |
2290 | ||
2291 | + (NSArray *) _attributeKeys { | |
2292 | return [NSArray arrayWithObjects: | |
2293 | @"applications", | |
2294 | @"architecture", | |
2295 | @"author", | |
2296 | @"depiction", | |
2297 | @"essential", | |
2298 | @"homepage", | |
2299 | @"icon", | |
2300 | @"id", | |
2301 | @"installed", | |
2302 | @"latest", | |
2303 | @"longDescription", | |
2304 | @"longSection", | |
2305 | @"maintainer", | |
2306 | @"md5sum", | |
2307 | @"mode", | |
2308 | @"name", | |
2309 | @"purposes", | |
2310 | @"relations", | |
2311 | @"section", | |
2312 | @"selection", | |
2313 | @"shortDescription", | |
2314 | @"shortSection", | |
2315 | @"simpleSection", | |
2316 | @"size", | |
2317 | @"source", | |
2318 | @"state", | |
2319 | @"support", | |
2320 | @"tags", | |
2321 | @"warnings", | |
2322 | nil]; | |
2323 | } | |
2324 | ||
2325 | - (NSArray *) attributeKeys { | |
2326 | return [[self class] _attributeKeys]; | |
2327 | } | |
2328 | ||
2329 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
2330 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
2331 | } | |
2332 | ||
2333 | - (NSArray *) relations { | |
2334 | @synchronized (database_) { | |
2335 | NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]); | |
2336 | for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep) | |
2337 | [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]]; | |
2338 | return relations; | |
2339 | } } | |
2340 | ||
2341 | - (NSString *) architecture { | |
2342 | [self parse]; | |
2343 | @synchronized (database_) { | |
2344 | return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_; | |
2345 | } } | |
2346 | ||
2347 | - (NSString *) getField:(NSString *)name { | |
2348 | @synchronized (database_) { | |
2349 | if ([database_ era] != era_ || file_.end()) | |
2350 | return nil; | |
2351 | ||
2352 | pkgRecords::Parser &parser([database_ records]->Lookup(file_)); | |
2353 | ||
2354 | const char *start, *end; | |
2355 | if (!parser.Find([name UTF8String], start, end)) | |
2356 | return (NSString *) [NSNull null]; | |
2357 | ||
2358 | return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]]; | |
2359 | } } | |
2360 | ||
2361 | - (NSString *) getRecord { | |
2362 | @synchronized (database_) { | |
2363 | if ([database_ era] != era_ || file_.end()) | |
2364 | return nil; | |
2365 | ||
2366 | pkgRecords::Parser &parser([database_ records]->Lookup(file_)); | |
2367 | ||
2368 | const char *start, *end; | |
2369 | parser.GetRec(start, end); | |
2370 | ||
2371 | return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]]; | |
2372 | } } | |
2373 | ||
2374 | - (void) parse { | |
2375 | if (parsed_ != NULL) | |
2376 | return; | |
2377 | @synchronized (database_) { | |
2378 | if ([database_ era] != era_ || file_.end()) | |
2379 | return; | |
2380 | ||
2381 | ParsedPackage *parsed(new ParsedPackage); | |
2382 | parsed_ = parsed; | |
2383 | ||
2384 | _profile(Package$parse) | |
2385 | pkgRecords::Parser *parser; | |
2386 | ||
2387 | _profile(Package$parse$Lookup) | |
2388 | parser = &[database_ records]->Lookup(file_); | |
2389 | _end | |
2390 | ||
2391 | CYString bugs; | |
2392 | CYString website; | |
2393 | ||
2394 | _profile(Package$parse$Find) | |
2395 | struct { | |
2396 | const char *name_; | |
2397 | CYString *value_; | |
2398 | } names[] = { | |
2399 | {"architecture", &parsed->architecture_}, | |
2400 | {"icon", &parsed->icon_}, | |
2401 | {"depiction", &parsed->depiction_}, | |
2402 | {"homepage", &parsed->homepage_}, | |
2403 | {"website", &website}, | |
2404 | {"bugs", &bugs}, | |
2405 | {"support", &parsed->support_}, | |
2406 | {"author", &parsed->author_}, | |
2407 | {"md5sum", &parsed->md5sum_}, | |
2408 | }; | |
2409 | ||
2410 | for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) { | |
2411 | const char *start, *end; | |
2412 | ||
2413 | if (parser->Find(names[i].name_, start, end)) { | |
2414 | CYString &value(*names[i].value_); | |
2415 | _profile(Package$parse$Value) | |
2416 | value.set(pool_, start, end - start); | |
2417 | _end | |
2418 | } | |
2419 | } | |
2420 | _end | |
2421 | ||
2422 | _profile(Package$parse$Tagline) | |
2423 | const char *start, *end; | |
2424 | if (parser->ShortDesc(start, end)) { | |
2425 | const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start))); | |
2426 | if (stop == NULL) | |
2427 | stop = end; | |
2428 | while (stop != start && stop[-1] == '\r') | |
2429 | --stop; | |
2430 | parsed->tagline_.set(pool_, start, stop - start); | |
2431 | } | |
2432 | _end | |
2433 | ||
2434 | _profile(Package$parse$Retain) | |
2435 | if (parsed->homepage_.empty()) | |
2436 | parsed->homepage_ = website; | |
2437 | if (parsed->homepage_ == parsed->depiction_) | |
2438 | parsed->homepage_.clear(); | |
2439 | if (parsed->support_.empty()) | |
2440 | parsed->support_ = bugs; | |
2441 | _end | |
2442 | _end | |
2443 | } } | |
2444 | ||
2445 | - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database { | |
2446 | if ((self = [super init]) != nil) { | |
2447 | _profile(Package$initWithVersion) | |
2448 | if (pool == NULL) | |
2449 | apr_pool_create(&pool_, NULL); | |
2450 | else { | |
2451 | pool_ = pool; | |
2452 | pooled_ = true; | |
2453 | } | |
2454 | ||
2455 | database_ = database; | |
2456 | era_ = [database era]; | |
2457 | ||
2458 | version_ = version; | |
2459 | ||
2460 | pkgCache::PkgIterator iterator(version.ParentPkg()); | |
2461 | iterator_ = iterator; | |
2462 | ||
2463 | _profile(Package$initWithVersion$Version) | |
2464 | if (!version_.end()) | |
2465 | file_ = version_.FileList(); | |
2466 | else { | |
2467 | pkgCache &cache([database_ cache]); | |
2468 | file_ = pkgCache::VerFileIterator(cache, cache.VerFileP); | |
2469 | } | |
2470 | _end | |
2471 | ||
2472 | _profile(Package$initWithVersion$Cache) | |
2473 | name_.set(NULL, iterator.Display()); | |
2474 | ||
2475 | latest_.set(NULL, StripVersion_(version_.VerStr())); | |
2476 | ||
2477 | pkgCache::VerIterator current(iterator.CurrentVer()); | |
2478 | if (!current.end()) | |
2479 | installed_.set(NULL, StripVersion_(current.VerStr())); | |
2480 | _end | |
2481 | ||
2482 | _profile(Package$initWithVersion$Transliterate) do { | |
2483 | if (CollationTransl_ == NULL) | |
2484 | break; | |
2485 | if (name_.empty()) | |
2486 | break; | |
2487 | ||
2488 | _profile(Package$initWithVersion$Transliterate$utf8) | |
2489 | const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data())); | |
2490 | for (size_t i(0), e(name_.size()); i != e; ++i) | |
2491 | if (data[i] >= 0x80) | |
2492 | goto extended; | |
2493 | break; extended:; | |
2494 | _end | |
2495 | ||
2496 | UErrorCode code(U_ZERO_ERROR); | |
2497 | int32_t length; | |
2498 | ||
2499 | _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub) | |
2500 | CollationString_.resize(name_.size()); | |
2501 | u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code); | |
2502 | if (!U_SUCCESS(code)) | |
2503 | break; | |
2504 | CollationString_.resize(length); | |
2505 | _end | |
2506 | ||
2507 | _profile(Package$initWithVersion$Transliterate$utrans_trans) | |
2508 | length = CollationString_.size(); | |
2509 | utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code); | |
2510 | if (!U_SUCCESS(code)) | |
2511 | break; | |
2512 | _assert(CollationString_.size() == length); | |
2513 | _end | |
2514 | ||
2515 | _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight) | |
2516 | u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code); | |
2517 | if (code == U_BUFFER_OVERFLOW_ERROR) | |
2518 | code = U_ZERO_ERROR; | |
2519 | else if (!U_SUCCESS(code)) | |
2520 | break; | |
2521 | _end | |
2522 | ||
2523 | char *transform; | |
2524 | _profile(Package$initWithVersion$Transliterate$apr_palloc) | |
2525 | transform = static_cast<char *>(apr_palloc(pool_, length)); | |
2526 | _end | |
2527 | _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform) | |
2528 | u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code); | |
2529 | if (!U_SUCCESS(code)) | |
2530 | break; | |
2531 | _end | |
2532 | ||
2533 | transform_.set(NULL, transform, length); | |
2534 | } while (false); _end | |
2535 | ||
2536 | _profile(Package$initWithVersion$Tags) | |
2537 | pkgCache::TagIterator tag(iterator.TagList()); | |
2538 | if (!tag.end()) { | |
2539 | tags_ = [NSMutableArray arrayWithCapacity:8]; | |
2540 | ||
2541 | goto tag; for (; !tag.end(); ++tag) tag: { | |
2542 | const char *name(tag.Name()); | |
2543 | NSString *string((NSString *) CYStringCreate(name)); | |
2544 | if (string == nil) | |
2545 | continue; | |
2546 | ||
2547 | [tags_ addObject:[string autorelease]]; | |
2548 | ||
2549 | if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) { | |
2550 | if (strcmp(name + 6, "enduser") == 0) | |
2551 | role_ = 1; | |
2552 | else if (strcmp(name + 6, "hacker") == 0) | |
2553 | role_ = 2; | |
2554 | else if (strcmp(name + 6, "developer") == 0) | |
2555 | role_ = 3; | |
2556 | else if (strcmp(name + 6, "cydia") == 0) | |
2557 | role_ = 7; | |
2558 | else | |
2559 | role_ = 4; | |
2560 | } | |
2561 | ||
2562 | if (strncmp(name, "cydia::", 7) == 0) { | |
2563 | if (strcmp(name + 7, "essential") == 0) | |
2564 | essential_ = true; | |
2565 | else if (strcmp(name + 7, "obsolete") == 0) | |
2566 | obsolete_ = true; | |
2567 | } | |
2568 | } | |
2569 | } | |
2570 | _end | |
2571 | ||
2572 | _profile(Package$initWithVersion$Metadata) | |
2573 | const char *mixed(iterator.Name()); | |
2574 | size_t size(strlen(mixed)); | |
2575 | static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1); | |
2576 | char lower[prefix + size + 5 + 1]; | |
2577 | ||
2578 | for (size_t i(0); i != size; ++i) | |
2579 | lower[prefix + i] = mixed[i] | 0x20; | |
2580 | ||
2581 | if (!installed_.empty()) { | |
2582 | memcpy(lower, "/var/lib/dpkg/info/", prefix); | |
2583 | memcpy(lower + prefix + size, ".list", 6); | |
2584 | struct stat info; | |
2585 | if (stat(lower, &info) != -1) | |
2586 | upgraded_ = info.st_birthtime; | |
2587 | } | |
2588 | ||
2589 | PackageValue *metadata(PackageFind(lower + prefix, size)); | |
2590 | metadata_ = metadata; | |
2591 | ||
2592 | id_.set(NULL, metadata->name_, size); | |
2593 | ||
2594 | const char *latest(version_.VerStr()); | |
2595 | size_t length(strlen(latest)); | |
2596 | ||
2597 | uint16_t vhash(hashlittle(latest, length)); | |
2598 | ||
2599 | size_t capped(std::min<size_t>(8, length)); | |
2600 | latest = latest + length - capped; | |
2601 | ||
2602 | if (metadata->first_ == 0) | |
2603 | metadata->first_ = now_; | |
2604 | ||
2605 | if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) { | |
2606 | strncpy(metadata->version_, latest, sizeof(metadata->version_)); | |
2607 | metadata->vhash_ = vhash; | |
2608 | metadata->last_ = now_; | |
2609 | } else if (metadata->last_ == 0) | |
2610 | metadata->last_ = metadata->first_; | |
2611 | _end | |
2612 | ||
2613 | _profile(Package$initWithVersion$Section) | |
2614 | section_ = version_.Section(); | |
2615 | _end | |
2616 | ||
2617 | _profile(Package$initWithVersion$Flags) | |
2618 | essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES); | |
2619 | ignored_ = iterator->SelectedState == pkgCache::State::Hold; | |
2620 | _end | |
2621 | _end } return self; | |
2622 | } | |
2623 | ||
2624 | + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database { | |
2625 | pkgCache::VerIterator version; | |
2626 | ||
2627 | _profile(Package$packageWithIterator$GetCandidateVer) | |
2628 | version = [database policy]->GetCandidateVer(iterator); | |
2629 | _end | |
2630 | ||
2631 | if (version.end()) | |
2632 | return nil; | |
2633 | ||
2634 | Package *package; | |
2635 | ||
2636 | _profile(Package$packageWithIterator$Allocate) | |
2637 | package = [Package allocWithZone:zone]; | |
2638 | _end | |
2639 | ||
2640 | _profile(Package$packageWithIterator$Initialize) | |
2641 | package = [package | |
2642 | initWithVersion:version | |
2643 | withZone:zone | |
2644 | inPool:pool | |
2645 | database:database | |
2646 | ]; | |
2647 | _end | |
2648 | ||
2649 | _profile(Package$packageWithIterator$Autorelease) | |
2650 | package = [package autorelease]; | |
2651 | _end | |
2652 | ||
2653 | return package; | |
2654 | } | |
2655 | ||
2656 | - (pkgCache::PkgIterator) iterator { | |
2657 | return iterator_; | |
2658 | } | |
2659 | ||
2660 | - (NSString *) section { | |
2661 | if (section$_ == nil) { | |
2662 | if (section_ == NULL) | |
2663 | return nil; | |
2664 | ||
2665 | _profile(Package$section$mappedSectionForPointer) | |
2666 | section$_ = [database_ mappedSectionForPointer:section_]; | |
2667 | _end | |
2668 | } return section$_; | |
2669 | } | |
2670 | ||
2671 | - (NSString *) simpleSection { | |
2672 | if (NSString *section = [self section]) | |
2673 | return Simplify(section); | |
2674 | else | |
2675 | return nil; | |
2676 | } | |
2677 | ||
2678 | - (NSString *) longSection { | |
2679 | return LocalizeSection([self section]); | |
2680 | } | |
2681 | ||
2682 | - (NSString *) shortSection { | |
2683 | return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"]; | |
2684 | } | |
2685 | ||
2686 | - (NSString *) uri { | |
2687 | return nil; | |
2688 | #if 0 | |
2689 | pkgIndexFile *index; | |
2690 | pkgCache::PkgFileIterator file(file_.File()); | |
2691 | if (![database_ list].FindIndex(file, index)) | |
2692 | return nil; | |
2693 | return [NSString stringWithUTF8String:iterator_->Path]; | |
2694 | //return [NSString stringWithUTF8String:file.Site()]; | |
2695 | //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()]; | |
2696 | #endif | |
2697 | } | |
2698 | ||
2699 | - (MIMEAddress *) maintainer { | |
2700 | @synchronized (database_) { | |
2701 | if ([database_ era] != era_ || file_.end()) | |
2702 | return nil; | |
2703 | ||
2704 | pkgRecords::Parser *parser = &[database_ records]->Lookup(file_); | |
2705 | const std::string &maintainer(parser->Maintainer()); | |
2706 | return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]]; | |
2707 | } } | |
2708 | ||
2709 | - (NSString *) md5sum { | |
2710 | return parsed_ == NULL ? nil : (id) parsed_->md5sum_; | |
2711 | } | |
2712 | ||
2713 | - (size_t) size { | |
2714 | @synchronized (database_) { | |
2715 | if ([database_ era] != era_ || version_.end()) | |
2716 | return 0; | |
2717 | ||
2718 | return version_->InstalledSize; | |
2719 | } } | |
2720 | ||
2721 | - (NSString *) longDescription { | |
2722 | @synchronized (database_) { | |
2723 | if ([database_ era] != era_ || file_.end()) | |
2724 | return nil; | |
2725 | ||
2726 | pkgRecords::Parser *parser = &[database_ records]->Lookup(file_); | |
2727 | NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]); | |
2728 | ||
2729 | NSArray *lines = [description componentsSeparatedByString:@"\n"]; | |
2730 | NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)]; | |
2731 | if ([lines count] < 2) | |
2732 | return nil; | |
2733 | ||
2734 | NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet]; | |
2735 | for (size_t i(1), e([lines count]); i != e; ++i) { | |
2736 | NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace]; | |
2737 | [trimmed addObject:trim]; | |
2738 | } | |
2739 | ||
2740 | return [trimmed componentsJoinedByString:@"\n"]; | |
2741 | } } | |
2742 | ||
2743 | - (NSString *) shortDescription { | |
2744 | if (parsed_ != NULL) | |
2745 | return static_cast<NSString *>(parsed_->tagline_); | |
2746 | ||
2747 | @synchronized (database_) { | |
2748 | pkgRecords::Parser &parser([database_ records]->Lookup(file_)); | |
2749 | ||
2750 | const char *start, *end; | |
2751 | if (!parser.ShortDesc(start, end)) | |
2752 | return nil; | |
2753 | ||
2754 | if (end - start > 200) | |
2755 | end = start + 200; | |
2756 | ||
2757 | /* | |
2758 | if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start))) | |
2759 | end = stop; | |
2760 | ||
2761 | while (end != start && end[-1] == '\r') | |
2762 | --end; | |
2763 | */ | |
2764 | ||
2765 | return [(id) CYStringCreate(start, end - start) autorelease]; | |
2766 | } } | |
2767 | ||
2768 | - (unichar) index { | |
2769 | _profile(Package$index) | |
2770 | CFStringRef name((CFStringRef) [self name]); | |
2771 | if (CFStringGetLength(name) == 0) | |
2772 | return '#'; | |
2773 | UniChar character(CFStringGetCharacterAtIndex(name, 0)); | |
2774 | if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet)) | |
2775 | return '#'; | |
2776 | return toupper(character); | |
2777 | _end | |
2778 | } | |
2779 | ||
2780 | - (PackageValue *) metadata { | |
2781 | return metadata_; | |
2782 | } | |
2783 | ||
2784 | - (time_t) seen { | |
2785 | PackageValue *metadata([self metadata]); | |
2786 | return metadata->subscribed_ ? metadata->last_ : metadata->first_; | |
2787 | } | |
2788 | ||
2789 | - (bool) subscribed { | |
2790 | return [self metadata]->subscribed_; | |
2791 | } | |
2792 | ||
2793 | - (bool) setSubscribed:(bool)subscribed { | |
2794 | PackageValue *metadata([self metadata]); | |
2795 | if (metadata->subscribed_ == subscribed) | |
2796 | return false; | |
2797 | metadata->subscribed_ = subscribed; | |
2798 | return true; | |
2799 | } | |
2800 | ||
2801 | - (BOOL) ignored { | |
2802 | return ignored_; | |
2803 | } | |
2804 | ||
2805 | - (NSString *) latest { | |
2806 | return latest_; | |
2807 | } | |
2808 | ||
2809 | - (NSString *) installed { | |
2810 | return installed_; | |
2811 | } | |
2812 | ||
2813 | - (BOOL) uninstalled { | |
2814 | return installed_.empty(); | |
2815 | } | |
2816 | ||
2817 | - (BOOL) valid { | |
2818 | return !version_.end(); | |
2819 | } | |
2820 | ||
2821 | - (BOOL) upgradableAndEssential:(BOOL)essential { | |
2822 | _profile(Package$upgradableAndEssential) | |
2823 | pkgCache::VerIterator current(iterator_.CurrentVer()); | |
2824 | if (current.end()) | |
2825 | return essential && essential_; | |
2826 | else | |
2827 | return !version_.end() && version_ != current; | |
2828 | _end | |
2829 | } | |
2830 | ||
2831 | - (BOOL) essential { | |
2832 | return essential_; | |
2833 | } | |
2834 | ||
2835 | - (BOOL) broken { | |
2836 | return [database_ cache][iterator_].InstBroken(); | |
2837 | } | |
2838 | ||
2839 | - (BOOL) unfiltered { | |
2840 | _profile(Package$unfiltered$obsolete) | |
2841 | if (_unlikely(obsolete_)) | |
2842 | return false; | |
2843 | _end | |
2844 | ||
2845 | _profile(Package$unfiltered$role) | |
2846 | if (_unlikely(role_ > 3)) | |
2847 | return false; | |
2848 | _end | |
2849 | ||
2850 | return true; | |
2851 | } | |
2852 | ||
2853 | - (BOOL) visible { | |
2854 | if (![self unfiltered]) | |
2855 | return false; | |
2856 | ||
2857 | NSString *section; | |
2858 | ||
2859 | _profile(Package$visible$section) | |
2860 | section = [self section]; | |
2861 | _end | |
2862 | ||
2863 | _profile(Package$visible$isSectionVisible) | |
2864 | if (!isSectionVisible(section)) | |
2865 | return false; | |
2866 | _end | |
2867 | ||
2868 | return true; | |
2869 | } | |
2870 | ||
2871 | - (BOOL) half { | |
2872 | unsigned char current(iterator_->CurrentState); | |
2873 | return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled; | |
2874 | } | |
2875 | ||
2876 | - (BOOL) halfConfigured { | |
2877 | return iterator_->CurrentState == pkgCache::State::HalfConfigured; | |
2878 | } | |
2879 | ||
2880 | - (BOOL) halfInstalled { | |
2881 | return iterator_->CurrentState == pkgCache::State::HalfInstalled; | |
2882 | } | |
2883 | ||
2884 | - (BOOL) hasMode { | |
2885 | @synchronized (database_) { | |
2886 | if ([database_ era] != era_ || iterator_.end()) | |
2887 | return NO; | |
2888 | ||
2889 | pkgDepCache::StateCache &state([database_ cache][iterator_]); | |
2890 | return state.Mode != pkgDepCache::ModeKeep; | |
2891 | } } | |
2892 | ||
2893 | - (NSString *) mode { | |
2894 | @synchronized (database_) { | |
2895 | if ([database_ era] != era_ || iterator_.end()) | |
2896 | return nil; | |
2897 | ||
2898 | pkgDepCache::StateCache &state([database_ cache][iterator_]); | |
2899 | ||
2900 | switch (state.Mode) { | |
2901 | case pkgDepCache::ModeDelete: | |
2902 | if ((state.iFlags & pkgDepCache::Purge) != 0) | |
2903 | return @"PURGE"; | |
2904 | else | |
2905 | return @"REMOVE"; | |
2906 | case pkgDepCache::ModeKeep: | |
2907 | if ((state.iFlags & pkgDepCache::ReInstall) != 0) | |
2908 | return @"REINSTALL"; | |
2909 | /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0) | |
2910 | return nil;*/ | |
2911 | else | |
2912 | return nil; | |
2913 | case pkgDepCache::ModeInstall: | |
2914 | /*if ((state.iFlags & pkgDepCache::ReInstall) != 0) | |
2915 | return @"REINSTALL"; | |
2916 | else*/ switch (state.Status) { | |
2917 | case -1: | |
2918 | return @"DOWNGRADE"; | |
2919 | case 0: | |
2920 | return @"INSTALL"; | |
2921 | case 1: | |
2922 | return @"UPGRADE"; | |
2923 | case 2: | |
2924 | return @"NEW_INSTALL"; | |
2925 | _nodefault | |
2926 | } | |
2927 | _nodefault | |
2928 | } | |
2929 | } } | |
2930 | ||
2931 | - (NSString *) id { | |
2932 | return id_; | |
2933 | } | |
2934 | ||
2935 | - (NSString *) name { | |
2936 | return name_.empty() ? id_ : name_; | |
2937 | } | |
2938 | ||
2939 | - (UIImage *) icon { | |
2940 | NSString *section = [self simpleSection]; | |
2941 | ||
2942 | UIImage *icon(nil); | |
2943 | if (parsed_ != NULL) | |
2944 | if (NSString *href = parsed_->icon_) | |
2945 | if ([href hasPrefix:@"file:///"]) | |
2946 | icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; | |
2947 | if (icon == nil) if (section != nil) | |
2948 | icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]; | |
2949 | if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon]) | |
2950 | if ([dicon hasPrefix:@"file:///"]) | |
2951 | icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; | |
2952 | if (icon == nil) | |
2953 | icon = [UIImage applicationImageNamed:@"unknown.png"]; | |
2954 | return icon; | |
2955 | } | |
2956 | ||
2957 | - (NSString *) homepage { | |
2958 | return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_); | |
2959 | } | |
2960 | ||
2961 | - (NSString *) depiction { | |
2962 | return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_]; | |
2963 | } | |
2964 | ||
2965 | - (MIMEAddress *) author { | |
2966 | return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_]; | |
2967 | } | |
2968 | ||
2969 | - (NSString *) support { | |
2970 | return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_]; | |
2971 | } | |
2972 | ||
2973 | - (NSArray *) files { | |
2974 | NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)]; | |
2975 | NSMutableArray *files = [NSMutableArray arrayWithCapacity:128]; | |
2976 | ||
2977 | std::ifstream fin; | |
2978 | fin.open([path UTF8String]); | |
2979 | if (!fin.is_open()) | |
2980 | return nil; | |
2981 | ||
2982 | std::string line; | |
2983 | while (std::getline(fin, line)) | |
2984 | [files addObject:[NSString stringWithUTF8String:line.c_str()]]; | |
2985 | ||
2986 | return files; | |
2987 | } | |
2988 | ||
2989 | - (NSString *) state { | |
2990 | @synchronized (database_) { | |
2991 | if ([database_ era] != era_ || file_.end()) | |
2992 | return nil; | |
2993 | ||
2994 | switch (iterator_->CurrentState) { | |
2995 | case pkgCache::State::NotInstalled: | |
2996 | return @"NotInstalled"; | |
2997 | case pkgCache::State::UnPacked: | |
2998 | return @"UnPacked"; | |
2999 | case pkgCache::State::HalfConfigured: | |
3000 | return @"HalfConfigured"; | |
3001 | case pkgCache::State::HalfInstalled: | |
3002 | return @"HalfInstalled"; | |
3003 | case pkgCache::State::ConfigFiles: | |
3004 | return @"ConfigFiles"; | |
3005 | case pkgCache::State::Installed: | |
3006 | return @"Installed"; | |
3007 | case pkgCache::State::TriggersAwaited: | |
3008 | return @"TriggersAwaited"; | |
3009 | case pkgCache::State::TriggersPending: | |
3010 | return @"TriggersPending"; | |
3011 | } | |
3012 | ||
3013 | return (NSString *) [NSNull null]; | |
3014 | } } | |
3015 | ||
3016 | - (NSString *) selection { | |
3017 | @synchronized (database_) { | |
3018 | if ([database_ era] != era_ || file_.end()) | |
3019 | return nil; | |
3020 | ||
3021 | switch (iterator_->SelectedState) { | |
3022 | case pkgCache::State::Unknown: | |
3023 | return @"Unknown"; | |
3024 | case pkgCache::State::Install: | |
3025 | return @"Install"; | |
3026 | case pkgCache::State::Hold: | |
3027 | return @"Hold"; | |
3028 | case pkgCache::State::DeInstall: | |
3029 | return @"DeInstall"; | |
3030 | case pkgCache::State::Purge: | |
3031 | return @"Purge"; | |
3032 | } | |
3033 | ||
3034 | return (NSString *) [NSNull null]; | |
3035 | } } | |
3036 | ||
3037 | - (NSArray *) warnings { | |
3038 | NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]); | |
3039 | const char *name(iterator_.Name()); | |
3040 | ||
3041 | size_t length(strlen(name)); | |
3042 | if (length < 2) invalid: | |
3043 | [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")]; | |
3044 | else for (size_t i(0); i != length; ++i) | |
3045 | if ( | |
3046 | /* XXX: technically this is not allowed */ | |
3047 | (name[i] < 'A' || name[i] > 'Z') && | |
3048 | (name[i] < 'a' || name[i] > 'z') && | |
3049 | (name[i] < '0' || name[i] > '9') && | |
3050 | (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.') | |
3051 | ) goto invalid; | |
3052 | ||
3053 | if (strcmp(name, "cydia") != 0) { | |
3054 | bool cydia = false; | |
3055 | bool user = false; | |
3056 | bool _private = false; | |
3057 | bool stash = false; | |
3058 | ||
3059 | bool repository = [[self section] isEqualToString:@"Repositories"]; | |
3060 | ||
3061 | if (NSArray *files = [self files]) | |
3062 | for (NSString *file in files) | |
3063 | if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"]) | |
3064 | cydia = true; | |
3065 | else if (!user && [file isEqualToString:@"/User"]) | |
3066 | user = true; | |
3067 | else if (!_private && [file isEqualToString:@"/private"]) | |
3068 | _private = true; | |
3069 | else if (!stash && [file isEqualToString:@"/var/stash"]) | |
3070 | stash = true; | |
3071 | ||
3072 | /* XXX: this is not sensitive enough. only some folders are valid. */ | |
3073 | if (cydia && !repository) | |
3074 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]]; | |
3075 | if (user) | |
3076 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]]; | |
3077 | if (_private) | |
3078 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]]; | |
3079 | if (stash) | |
3080 | [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]]; | |
3081 | } | |
3082 | ||
3083 | return [warnings count] == 0 ? nil : warnings; | |
3084 | } | |
3085 | ||
3086 | - (NSArray *) applications { | |
3087 | NSString *me([[NSBundle mainBundle] bundleIdentifier]); | |
3088 | ||
3089 | NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]); | |
3090 | ||
3091 | static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$"); | |
3092 | if (NSArray *files = [self files]) | |
3093 | for (NSString *file in files) | |
3094 | if (application_r(file)) { | |
3095 | NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]); | |
3096 | NSString *id([info objectForKey:@"CFBundleIdentifier"]); | |
3097 | if ([id isEqualToString:me]) | |
3098 | continue; | |
3099 | ||
3100 | NSString *display([info objectForKey:@"CFBundleDisplayName"]); | |
3101 | if (display == nil) | |
3102 | display = application_r[1]; | |
3103 | ||
3104 | NSString *bundle([file stringByDeletingLastPathComponent]); | |
3105 | NSString *icon([info objectForKey:@"CFBundleIconFile"]); | |
3106 | // XXX: maybe this should check if this is really a string, not just for length | |
3107 | if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0) | |
3108 | icon = @"icon.png"; | |
3109 | NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]); | |
3110 | ||
3111 | NSMutableArray *application([NSMutableArray arrayWithCapacity:2]); | |
3112 | [applications addObject:application]; | |
3113 | ||
3114 | [application addObject:id]; | |
3115 | [application addObject:display]; | |
3116 | [application addObject:url]; | |
3117 | } | |
3118 | ||
3119 | return [applications count] == 0 ? nil : applications; | |
3120 | } | |
3121 | ||
3122 | - (Source *) source { | |
3123 | if (source_ == nil) { | |
3124 | @synchronized (database_) { | |
3125 | if ([database_ era] != era_ || file_.end()) | |
3126 | source_ = (Source *) [NSNull null]; | |
3127 | else | |
3128 | source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null]; | |
3129 | } | |
3130 | } | |
3131 | ||
3132 | return source_ == (Source *) [NSNull null] ? nil : source_; | |
3133 | } | |
3134 | ||
3135 | - (time_t) upgraded { | |
3136 | return upgraded_; | |
3137 | } | |
3138 | ||
3139 | - (uint32_t) recent { | |
3140 | return std::numeric_limits<uint32_t>::max() - upgraded_; | |
3141 | } | |
3142 | ||
3143 | - (uint32_t) rank { | |
3144 | return rank_; | |
3145 | } | |
3146 | ||
3147 | - (BOOL) matches:(NSArray *)query { | |
3148 | if (query == nil || [query count] == 0) | |
3149 | return NO; | |
3150 | ||
3151 | rank_ = 0; | |
3152 | ||
3153 | NSString *string; | |
3154 | NSRange range; | |
3155 | NSUInteger length; | |
3156 | ||
3157 | string = [self name]; | |
3158 | length = [string length]; | |
3159 | ||
3160 | if (length != 0) | |
3161 | for (NSString *term in query) { | |
3162 | range = [string rangeOfString:term options:MatchCompareOptions_]; | |
3163 | if (range.location != NSNotFound) | |
3164 | rank_ -= 6 * 1000000 / length; | |
3165 | } | |
3166 | ||
3167 | if (rank_ == 0) { | |
3168 | string = [self id]; | |
3169 | length = [string length]; | |
3170 | ||
3171 | if (length != 0) | |
3172 | for (NSString *term in query) { | |
3173 | range = [string rangeOfString:term options:MatchCompareOptions_]; | |
3174 | if (range.location != NSNotFound) | |
3175 | rank_ -= 6 * 1000000 / length; | |
3176 | } | |
3177 | } | |
3178 | ||
3179 | string = [self shortDescription]; | |
3180 | length = [string length]; | |
3181 | NSUInteger stop(std::min<NSUInteger>(length, 200)); | |
3182 | ||
3183 | if (length != 0) | |
3184 | for (NSString *term in query) { | |
3185 | range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)]; | |
3186 | if (range.location != NSNotFound) | |
3187 | rank_ -= 2 * 100000; | |
3188 | } | |
3189 | ||
3190 | return rank_ != 0; | |
3191 | } | |
3192 | ||
3193 | - (NSArray *) tags { | |
3194 | return tags_; | |
3195 | } | |
3196 | ||
3197 | - (BOOL) hasTag:(NSString *)tag { | |
3198 | return tags_ == nil ? NO : [tags_ containsObject:tag]; | |
3199 | } | |
3200 | ||
3201 | - (NSString *) primaryPurpose { | |
3202 | for (NSString *tag in (NSArray *) tags_) | |
3203 | if ([tag hasPrefix:@"purpose::"]) | |
3204 | return [tag substringFromIndex:9]; | |
3205 | return nil; | |
3206 | } | |
3207 | ||
3208 | - (NSArray *) purposes { | |
3209 | NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]); | |
3210 | for (NSString *tag in (NSArray *) tags_) | |
3211 | if ([tag hasPrefix:@"purpose::"]) | |
3212 | [purposes addObject:[tag substringFromIndex:9]]; | |
3213 | return [purposes count] == 0 ? nil : purposes; | |
3214 | } | |
3215 | ||
3216 | - (bool) isCommercial { | |
3217 | return [self hasTag:@"cydia::commercial"]; | |
3218 | } | |
3219 | ||
3220 | - (void) setIndex:(size_t)index { | |
3221 | if (metadata_->index_ != index) | |
3222 | metadata_->index_ = index; | |
3223 | } | |
3224 | ||
3225 | - (CYString &) cyname { | |
3226 | return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_; | |
3227 | } | |
3228 | ||
3229 | - (uint32_t) compareBySection:(NSArray *)sections { | |
3230 | NSString *section([self section]); | |
3231 | for (size_t i(0), e([sections count]); i != e; ++i) { | |
3232 | if ([section isEqualToString:[[sections objectAtIndex:i] name]]) | |
3233 | return i; | |
3234 | } | |
3235 | ||
3236 | return _not(uint32_t); | |
3237 | } | |
3238 | ||
3239 | - (void) clear { | |
3240 | @synchronized (database_) { | |
3241 | pkgProblemResolver *resolver = [database_ resolver]; | |
3242 | resolver->Clear(iterator_); | |
3243 | ||
3244 | pkgCacheFile &cache([database_ cache]); | |
3245 | cache->SetReInstall(iterator_, false); | |
3246 | cache->MarkKeep(iterator_, false); | |
3247 | } } | |
3248 | ||
3249 | - (void) install { | |
3250 | @synchronized (database_) { | |
3251 | pkgProblemResolver *resolver = [database_ resolver]; | |
3252 | resolver->Clear(iterator_); | |
3253 | resolver->Protect(iterator_); | |
3254 | ||
3255 | pkgCacheFile &cache([database_ cache]); | |
3256 | cache->SetReInstall(iterator_, false); | |
3257 | cache->MarkInstall(iterator_, false); | |
3258 | ||
3259 | pkgDepCache::StateCache &state((*cache)[iterator_]); | |
3260 | if (!state.Install()) | |
3261 | cache->SetReInstall(iterator_, true); | |
3262 | } } | |
3263 | ||
3264 | - (void) remove { | |
3265 | @synchronized (database_) { | |
3266 | pkgProblemResolver *resolver = [database_ resolver]; | |
3267 | resolver->Clear(iterator_); | |
3268 | resolver->Remove(iterator_); | |
3269 | resolver->Protect(iterator_); | |
3270 | ||
3271 | pkgCacheFile &cache([database_ cache]); | |
3272 | cache->SetReInstall(iterator_, false); | |
3273 | cache->MarkDelete(iterator_, true); | |
3274 | } } | |
3275 | ||
3276 | @end | |
3277 | /* }}} */ | |
3278 | /* Section Class {{{ */ | |
3279 | @interface Section : NSObject { | |
3280 | _H<NSString> name_; | |
3281 | size_t row_; | |
3282 | size_t count_; | |
3283 | _H<NSString> localized_; | |
3284 | } | |
3285 | ||
3286 | - (NSComparisonResult) compareByLocalized:(Section *)section; | |
3287 | - (Section *) initWithName:(NSString *)name localized:(NSString *)localized; | |
3288 | - (Section *) initWithName:(NSString *)name localize:(BOOL)localize; | |
3289 | - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize; | |
3290 | ||
3291 | - (NSString *) name; | |
3292 | - (void) setName:(NSString *)name; | |
3293 | ||
3294 | - (size_t) row; | |
3295 | - (size_t) count; | |
3296 | ||
3297 | - (void) addToRow; | |
3298 | - (void) addToCount; | |
3299 | ||
3300 | - (void) setCount:(size_t)count; | |
3301 | - (NSString *) localized; | |
3302 | ||
3303 | @end | |
3304 | ||
3305 | @implementation Section | |
3306 | ||
3307 | - (NSComparisonResult) compareByLocalized:(Section *)section { | |
3308 | NSString *lhs(localized_); | |
3309 | NSString *rhs([section localized]); | |
3310 | ||
3311 | /*if ([lhs length] != 0 && [rhs length] != 0) { | |
3312 | unichar lhc = [lhs characterAtIndex:0]; | |
3313 | unichar rhc = [rhs characterAtIndex:0]; | |
3314 | ||
3315 | if (isalpha(lhc) && !isalpha(rhc)) | |
3316 | return NSOrderedAscending; | |
3317 | else if (!isalpha(lhc) && isalpha(rhc)) | |
3318 | return NSOrderedDescending; | |
3319 | }*/ | |
3320 | ||
3321 | return [lhs compare:rhs options:LaxCompareOptions_]; | |
3322 | } | |
3323 | ||
3324 | - (Section *) initWithName:(NSString *)name localized:(NSString *)localized { | |
3325 | if ((self = [self initWithName:name localize:NO]) != nil) { | |
3326 | if (localized != nil) | |
3327 | localized_ = localized; | |
3328 | } return self; | |
3329 | } | |
3330 | ||
3331 | - (Section *) initWithName:(NSString *)name localize:(BOOL)localize { | |
3332 | return [self initWithName:name row:0 localize:localize]; | |
3333 | } | |
3334 | ||
3335 | - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize { | |
3336 | if ((self = [super init]) != nil) { | |
3337 | name_ = name; | |
3338 | row_ = row; | |
3339 | if (localize) | |
3340 | localized_ = LocalizeSection(name_); | |
3341 | } return self; | |
3342 | } | |
3343 | ||
3344 | - (NSString *) name { | |
3345 | return name_; | |
3346 | } | |
3347 | ||
3348 | - (void) setName:(NSString *)name { | |
3349 | name_ = name; | |
3350 | } | |
3351 | ||
3352 | - (size_t) row { | |
3353 | return row_; | |
3354 | } | |
3355 | ||
3356 | - (size_t) count { | |
3357 | return count_; | |
3358 | } | |
3359 | ||
3360 | - (void) addToRow { | |
3361 | ++row_; | |
3362 | } | |
3363 | ||
3364 | - (void) addToCount { | |
3365 | ++count_; | |
3366 | } | |
3367 | ||
3368 | - (void) setCount:(size_t)count { | |
3369 | count_ = count; | |
3370 | } | |
3371 | ||
3372 | - (NSString *) localized { | |
3373 | return localized_; | |
3374 | } | |
3375 | ||
3376 | @end | |
3377 | /* }}} */ | |
3378 | ||
3379 | class CydiaLogCleaner : | |
3380 | public pkgArchiveCleaner | |
3381 | { | |
3382 | protected: | |
3383 | virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) { | |
3384 | unlink(File); | |
3385 | } | |
3386 | }; | |
3387 | ||
3388 | /* Database Implementation {{{ */ | |
3389 | @implementation Database | |
3390 | ||
3391 | + (Database *) sharedInstance { | |
3392 | static _H<Database> instance; | |
3393 | if (instance == nil) | |
3394 | instance = [[[Database alloc] init] autorelease]; | |
3395 | return instance; | |
3396 | } | |
3397 | ||
3398 | - (unsigned) era { | |
3399 | return era_; | |
3400 | } | |
3401 | ||
3402 | - (void) releasePackages { | |
3403 | CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL); | |
3404 | CFArrayRemoveAllValues(packages_); | |
3405 | } | |
3406 | ||
3407 | - (void) dealloc { | |
3408 | // XXX: actually implement this thing | |
3409 | _assert(false); | |
3410 | [self releasePackages]; | |
3411 | apr_pool_destroy(pool_); | |
3412 | NSRecycleZone(zone_); | |
3413 | [super dealloc]; | |
3414 | } | |
3415 | ||
3416 | - (void) _readCydia:(NSNumber *)fd { | |
3417 | __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in); | |
3418 | std::istream is(&ib); | |
3419 | std::string line; | |
3420 | ||
3421 | static Pcre finish_r("^finish:([^:]*)$"); | |
3422 | ||
3423 | while (std::getline(is, line)) { | |
3424 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
3425 | ||
3426 | const char *data(line.c_str()); | |
3427 | size_t size = line.size(); | |
3428 | lprintf("C:%s\n", data); | |
3429 | ||
3430 | if (finish_r(data, size)) { | |
3431 | NSString *finish = finish_r[1]; | |
3432 | int index = [Finishes_ indexOfObject:finish]; | |
3433 | if (index != INT_MAX && index > Finish_) | |
3434 | Finish_ = index; | |
3435 | } | |
3436 | ||
3437 | [pool release]; | |
3438 | } | |
3439 | ||
3440 | _assume(false); | |
3441 | } | |
3442 | ||
3443 | - (void) _readStatus:(NSNumber *)fd { | |
3444 | __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in); | |
3445 | std::istream is(&ib); | |
3446 | std::string line; | |
3447 | ||
3448 | static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$"); | |
3449 | static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$"); | |
3450 | ||
3451 | while (std::getline(is, line)) { | |
3452 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
3453 | ||
3454 | const char *data(line.c_str()); | |
3455 | size_t size(line.size()); | |
3456 | lprintf("S:%s\n", data); | |
3457 | ||
3458 | if (conffile_r(data, size)) { | |
3459 | // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1 | |
3460 | [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES]; | |
3461 | } else if (strncmp(data, "status: ", 8) == 0) { | |
3462 | // status: <package>: {unpacked,half-configured,installed} | |
3463 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]); | |
3464 | [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
3465 | } else if (strncmp(data, "processing: ", 12) == 0) { | |
3466 | // processing: configure: config-test | |
3467 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]); | |
3468 | [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
3469 | } else if (pmstatus_r(data, size)) { | |
3470 | std::string type([pmstatus_r[1] UTF8String]); | |
3471 | ||
3472 | NSString *package = pmstatus_r[2]; | |
3473 | if ([package isEqualToString:@"dpkg-exec"]) | |
3474 | package = nil; | |
3475 | ||
3476 | float percent([pmstatus_r[3] floatValue]); | |
3477 | [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES]; | |
3478 | ||
3479 | NSString *string = pmstatus_r[4]; | |
3480 | ||
3481 | if (type == "pmerror") { | |
3482 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]); | |
3483 | [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
3484 | } else if (type == "pmstatus") { | |
3485 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]); | |
3486 | [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
3487 | } else if (type == "pmconffile") | |
3488 | [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES]; | |
3489 | else | |
3490 | lprintf("E:unknown pmstatus\n"); | |
3491 | } else | |
3492 | lprintf("E:unknown status\n"); | |
3493 | ||
3494 | [pool release]; | |
3495 | } | |
3496 | ||
3497 | _assume(false); | |
3498 | } | |
3499 | ||
3500 | - (void) _readOutput:(NSNumber *)fd { | |
3501 | __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in); | |
3502 | std::istream is(&ib); | |
3503 | std::string line; | |
3504 | ||
3505 | while (std::getline(is, line)) { | |
3506 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
3507 | ||
3508 | lprintf("O:%s\n", line.c_str()); | |
3509 | ||
3510 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]); | |
3511 | [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES]; | |
3512 | ||
3513 | [pool release]; | |
3514 | } | |
3515 | ||
3516 | _assume(false); | |
3517 | } | |
3518 | ||
3519 | - (FILE *) input { | |
3520 | return input_; | |
3521 | } | |
3522 | ||
3523 | - (Package *) packageWithName:(NSString *)name { | |
3524 | if (name == nil) | |
3525 | return nil; | |
3526 | @synchronized (self) { | |
3527 | if (static_cast<pkgDepCache *>(cache_) == NULL) | |
3528 | return nil; | |
3529 | pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String])); | |
3530 | return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self]; | |
3531 | } } | |
3532 | ||
3533 | - (id) init { | |
3534 | if ((self = [super init]) != nil) { | |
3535 | policy_ = NULL; | |
3536 | records_ = NULL; | |
3537 | resolver_ = NULL; | |
3538 | fetcher_ = NULL; | |
3539 | lock_ = NULL; | |
3540 | ||
3541 | zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO); | |
3542 | apr_pool_create(&pool_, NULL); | |
3543 | ||
3544 | size_t capacity(MetaFile_->active_); | |
3545 | if (capacity == 0) | |
3546 | capacity = 16384; | |
3547 | else | |
3548 | capacity += 1024; | |
3549 | ||
3550 | packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL); | |
3551 | sourceList_ = [NSMutableArray arrayWithCapacity:16]; | |
3552 | ||
3553 | int fds[2]; | |
3554 | ||
3555 | _assert(pipe(fds) != -1); | |
3556 | cydiafd_ = fds[1]; | |
3557 | ||
3558 | _config->Set("APT::Keep-Fds::", cydiafd_); | |
3559 | setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int)); | |
3560 | ||
3561 | [NSThread | |
3562 | detachNewThreadSelector:@selector(_readCydia:) | |
3563 | toTarget:self | |
3564 | withObject:[NSNumber numberWithInt:fds[0]] | |
3565 | ]; | |
3566 | ||
3567 | _assert(pipe(fds) != -1); | |
3568 | statusfd_ = fds[1]; | |
3569 | ||
3570 | [NSThread | |
3571 | detachNewThreadSelector:@selector(_readStatus:) | |
3572 | toTarget:self | |
3573 | withObject:[NSNumber numberWithInt:fds[0]] | |
3574 | ]; | |
3575 | ||
3576 | _assert(pipe(fds) != -1); | |
3577 | _assert(dup2(fds[0], 0) != -1); | |
3578 | _assert(close(fds[0]) != -1); | |
3579 | ||
3580 | input_ = fdopen(fds[1], "a"); | |
3581 | ||
3582 | _assert(pipe(fds) != -1); | |
3583 | _assert(dup2(fds[1], 1) != -1); | |
3584 | _assert(close(fds[1]) != -1); | |
3585 | ||
3586 | [NSThread | |
3587 | detachNewThreadSelector:@selector(_readOutput:) | |
3588 | toTarget:self | |
3589 | withObject:[NSNumber numberWithInt:fds[0]] | |
3590 | ]; | |
3591 | } return self; | |
3592 | } | |
3593 | ||
3594 | - (pkgCacheFile &) cache { | |
3595 | return cache_; | |
3596 | } | |
3597 | ||
3598 | - (pkgDepCache::Policy *) policy { | |
3599 | return policy_; | |
3600 | } | |
3601 | ||
3602 | - (pkgRecords *) records { | |
3603 | return records_; | |
3604 | } | |
3605 | ||
3606 | - (pkgProblemResolver *) resolver { | |
3607 | return resolver_; | |
3608 | } | |
3609 | ||
3610 | - (pkgAcquire &) fetcher { | |
3611 | return *fetcher_; | |
3612 | } | |
3613 | ||
3614 | - (pkgSourceList &) list { | |
3615 | return *list_; | |
3616 | } | |
3617 | ||
3618 | - (NSArray *) packages { | |
3619 | return (NSArray *) packages_; | |
3620 | } | |
3621 | ||
3622 | - (NSArray *) sources { | |
3623 | return sourceList_; | |
3624 | } | |
3625 | ||
3626 | - (Source *) sourceWithKey:(NSString *)key { | |
3627 | for (Source *source in [self sources]) { | |
3628 | if ([[source key] isEqualToString:key]) | |
3629 | return source; | |
3630 | } return nil; | |
3631 | } | |
3632 | ||
3633 | - (bool) popErrorWithTitle:(NSString *)title { | |
3634 | bool fatal(false); | |
3635 | ||
3636 | while (!_error->empty()) { | |
3637 | std::string error; | |
3638 | bool warning(!_error->PopMessage(error)); | |
3639 | if (!warning) | |
3640 | fatal = true; | |
3641 | ||
3642 | for (;;) { | |
3643 | size_t size(error.size()); | |
3644 | if (size == 0 || error[size - 1] != '\n') | |
3645 | break; | |
3646 | error.resize(size - 1); | |
3647 | } | |
3648 | ||
3649 | lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str()); | |
3650 | ||
3651 | static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$"); | |
3652 | if (warning && no_pubkey(error.c_str())) | |
3653 | continue; | |
3654 | ||
3655 | [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title]; | |
3656 | } | |
3657 | ||
3658 | return fatal; | |
3659 | } | |
3660 | ||
3661 | - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success { | |
3662 | return [self popErrorWithTitle:title] || !success; | |
3663 | } | |
3664 | ||
3665 | - (void) reloadDataWithInvocation:(NSInvocation *)invocation { | |
3666 | @synchronized (self) { | |
3667 | ++era_; | |
3668 | ||
3669 | [self releasePackages]; | |
3670 | ||
3671 | sourceMap_.clear(); | |
3672 | [sourceList_ removeAllObjects]; | |
3673 | ||
3674 | _error->Discard(); | |
3675 | ||
3676 | delete list_; | |
3677 | list_ = NULL; | |
3678 | manager_ = NULL; | |
3679 | delete lock_; | |
3680 | lock_ = NULL; | |
3681 | delete fetcher_; | |
3682 | fetcher_ = NULL; | |
3683 | delete resolver_; | |
3684 | resolver_ = NULL; | |
3685 | delete records_; | |
3686 | records_ = NULL; | |
3687 | delete policy_; | |
3688 | policy_ = NULL; | |
3689 | ||
3690 | cache_.Close(); | |
3691 | ||
3692 | apr_pool_clear(pool_); | |
3693 | ||
3694 | NSRecycleZone(zone_); | |
3695 | zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO); | |
3696 | ||
3697 | int chk(creat("/tmp/cydia.chk", 0644)); | |
3698 | if (chk != -1) | |
3699 | close(chk); | |
3700 | ||
3701 | if (invocation != nil) | |
3702 | [invocation invoke]; | |
3703 | ||
3704 | NSString *title(UCLocalize("DATABASE")); | |
3705 | ||
3706 | list_ = new pkgSourceList(); | |
3707 | _profile(reloadDataWithInvocation$ReadMainList) | |
3708 | if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()]) | |
3709 | return; | |
3710 | _end | |
3711 | ||
3712 | _profile(reloadDataWithInvocation$Source$initWithMetaIndex) | |
3713 | for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) { | |
3714 | Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]); | |
3715 | [sourceList_ addObject:object]; | |
3716 | } | |
3717 | _end | |
3718 | ||
3719 | _trace(); | |
3720 | OpProgress progress; | |
3721 | bool opened; | |
3722 | open: | |
3723 | _profile(reloadDataWithInvocation$pkgCacheFile) | |
3724 | opened = cache_.Open(progress, true); | |
3725 | _end | |
3726 | if (!opened) { | |
3727 | // XXX: what if there are errors, but Open() == true? this should be merged with popError: | |
3728 | while (!_error->empty()) { | |
3729 | std::string error; | |
3730 | bool warning(!_error->PopMessage(error)); | |
3731 | ||
3732 | lprintf("cache_.Open():[%s]\n", error.c_str()); | |
3733 | ||
3734 | [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title]; | |
3735 | ||
3736 | SEL repair(NULL); | |
3737 | if (false); | |
3738 | else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ") | |
3739 | repair = @selector(configure); | |
3740 | //else if (error == "The package lists or status file could not be parsed or opened.") | |
3741 | // repair = @selector(update); | |
3742 | // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)") | |
3743 | // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)") | |
3744 | // else if (error == "Malformed Status line") | |
3745 | // else if (error == "The list of sources could not be read.") | |
3746 | ||
3747 | if (repair != NULL) { | |
3748 | _error->Discard(); | |
3749 | [delegate_ repairWithSelector:repair]; | |
3750 | goto open; | |
3751 | } | |
3752 | } | |
3753 | ||
3754 | return; | |
3755 | } | |
3756 | _trace(); | |
3757 | ||
3758 | unlink("/tmp/cydia.chk"); | |
3759 | ||
3760 | now_ = [[NSDate date] timeIntervalSince1970]; | |
3761 | ||
3762 | policy_ = new pkgDepCache::Policy(); | |
3763 | records_ = new pkgRecords(cache_); | |
3764 | resolver_ = new pkgProblemResolver(cache_); | |
3765 | fetcher_ = new pkgAcquire(&status_); | |
3766 | lock_ = NULL; | |
3767 | ||
3768 | if (cache_->DelCount() != 0 || cache_->InstCount() != 0) { | |
3769 | [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title]; | |
3770 | return; | |
3771 | } | |
3772 | ||
3773 | _profile(reloadDataWithInvocation$pkgApplyStatus) | |
3774 | if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)]) | |
3775 | return; | |
3776 | _end | |
3777 | ||
3778 | if (cache_->BrokenCount() != 0) { | |
3779 | _profile(pkgApplyStatus$pkgFixBroken) | |
3780 | if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)]) | |
3781 | return; | |
3782 | _end | |
3783 | ||
3784 | if (cache_->BrokenCount() != 0) { | |
3785 | [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title]; | |
3786 | return; | |
3787 | } | |
3788 | ||
3789 | _profile(pkgApplyStatus$pkgMinimizeUpgrade) | |
3790 | if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)]) | |
3791 | return; | |
3792 | _end | |
3793 | } | |
3794 | ||
3795 | for (Source *object in (id) sourceList_) { | |
3796 | metaIndex *source([object metaIndex]); | |
3797 | std::vector<pkgIndexFile *> *indices = source->GetIndexFiles(); | |
3798 | for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index) | |
3799 | // XXX: this could be more intelligent | |
3800 | if (dynamic_cast<debPackagesIndex *>(*index) != NULL) { | |
3801 | pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_)); | |
3802 | if (!cached.end()) | |
3803 | sourceMap_[cached->ID] = object; | |
3804 | } | |
3805 | } | |
3806 | ||
3807 | { | |
3808 | /*std::vector<Package *> packages; | |
3809 | packages.reserve(std::max(10000U, [packages_ count] + 1000)); | |
3810 | packages_ = nil;*/ | |
3811 | ||
3812 | _profile(reloadDataWithInvocation$packageWithIterator) | |
3813 | for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator) | |
3814 | if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self]) | |
3815 | //packages.push_back(package); | |
3816 | CFArrayAppendValue(packages_, CFRetain(package)); | |
3817 | _end | |
3818 | ||
3819 | ||
3820 | /*if (packages.empty()) | |
3821 | packages_ = [[NSArray alloc] init]; | |
3822 | else | |
3823 | packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()]; | |
3824 | _trace();*/ | |
3825 | ||
3826 | _profile(reloadDataWithInvocation$radix$8) | |
3827 | [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)]; | |
3828 | _end | |
3829 | ||
3830 | _profile(reloadDataWithInvocation$radix$4) | |
3831 | [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)]; | |
3832 | _end | |
3833 | ||
3834 | _profile(reloadDataWithInvocation$radix$0) | |
3835 | [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)]; | |
3836 | _end | |
3837 | ||
3838 | _profile(reloadDataWithInvocation$insertion) | |
3839 | CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL); | |
3840 | _end | |
3841 | ||
3842 | /*_profile(reloadDataWithInvocation$CFQSortArray) | |
3843 | CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL); | |
3844 | _end*/ | |
3845 | ||
3846 | /*_profile(reloadDataWithInvocation$stdsort) | |
3847 | std::sort(packages.begin(), packages.end(), PackageNameOrdering()); | |
3848 | _end*/ | |
3849 | ||
3850 | /*_profile(reloadDataWithInvocation$CFArraySortValues) | |
3851 | CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL); | |
3852 | _end*/ | |
3853 | ||
3854 | /*_profile(reloadDataWithInvocation$sortUsingFunction) | |
3855 | [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL]; | |
3856 | _end*/ | |
3857 | ||
3858 | ||
3859 | size_t count(CFArrayGetCount(packages_)); | |
3860 | MetaFile_->active_ = count; | |
3861 | for (size_t index(0); index != count; ++index) | |
3862 | [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index]; | |
3863 | } | |
3864 | } } | |
3865 | ||
3866 | - (void) clear { | |
3867 | @synchronized (self) { | |
3868 | delete resolver_; | |
3869 | resolver_ = new pkgProblemResolver(cache_); | |
3870 | ||
3871 | for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) | |
3872 | if (!cache_[iterator].Keep()) | |
3873 | cache_->MarkKeep(iterator, false); | |
3874 | else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0) | |
3875 | cache_->SetReInstall(iterator, false); | |
3876 | } } | |
3877 | ||
3878 | - (void) configure { | |
3879 | NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_]; | |
3880 | _trace(); | |
3881 | system([dpkg UTF8String]); | |
3882 | _trace(); | |
3883 | } | |
3884 | ||
3885 | - (bool) clean { | |
3886 | @synchronized (self) { | |
3887 | // XXX: I don't remember this condition | |
3888 | if (lock_ != NULL) | |
3889 | return false; | |
3890 | ||
3891 | FileFd Lock; | |
3892 | Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock")); | |
3893 | ||
3894 | NSString *title(UCLocalize("CLEAN_ARCHIVES")); | |
3895 | ||
3896 | if ([self popErrorWithTitle:title]) | |
3897 | return false; | |
3898 | ||
3899 | pkgAcquire fetcher; | |
3900 | fetcher.Clean(_config->FindDir("Dir::Cache::Archives")); | |
3901 | ||
3902 | CydiaLogCleaner cleaner; | |
3903 | if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)]) | |
3904 | return false; | |
3905 | ||
3906 | return true; | |
3907 | } } | |
3908 | ||
3909 | - (bool) prepare { | |
3910 | fetcher_->Shutdown(); | |
3911 | ||
3912 | pkgRecords records(cache_); | |
3913 | ||
3914 | lock_ = new FileFd(); | |
3915 | lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock")); | |
3916 | ||
3917 | NSString *title(UCLocalize("PREPARE_ARCHIVES")); | |
3918 | ||
3919 | if ([self popErrorWithTitle:title]) | |
3920 | return false; | |
3921 | ||
3922 | pkgSourceList list; | |
3923 | if ([self popErrorWithTitle:title forOperation:list.ReadMainList()]) | |
3924 | return false; | |
3925 | ||
3926 | manager_ = (_system->CreatePM(cache_)); | |
3927 | if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)]) | |
3928 | return false; | |
3929 | ||
3930 | return true; | |
3931 | } | |
3932 | ||
3933 | - (void) perform { | |
3934 | bool substrate(RestartSubstrate_); | |
3935 | RestartSubstrate_ = false; | |
3936 | ||
3937 | NSString *title(UCLocalize("PERFORM_SELECTIONS")); | |
3938 | ||
3939 | NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; { | |
3940 | pkgSourceList list; | |
3941 | if ([self popErrorWithTitle:title forOperation:list.ReadMainList()]) | |
3942 | return; | |
3943 | for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source) | |
3944 | [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]]; | |
3945 | } | |
3946 | ||
3947 | [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES]; | |
3948 | ||
3949 | if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) { | |
3950 | _trace(); | |
3951 | [self popErrorWithTitle:title]; | |
3952 | return; | |
3953 | } | |
3954 | ||
3955 | bool failed = false; | |
3956 | for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) { | |
3957 | if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete) | |
3958 | continue; | |
3959 | if ((*item)->Status == pkgAcquire::Item::StatIdle) | |
3960 | continue; | |
3961 | ||
3962 | std::string uri = (*item)->DescURI(); | |
3963 | std::string error = (*item)->ErrorText; | |
3964 | ||
3965 | lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str()); | |
3966 | failed = true; | |
3967 | ||
3968 | CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]); | |
3969 | [delegate_ addProgressEventOnMainThread:event forTask:title]; | |
3970 | } | |
3971 | ||
3972 | [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES]; | |
3973 | ||
3974 | if (failed) { | |
3975 | _trace(); | |
3976 | return; | |
3977 | } | |
3978 | ||
3979 | if (substrate) | |
3980 | RestartSubstrate_ = true; | |
3981 | ||
3982 | _system->UnLock(); | |
3983 | pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_); | |
3984 | if ([self popErrorWithTitle:title]) | |
3985 | return; | |
3986 | ||
3987 | if (result == pkgPackageManager::Failed) { | |
3988 | _trace(); | |
3989 | return; | |
3990 | } | |
3991 | ||
3992 | if (result != pkgPackageManager::Completed) { | |
3993 | _trace(); | |
3994 | return; | |
3995 | } | |
3996 | ||
3997 | NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; { | |
3998 | pkgSourceList list; | |
3999 | if ([self popErrorWithTitle:title forOperation:list.ReadMainList()]) | |
4000 | return; | |
4001 | for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source) | |
4002 | [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]]; | |
4003 | } | |
4004 | ||
4005 | if (![before isEqualToArray:after]) | |
4006 | [self update]; | |
4007 | } | |
4008 | ||
4009 | - (bool) upgrade { | |
4010 | NSString *title(UCLocalize("UPGRADE")); | |
4011 | if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)]) | |
4012 | return false; | |
4013 | return true; | |
4014 | } | |
4015 | ||
4016 | - (void) update { | |
4017 | [self updateWithStatus:status_]; | |
4018 | } | |
4019 | ||
4020 | - (void) updateWithStatus:(CancelStatus &)status { | |
4021 | NSString *title(UCLocalize("REFRESHING_DATA")); | |
4022 | ||
4023 | pkgSourceList list; | |
4024 | if ([self popErrorWithTitle:title forOperation:list.ReadMainList()]) | |
4025 | return; | |
4026 | ||
4027 | FileFd lock; | |
4028 | lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock")); | |
4029 | if ([self popErrorWithTitle:title]) | |
4030 | return; | |
4031 | ||
4032 | [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES]; | |
4033 | ||
4034 | bool success(ListUpdate(status, list, PulseInterval_)); | |
4035 | if (status.WasCancelled()) | |
4036 | _error->Discard(); | |
4037 | else { | |
4038 | [self popErrorWithTitle:title forOperation:success]; | |
4039 | [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"]; | |
4040 | Changed_ = true; | |
4041 | } | |
4042 | ||
4043 | [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES]; | |
4044 | } | |
4045 | ||
4046 | - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate { | |
4047 | delegate_ = delegate; | |
4048 | } | |
4049 | ||
4050 | - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate { | |
4051 | progress_ = delegate; | |
4052 | status_.setDelegate(delegate); | |
4053 | } | |
4054 | ||
4055 | - (NSObject<ProgressDelegate> *) progressDelegate { | |
4056 | return progress_; | |
4057 | } | |
4058 | ||
4059 | - (Source *) getSource:(pkgCache::PkgFileIterator)file { | |
4060 | SourceMap::const_iterator i(sourceMap_.find(file->ID)); | |
4061 | return i == sourceMap_.end() ? nil : i->second; | |
4062 | } | |
4063 | ||
4064 | - (void) setFetch:(bool)fetch forURI:(const char *)uri { | |
4065 | for (Source *source in (id) sourceList_) | |
4066 | [source setFetch:fetch forURI:uri]; | |
4067 | } | |
4068 | ||
4069 | - (void) resetFetch { | |
4070 | for (Source *source in (id) sourceList_) | |
4071 | [source resetFetch]; | |
4072 | } | |
4073 | ||
4074 | - (NSString *) mappedSectionForPointer:(const char *)section { | |
4075 | _H<NSString> *mapped; | |
4076 | ||
4077 | _profile(Database$mappedSectionForPointer$Cache) | |
4078 | mapped = §ions_[section]; | |
4079 | _end | |
4080 | ||
4081 | if (*mapped == NULL) { | |
4082 | size_t length(strlen(section)); | |
4083 | char spaced[length + 1]; | |
4084 | ||
4085 | _profile(Database$mappedSectionForPointer$Replace) | |
4086 | for (size_t index(0); index != length; ++index) | |
4087 | spaced[index] = section[index] == '_' ? ' ' : section[index]; | |
4088 | spaced[length] = '\0'; | |
4089 | _end | |
4090 | ||
4091 | NSString *string; | |
4092 | ||
4093 | _profile(Database$mappedSectionForPointer$stringWithUTF8String) | |
4094 | string = [NSString stringWithUTF8String:spaced]; | |
4095 | _end | |
4096 | ||
4097 | _profile(Database$mappedSectionForPointer$Map) | |
4098 | string = [SectionMap_ objectForKey:string] ?: string; | |
4099 | _end | |
4100 | ||
4101 | *mapped = string; | |
4102 | } return *mapped; | |
4103 | } | |
4104 | ||
4105 | @end | |
4106 | /* }}} */ | |
4107 | ||
4108 | static _H<NSMutableSet> Diversions_; | |
4109 | ||
4110 | @interface Diversion : NSObject { | |
4111 | Pcre pattern_; | |
4112 | _H<NSString> key_; | |
4113 | _H<NSString> format_; | |
4114 | } | |
4115 | ||
4116 | @end | |
4117 | ||
4118 | @implementation Diversion | |
4119 | ||
4120 | - (id) initWithFrom:(NSString *)from to:(NSString *)to { | |
4121 | if ((self = [super init]) != nil) { | |
4122 | pattern_ = [from UTF8String]; | |
4123 | key_ = from; | |
4124 | format_ = to; | |
4125 | } return self; | |
4126 | } | |
4127 | ||
4128 | - (NSString *) divert:(NSString *)url { | |
4129 | return !pattern_(url) ? nil : pattern_->*format_; | |
4130 | } | |
4131 | ||
4132 | + (NSURL *) divertURL:(NSURL *)url { | |
4133 | divert: | |
4134 | NSString *href([url absoluteString]); | |
4135 | ||
4136 | for (Diversion *diversion in (id) Diversions_) | |
4137 | if (NSString *diverted = [diversion divert:href]) { | |
4138 | #if !ForRelease | |
4139 | NSLog(@"div: %@", diverted); | |
4140 | #endif | |
4141 | url = [NSURL URLWithString:diverted]; | |
4142 | goto divert; | |
4143 | } | |
4144 | ||
4145 | return url; | |
4146 | } | |
4147 | ||
4148 | - (NSString *) key { | |
4149 | return key_; | |
4150 | } | |
4151 | ||
4152 | - (NSUInteger) hash { | |
4153 | return [key_ hash]; | |
4154 | } | |
4155 | ||
4156 | - (BOOL) isEqual:(Diversion *)object { | |
4157 | return self == object || [self class] == [object class] && [key_ isEqual:[object key]]; | |
4158 | } | |
4159 | ||
4160 | @end | |
4161 | ||
4162 | @interface CydiaObject : NSObject { | |
4163 | _H<CyteWebViewController> indirect_; | |
4164 | _transient id delegate_; | |
4165 | } | |
4166 | ||
4167 | - (id) initWithDelegate:(IndirectDelegate *)indirect; | |
4168 | ||
4169 | @end | |
4170 | ||
4171 | @class CydiaObject; | |
4172 | ||
4173 | @interface CydiaWebViewController : CyteWebViewController { | |
4174 | _H<CydiaObject> cydia_; | |
4175 | } | |
4176 | ||
4177 | + (void) addDiversion:(Diversion *)diversion; | |
4178 | + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request; | |
4179 | + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia; | |
4180 | - (void) setDelegate:(id)delegate; | |
4181 | ||
4182 | @end | |
4183 | ||
4184 | /* Web Scripting {{{ */ | |
4185 | @implementation CydiaObject | |
4186 | ||
4187 | - (id) initWithDelegate:(IndirectDelegate *)indirect { | |
4188 | if ((self = [super init]) != nil) { | |
4189 | indirect_ = (CyteWebViewController *) indirect; | |
4190 | } return self; | |
4191 | } | |
4192 | ||
4193 | - (void) setDelegate:(id)delegate { | |
4194 | delegate_ = delegate; | |
4195 | } | |
4196 | ||
4197 | + (NSArray *) _attributeKeys { | |
4198 | return [NSArray arrayWithObjects: | |
4199 | @"bbsnum", | |
4200 | @"build", | |
4201 | @"coreFoundationVersionNumber", | |
4202 | @"device", | |
4203 | @"ecid", | |
4204 | @"firmware", | |
4205 | @"hostname", | |
4206 | @"idiom", | |
4207 | @"mcc", | |
4208 | @"mnc", | |
4209 | @"model", | |
4210 | @"operator", | |
4211 | @"role", | |
4212 | @"serial", | |
4213 | @"token", | |
4214 | @"version", | |
4215 | nil]; | |
4216 | } | |
4217 | ||
4218 | - (NSArray *) attributeKeys { | |
4219 | return [[self class] _attributeKeys]; | |
4220 | } | |
4221 | ||
4222 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
4223 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
4224 | } | |
4225 | ||
4226 | - (NSString *) version { | |
4227 | return Cydia_; | |
4228 | } | |
4229 | ||
4230 | - (NSString *) build { | |
4231 | return System_; | |
4232 | } | |
4233 | ||
4234 | - (NSString *) coreFoundationVersionNumber { | |
4235 | return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber]; | |
4236 | } | |
4237 | ||
4238 | - (NSString *) device { | |
4239 | return UniqueIdentifier(); | |
4240 | } | |
4241 | ||
4242 | - (NSString *) firmware { | |
4243 | return [[UIDevice currentDevice] systemVersion]; | |
4244 | } | |
4245 | ||
4246 | - (NSString *) hostname { | |
4247 | return [[UIDevice currentDevice] name]; | |
4248 | } | |
4249 | ||
4250 | - (NSString *) idiom { | |
4251 | return (id) Idiom_ ?: [NSNull null]; | |
4252 | } | |
4253 | ||
4254 | - (NSString *) mcc { | |
4255 | if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"))) | |
4256 | return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease]; | |
4257 | return nil; | |
4258 | } | |
4259 | ||
4260 | - (NSString *) mnc { | |
4261 | if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode"))) | |
4262 | return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease]; | |
4263 | return nil; | |
4264 | } | |
4265 | ||
4266 | - (NSString *) operator { | |
4267 | if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName"))) | |
4268 | return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease]; | |
4269 | return nil; | |
4270 | } | |
4271 | ||
4272 | - (NSString *) bbsnum { | |
4273 | return (id) BBSNum_ ?: [NSNull null]; | |
4274 | } | |
4275 | ||
4276 | - (NSString *) ecid { | |
4277 | return (id) ChipID_ ?: [NSNull null]; | |
4278 | } | |
4279 | ||
4280 | - (NSString *) serial { | |
4281 | return SerialNumber_; | |
4282 | } | |
4283 | ||
4284 | - (NSString *) role { | |
4285 | return (id) [NSNull null]; | |
4286 | } | |
4287 | ||
4288 | - (NSString *) model { | |
4289 | return [NSString stringWithUTF8String:Machine_]; | |
4290 | } | |
4291 | ||
4292 | - (NSString *) token { | |
4293 | return (id) Token_ ?: [NSNull null]; | |
4294 | } | |
4295 | ||
4296 | + (NSString *) webScriptNameForSelector:(SEL)selector { | |
4297 | if (false); | |
4298 | else if (selector == @selector(addBridgedHost:)) | |
4299 | return @"addBridgedHost"; | |
4300 | else if (selector == @selector(addInsecureHost:)) | |
4301 | return @"addInsecureHost"; | |
4302 | else if (selector == @selector(addInternalRedirect::)) | |
4303 | return @"addInternalRedirect"; | |
4304 | else if (selector == @selector(addPipelinedHost:scheme:)) | |
4305 | return @"addPipelinedHost"; | |
4306 | else if (selector == @selector(addSource:::)) | |
4307 | return @"addSource"; | |
4308 | else if (selector == @selector(addTokenHost:)) | |
4309 | return @"addTokenHost"; | |
4310 | else if (selector == @selector(addTrivialSource:)) | |
4311 | return @"addTrivialSource"; | |
4312 | else if (selector == @selector(close)) | |
4313 | return @"close"; | |
4314 | else if (selector == @selector(du:)) | |
4315 | return @"du"; | |
4316 | else if (selector == @selector(stringWithFormat:arguments:)) | |
4317 | return @"format"; | |
4318 | else if (selector == @selector(getAllSources)) | |
4319 | return @"getAllSources"; | |
4320 | else if (selector == @selector(getApplicationInfo:value:)) | |
4321 | return @"getApplicationInfoValue"; | |
4322 | else if (selector == @selector(getKernelNumber:)) | |
4323 | return @"getKernelNumber"; | |
4324 | else if (selector == @selector(getKernelString:)) | |
4325 | return @"getKernelString"; | |
4326 | else if (selector == @selector(getInstalledPackages)) | |
4327 | return @"getInstalledPackages"; | |
4328 | else if (selector == @selector(getIORegistryEntry::)) | |
4329 | return @"getIORegistryEntry"; | |
4330 | else if (selector == @selector(getLocaleIdentifier)) | |
4331 | return @"getLocaleIdentifier"; | |
4332 | else if (selector == @selector(getPreferredLanguages)) | |
4333 | return @"getPreferredLanguages"; | |
4334 | else if (selector == @selector(getPackageById:)) | |
4335 | return @"getPackageById"; | |
4336 | else if (selector == @selector(getMetadataKeys)) | |
4337 | return @"getMetadataKeys"; | |
4338 | else if (selector == @selector(getMetadataValue:)) | |
4339 | return @"getMetadataValue"; | |
4340 | else if (selector == @selector(getSessionValue:)) | |
4341 | return @"getSessionValue"; | |
4342 | else if (selector == @selector(installPackages:)) | |
4343 | return @"installPackages"; | |
4344 | else if (selector == @selector(isReachable:)) | |
4345 | return @"isReachable"; | |
4346 | else if (selector == @selector(localizedStringForKey:value:table:)) | |
4347 | return @"localize"; | |
4348 | else if (selector == @selector(popViewController:)) | |
4349 | return @"popViewController"; | |
4350 | else if (selector == @selector(refreshSources)) | |
4351 | return @"refreshSources"; | |
4352 | else if (selector == @selector(registerFrame:)) | |
4353 | return @"registerFrame"; | |
4354 | else if (selector == @selector(removeButton)) | |
4355 | return @"removeButton"; | |
4356 | else if (selector == @selector(saveConfig)) | |
4357 | return @"saveConfig"; | |
4358 | else if (selector == @selector(setMetadataValue::)) | |
4359 | return @"setMetadataValue"; | |
4360 | else if (selector == @selector(setSessionValue::)) | |
4361 | return @"setSessionValue"; | |
4362 | else if (selector == @selector(substitutePackageNames:)) | |
4363 | return @"substitutePackageNames"; | |
4364 | else if (selector == @selector(scrollToBottom:)) | |
4365 | return @"scrollToBottom"; | |
4366 | else if (selector == @selector(setAllowsNavigationAction:)) | |
4367 | return @"setAllowsNavigationAction"; | |
4368 | else if (selector == @selector(setBadgeValue:)) | |
4369 | return @"setBadgeValue"; | |
4370 | else if (selector == @selector(setButtonImage:withStyle:toFunction:)) | |
4371 | return @"setButtonImage"; | |
4372 | else if (selector == @selector(setButtonTitle:withStyle:toFunction:)) | |
4373 | return @"setButtonTitle"; | |
4374 | else if (selector == @selector(setHidesBackButton:)) | |
4375 | return @"setHidesBackButton"; | |
4376 | else if (selector == @selector(setHidesNavigationBar:)) | |
4377 | return @"setHidesNavigationBar"; | |
4378 | else if (selector == @selector(setNavigationBarStyle:)) | |
4379 | return @"setNavigationBarStyle"; | |
4380 | else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:)) | |
4381 | return @"setNavigationBarTintColor"; | |
4382 | else if (selector == @selector(setPasteboardString:)) | |
4383 | return @"setPasteboardString"; | |
4384 | else if (selector == @selector(setPasteboardURL:)) | |
4385 | return @"setPasteboardURL"; | |
4386 | else if (selector == @selector(setScrollAlwaysBounceVertical:)) | |
4387 | return @"setScrollAlwaysBounceVertical"; | |
4388 | else if (selector == @selector(setScrollIndicatorStyle:)) | |
4389 | return @"setScrollIndicatorStyle"; | |
4390 | else if (selector == @selector(setToken:)) | |
4391 | return @"setToken"; | |
4392 | else if (selector == @selector(setViewportWidth:)) | |
4393 | return @"setViewportWidth"; | |
4394 | else if (selector == @selector(statfs:)) | |
4395 | return @"statfs"; | |
4396 | else if (selector == @selector(supports:)) | |
4397 | return @"supports"; | |
4398 | else if (selector == @selector(unload)) | |
4399 | return @"unload"; | |
4400 | else | |
4401 | return nil; | |
4402 | } | |
4403 | ||
4404 | + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector { | |
4405 | return [self webScriptNameForSelector:selector] == nil; | |
4406 | } | |
4407 | ||
4408 | - (BOOL) supports:(NSString *)feature { | |
4409 | return [feature isEqualToString:@"window.open"]; | |
4410 | } | |
4411 | ||
4412 | - (void) unload { | |
4413 | [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO]; | |
4414 | } | |
4415 | ||
4416 | - (void) setScrollAlwaysBounceVertical:(NSNumber *)value { | |
4417 | [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO]; | |
4418 | } | |
4419 | ||
4420 | - (void) setScrollIndicatorStyle:(NSString *)style { | |
4421 | [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO]; | |
4422 | } | |
4423 | ||
4424 | - (void) addInternalRedirect:(NSString *)from :(NSString *)to { | |
4425 | [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO]; | |
4426 | } | |
4427 | ||
4428 | - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key { | |
4429 | char path[1024]; | |
4430 | if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0) | |
4431 | return (id) [NSNull null]; | |
4432 | NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]); | |
4433 | if (info == nil) | |
4434 | return (id) [NSNull null]; | |
4435 | return [info objectForKey:key]; | |
4436 | } | |
4437 | ||
4438 | - (NSNumber *) getKernelNumber:(NSString *)name { | |
4439 | const char *string([name UTF8String]); | |
4440 | ||
4441 | size_t size; | |
4442 | if (sysctlbyname(string, NULL, &size, NULL, 0) == -1) | |
4443 | return (id) [NSNull null]; | |
4444 | ||
4445 | if (size != sizeof(int)) | |
4446 | return (id) [NSNull null]; | |
4447 | ||
4448 | int value; | |
4449 | if (sysctlbyname(string, &value, &size, NULL, 0) == -1) | |
4450 | return (id) [NSNull null]; | |
4451 | ||
4452 | return [NSNumber numberWithInt:value]; | |
4453 | } | |
4454 | ||
4455 | - (NSString *) getKernelString:(NSString *)name { | |
4456 | const char *string([name UTF8String]); | |
4457 | ||
4458 | size_t size; | |
4459 | if (sysctlbyname(string, NULL, &size, NULL, 0) == -1) | |
4460 | return (id) [NSNull null]; | |
4461 | ||
4462 | char value[size + 1]; | |
4463 | if (sysctlbyname(string, value, &size, NULL, 0) == -1) | |
4464 | return (id) [NSNull null]; | |
4465 | ||
4466 | // XXX: just in case you request something ludicrous | |
4467 | value[size] = '\0'; | |
4468 | ||
4469 | return [NSString stringWithCString:value]; | |
4470 | } | |
4471 | ||
4472 | - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry { | |
4473 | NSObject *value(CYIOGetValue([path UTF8String], entry)); | |
4474 | ||
4475 | if (value != nil) | |
4476 | if ([value isKindOfClass:[NSData class]]) | |
4477 | value = CYHex((NSData *) value); | |
4478 | ||
4479 | return value; | |
4480 | } | |
4481 | ||
4482 | - (NSArray *) getMetadataKeys { | |
4483 | @synchronized (Values_) { | |
4484 | return [Values_ allKeys]; | |
4485 | } } | |
4486 | ||
4487 | - (void) registerFrame:(DOMHTMLIFrameElement *)iframe { | |
4488 | WebFrame *frame([iframe contentFrame]); | |
4489 | [indirect_ registerFrame:frame]; | |
4490 | } | |
4491 | ||
4492 | - (id) getMetadataValue:(NSString *)key { | |
4493 | @synchronized (Values_) { | |
4494 | return [Values_ objectForKey:key]; | |
4495 | } } | |
4496 | ||
4497 | - (void) setMetadataValue:(NSString *)key :(NSString *)value { | |
4498 | @synchronized (Values_) { | |
4499 | if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null]) | |
4500 | [Values_ removeObjectForKey:key]; | |
4501 | else | |
4502 | [Values_ setObject:value forKey:key]; | |
4503 | ||
4504 | [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES]; | |
4505 | } } | |
4506 | ||
4507 | - (id) getSessionValue:(NSString *)key { | |
4508 | @synchronized (SessionData_) { | |
4509 | return [SessionData_ objectForKey:key]; | |
4510 | } } | |
4511 | ||
4512 | - (void) setSessionValue:(NSString *)key :(NSString *)value { | |
4513 | @synchronized (SessionData_) { | |
4514 | if (value == (id) [WebUndefined undefined]) | |
4515 | [SessionData_ removeObjectForKey:key]; | |
4516 | else | |
4517 | [SessionData_ setObject:value forKey:key]; | |
4518 | } } | |
4519 | ||
4520 | - (void) addBridgedHost:(NSString *)host { | |
4521 | @synchronized (HostConfig_) { | |
4522 | [BridgedHosts_ addObject:host]; | |
4523 | } } | |
4524 | ||
4525 | - (void) addInsecureHost:(NSString *)host { | |
4526 | @synchronized (HostConfig_) { | |
4527 | [InsecureHosts_ addObject:host]; | |
4528 | } } | |
4529 | ||
4530 | - (void) addTokenHost:(NSString *)host { | |
4531 | @synchronized (HostConfig_) { | |
4532 | [TokenHosts_ addObject:host]; | |
4533 | } } | |
4534 | ||
4535 | - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme { | |
4536 | @synchronized (HostConfig_) { | |
4537 | if (scheme != (id) [WebUndefined undefined]) | |
4538 | host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host]; | |
4539 | ||
4540 | [PipelinedHosts_ addObject:host]; | |
4541 | } } | |
4542 | ||
4543 | - (void) popViewController:(NSNumber *)value { | |
4544 | if (value == (id) [WebUndefined undefined]) | |
4545 | value = [NSNumber numberWithBool:YES]; | |
4546 | [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO]; | |
4547 | } | |
4548 | ||
4549 | - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections { | |
4550 | NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]); | |
4551 | ||
4552 | for (NSString *section in sections) | |
4553 | [array addObject:section]; | |
4554 | ||
4555 | [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys: | |
4556 | @"deb", @"Type", | |
4557 | href, @"URI", | |
4558 | distribution, @"Distribution", | |
4559 | array, @"Sections", | |
4560 | nil] waitUntilDone:NO]; | |
4561 | } | |
4562 | ||
4563 | - (void) addTrivialSource:(NSString *)href { | |
4564 | [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO]; | |
4565 | } | |
4566 | ||
4567 | - (void) refreshSources { | |
4568 | [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO]; | |
4569 | } | |
4570 | ||
4571 | - (void) saveConfig { | |
4572 | [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO]; | |
4573 | } | |
4574 | ||
4575 | - (NSArray *) getAllSources { | |
4576 | return [[Database sharedInstance] sources]; | |
4577 | } | |
4578 | ||
4579 | - (NSArray *) getInstalledPackages { | |
4580 | Database *database([Database sharedInstance]); | |
4581 | @synchronized (database) { | |
4582 | NSArray *packages([database packages]); | |
4583 | NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]); | |
4584 | for (Package *package in packages) | |
4585 | if (![package uninstalled]) | |
4586 | [installed addObject:package]; | |
4587 | return installed; | |
4588 | } } | |
4589 | ||
4590 | - (Package *) getPackageById:(NSString *)id { | |
4591 | if (Package *package = [[Database sharedInstance] packageWithName:id]) { | |
4592 | [package parse]; | |
4593 | return package; | |
4594 | } else | |
4595 | return (Package *) [NSNull null]; | |
4596 | } | |
4597 | ||
4598 | - (NSString *) getLocaleIdentifier { | |
4599 | return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_); | |
4600 | } | |
4601 | ||
4602 | - (NSArray *) getPreferredLanguages { | |
4603 | return Languages_; | |
4604 | } | |
4605 | ||
4606 | - (NSArray *) statfs:(NSString *)path { | |
4607 | struct statfs stat; | |
4608 | ||
4609 | if (path == nil || statfs([path UTF8String], &stat) == -1) | |
4610 | return nil; | |
4611 | ||
4612 | return [NSArray arrayWithObjects: | |
4613 | [NSNumber numberWithUnsignedLong:stat.f_bsize], | |
4614 | [NSNumber numberWithUnsignedLong:stat.f_blocks], | |
4615 | [NSNumber numberWithUnsignedLong:stat.f_bfree], | |
4616 | nil]; | |
4617 | } | |
4618 | ||
4619 | - (NSNumber *) du:(NSString *)path { | |
4620 | NSNumber *value(nil); | |
4621 | ||
4622 | int fds[2]; | |
4623 | _assert(pipe(fds) != -1); | |
4624 | ||
4625 | pid_t pid(ExecFork()); | |
4626 | if (pid == 0) { | |
4627 | _assert(dup2(fds[1], 1) != -1); | |
4628 | _assert(close(fds[0]) != -1); | |
4629 | _assert(close(fds[1]) != -1); | |
4630 | /* XXX: this should probably not use du */ | |
4631 | execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL); | |
4632 | exit(1); | |
4633 | } else { | |
4634 | _assert(close(fds[1]) != -1); | |
4635 | ||
4636 | if (FILE *du = fdopen(fds[0], "r")) { | |
4637 | char line[1024]; | |
4638 | while (fgets(line, sizeof(line), du) != NULL) { | |
4639 | size_t length(strlen(line)); | |
4640 | while (length != 0 && line[length - 1] == '\n') | |
4641 | line[--length] = '\0'; | |
4642 | if (char *tab = strchr(line, '\t')) { | |
4643 | *tab = '\0'; | |
4644 | value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)]; | |
4645 | } | |
4646 | } | |
4647 | ||
4648 | fclose(du); | |
4649 | } else | |
4650 | _assert(close(fds[0]) != -1); | |
4651 | } ReapZombie(pid); | |
4652 | ||
4653 | return value; | |
4654 | } | |
4655 | ||
4656 | - (void) close { | |
4657 | [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO]; | |
4658 | } | |
4659 | ||
4660 | - (NSNumber *) isReachable:(NSString *)name { | |
4661 | return [NSNumber numberWithBool:IsReachable([name UTF8String])]; | |
4662 | } | |
4663 | ||
4664 | - (void) installPackages:(NSArray *)packages { | |
4665 | [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO]; | |
4666 | } | |
4667 | ||
4668 | - (NSString *) substitutePackageNames:(NSString *)message { | |
4669 | NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]); | |
4670 | for (size_t i(0), e([words count]); i != e; ++i) { | |
4671 | NSString *word([words objectAtIndex:i]); | |
4672 | if (Package *package = [[Database sharedInstance] packageWithName:word]) | |
4673 | [words replaceObjectAtIndex:i withObject:[package name]]; | |
4674 | } | |
4675 | ||
4676 | return [words componentsJoinedByString:@" "]; | |
4677 | } | |
4678 | ||
4679 | - (void) removeButton { | |
4680 | [indirect_ removeButton]; | |
4681 | } | |
4682 | ||
4683 | - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function { | |
4684 | [indirect_ setButtonImage:button withStyle:style toFunction:function]; | |
4685 | } | |
4686 | ||
4687 | - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function { | |
4688 | [indirect_ setButtonTitle:button withStyle:style toFunction:function]; | |
4689 | } | |
4690 | ||
4691 | - (void) setBadgeValue:(id)value { | |
4692 | [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO]; | |
4693 | } | |
4694 | ||
4695 | - (void) setAllowsNavigationAction:(NSString *)value { | |
4696 | [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO]; | |
4697 | } | |
4698 | ||
4699 | - (void) setHidesBackButton:(NSString *)value { | |
4700 | [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO]; | |
4701 | } | |
4702 | ||
4703 | - (void) setHidesNavigationBar:(NSString *)value { | |
4704 | [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO]; | |
4705 | } | |
4706 | ||
4707 | - (void) setNavigationBarStyle:(NSString *)value { | |
4708 | [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO]; | |
4709 | } | |
4710 | ||
4711 | - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha { | |
4712 | float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]); | |
4713 | UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]); | |
4714 | [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO]; | |
4715 | } | |
4716 | ||
4717 | - (void) setPasteboardString:(NSString *)value { | |
4718 | [[objc_getClass("UIPasteboard") generalPasteboard] setString:value]; | |
4719 | } | |
4720 | ||
4721 | - (void) setPasteboardURL:(NSString *)value { | |
4722 | [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]]; | |
4723 | } | |
4724 | ||
4725 | - (void) _setToken:(NSString *)token { | |
4726 | Token_ = token; | |
4727 | ||
4728 | if (token == nil) | |
4729 | [Metadata_ removeObjectForKey:@"Token"]; | |
4730 | else | |
4731 | [Metadata_ setObject:Token_ forKey:@"Token"]; | |
4732 | ||
4733 | Changed_ = true; | |
4734 | } | |
4735 | ||
4736 | - (void) setToken:(NSString *)token { | |
4737 | [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO]; | |
4738 | } | |
4739 | ||
4740 | - (void) scrollToBottom:(NSNumber *)animated { | |
4741 | [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO]; | |
4742 | } | |
4743 | ||
4744 | - (void) setViewportWidth:(float)width { | |
4745 | [indirect_ setViewportWidthOnMainThread:width]; | |
4746 | } | |
4747 | ||
4748 | - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments { | |
4749 | //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]); | |
4750 | unsigned count([arguments count]); | |
4751 | id values[count]; | |
4752 | for (unsigned i(0); i != count; ++i) | |
4753 | values[i] = [arguments objectAtIndex:i]; | |
4754 | return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease]; | |
4755 | } | |
4756 | ||
4757 | - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table { | |
4758 | if (reinterpret_cast<id>(value) == [WebUndefined undefined]) | |
4759 | value = nil; | |
4760 | if (reinterpret_cast<id>(table) == [WebUndefined undefined]) | |
4761 | table = nil; | |
4762 | return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table]; | |
4763 | } | |
4764 | ||
4765 | @end | |
4766 | /* }}} */ | |
4767 | ||
4768 | @interface NSURL (CydiaSecure) | |
4769 | @end | |
4770 | ||
4771 | @implementation NSURL (CydiaSecure) | |
4772 | ||
4773 | - (bool) isCydiaSecure { | |
4774 | if ([[[self scheme] lowercaseString] isEqualToString:@"https"]) | |
4775 | return true; | |
4776 | ||
4777 | @synchronized (HostConfig_) { | |
4778 | if ([InsecureHosts_ containsObject:[self host]]) | |
4779 | return true; | |
4780 | } | |
4781 | ||
4782 | return false; | |
4783 | } | |
4784 | ||
4785 | @end | |
4786 | ||
4787 | /* Cydia Browser Controller {{{ */ | |
4788 | @implementation CydiaWebViewController | |
4789 | ||
4790 | - (NSURL *) navigationURL { | |
4791 | return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]]; | |
4792 | } | |
4793 | ||
4794 | + (void) _initialize { | |
4795 | [super _initialize]; | |
4796 | ||
4797 | Diversions_ = [NSMutableSet setWithCapacity:0]; | |
4798 | } | |
4799 | ||
4800 | + (void) addDiversion:(Diversion *)diversion { | |
4801 | [Diversions_ addObject:diversion]; | |
4802 | } | |
4803 | ||
4804 | - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { | |
4805 | [super webView:view didClearWindowObject:window forFrame:frame]; | |
4806 | [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_]; | |
4807 | } | |
4808 | ||
4809 | + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia { | |
4810 | WebDataSource *source([frame dataSource]); | |
4811 | NSURLResponse *response([source response]); | |
4812 | NSURL *url([response URL]); | |
4813 | NSString *scheme([[url scheme] lowercaseString]); | |
4814 | ||
4815 | bool bridged(false); | |
4816 | ||
4817 | @synchronized (HostConfig_) { | |
4818 | if ([scheme isEqualToString:@"file"]) | |
4819 | bridged = true; | |
4820 | else if ([scheme isEqualToString:@"https"]) | |
4821 | if ([BridgedHosts_ containsObject:[url host]]) | |
4822 | bridged = true; | |
4823 | } | |
4824 | ||
4825 | if (bridged) | |
4826 | [window setValue:cydia forKey:@"cydia"]; | |
4827 | } | |
4828 | ||
4829 | - (void) _setupMail:(MFMailComposeViewController *)controller { | |
4830 | [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"]; | |
4831 | ||
4832 | system("/usr/bin/dpkg -l >/tmp/dpkgl.log"); | |
4833 | [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"]; | |
4834 | } | |
4835 | ||
4836 | - (NSURL *) URLWithURL:(NSURL *)url { | |
4837 | return [Diversion divertURL:url]; | |
4838 | } | |
4839 | ||
4840 | - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source { | |
4841 | return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]]; | |
4842 | } | |
4843 | ||
4844 | + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request { | |
4845 | NSMutableURLRequest *copy([[request mutableCopy] autorelease]); | |
4846 | ||
4847 | NSURL *url([copy URL]); | |
4848 | NSString *href([url absoluteString]); | |
4849 | NSString *host([url host]); | |
4850 | ||
4851 | if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) { | |
4852 | if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) { | |
4853 | [copy setValue:agent forHTTPHeaderField:@"User-Agent"]; | |
4854 | [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"]; | |
4855 | } | |
4856 | ||
4857 | [copy setValue:nil forHTTPHeaderField:@"Referer"]; | |
4858 | [copy setValue:nil forHTTPHeaderField:@"Origin"]; | |
4859 | ||
4860 | [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]]; | |
4861 | return copy; | |
4862 | } | |
4863 | ||
4864 | if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil) | |
4865 | [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"]; | |
4866 | if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil) | |
4867 | [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"]; | |
4868 | ||
4869 | bool bridged; | |
4870 | bool token; | |
4871 | ||
4872 | @synchronized (HostConfig_) { | |
4873 | bridged = [BridgedHosts_ containsObject:host]; | |
4874 | token = [TokenHosts_ containsObject:host]; | |
4875 | } | |
4876 | ||
4877 | if ([url isCydiaSecure]) { | |
4878 | if (bridged) { | |
4879 | if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil) | |
4880 | [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"]; | |
4881 | } else if (token) { | |
4882 | if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil) | |
4883 | [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"]; | |
4884 | } | |
4885 | } | |
4886 | ||
4887 | return copy; | |
4888 | } | |
4889 | ||
4890 | - (void) setDelegate:(id)delegate { | |
4891 | [super setDelegate:delegate]; | |
4892 | [cydia_ setDelegate:delegate]; | |
4893 | } | |
4894 | ||
4895 | - (NSString *) applicationNameForUserAgent { | |
4896 | return UserAgent_; | |
4897 | } | |
4898 | ||
4899 | - (id) init { | |
4900 | if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) { | |
4901 | cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease]; | |
4902 | } return self; | |
4903 | } | |
4904 | ||
4905 | @end | |
4906 | ||
4907 | @interface AppCacheController : CydiaWebViewController { | |
4908 | } | |
4909 | ||
4910 | @end | |
4911 | ||
4912 | @implementation AppCacheController | |
4913 | ||
4914 | - (void) didReceiveMemoryWarning { | |
4915 | // XXX: this doesn't work | |
4916 | } | |
4917 | ||
4918 | - (bool) retainsNetworkActivityIndicator { | |
4919 | return false; | |
4920 | } | |
4921 | ||
4922 | @end | |
4923 | /* }}} */ | |
4924 | ||
4925 | // CydiaScript {{{ | |
4926 | @interface NSObject (CydiaScript) | |
4927 | - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context; | |
4928 | @end | |
4929 | ||
4930 | @implementation NSObject (CydiaScript) | |
4931 | ||
4932 | - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context { | |
4933 | return self; | |
4934 | } | |
4935 | ||
4936 | @end | |
4937 | ||
4938 | @implementation NSArray (CydiaScript) | |
4939 | ||
4940 | - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context { | |
4941 | WebScriptObject *object([context evaluateWebScript:@"[]"]); | |
4942 | for (size_t i(0), e([self count]); i != e; ++i) | |
4943 | [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]]; | |
4944 | return object; | |
4945 | } | |
4946 | ||
4947 | @end | |
4948 | ||
4949 | @implementation NSDictionary (CydiaScript) | |
4950 | ||
4951 | - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context { | |
4952 | WebScriptObject *object([context evaluateWebScript:@"({})"]); | |
4953 | for (id i in self) | |
4954 | [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i]; | |
4955 | return object; | |
4956 | } | |
4957 | ||
4958 | @end | |
4959 | // }}} | |
4960 | ||
4961 | /* Confirmation Controller {{{ */ | |
4962 | bool DepSubstrate(const pkgCache::VerIterator &iterator) { | |
4963 | if (!iterator.end()) | |
4964 | for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) { | |
4965 | if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends) | |
4966 | continue; | |
4967 | pkgCache::PkgIterator package(dep.TargetPkg()); | |
4968 | if (package.end()) | |
4969 | continue; | |
4970 | if (strcmp(package.Name(), "mobilesubstrate") == 0) | |
4971 | return true; | |
4972 | } | |
4973 | ||
4974 | return false; | |
4975 | } | |
4976 | ||
4977 | @protocol ConfirmationControllerDelegate | |
4978 | - (void) cancelAndClear:(bool)clear; | |
4979 | - (void) confirmWithNavigationController:(UINavigationController *)navigation; | |
4980 | - (void) queue; | |
4981 | @end | |
4982 | ||
4983 | @interface ConfirmationController : CydiaWebViewController { | |
4984 | _transient Database *database_; | |
4985 | ||
4986 | _H<UIAlertView> essential_; | |
4987 | ||
4988 | _H<NSDictionary> changes_; | |
4989 | _H<NSMutableArray> issues_; | |
4990 | _H<NSDictionary> sizes_; | |
4991 | ||
4992 | BOOL substrate_; | |
4993 | } | |
4994 | ||
4995 | - (id) initWithDatabase:(Database *)database; | |
4996 | ||
4997 | @end | |
4998 | ||
4999 | @implementation ConfirmationController | |
5000 | ||
5001 | - (void) complete { | |
5002 | if (substrate_) | |
5003 | RestartSubstrate_ = true; | |
5004 | [delegate_ confirmWithNavigationController:[self navigationController]]; | |
5005 | } | |
5006 | ||
5007 | - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
5008 | NSString *context([alert context]); | |
5009 | ||
5010 | if ([context isEqualToString:@"remove"]) { | |
5011 | if (button == [alert cancelButtonIndex]) | |
5012 | [self dismissModalViewControllerAnimated:YES]; | |
5013 | else if (button == [alert firstOtherButtonIndex]) { | |
5014 | [self performSelector:@selector(complete) withObject:nil afterDelay:0]; | |
5015 | } | |
5016 | ||
5017 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
5018 | } else if ([context isEqualToString:@"unable"]) { | |
5019 | [self dismissModalViewControllerAnimated:YES]; | |
5020 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
5021 | } else { | |
5022 | [super alertView:alert clickedButtonAtIndex:button]; | |
5023 | } | |
5024 | } | |
5025 | ||
5026 | - (void) _doContinue { | |
5027 | [delegate_ cancelAndClear:NO]; | |
5028 | [self dismissModalViewControllerAnimated:YES]; | |
5029 | } | |
5030 | ||
5031 | - (id) invokeDefaultMethodWithArguments:(NSArray *)args { | |
5032 | [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO]; | |
5033 | return nil; | |
5034 | } | |
5035 | ||
5036 | - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { | |
5037 | [super webView:view didClearWindowObject:window forFrame:frame]; | |
5038 | ||
5039 | [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys: | |
5040 | (id) changes_, @"changes", | |
5041 | (id) issues_, @"issues", | |
5042 | (id) sizes_, @"sizes", | |
5043 | self, @"queue", | |
5044 | nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"]; | |
5045 | } | |
5046 | ||
5047 | - (id) initWithDatabase:(Database *)database { | |
5048 | if ((self = [super init]) != nil) { | |
5049 | database_ = database; | |
5050 | ||
5051 | NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]); | |
5052 | NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]); | |
5053 | NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]); | |
5054 | NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]); | |
5055 | NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]); | |
5056 | ||
5057 | bool remove(false); | |
5058 | ||
5059 | pkgCacheFile &cache([database_ cache]); | |
5060 | NSArray *packages([database_ packages]); | |
5061 | pkgDepCache::Policy *policy([database_ policy]); | |
5062 | ||
5063 | issues_ = [NSMutableArray arrayWithCapacity:4]; | |
5064 | ||
5065 | for (Package *package in packages) { | |
5066 | pkgCache::PkgIterator iterator([package iterator]); | |
5067 | NSString *name([package id]); | |
5068 | ||
5069 | if ([package broken]) { | |
5070 | NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]); | |
5071 | ||
5072 | [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys: | |
5073 | name, @"package", | |
5074 | reasons, @"reasons", | |
5075 | nil]]; | |
5076 | ||
5077 | pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache)); | |
5078 | if (ver.end()) | |
5079 | continue; | |
5080 | ||
5081 | for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) { | |
5082 | pkgCache::DepIterator start; | |
5083 | pkgCache::DepIterator end; | |
5084 | dep.GlobOr(start, end); // ++dep | |
5085 | ||
5086 | if (!cache->IsImportantDep(end)) | |
5087 | continue; | |
5088 | if ((cache[end] & pkgDepCache::DepGInstall) != 0) | |
5089 | continue; | |
5090 | ||
5091 | NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]); | |
5092 | ||
5093 | [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys: | |
5094 | [NSString stringWithUTF8String:start.DepType()], @"relationship", | |
5095 | clauses, @"clauses", | |
5096 | nil]]; | |
5097 | ||
5098 | _forever { | |
5099 | NSString *reason, *installed((NSString *) [WebUndefined undefined]); | |
5100 | ||
5101 | pkgCache::PkgIterator target(start.TargetPkg()); | |
5102 | if (target->ProvidesList != 0) | |
5103 | reason = @"missing"; | |
5104 | else { | |
5105 | pkgCache::VerIterator ver(cache[target].InstVerIter(cache)); | |
5106 | if (!ver.end()) { | |
5107 | reason = @"installed"; | |
5108 | installed = [NSString stringWithUTF8String:ver.VerStr()]; | |
5109 | } else if (!cache[target].CandidateVerIter(cache).end()) | |
5110 | reason = @"uninstalled"; | |
5111 | else if (target->ProvidesList == 0) | |
5112 | reason = @"uninstallable"; | |
5113 | else | |
5114 | reason = @"virtual"; | |
5115 | } | |
5116 | ||
5117 | NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys: | |
5118 | [NSString stringWithUTF8String:start.CompType()], @"operator", | |
5119 | [NSString stringWithUTF8String:start.TargetVer()], @"value", | |
5120 | nil]); | |
5121 | ||
5122 | [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys: | |
5123 | [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package", | |
5124 | version, @"version", | |
5125 | reason, @"reason", | |
5126 | installed, @"installed", | |
5127 | nil]]; | |
5128 | ||
5129 | // yes, seriously. (wtf?) | |
5130 | if (start == end) | |
5131 | break; | |
5132 | ++start; | |
5133 | } | |
5134 | } | |
5135 | } | |
5136 | ||
5137 | pkgDepCache::StateCache &state(cache[iterator]); | |
5138 | ||
5139 | static Pcre special_r("^(firmware$|gsc\\.|cy\\+)"); | |
5140 | ||
5141 | if (state.NewInstall()) | |
5142 | [installs addObject:name]; | |
5143 | // XXX: else if (state.Install()) | |
5144 | else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall) | |
5145 | [reinstalls addObject:name]; | |
5146 | // XXX: move before previous if | |
5147 | else if (state.Upgrade()) | |
5148 | [upgrades addObject:name]; | |
5149 | else if (state.Downgrade()) | |
5150 | [downgrades addObject:name]; | |
5151 | else if (!state.Delete()) | |
5152 | // XXX: _assert(state.Keep()); | |
5153 | continue; | |
5154 | else if (special_r(name)) | |
5155 | [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys: | |
5156 | [NSNull null], @"package", | |
5157 | [NSArray arrayWithObjects: | |
5158 | [NSDictionary dictionaryWithObjectsAndKeys: | |
5159 | @"Conflicts", @"relationship", | |
5160 | [NSArray arrayWithObjects: | |
5161 | [NSDictionary dictionaryWithObjectsAndKeys: | |
5162 | name, @"package", | |
5163 | [NSNull null], @"version", | |
5164 | @"installed", @"reason", | |
5165 | nil], | |
5166 | nil], @"clauses", | |
5167 | nil], | |
5168 | nil], @"reasons", | |
5169 | nil]]; | |
5170 | else { | |
5171 | if ([package essential]) | |
5172 | remove = true; | |
5173 | [removes addObject:name]; | |
5174 | } | |
5175 | ||
5176 | substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator)); | |
5177 | substrate_ |= DepSubstrate(iterator.CurrentVer()); | |
5178 | } | |
5179 | ||
5180 | if (!remove) | |
5181 | essential_ = nil; | |
5182 | else if (Advanced_) { | |
5183 | NSString *parenthetical(UCLocalize("PARENTHETICAL")); | |
5184 | ||
5185 | essential_ = [[[UIAlertView alloc] | |
5186 | initWithTitle:UCLocalize("REMOVING_ESSENTIALS") | |
5187 | message:UCLocalize("REMOVING_ESSENTIALS_EX") | |
5188 | delegate:self | |
5189 | cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")] | |
5190 | otherButtonTitles: | |
5191 | [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], | |
5192 | nil | |
5193 | ] autorelease]; | |
5194 | ||
5195 | [essential_ setContext:@"remove"]; | |
5196 | [essential_ setNumberOfRows:2]; | |
5197 | } else { | |
5198 | essential_ = [[[UIAlertView alloc] | |
5199 | initWithTitle:UCLocalize("UNABLE_TO_COMPLY") | |
5200 | message:UCLocalize("UNABLE_TO_COMPLY_EX") | |
5201 | delegate:self | |
5202 | cancelButtonTitle:UCLocalize("OKAY") | |
5203 | otherButtonTitles:nil | |
5204 | ] autorelease]; | |
5205 | ||
5206 | [essential_ setContext:@"unable"]; | |
5207 | } | |
5208 | ||
5209 | changes_ = [NSDictionary dictionaryWithObjectsAndKeys: | |
5210 | installs, @"installs", | |
5211 | reinstalls, @"reinstalls", | |
5212 | upgrades, @"upgrades", | |
5213 | downgrades, @"downgrades", | |
5214 | removes, @"removes", | |
5215 | nil]; | |
5216 | ||
5217 | sizes_ = [NSDictionary dictionaryWithObjectsAndKeys: | |
5218 | [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading", | |
5219 | [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming", | |
5220 | nil]; | |
5221 | ||
5222 | [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]]; | |
5223 | } return self; | |
5224 | } | |
5225 | ||
5226 | - (UIBarButtonItem *) leftButton { | |
5227 | return [[[UIBarButtonItem alloc] | |
5228 | initWithTitle:UCLocalize("CANCEL") | |
5229 | style:UIBarButtonItemStylePlain | |
5230 | target:self | |
5231 | action:@selector(cancelButtonClicked) | |
5232 | ] autorelease]; | |
5233 | } | |
5234 | ||
5235 | #if !AlwaysReload | |
5236 | - (void) applyRightButton { | |
5237 | if ([issues_ count] == 0 && ![self isLoading]) | |
5238 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
5239 | initWithTitle:UCLocalize("CONFIRM") | |
5240 | style:UIBarButtonItemStyleDone | |
5241 | target:self | |
5242 | action:@selector(confirmButtonClicked) | |
5243 | ] autorelease]]; | |
5244 | else | |
5245 | [[self navigationItem] setRightBarButtonItem:nil]; | |
5246 | } | |
5247 | #endif | |
5248 | ||
5249 | - (void) cancelButtonClicked { | |
5250 | [delegate_ cancelAndClear:YES]; | |
5251 | [self dismissModalViewControllerAnimated:YES]; | |
5252 | } | |
5253 | ||
5254 | #if !AlwaysReload | |
5255 | - (void) confirmButtonClicked { | |
5256 | if (essential_ != nil) | |
5257 | [essential_ show]; | |
5258 | else | |
5259 | [self complete]; | |
5260 | } | |
5261 | #endif | |
5262 | ||
5263 | @end | |
5264 | /* }}} */ | |
5265 | ||
5266 | /* Progress Data {{{ */ | |
5267 | @interface CydiaProgressData : NSObject { | |
5268 | _transient id delegate_; | |
5269 | ||
5270 | bool running_; | |
5271 | float percent_; | |
5272 | ||
5273 | float current_; | |
5274 | float total_; | |
5275 | float speed_; | |
5276 | ||
5277 | _H<NSMutableArray> events_; | |
5278 | _H<NSString> title_; | |
5279 | ||
5280 | _H<NSString> status_; | |
5281 | _H<NSString> finish_; | |
5282 | } | |
5283 | ||
5284 | @end | |
5285 | ||
5286 | @implementation CydiaProgressData | |
5287 | ||
5288 | + (NSArray *) _attributeKeys { | |
5289 | return [NSArray arrayWithObjects: | |
5290 | @"current", | |
5291 | @"events", | |
5292 | @"finish", | |
5293 | @"percent", | |
5294 | @"running", | |
5295 | @"speed", | |
5296 | @"title", | |
5297 | @"total", | |
5298 | nil]; | |
5299 | } | |
5300 | ||
5301 | - (NSArray *) attributeKeys { | |
5302 | return [[self class] _attributeKeys]; | |
5303 | } | |
5304 | ||
5305 | + (BOOL) isKeyExcludedFromWebScript:(const char *)name { | |
5306 | return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name]; | |
5307 | } | |
5308 | ||
5309 | - (id) init { | |
5310 | if ((self = [super init]) != nil) { | |
5311 | events_ = [NSMutableArray arrayWithCapacity:32]; | |
5312 | } return self; | |
5313 | } | |
5314 | ||
5315 | - (id) delegate { | |
5316 | return delegate_; | |
5317 | } | |
5318 | ||
5319 | - (void) setDelegate:(id)delegate { | |
5320 | delegate_ = delegate; | |
5321 | } | |
5322 | ||
5323 | - (void) setPercent:(float)value { | |
5324 | percent_ = value; | |
5325 | } | |
5326 | ||
5327 | - (NSNumber *) percent { | |
5328 | return [NSNumber numberWithFloat:percent_]; | |
5329 | } | |
5330 | ||
5331 | - (void) setCurrent:(float)value { | |
5332 | current_ = value; | |
5333 | } | |
5334 | ||
5335 | - (NSNumber *) current { | |
5336 | return [NSNumber numberWithFloat:current_]; | |
5337 | } | |
5338 | ||
5339 | - (void) setTotal:(float)value { | |
5340 | total_ = value; | |
5341 | } | |
5342 | ||
5343 | - (NSNumber *) total { | |
5344 | return [NSNumber numberWithFloat:total_]; | |
5345 | } | |
5346 | ||
5347 | - (void) setSpeed:(float)value { | |
5348 | speed_ = value; | |
5349 | } | |
5350 | ||
5351 | - (NSNumber *) speed { | |
5352 | return [NSNumber numberWithFloat:speed_]; | |
5353 | } | |
5354 | ||
5355 | - (NSArray *) events { | |
5356 | return events_; | |
5357 | } | |
5358 | ||
5359 | - (void) removeAllEvents { | |
5360 | [events_ removeAllObjects]; | |
5361 | } | |
5362 | ||
5363 | - (void) addEvent:(CydiaProgressEvent *)event { | |
5364 | [events_ addObject:event]; | |
5365 | } | |
5366 | ||
5367 | - (void) setTitle:(NSString *)text { | |
5368 | title_ = text; | |
5369 | } | |
5370 | ||
5371 | - (NSString *) title { | |
5372 | return title_; | |
5373 | } | |
5374 | ||
5375 | - (void) setFinish:(NSString *)text { | |
5376 | finish_ = text; | |
5377 | } | |
5378 | ||
5379 | - (NSString *) finish { | |
5380 | return (id) finish_ ?: [NSNull null]; | |
5381 | } | |
5382 | ||
5383 | - (void) setRunning:(bool)running { | |
5384 | running_ = running; | |
5385 | } | |
5386 | ||
5387 | - (NSNumber *) running { | |
5388 | return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse; | |
5389 | } | |
5390 | ||
5391 | @end | |
5392 | /* }}} */ | |
5393 | /* Progress Controller {{{ */ | |
5394 | @interface ProgressController : CydiaWebViewController < | |
5395 | ProgressDelegate | |
5396 | > { | |
5397 | _transient Database *database_; | |
5398 | _H<CydiaProgressData, 1> progress_; | |
5399 | unsigned cancel_; | |
5400 | } | |
5401 | ||
5402 | - (id) initWithDatabase:(Database *)database delegate:(id)delegate; | |
5403 | ||
5404 | - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title; | |
5405 | ||
5406 | - (void) setTitle:(NSString *)title; | |
5407 | - (void) setCancellable:(bool)cancellable; | |
5408 | ||
5409 | @end | |
5410 | ||
5411 | @implementation ProgressController | |
5412 | ||
5413 | - (void) dealloc { | |
5414 | [database_ setProgressDelegate:nil]; | |
5415 | [super dealloc]; | |
5416 | } | |
5417 | ||
5418 | - (UIBarButtonItem *) leftButton { | |
5419 | return cancel_ == 1 ? [[[UIBarButtonItem alloc] | |
5420 | initWithTitle:UCLocalize("CANCEL") | |
5421 | style:UIBarButtonItemStylePlain | |
5422 | target:self | |
5423 | action:@selector(cancel) | |
5424 | ] autorelease] : nil; | |
5425 | } | |
5426 | ||
5427 | - (void) updateCancel { | |
5428 | [super applyLeftButton]; | |
5429 | } | |
5430 | ||
5431 | - (id) initWithDatabase:(Database *)database delegate:(id)delegate { | |
5432 | if ((self = [super init]) != nil) { | |
5433 | database_ = database; | |
5434 | delegate_ = delegate; | |
5435 | ||
5436 | [database_ setProgressDelegate:self]; | |
5437 | ||
5438 | progress_ = [[[CydiaProgressData alloc] init] autorelease]; | |
5439 | [progress_ setDelegate:self]; | |
5440 | ||
5441 | [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]]; | |
5442 | ||
5443 | [scroller_ setBackgroundColor:[UIColor blackColor]]; | |
5444 | ||
5445 | [[self navigationItem] setHidesBackButton:YES]; | |
5446 | ||
5447 | [self updateCancel]; | |
5448 | } return self; | |
5449 | } | |
5450 | ||
5451 | - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame { | |
5452 | [super webView:view didClearWindowObject:window forFrame:frame]; | |
5453 | [window setValue:progress_ forKey:@"cydiaProgress"]; | |
5454 | } | |
5455 | ||
5456 | - (void) updateProgress { | |
5457 | [self dispatchEvent:@"CydiaProgressUpdate"]; | |
5458 | } | |
5459 | ||
5460 | - (void) viewWillAppear:(BOOL)animated { | |
5461 | [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack]; | |
5462 | [super viewWillAppear:animated]; | |
5463 | } | |
5464 | ||
5465 | - (void) reloadSpringBoard { | |
5466 | if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x | |
5467 | system("/bin/launchctl stop com.apple.backboardd"); | |
5468 | sleep(15); | |
5469 | system("/usr/bin/killall backboardd SpringBoard sbreload"); | |
5470 | return; | |
5471 | } | |
5472 | ||
5473 | pid_t pid(ExecFork()); | |
5474 | if (pid == 0) { | |
5475 | if (setsid() == -1) | |
5476 | perror("setsid"); | |
5477 | ||
5478 | pid_t pid(ExecFork()); | |
5479 | if (pid == 0) { | |
5480 | execl("/usr/bin/sbreload", "sbreload", NULL); | |
5481 | perror("sbreload"); | |
5482 | ||
5483 | exit(0); | |
5484 | } ReapZombie(pid); | |
5485 | ||
5486 | exit(0); | |
5487 | } ReapZombie(pid); | |
5488 | ||
5489 | sleep(15); | |
5490 | system("/usr/bin/killall backboardd SpringBoard sbreload"); | |
5491 | } | |
5492 | ||
5493 | - (void) close { | |
5494 | UpdateExternalStatus(0); | |
5495 | ||
5496 | if (Finish_ > 1) | |
5497 | [delegate_ saveState]; | |
5498 | ||
5499 | switch (Finish_) { | |
5500 | case 0: | |
5501 | [delegate_ returnToCydia]; | |
5502 | break; | |
5503 | ||
5504 | case 1: | |
5505 | [delegate_ terminateWithSuccess]; | |
5506 | /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)]) | |
5507 | [delegate_ suspendWithAnimation:YES]; | |
5508 | else | |
5509 | [delegate_ suspend];*/ | |
5510 | break; | |
5511 | ||
5512 | case 2: | |
5513 | _trace(); | |
5514 | goto reload; | |
5515 | ||
5516 | case 3: | |
5517 | _trace(); | |
5518 | goto reload; | |
5519 | ||
5520 | reload: { | |
5521 | UIProgressHUD *hud([delegate_ addProgressHUD]); | |
5522 | [hud setText:UCLocalize("LOADING")]; | |
5523 | [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5]; | |
5524 | return; | |
5525 | } | |
5526 | ||
5527 | case 4: | |
5528 | _trace(); | |
5529 | if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot"))) | |
5530 | SBReboot(SBSSpringBoardServerPort()); | |
5531 | else | |
5532 | reboot2(RB_AUTOBOOT); | |
5533 | break; | |
5534 | } | |
5535 | ||
5536 | [super close]; | |
5537 | } | |
5538 | ||
5539 | - (void) setTitle:(NSString *)title { | |
5540 | [progress_ setTitle:title]; | |
5541 | [self updateProgress]; | |
5542 | } | |
5543 | ||
5544 | - (UIBarButtonItem *) rightButton { | |
5545 | return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc] | |
5546 | initWithTitle:UCLocalize("CLOSE") | |
5547 | style:UIBarButtonItemStylePlain | |
5548 | target:self | |
5549 | action:@selector(close) | |
5550 | ] autorelease]; | |
5551 | } | |
5552 | ||
5553 | - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title { | |
5554 | UpdateExternalStatus(1); | |
5555 | ||
5556 | [progress_ setRunning:true]; | |
5557 | [self setTitle:title]; | |
5558 | // implicit updateProgress | |
5559 | ||
5560 | SHA1SumValue notifyconf; { | |
5561 | FileFd file; | |
5562 | if (!file.Open(NotifyConfig_, FileFd::ReadOnly)) | |
5563 | _error->Discard(); | |
5564 | else { | |
5565 | MMap mmap(file, MMap::ReadOnly); | |
5566 | SHA1Summation sha1; | |
5567 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
5568 | notifyconf = sha1.Result(); | |
5569 | } | |
5570 | } | |
5571 | ||
5572 | SHA1SumValue springlist; { | |
5573 | FileFd file; | |
5574 | if (!file.Open(SpringBoard_, FileFd::ReadOnly)) | |
5575 | _error->Discard(); | |
5576 | else { | |
5577 | MMap mmap(file, MMap::ReadOnly); | |
5578 | SHA1Summation sha1; | |
5579 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
5580 | springlist = sha1.Result(); | |
5581 | } | |
5582 | } | |
5583 | ||
5584 | if (invocation != nil) { | |
5585 | [invocation yieldToSelector:@selector(invoke)]; | |
5586 | [self setTitle:@"COMPLETE"]; | |
5587 | } | |
5588 | ||
5589 | if (Finish_ < 4) { | |
5590 | FileFd file; | |
5591 | if (!file.Open(NotifyConfig_, FileFd::ReadOnly)) | |
5592 | _error->Discard(); | |
5593 | else { | |
5594 | MMap mmap(file, MMap::ReadOnly); | |
5595 | SHA1Summation sha1; | |
5596 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
5597 | if (!(notifyconf == sha1.Result())) | |
5598 | Finish_ = 4; | |
5599 | } | |
5600 | } | |
5601 | ||
5602 | if (Finish_ < 3) { | |
5603 | FileFd file; | |
5604 | if (!file.Open(SpringBoard_, FileFd::ReadOnly)) | |
5605 | _error->Discard(); | |
5606 | else { | |
5607 | MMap mmap(file, MMap::ReadOnly); | |
5608 | SHA1Summation sha1; | |
5609 | sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size()); | |
5610 | if (!(springlist == sha1.Result())) | |
5611 | Finish_ = 3; | |
5612 | } | |
5613 | } | |
5614 | ||
5615 | if (Finish_ < 2) { | |
5616 | if (RestartSubstrate_) | |
5617 | Finish_ = 2; | |
5618 | } | |
5619 | ||
5620 | RestartSubstrate_ = false; | |
5621 | ||
5622 | switch (Finish_) { | |
5623 | case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */ | |
5624 | case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break; | |
5625 | case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break; | |
5626 | case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break; | |
5627 | case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break; | |
5628 | } | |
5629 | ||
5630 | UpdateExternalStatus(Finish_ == 0 ? 0 : 2); | |
5631 | ||
5632 | [progress_ setRunning:false]; | |
5633 | [self updateProgress]; | |
5634 | ||
5635 | [self applyRightButton]; | |
5636 | } | |
5637 | ||
5638 | - (void) addProgressEvent:(CydiaProgressEvent *)event { | |
5639 | [progress_ addEvent:event]; | |
5640 | [self updateProgress]; | |
5641 | } | |
5642 | ||
5643 | - (bool) isProgressCancelled { | |
5644 | return cancel_ == 2; | |
5645 | } | |
5646 | ||
5647 | - (void) cancel { | |
5648 | cancel_ = 2; | |
5649 | [self updateCancel]; | |
5650 | } | |
5651 | ||
5652 | - (void) setCancellable:(bool)cancellable { | |
5653 | unsigned cancel(cancel_); | |
5654 | ||
5655 | if (!cancellable) | |
5656 | cancel_ = 0; | |
5657 | else if (cancel_ == 0) | |
5658 | cancel_ = 1; | |
5659 | ||
5660 | if (cancel != cancel_) | |
5661 | [self updateCancel]; | |
5662 | } | |
5663 | ||
5664 | - (void) setProgressCancellable:(NSNumber *)cancellable { | |
5665 | [self setCancellable:[cancellable boolValue]]; | |
5666 | } | |
5667 | ||
5668 | - (void) setProgressPercent:(NSNumber *)percent { | |
5669 | [progress_ setPercent:[percent floatValue]]; | |
5670 | [self updateProgress]; | |
5671 | } | |
5672 | ||
5673 | - (void) setProgressStatus:(NSDictionary *)status { | |
5674 | if (status == nil) { | |
5675 | [progress_ setCurrent:0]; | |
5676 | [progress_ setTotal:0]; | |
5677 | [progress_ setSpeed:0]; | |
5678 | } else { | |
5679 | [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]]; | |
5680 | ||
5681 | [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]]; | |
5682 | [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]]; | |
5683 | [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]]; | |
5684 | } | |
5685 | ||
5686 | [self updateProgress]; | |
5687 | } | |
5688 | ||
5689 | @end | |
5690 | /* }}} */ | |
5691 | ||
5692 | /* Package Cell {{{ */ | |
5693 | @interface PackageCell : CyteTableViewCell < | |
5694 | CyteTableViewCellDelegate | |
5695 | > { | |
5696 | _H<UIImage> icon_; | |
5697 | _H<NSString> name_; | |
5698 | _H<NSString> description_; | |
5699 | bool commercial_; | |
5700 | _H<NSString> source_; | |
5701 | _H<UIImage> badge_; | |
5702 | _H<UIImage> placard_; | |
5703 | bool summarized_; | |
5704 | } | |
5705 | ||
5706 | - (PackageCell *) init; | |
5707 | - (void) setPackage:(Package *)package asSummary:(bool)summary; | |
5708 | ||
5709 | - (void) drawContentRect:(CGRect)rect; | |
5710 | ||
5711 | @end | |
5712 | ||
5713 | @implementation PackageCell | |
5714 | ||
5715 | - (PackageCell *) init { | |
5716 | CGRect frame(CGRectMake(0, 0, 320, 74)); | |
5717 | if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) { | |
5718 | UIView *content([self contentView]); | |
5719 | CGRect bounds([content bounds]); | |
5720 | ||
5721 | content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease]; | |
5722 | [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
5723 | [content addSubview:content_]; | |
5724 | ||
5725 | [content_ setDelegate:self]; | |
5726 | [content_ setOpaque:YES]; | |
5727 | } return self; | |
5728 | } | |
5729 | ||
5730 | - (NSString *) accessibilityLabel { | |
5731 | return name_; | |
5732 | } | |
5733 | ||
5734 | - (void) setPackage:(Package *)package asSummary:(bool)summary { | |
5735 | summarized_ = summary; | |
5736 | ||
5737 | icon_ = nil; | |
5738 | name_ = nil; | |
5739 | description_ = nil; | |
5740 | source_ = nil; | |
5741 | badge_ = nil; | |
5742 | placard_ = nil; | |
5743 | ||
5744 | if (package == nil) | |
5745 | [content_ setBackgroundColor:[UIColor whiteColor]]; | |
5746 | else { | |
5747 | [package parse]; | |
5748 | ||
5749 | Source *source = [package source]; | |
5750 | ||
5751 | icon_ = [package icon]; | |
5752 | ||
5753 | if (NSString *name = [package name]) | |
5754 | name_ = [NSString stringWithString:name]; | |
5755 | ||
5756 | if (NSString *description = [package shortDescription]) | |
5757 | description_ = [NSString stringWithString:description]; | |
5758 | ||
5759 | commercial_ = [package isCommercial]; | |
5760 | ||
5761 | NSString *label = nil; | |
5762 | bool trusted = false; | |
5763 | ||
5764 | if (source != nil) { | |
5765 | label = [source label]; | |
5766 | trusted = [source trusted]; | |
5767 | } else if ([[package id] isEqualToString:@"firmware"]) | |
5768 | label = UCLocalize("APPLE"); | |
5769 | else | |
5770 | label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")]; | |
5771 | ||
5772 | NSString *from(label); | |
5773 | ||
5774 | NSString *section = [package simpleSection]; | |
5775 | if (section != nil && ![section isEqualToString:label]) { | |
5776 | section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"]; | |
5777 | from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section]; | |
5778 | } | |
5779 | ||
5780 | source_ = [NSString stringWithFormat:UCLocalize("FROM"), from]; | |
5781 | ||
5782 | if (NSString *purpose = [package primaryPurpose]) | |
5783 | badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]; | |
5784 | ||
5785 | UIColor *color; | |
5786 | NSString *placard; | |
5787 | ||
5788 | if (NSString *mode = [package mode]) { | |
5789 | if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) { | |
5790 | color = RemovingColor_; | |
5791 | placard = @"removing"; | |
5792 | } else { | |
5793 | color = InstallingColor_; | |
5794 | placard = @"installing"; | |
5795 | } | |
5796 | } else { | |
5797 | color = [UIColor whiteColor]; | |
5798 | ||
5799 | if ([package installed] != nil) | |
5800 | placard = @"installed"; | |
5801 | else | |
5802 | placard = nil; | |
5803 | } | |
5804 | ||
5805 | [content_ setBackgroundColor:color]; | |
5806 | ||
5807 | if (placard != nil) | |
5808 | placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]; | |
5809 | } | |
5810 | ||
5811 | [self setNeedsDisplay]; | |
5812 | [content_ setNeedsDisplay]; | |
5813 | } | |
5814 | ||
5815 | - (void) drawSummaryContentRect:(CGRect)rect { | |
5816 | bool highlighted(highlighted_); | |
5817 | float width([self bounds].size.width); | |
5818 | ||
5819 | if (icon_ != nil) { | |
5820 | CGRect rect; | |
5821 | rect.size = [(UIImage *) icon_ size]; | |
5822 | ||
5823 | while (rect.size.width > 16 || rect.size.height > 16) { | |
5824 | rect.size.width /= 2; | |
5825 | rect.size.height /= 2; | |
5826 | } | |
5827 | ||
5828 | rect.origin.x = 19 - rect.size.width / 2; | |
5829 | rect.origin.y = 19 - rect.size.height / 2; | |
5830 | ||
5831 | [icon_ drawInRect:rect]; | |
5832 | } | |
5833 | ||
5834 | if (badge_ != nil) { | |
5835 | CGRect rect; | |
5836 | rect.size = [(UIImage *) badge_ size]; | |
5837 | ||
5838 | rect.size.width /= 4; | |
5839 | rect.size.height /= 4; | |
5840 | ||
5841 | rect.origin.x = 25 - rect.size.width / 2; | |
5842 | rect.origin.y = 25 - rect.size.height / 2; | |
5843 | ||
5844 | [badge_ drawInRect:rect]; | |
5845 | } | |
5846 | ||
5847 | if (highlighted && kCFCoreFoundationVersionNumber < 800) | |
5848 | UISetColor(White_); | |
5849 | ||
5850 | if (!highlighted) | |
5851 | UISetColor(commercial_ ? Purple_ : Black_); | |
5852 | [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
5853 | ||
5854 | if (placard_ != nil) | |
5855 | [placard_ drawAtPoint:CGPointMake(width - 52, 11)]; | |
5856 | } | |
5857 | ||
5858 | - (void) drawNormalContentRect:(CGRect)rect { | |
5859 | bool highlighted(highlighted_); | |
5860 | float width([self bounds].size.width); | |
5861 | ||
5862 | if (icon_ != nil) { | |
5863 | CGRect rect; | |
5864 | rect.size = [(UIImage *) icon_ size]; | |
5865 | ||
5866 | while (rect.size.width > 32 || rect.size.height > 32) { | |
5867 | rect.size.width /= 2; | |
5868 | rect.size.height /= 2; | |
5869 | } | |
5870 | ||
5871 | rect.origin.x = 25 - rect.size.width / 2; | |
5872 | rect.origin.y = 25 - rect.size.height / 2; | |
5873 | ||
5874 | [icon_ drawInRect:rect]; | |
5875 | } | |
5876 | ||
5877 | if (badge_ != nil) { | |
5878 | CGRect rect; | |
5879 | rect.size = [(UIImage *) badge_ size]; | |
5880 | ||
5881 | rect.size.width /= 2; | |
5882 | rect.size.height /= 2; | |
5883 | ||
5884 | rect.origin.x = 36 - rect.size.width / 2; | |
5885 | rect.origin.y = 36 - rect.size.height / 2; | |
5886 | ||
5887 | [badge_ drawInRect:rect]; | |
5888 | } | |
5889 | ||
5890 | if (highlighted && kCFCoreFoundationVersionNumber < 800) | |
5891 | UISetColor(White_); | |
5892 | ||
5893 | if (!highlighted) | |
5894 | UISetColor(commercial_ ? Purple_ : Black_); | |
5895 | [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
5896 | [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
5897 | ||
5898 | if (!highlighted) | |
5899 | UISetColor(commercial_ ? Purplish_ : Gray_); | |
5900 | [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
5901 | ||
5902 | if (placard_ != nil) | |
5903 | [placard_ drawAtPoint:CGPointMake(width - 52, 9)]; | |
5904 | } | |
5905 | ||
5906 | - (void) drawContentRect:(CGRect)rect { | |
5907 | if (summarized_) | |
5908 | [self drawSummaryContentRect:rect]; | |
5909 | else | |
5910 | [self drawNormalContentRect:rect]; | |
5911 | } | |
5912 | ||
5913 | @end | |
5914 | /* }}} */ | |
5915 | /* Section Cell {{{ */ | |
5916 | @interface SectionCell : CyteTableViewCell < | |
5917 | CyteTableViewCellDelegate | |
5918 | > { | |
5919 | _H<NSString> basic_; | |
5920 | _H<NSString> section_; | |
5921 | _H<NSString> name_; | |
5922 | _H<NSString> count_; | |
5923 | _H<UIImage> icon_; | |
5924 | _H<UISwitch> switch_; | |
5925 | BOOL editing_; | |
5926 | } | |
5927 | ||
5928 | - (void) setSection:(Section *)section editing:(BOOL)editing; | |
5929 | ||
5930 | @end | |
5931 | ||
5932 | @implementation SectionCell | |
5933 | ||
5934 | - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { | |
5935 | if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) { | |
5936 | icon_ = [UIImage applicationImageNamed:@"folder.png"]; | |
5937 | // XXX: this initial frame is wrong, but is fixed later | |
5938 | switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease]; | |
5939 | [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged]; | |
5940 | ||
5941 | UIView *content([self contentView]); | |
5942 | CGRect bounds([content bounds]); | |
5943 | ||
5944 | content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease]; | |
5945 | [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
5946 | [content addSubview:content_]; | |
5947 | [content_ setBackgroundColor:[UIColor whiteColor]]; | |
5948 | ||
5949 | [content_ setDelegate:self]; | |
5950 | } return self; | |
5951 | } | |
5952 | ||
5953 | - (void) onSwitch:(id)sender { | |
5954 | NSMutableDictionary *metadata([Sections_ objectForKey:basic_]); | |
5955 | if (metadata == nil) { | |
5956 | metadata = [NSMutableDictionary dictionaryWithCapacity:2]; | |
5957 | [Sections_ setObject:metadata forKey:basic_]; | |
5958 | } | |
5959 | ||
5960 | [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"]; | |
5961 | Changed_ = true; | |
5962 | } | |
5963 | ||
5964 | - (void) setSection:(Section *)section editing:(BOOL)editing { | |
5965 | if (editing != editing_) { | |
5966 | if (editing_) | |
5967 | [switch_ removeFromSuperview]; | |
5968 | else | |
5969 | [self addSubview:switch_]; | |
5970 | editing_ = editing; | |
5971 | } | |
5972 | ||
5973 | basic_ = nil; | |
5974 | section_ = nil; | |
5975 | name_ = nil; | |
5976 | count_ = nil; | |
5977 | ||
5978 | if (section == nil) { | |
5979 | name_ = UCLocalize("ALL_PACKAGES"); | |
5980 | count_ = nil; | |
5981 | } else { | |
5982 | basic_ = [section name]; | |
5983 | section_ = [section localized]; | |
5984 | ||
5985 | name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_; | |
5986 | count_ = [NSString stringWithFormat:@"%zd", [section count]]; | |
5987 | ||
5988 | if (editing_) | |
5989 | [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO]; | |
5990 | } | |
5991 | ||
5992 | [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator]; | |
5993 | [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue]; | |
5994 | ||
5995 | [content_ setNeedsDisplay]; | |
5996 | } | |
5997 | ||
5998 | - (void) setFrame:(CGRect)frame { | |
5999 | [super setFrame:frame]; | |
6000 | ||
6001 | CGRect rect([switch_ frame]); | |
6002 | [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)]; | |
6003 | } | |
6004 | ||
6005 | - (NSString *) accessibilityLabel { | |
6006 | return name_; | |
6007 | } | |
6008 | ||
6009 | - (void) drawContentRect:(CGRect)rect { | |
6010 | bool highlighted(highlighted_ && !editing_); | |
6011 | ||
6012 | [icon_ drawInRect:CGRectMake(7, 7, 32, 32)]; | |
6013 | ||
6014 | if (highlighted && kCFCoreFoundationVersionNumber < 800) | |
6015 | UISetColor(White_); | |
6016 | ||
6017 | float width(rect.size.width); | |
6018 | if (editing_) | |
6019 | width -= 9 + [switch_ frame].size.width; | |
6020 | ||
6021 | if (!highlighted) | |
6022 | UISetColor(Black_); | |
6023 | [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
6024 | ||
6025 | CGSize size = [count_ sizeWithFont:Font14_]; | |
6026 | ||
6027 | UISetColor(Folder_); | |
6028 | if (count_ != nil) | |
6029 | [count_ drawAtPoint:CGPointMake(10 + (30 - size.width) / 2, 18) withFont:Font12Bold_]; | |
6030 | } | |
6031 | ||
6032 | @end | |
6033 | /* }}} */ | |
6034 | ||
6035 | /* File Table {{{ */ | |
6036 | @interface FileTable : CyteViewController < | |
6037 | UITableViewDataSource, | |
6038 | UITableViewDelegate | |
6039 | > { | |
6040 | _transient Database *database_; | |
6041 | _H<Package> package_; | |
6042 | _H<NSString> name_; | |
6043 | _H<NSMutableArray> files_; | |
6044 | _H<UITableView, 2> list_; | |
6045 | } | |
6046 | ||
6047 | - (id) initWithDatabase:(Database *)database; | |
6048 | - (void) setPackage:(Package *)package; | |
6049 | ||
6050 | @end | |
6051 | ||
6052 | @implementation FileTable | |
6053 | ||
6054 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
6055 | return files_ == nil ? 0 : [files_ count]; | |
6056 | } | |
6057 | ||
6058 | /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { | |
6059 | return 24.0f; | |
6060 | }*/ | |
6061 | ||
6062 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
6063 | static NSString *reuseIdentifier = @"Cell"; | |
6064 | ||
6065 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; | |
6066 | if (cell == nil) { | |
6067 | cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease]; | |
6068 | [cell setFont:[UIFont systemFontOfSize:16]]; | |
6069 | } | |
6070 | [cell setText:[files_ objectAtIndex:indexPath.row]]; | |
6071 | [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; | |
6072 | ||
6073 | return cell; | |
6074 | } | |
6075 | ||
6076 | - (NSURL *) navigationURL { | |
6077 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]]; | |
6078 | } | |
6079 | ||
6080 | - (void) loadView { | |
6081 | list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]; | |
6082 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
6083 | [list_ setRowHeight:24.0f]; | |
6084 | [(UITableView *) list_ setDataSource:self]; | |
6085 | [list_ setDelegate:self]; | |
6086 | [self setView:list_]; | |
6087 | } | |
6088 | ||
6089 | - (void) viewDidLoad { | |
6090 | [super viewDidLoad]; | |
6091 | ||
6092 | [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")]; | |
6093 | } | |
6094 | ||
6095 | - (void) releaseSubviews { | |
6096 | list_ = nil; | |
6097 | ||
6098 | package_ = nil; | |
6099 | files_ = nil; | |
6100 | ||
6101 | [super releaseSubviews]; | |
6102 | } | |
6103 | ||
6104 | - (id) initWithDatabase:(Database *)database { | |
6105 | if ((self = [super init]) != nil) { | |
6106 | database_ = database; | |
6107 | } return self; | |
6108 | } | |
6109 | ||
6110 | - (void) setPackage:(Package *)package { | |
6111 | package_ = nil; | |
6112 | name_ = nil; | |
6113 | ||
6114 | files_ = [NSMutableArray arrayWithCapacity:32]; | |
6115 | ||
6116 | if (package != nil) { | |
6117 | package_ = package; | |
6118 | name_ = [package id]; | |
6119 | ||
6120 | if (NSArray *files = [package files]) | |
6121 | [files_ addObjectsFromArray:files]; | |
6122 | ||
6123 | if ([files_ count] != 0) { | |
6124 | if ([[files_ objectAtIndex:0] isEqualToString:@"/."]) | |
6125 | [files_ removeObjectAtIndex:0]; | |
6126 | [files_ sortUsingSelector:@selector(compareByPath:)]; | |
6127 | ||
6128 | NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8]; | |
6129 | [stack addObject:@"/"]; | |
6130 | ||
6131 | for (int i(0), e([files_ count]); i != e; ++i) { | |
6132 | NSString *file = [files_ objectAtIndex:i]; | |
6133 | while (![file hasPrefix:[stack lastObject]]) | |
6134 | [stack removeLastObject]; | |
6135 | NSString *directory = [stack lastObject]; | |
6136 | [stack addObject:[file stringByAppendingString:@"/"]]; | |
6137 | [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@", | |
6138 | ([stack count] - 2) * 3, "", | |
6139 | [file substringFromIndex:[directory length]] | |
6140 | ]]; | |
6141 | } | |
6142 | } | |
6143 | } | |
6144 | ||
6145 | [list_ reloadData]; | |
6146 | } | |
6147 | ||
6148 | - (void) reloadData { | |
6149 | [super reloadData]; | |
6150 | ||
6151 | [self setPackage:[database_ packageWithName:name_]]; | |
6152 | } | |
6153 | ||
6154 | @end | |
6155 | /* }}} */ | |
6156 | /* Package Controller {{{ */ | |
6157 | @interface CYPackageController : CydiaWebViewController < | |
6158 | UIActionSheetDelegate | |
6159 | > { | |
6160 | _transient Database *database_; | |
6161 | _H<Package> package_; | |
6162 | _H<NSString> name_; | |
6163 | bool commercial_; | |
6164 | _H<NSMutableArray> buttons_; | |
6165 | _H<UIBarButtonItem> button_; | |
6166 | } | |
6167 | ||
6168 | - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer; | |
6169 | ||
6170 | @end | |
6171 | ||
6172 | @implementation CYPackageController | |
6173 | ||
6174 | - (NSURL *) navigationURL { | |
6175 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]]; | |
6176 | } | |
6177 | ||
6178 | /* XXX: this is not safe at all... localization of /fail/ */ | |
6179 | - (void) _clickButtonWithName:(NSString *)name { | |
6180 | if ([name isEqualToString:UCLocalize("CLEAR")]) | |
6181 | [delegate_ clearPackage:package_]; | |
6182 | else if ([name isEqualToString:UCLocalize("INSTALL")]) | |
6183 | [delegate_ installPackage:package_]; | |
6184 | else if ([name isEqualToString:UCLocalize("REINSTALL")]) | |
6185 | [delegate_ installPackage:package_]; | |
6186 | else if ([name isEqualToString:UCLocalize("REMOVE")]) | |
6187 | [delegate_ removePackage:package_]; | |
6188 | else if ([name isEqualToString:UCLocalize("UPGRADE")]) | |
6189 | [delegate_ installPackage:package_]; | |
6190 | else _assert(false); | |
6191 | } | |
6192 | ||
6193 | - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button { | |
6194 | NSString *context([sheet context]); | |
6195 | ||
6196 | if ([context isEqualToString:@"modify"]) { | |
6197 | if (button != [sheet cancelButtonIndex]) { | |
6198 | NSString *buttonName = [buttons_ objectAtIndex:button]; | |
6199 | [self _clickButtonWithName:buttonName]; | |
6200 | } | |
6201 | ||
6202 | [sheet dismissWithClickedButtonIndex:-1 animated:YES]; | |
6203 | } | |
6204 | } | |
6205 | ||
6206 | - (bool) _allowJavaScriptPanel { | |
6207 | return commercial_; | |
6208 | } | |
6209 | ||
6210 | #if !AlwaysReload | |
6211 | - (void) _customButtonClicked { | |
6212 | int count([buttons_ count]); | |
6213 | if (count == 0) | |
6214 | return; | |
6215 | ||
6216 | if (count == 1) | |
6217 | [self _clickButtonWithName:[buttons_ objectAtIndex:0]]; | |
6218 | else { | |
6219 | NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count]; | |
6220 | [buttons addObjectsFromArray:buttons_]; | |
6221 | ||
6222 | UIActionSheet *sheet = [[[UIActionSheet alloc] | |
6223 | initWithTitle:nil | |
6224 | delegate:self | |
6225 | cancelButtonTitle:nil | |
6226 | destructiveButtonTitle:nil | |
6227 | otherButtonTitles:nil | |
6228 | ] autorelease]; | |
6229 | ||
6230 | for (NSString *button in buttons) [sheet addButtonWithTitle:button]; | |
6231 | if (!IsWildcat_) { | |
6232 | [sheet addButtonWithTitle:UCLocalize("CANCEL")]; | |
6233 | [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1]; | |
6234 | } | |
6235 | [sheet setContext:@"modify"]; | |
6236 | ||
6237 | [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]]; | |
6238 | } | |
6239 | } | |
6240 | ||
6241 | - (void) reloadButtonClicked { | |
6242 | if (commercial_ && function_ == nil && [package_ uninstalled]) | |
6243 | return; | |
6244 | [self customButtonClicked]; | |
6245 | } | |
6246 | ||
6247 | - (void) applyLoadingTitle { | |
6248 | // Don't show "Loading" as the title. Ever. | |
6249 | } | |
6250 | ||
6251 | - (UIBarButtonItem *) rightButton { | |
6252 | return button_; | |
6253 | } | |
6254 | #endif | |
6255 | ||
6256 | - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer { | |
6257 | if ((self = [super init]) != nil) { | |
6258 | database_ = database; | |
6259 | buttons_ = [NSMutableArray arrayWithCapacity:4]; | |
6260 | name_ = name == nil ? @"" : [NSString stringWithString:name]; | |
6261 | [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer]; | |
6262 | } return self; | |
6263 | } | |
6264 | ||
6265 | - (void) reloadData { | |
6266 | [super reloadData]; | |
6267 | ||
6268 | package_ = [database_ packageWithName:name_]; | |
6269 | ||
6270 | [buttons_ removeAllObjects]; | |
6271 | ||
6272 | if (package_ != nil) { | |
6273 | [(Package *) package_ parse]; | |
6274 | ||
6275 | commercial_ = [package_ isCommercial]; | |
6276 | ||
6277 | if ([package_ mode] != nil) | |
6278 | [buttons_ addObject:UCLocalize("CLEAR")]; | |
6279 | if ([package_ source] == nil); | |
6280 | else if ([package_ upgradableAndEssential:NO]) | |
6281 | [buttons_ addObject:UCLocalize("UPGRADE")]; | |
6282 | else if ([package_ uninstalled]) | |
6283 | [buttons_ addObject:UCLocalize("INSTALL")]; | |
6284 | else | |
6285 | [buttons_ addObject:UCLocalize("REINSTALL")]; | |
6286 | if (![package_ uninstalled]) | |
6287 | [buttons_ addObject:UCLocalize("REMOVE")]; | |
6288 | } | |
6289 | ||
6290 | NSString *title; | |
6291 | switch ([buttons_ count]) { | |
6292 | case 0: title = nil; break; | |
6293 | case 1: title = [buttons_ objectAtIndex:0]; break; | |
6294 | default: title = UCLocalize("MODIFY"); break; | |
6295 | } | |
6296 | ||
6297 | button_ = [[[UIBarButtonItem alloc] | |
6298 | initWithTitle:title | |
6299 | style:UIBarButtonItemStylePlain | |
6300 | target:self | |
6301 | action:@selector(customButtonClicked) | |
6302 | ] autorelease]; | |
6303 | } | |
6304 | ||
6305 | - (bool) isLoading { | |
6306 | return commercial_ ? [super isLoading] : false; | |
6307 | } | |
6308 | ||
6309 | @end | |
6310 | /* }}} */ | |
6311 | ||
6312 | /* Package List Controller {{{ */ | |
6313 | @interface PackageListController : CyteViewController < | |
6314 | UITableViewDataSource, | |
6315 | UITableViewDelegate | |
6316 | > { | |
6317 | _transient Database *database_; | |
6318 | unsigned era_; | |
6319 | _H<NSArray> packages_; | |
6320 | _H<NSArray> sections_; | |
6321 | _H<UITableView, 2> list_; | |
6322 | ||
6323 | _H<NSArray> thumbs_; | |
6324 | std::vector<NSInteger> offset_; | |
6325 | ||
6326 | _H<NSString> title_; | |
6327 | unsigned reloading_; | |
6328 | } | |
6329 | ||
6330 | - (id) initWithDatabase:(Database *)database title:(NSString *)title; | |
6331 | - (void) setDelegate:(id)delegate; | |
6332 | - (void) resetCursor; | |
6333 | - (void) clearData; | |
6334 | ||
6335 | - (NSArray *) sectionsForPackages:(NSMutableArray *)packages; | |
6336 | ||
6337 | @end | |
6338 | ||
6339 | @implementation PackageListController | |
6340 | ||
6341 | - (NSURL *) referrerURL { | |
6342 | return [self navigationURL]; | |
6343 | } | |
6344 | ||
6345 | - (bool) isSummarized { | |
6346 | return false; | |
6347 | } | |
6348 | ||
6349 | - (bool) showsSections { | |
6350 | return true; | |
6351 | } | |
6352 | ||
6353 | - (void) deselectWithAnimation:(BOOL)animated { | |
6354 | [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; | |
6355 | } | |
6356 | ||
6357 | - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve { | |
6358 | CGRect base = [[self view] bounds]; | |
6359 | base.size.height -= bounds.size.height; | |
6360 | base.origin = [list_ frame].origin; | |
6361 | ||
6362 | [UIView beginAnimations:nil context:NULL]; | |
6363 | [UIView setAnimationBeginsFromCurrentState:YES]; | |
6364 | [UIView setAnimationCurve:curve]; | |
6365 | [UIView setAnimationDuration:duration]; | |
6366 | [list_ setFrame:base]; | |
6367 | [UIView commitAnimations]; | |
6368 | } | |
6369 | ||
6370 | - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration { | |
6371 | [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear]; | |
6372 | } | |
6373 | ||
6374 | - (void) resizeForKeyboardBounds:(CGRect)bounds { | |
6375 | [self resizeForKeyboardBounds:bounds duration:0]; | |
6376 | } | |
6377 | ||
6378 | - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification { | |
6379 | if (&UIKeyboardAnimationCurveUserInfoKey == NULL) | |
6380 | *curve = UIViewAnimationCurveEaseInOut; | |
6381 | else | |
6382 | [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve]; | |
6383 | ||
6384 | if (&UIKeyboardAnimationDurationUserInfoKey == NULL) | |
6385 | *duration = 0.3; | |
6386 | else | |
6387 | [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration]; | |
6388 | } | |
6389 | ||
6390 | - (void) keyboardWillShow:(NSNotification *)notification { | |
6391 | CGRect bounds; | |
6392 | CGPoint center; | |
6393 | [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds]; | |
6394 | [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er]; | |
6395 | ||
6396 | NSTimeInterval duration; | |
6397 | UIViewAnimationCurve curve; | |
6398 | [self getKeyboardCurve:&curve duration:&duration forNotification:notification]; | |
6399 | ||
6400 | 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); | |
6401 | UIViewController *base = self; | |
6402 | while ([base parentOrPresentingViewController] != nil) | |
6403 | base = [base parentOrPresentingViewController]; | |
6404 | CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]]; | |
6405 | CGRect intersection = CGRectIntersection(viewframe, kbframe); | |
6406 | ||
6407 | if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4) | |
6408 | intersection.size.height += CYStatusBarHeight(); | |
6409 | ||
6410 | [self resizeForKeyboardBounds:intersection duration:duration curve:curve]; | |
6411 | } | |
6412 | ||
6413 | - (void) keyboardWillHide:(NSNotification *)notification { | |
6414 | NSTimeInterval duration; | |
6415 | UIViewAnimationCurve curve; | |
6416 | [self getKeyboardCurve:&curve duration:&duration forNotification:notification]; | |
6417 | ||
6418 | [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve]; | |
6419 | } | |
6420 | ||
6421 | - (void) viewWillAppear:(BOOL)animated { | |
6422 | [super viewWillAppear:animated]; | |
6423 | ||
6424 | [self resizeForKeyboardBounds:CGRectZero]; | |
6425 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; | |
6426 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; | |
6427 | } | |
6428 | ||
6429 | - (void) viewWillDisappear:(BOOL)animated { | |
6430 | [super viewWillDisappear:animated]; | |
6431 | ||
6432 | [self resizeForKeyboardBounds:CGRectZero]; | |
6433 | [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; | |
6434 | [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; | |
6435 | } | |
6436 | ||
6437 | - (void) viewDidAppear:(BOOL)animated { | |
6438 | [super viewDidAppear:animated]; | |
6439 | [self deselectWithAnimation:animated]; | |
6440 | } | |
6441 | ||
6442 | - (void) didSelectPackage:(Package *)package { | |
6443 | CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]); | |
6444 | [view setDelegate:delegate_]; | |
6445 | [[self navigationController] pushViewController:view animated:YES]; | |
6446 | } | |
6447 | ||
6448 | - (NSInteger) numberOfSectionsInTableView:(UITableView *)list { | |
6449 | NSInteger count([sections_ count]); | |
6450 | return count == 0 ? 1 : count; | |
6451 | } | |
6452 | ||
6453 | - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section { | |
6454 | if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0) | |
6455 | return nil; | |
6456 | return [[sections_ objectAtIndex:section] name]; | |
6457 | } | |
6458 | ||
6459 | - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section { | |
6460 | if ([sections_ count] == 0) | |
6461 | return 0; | |
6462 | return [[sections_ objectAtIndex:section] count]; | |
6463 | } | |
6464 | ||
6465 | - (Package *) packageAtIndexPath:(NSIndexPath *)path { | |
6466 | @synchronized (database_) { | |
6467 | if ([database_ era] != era_) | |
6468 | return nil; | |
6469 | ||
6470 | Section *section([sections_ objectAtIndex:[path section]]); | |
6471 | NSInteger row([path row]); | |
6472 | Package *package([packages_ objectAtIndex:([section row] + row)]); | |
6473 | return [[package retain] autorelease]; | |
6474 | } } | |
6475 | ||
6476 | - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path { | |
6477 | PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]); | |
6478 | if (cell == nil) | |
6479 | cell = [[[PackageCell alloc] init] autorelease]; | |
6480 | ||
6481 | Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]); | |
6482 | [cell setPackage:package asSummary:[self isSummarized]]; | |
6483 | return cell; | |
6484 | } | |
6485 | ||
6486 | - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path { | |
6487 | Package *package([self packageAtIndexPath:path]); | |
6488 | package = [database_ packageWithName:[package id]]; | |
6489 | [self didSelectPackage:package]; | |
6490 | } | |
6491 | ||
6492 | - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView { | |
6493 | return thumbs_; | |
6494 | } | |
6495 | ||
6496 | - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { | |
6497 | return offset_[index]; | |
6498 | } | |
6499 | ||
6500 | - (void) updateHeight { | |
6501 | [list_ setRowHeight:([self isSummarized] ? 38 : 73)]; | |
6502 | } | |
6503 | ||
6504 | - (id) initWithDatabase:(Database *)database title:(NSString *)title { | |
6505 | if ((self = [super init]) != nil) { | |
6506 | database_ = database; | |
6507 | title_ = [title copy]; | |
6508 | [[self navigationItem] setTitle:title_]; | |
6509 | } return self; | |
6510 | } | |
6511 | ||
6512 | - (void) loadView { | |
6513 | UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]); | |
6514 | [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)]; | |
6515 | [self setView:view]; | |
6516 | ||
6517 | list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease]; | |
6518 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
6519 | [view addSubview:list_]; | |
6520 | ||
6521 | // XXX: is 20 the most optimal number here? | |
6522 | [list_ setSectionIndexMinimumDisplayRowCount:20]; | |
6523 | ||
6524 | [(UITableView *) list_ setDataSource:self]; | |
6525 | [list_ setDelegate:self]; | |
6526 | ||
6527 | [self updateHeight]; | |
6528 | } | |
6529 | ||
6530 | - (void) releaseSubviews { | |
6531 | list_ = nil; | |
6532 | ||
6533 | packages_ = nil; | |
6534 | sections_ = nil; | |
6535 | ||
6536 | thumbs_ = nil; | |
6537 | offset_.clear(); | |
6538 | ||
6539 | [super releaseSubviews]; | |
6540 | } | |
6541 | ||
6542 | - (void) setDelegate:(id)delegate { | |
6543 | delegate_ = delegate; | |
6544 | } | |
6545 | ||
6546 | - (bool) shouldYield { | |
6547 | return false; | |
6548 | } | |
6549 | ||
6550 | - (bool) shouldBlock { | |
6551 | return false; | |
6552 | } | |
6553 | ||
6554 | - (NSMutableArray *) _reloadPackages { | |
6555 | @synchronized (database_) { | |
6556 | era_ = [database_ era]; | |
6557 | NSArray *packages([database_ packages]); | |
6558 | ||
6559 | return [NSMutableArray arrayWithArray:packages]; | |
6560 | } } | |
6561 | ||
6562 | - (void) _reloadData { | |
6563 | if (reloading_ != 0) { | |
6564 | reloading_ = 2; | |
6565 | return; | |
6566 | } | |
6567 | ||
6568 | NSMutableArray *packages; | |
6569 | ||
6570 | reload: | |
6571 | if ([self shouldYield]) { | |
6572 | do { | |
6573 | UIProgressHUD *hud; | |
6574 | ||
6575 | if (![self shouldBlock]) | |
6576 | hud = nil; | |
6577 | else { | |
6578 | hud = [delegate_ addProgressHUD]; | |
6579 | [hud setText:UCLocalize("LOADING")]; | |
6580 | } | |
6581 | ||
6582 | reloading_ = 1; | |
6583 | packages = [self yieldToSelector:@selector(_reloadPackages)]; | |
6584 | ||
6585 | if (hud != nil) | |
6586 | [delegate_ removeProgressHUD:hud]; | |
6587 | } while (reloading_ == 2); | |
6588 | } else { | |
6589 | packages = [self _reloadPackages]; | |
6590 | } | |
6591 | ||
6592 | @synchronized (database_) { | |
6593 | if (era_ != [database_ era]) | |
6594 | goto reload; | |
6595 | reloading_ = 0; | |
6596 | ||
6597 | thumbs_ = nil; | |
6598 | offset_.clear(); | |
6599 | ||
6600 | packages_ = packages; | |
6601 | ||
6602 | if ([self showsSections]) | |
6603 | sections_ = [self sectionsForPackages:packages]; | |
6604 | else { | |
6605 | Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]); | |
6606 | [section setCount:[packages_ count]]; | |
6607 | sections_ = [NSArray arrayWithObject:section]; | |
6608 | } | |
6609 | ||
6610 | [self updateHeight]; | |
6611 | ||
6612 | _profile(PackageTable$reloadData$List) | |
6613 | [(UITableView *) list_ setDataSource:self]; | |
6614 | [list_ reloadData]; | |
6615 | _end | |
6616 | } | |
6617 | ||
6618 | PrintTimes(); | |
6619 | } | |
6620 | ||
6621 | - (NSArray *) sectionsForPackages:(NSMutableArray *)packages { | |
6622 | Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]); | |
6623 | size_t end([packages count]); | |
6624 | ||
6625 | NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]); | |
6626 | Section *section(prefix); | |
6627 | ||
6628 | thumbs_ = CollationThumbs_; | |
6629 | offset_ = CollationOffset_; | |
6630 | ||
6631 | size_t offset(0); | |
6632 | size_t offsets([CollationStarts_ count]); | |
6633 | ||
6634 | NSString *start([CollationStarts_ objectAtIndex:offset]); | |
6635 | size_t length([start length]); | |
6636 | ||
6637 | for (size_t index(0); index != end; ++index) { | |
6638 | if (start != nil) { | |
6639 | Package *package([packages objectAtIndex:index]); | |
6640 | NSString *name(PackageName(package, @selector(cyname))); | |
6641 | ||
6642 | //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) { | |
6643 | while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) { | |
6644 | NSString *title([CollationTitles_ objectAtIndex:offset]); | |
6645 | section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease]; | |
6646 | [sections addObject:section]; | |
6647 | ||
6648 | start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset]; | |
6649 | if (start == nil) | |
6650 | break; | |
6651 | length = [start length]; | |
6652 | } | |
6653 | } | |
6654 | ||
6655 | [section addToCount]; | |
6656 | } | |
6657 | ||
6658 | for (; offset != offsets; ++offset) { | |
6659 | NSString *title([CollationTitles_ objectAtIndex:offset]); | |
6660 | Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]); | |
6661 | [sections addObject:section]; | |
6662 | } | |
6663 | ||
6664 | if ([prefix count] != 0) { | |
6665 | Section *suffix([sections lastObject]); | |
6666 | [prefix setName:[suffix name]]; | |
6667 | [suffix setName:nil]; | |
6668 | [sections insertObject:prefix atIndex:(offsets - 1)]; | |
6669 | } | |
6670 | ||
6671 | return sections; | |
6672 | } | |
6673 | ||
6674 | - (void) reloadData { | |
6675 | [super reloadData]; | |
6676 | ||
6677 | if ([self shouldYield]) | |
6678 | [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0]; | |
6679 | else | |
6680 | [self _reloadData]; | |
6681 | } | |
6682 | ||
6683 | - (void) resetCursor { | |
6684 | [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO]; | |
6685 | } | |
6686 | ||
6687 | - (void) clearData { | |
6688 | [self updateHeight]; | |
6689 | ||
6690 | [list_ setDataSource:nil]; | |
6691 | [list_ reloadData]; | |
6692 | ||
6693 | [self resetCursor]; | |
6694 | } | |
6695 | ||
6696 | @end | |
6697 | /* }}} */ | |
6698 | /* Filtered Package List Controller {{{ */ | |
6699 | typedef Function<bool, Package *> PackageFilter; | |
6700 | typedef Function<void, NSMutableArray *> PackageSorter; | |
6701 | @interface FilteredPackageListController : PackageListController { | |
6702 | PackageFilter filter_; | |
6703 | PackageSorter sorter_; | |
6704 | } | |
6705 | ||
6706 | - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter; | |
6707 | ||
6708 | - (void) setFilter:(PackageFilter)filter; | |
6709 | - (void) setSorter:(PackageSorter)sorter; | |
6710 | ||
6711 | @end | |
6712 | ||
6713 | @implementation FilteredPackageListController | |
6714 | ||
6715 | - (void) setFilter:(PackageFilter)filter { | |
6716 | @synchronized (self) { | |
6717 | filter_ = filter; | |
6718 | } } | |
6719 | ||
6720 | - (void) setSorter:(PackageSorter)sorter { | |
6721 | @synchronized (self) { | |
6722 | sorter_ = sorter; | |
6723 | } } | |
6724 | ||
6725 | - (NSMutableArray *) _reloadPackages { | |
6726 | @synchronized (database_) { | |
6727 | era_ = [database_ era]; | |
6728 | ||
6729 | NSArray *packages([database_ packages]); | |
6730 | NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]); | |
6731 | ||
6732 | PackageFilter filter; | |
6733 | PackageSorter sorter; | |
6734 | ||
6735 | @synchronized (self) { | |
6736 | filter = filter_; | |
6737 | sorter = sorter_; | |
6738 | } | |
6739 | ||
6740 | _profile(PackageTable$reloadData$Filter) | |
6741 | for (Package *package in packages) | |
6742 | if ([package valid] && filter(package)) | |
6743 | [filtered addObject:package]; | |
6744 | _end | |
6745 | ||
6746 | if (sorter) | |
6747 | sorter(filtered); | |
6748 | return filtered; | |
6749 | } } | |
6750 | ||
6751 | - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter { | |
6752 | if ((self = [super initWithDatabase:database title:title]) != nil) { | |
6753 | [self setFilter:filter]; | |
6754 | } return self; | |
6755 | } | |
6756 | ||
6757 | @end | |
6758 | /* }}} */ | |
6759 | ||
6760 | /* Home Controller {{{ */ | |
6761 | @interface HomeController : CydiaWebViewController { | |
6762 | CFRunLoopRef runloop_; | |
6763 | SCNetworkReachabilityRef reachability_; | |
6764 | } | |
6765 | ||
6766 | @end | |
6767 | ||
6768 | @implementation HomeController | |
6769 | ||
6770 | static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) { | |
6771 | [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"]; | |
6772 | } | |
6773 | ||
6774 | - (id) init { | |
6775 | if ((self = [super init]) != nil) { | |
6776 | [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]]; | |
6777 | [self reloadData]; | |
6778 | ||
6779 | reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com"); | |
6780 | if (reachability_ != NULL) { | |
6781 | SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL}; | |
6782 | SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context); | |
6783 | ||
6784 | CFRunLoopRef runloop(CFRunLoopGetCurrent()); | |
6785 | if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode)) | |
6786 | runloop_ = runloop; | |
6787 | } | |
6788 | } return self; | |
6789 | } | |
6790 | ||
6791 | - (void) dealloc { | |
6792 | if (reachability_ != NULL && runloop_ != NULL) | |
6793 | SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode); | |
6794 | [super dealloc]; | |
6795 | } | |
6796 | ||
6797 | - (NSURL *) navigationURL { | |
6798 | return [NSURL URLWithString:@"cydia://home"]; | |
6799 | } | |
6800 | ||
6801 | - (void) aboutButtonClicked { | |
6802 | UIAlertView *alert([[[UIAlertView alloc] init] autorelease]); | |
6803 | ||
6804 | [alert setTitle:UCLocalize("ABOUT_CYDIA")]; | |
6805 | [alert addButtonWithTitle:UCLocalize("CLOSE")]; | |
6806 | [alert setCancelButtonIndex:0]; | |
6807 | ||
6808 | [alert setMessage: | |
6809 | @"Copyright \u00a9 2008-2013\n" | |
6810 | "SaurikIT, LLC\n" | |
6811 | "\n" | |
6812 | "Jay Freeman (saurik)\n" | |
6813 | "saurik@saurik.com\n" | |
6814 | "http://www.saurik.com/" | |
6815 | ]; | |
6816 | ||
6817 | [alert show]; | |
6818 | } | |
6819 | ||
6820 | - (UIBarButtonItem *) leftButton { | |
6821 | return [[[UIBarButtonItem alloc] | |
6822 | initWithTitle:UCLocalize("ABOUT") | |
6823 | style:UIBarButtonItemStylePlain | |
6824 | target:self | |
6825 | action:@selector(aboutButtonClicked) | |
6826 | ] autorelease]; | |
6827 | } | |
6828 | ||
6829 | @end | |
6830 | /* }}} */ | |
6831 | ||
6832 | /* Cydia Navigation Controller Interface {{{ */ | |
6833 | @interface UINavigationController (Cydia) | |
6834 | ||
6835 | - (NSArray *) navigationURLCollection; | |
6836 | - (void) unloadData; | |
6837 | ||
6838 | @end | |
6839 | /* }}} */ | |
6840 | ||
6841 | /* Cydia Tab Bar Controller {{{ */ | |
6842 | @interface CydiaTabBarController : CyteTabBarController < | |
6843 | UITabBarControllerDelegate, | |
6844 | FetchDelegate | |
6845 | > { | |
6846 | _transient Database *database_; | |
6847 | ||
6848 | _H<UIActivityIndicatorView> indicator_; | |
6849 | ||
6850 | bool updating_; | |
6851 | // XXX: ok, "updatedelegate_"?... | |
6852 | _transient NSObject<CydiaDelegate> *updatedelegate_; | |
6853 | } | |
6854 | ||
6855 | - (NSArray *) navigationURLCollection; | |
6856 | - (void) beginUpdate; | |
6857 | - (BOOL) updating; | |
6858 | ||
6859 | @end | |
6860 | ||
6861 | @implementation CydiaTabBarController | |
6862 | ||
6863 | - (NSArray *) navigationURLCollection { | |
6864 | NSMutableArray *items([NSMutableArray array]); | |
6865 | ||
6866 | // XXX: Should this deal with transient view controllers? | |
6867 | for (id navigation in [self viewControllers]) { | |
6868 | NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)]; | |
6869 | if (stack != nil) | |
6870 | [items addObject:stack]; | |
6871 | } | |
6872 | ||
6873 | return items; | |
6874 | } | |
6875 | ||
6876 | - (id) initWithDatabase:(Database *)database { | |
6877 | if ((self = [super init]) != nil) { | |
6878 | database_ = database; | |
6879 | [self setDelegate:self]; | |
6880 | ||
6881 | indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease]; | |
6882 | [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)]; | |
6883 | ||
6884 | [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
6885 | } return self; | |
6886 | } | |
6887 | ||
6888 | - (void) setUpdate:(NSDate *)date { | |
6889 | [self beginUpdate]; | |
6890 | } | |
6891 | ||
6892 | - (void) beginUpdate { | |
6893 | if (updating_) | |
6894 | return; | |
6895 | ||
6896 | UIViewController *controller([[self viewControllers] objectAtIndex:1]); | |
6897 | UITabBarItem *item([controller tabBarItem]); | |
6898 | ||
6899 | [item setBadgeValue:@""]; | |
6900 | UIView *badge(MSHookIvar<UIView *>([item view], "_badge")); | |
6901 | ||
6902 | [indicator_ startAnimating]; | |
6903 | [badge addSubview:indicator_]; | |
6904 | ||
6905 | [updatedelegate_ retainNetworkActivityIndicator]; | |
6906 | updating_ = true; | |
6907 | ||
6908 | [NSThread | |
6909 | detachNewThreadSelector:@selector(performUpdate) | |
6910 | toTarget:self | |
6911 | withObject:nil | |
6912 | ]; | |
6913 | } | |
6914 | ||
6915 | - (void) performUpdate { | |
6916 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
6917 | ||
6918 | SourceStatus status(self, database_); | |
6919 | [database_ updateWithStatus:status]; | |
6920 | ||
6921 | [self | |
6922 | performSelectorOnMainThread:@selector(completeUpdate) | |
6923 | withObject:nil | |
6924 | waitUntilDone:NO | |
6925 | ]; | |
6926 | ||
6927 | [pool release]; | |
6928 | } | |
6929 | ||
6930 | - (void) stopUpdateWithSelector:(SEL)selector { | |
6931 | updating_ = false; | |
6932 | [updatedelegate_ releaseNetworkActivityIndicator]; | |
6933 | ||
6934 | UIViewController *controller([[self viewControllers] objectAtIndex:1]); | |
6935 | [[controller tabBarItem] setBadgeValue:nil]; | |
6936 | ||
6937 | [indicator_ removeFromSuperview]; | |
6938 | [indicator_ stopAnimating]; | |
6939 | ||
6940 | [updatedelegate_ performSelector:selector withObject:nil afterDelay:0]; | |
6941 | } | |
6942 | ||
6943 | - (void) completeUpdate { | |
6944 | if (!updating_) | |
6945 | return; | |
6946 | [self stopUpdateWithSelector:@selector(reloadData)]; | |
6947 | } | |
6948 | ||
6949 | - (void) cancelUpdate { | |
6950 | [self stopUpdateWithSelector:@selector(updateDataAndLoad)]; | |
6951 | } | |
6952 | ||
6953 | - (void) cancelPressed { | |
6954 | [self cancelUpdate]; | |
6955 | } | |
6956 | ||
6957 | - (BOOL) updating { | |
6958 | return updating_; | |
6959 | } | |
6960 | ||
6961 | - (bool) isSourceCancelled { | |
6962 | return !updating_; | |
6963 | } | |
6964 | ||
6965 | - (void) startSourceFetch:(NSString *)uri { | |
6966 | } | |
6967 | ||
6968 | - (void) stopSourceFetch:(NSString *)uri { | |
6969 | } | |
6970 | ||
6971 | - (void) setUpdateDelegate:(id)delegate { | |
6972 | updatedelegate_ = delegate; | |
6973 | } | |
6974 | ||
6975 | - (UIView *) transitionView { | |
6976 | if (![self respondsToSelector:@selector(_transitionView)]) | |
6977 | return MSHookIvar<id>(self, "_viewControllerTransitionView"); | |
6978 | else if (kCFCoreFoundationVersionNumber < 800) | |
6979 | return [self _transitionView]; | |
6980 | else | |
6981 | return [[[self _transitionView] superview] superview]; | |
6982 | } | |
6983 | ||
6984 | @end | |
6985 | /* }}} */ | |
6986 | ||
6987 | /* Cydia Navigation Controller Implementation {{{ */ | |
6988 | @implementation UINavigationController (Cydia) | |
6989 | ||
6990 | - (NSArray *) navigationURLCollection { | |
6991 | NSMutableArray *stack([NSMutableArray array]); | |
6992 | ||
6993 | for (CyteViewController *controller in [self viewControllers]) { | |
6994 | NSString *url = [[controller navigationURL] absoluteString]; | |
6995 | if (url != nil) | |
6996 | [stack addObject:url]; | |
6997 | } | |
6998 | ||
6999 | return stack; | |
7000 | } | |
7001 | ||
7002 | - (void) reloadData { | |
7003 | [super reloadData]; | |
7004 | ||
7005 | UIViewController *visible([self visibleViewController]); | |
7006 | if (visible != nil) | |
7007 | [visible reloadData]; | |
7008 | ||
7009 | // on the iPad, this view controller is ALSO visible. :( | |
7010 | if (IsWildcat_) | |
7011 | if (UIViewController *top = [self topViewController]) | |
7012 | if (top != visible) | |
7013 | [top reloadData]; | |
7014 | } | |
7015 | ||
7016 | - (void) unloadData { | |
7017 | for (CyteViewController *page in [self viewControllers]) | |
7018 | [page unloadData]; | |
7019 | ||
7020 | [super unloadData]; | |
7021 | } | |
7022 | ||
7023 | @end | |
7024 | /* }}} */ | |
7025 | ||
7026 | /* Cydia:// Protocol {{{ */ | |
7027 | @interface CydiaURLProtocol : NSURLProtocol { | |
7028 | } | |
7029 | ||
7030 | @end | |
7031 | ||
7032 | @implementation CydiaURLProtocol | |
7033 | ||
7034 | + (BOOL) canInitWithRequest:(NSURLRequest *)request { | |
7035 | NSURL *url([request URL]); | |
7036 | if (url == nil) | |
7037 | return NO; | |
7038 | ||
7039 | NSString *scheme([[url scheme] lowercaseString]); | |
7040 | if (scheme != nil && [scheme isEqualToString:@"cydia"]) | |
7041 | return YES; | |
7042 | if ([[url absoluteString] hasPrefix:@"about:cydia-"]) | |
7043 | return YES; | |
7044 | ||
7045 | return NO; | |
7046 | } | |
7047 | ||
7048 | + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request { | |
7049 | return request; | |
7050 | } | |
7051 | ||
7052 | - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request { | |
7053 | id<NSURLProtocolClient> client([self client]); | |
7054 | if (icon == nil) | |
7055 | [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]]; | |
7056 | else { | |
7057 | NSData *data(UIImagePNGRepresentation(icon)); | |
7058 | ||
7059 | NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]); | |
7060 | [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; | |
7061 | [client URLProtocol:self didLoadData:data]; | |
7062 | [client URLProtocolDidFinishLoading:self]; | |
7063 | } | |
7064 | } | |
7065 | ||
7066 | - (void) startLoading { | |
7067 | id<NSURLProtocolClient> client([self client]); | |
7068 | NSURLRequest *request([self request]); | |
7069 | ||
7070 | NSURL *url([request URL]); | |
7071 | NSString *href([url absoluteString]); | |
7072 | NSString *scheme([[url scheme] lowercaseString]); | |
7073 | ||
7074 | NSString *path; | |
7075 | ||
7076 | if ([scheme isEqualToString:@"cydia"]) | |
7077 | path = [href substringFromIndex:8]; | |
7078 | else if ([scheme isEqualToString:@"about"]) | |
7079 | path = [href substringFromIndex:12]; | |
7080 | else _assert(false); | |
7081 | ||
7082 | NSRange slash([path rangeOfString:@"/"]); | |
7083 | ||
7084 | NSString *command; | |
7085 | if (slash.location == NSNotFound) { | |
7086 | command = path; | |
7087 | path = nil; | |
7088 | } else { | |
7089 | command = [path substringToIndex:slash.location]; | |
7090 | path = [path substringFromIndex:(slash.location + 1)]; | |
7091 | } | |
7092 | ||
7093 | Database *database([Database sharedInstance]); | |
7094 | ||
7095 | if ([command isEqualToString:@"package-icon"]) { | |
7096 | if (path == nil) | |
7097 | goto fail; | |
7098 | path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
7099 | Package *package([database packageWithName:path]); | |
7100 | if (package == nil) | |
7101 | goto fail; | |
7102 | [package parse]; | |
7103 | UIImage *icon([package icon]); | |
7104 | [self _returnPNGWithImage:icon forRequest:request]; | |
7105 | } else if ([command isEqualToString:@"uikit-image"]) { | |
7106 | if (path == nil) | |
7107 | goto fail; | |
7108 | path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
7109 | UIImage *icon(_UIImageWithName(path)); | |
7110 | [self _returnPNGWithImage:icon forRequest:request]; | |
7111 | } else if ([command isEqualToString:@"section-icon"]) { | |
7112 | if (path == nil) | |
7113 | goto fail; | |
7114 | path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
7115 | UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]); | |
7116 | if (icon == nil) | |
7117 | icon = [UIImage applicationImageNamed:@"unknown.png"]; | |
7118 | [self _returnPNGWithImage:icon forRequest:request]; | |
7119 | } else fail: { | |
7120 | [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]]; | |
7121 | } | |
7122 | } | |
7123 | ||
7124 | - (void) stopLoading { | |
7125 | } | |
7126 | ||
7127 | @end | |
7128 | /* }}} */ | |
7129 | ||
7130 | /* Section Controller {{{ */ | |
7131 | @interface SectionController : FilteredPackageListController { | |
7132 | _H<NSString> key_; | |
7133 | _H<NSString> section_; | |
7134 | } | |
7135 | ||
7136 | - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section; | |
7137 | ||
7138 | @end | |
7139 | ||
7140 | @implementation SectionController | |
7141 | ||
7142 | - (NSURL *) referrerURL { | |
7143 | NSString *name(section_); | |
7144 | name = name ?: @"*"; | |
7145 | NSString *key(key_); | |
7146 | key = key ?: @"*"; | |
7147 | return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]]; | |
7148 | } | |
7149 | ||
7150 | - (NSURL *) navigationURL { | |
7151 | NSString *name(section_); | |
7152 | name = name ?: @"*"; | |
7153 | NSString *key(key_); | |
7154 | key = key ?: @"*"; | |
7155 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]]; | |
7156 | } | |
7157 | ||
7158 | - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section { | |
7159 | NSString *title; | |
7160 | if (section == nil) | |
7161 | title = UCLocalize("ALL_PACKAGES"); | |
7162 | else if (![section isEqual:@""]) | |
7163 | title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"]; | |
7164 | else | |
7165 | title = UCLocalize("NO_SECTION"); | |
7166 | ||
7167 | if ((self = [super initWithDatabase:database title:title]) != nil) { | |
7168 | key_ = [source key]; | |
7169 | section_ = section; | |
7170 | } return self; | |
7171 | } | |
7172 | ||
7173 | - (void) reloadData { | |
7174 | Source *source([database_ sourceWithKey:key_]); | |
7175 | _H<NSString> name(section_); | |
7176 | ||
7177 | [self setFilter:[=](Package *package) { | |
7178 | NSString *section([package section]); | |
7179 | ||
7180 | return ( | |
7181 | name == nil || | |
7182 | section == nil && [name length] == 0 || | |
7183 | [name isEqualToString:section] | |
7184 | ) && ( | |
7185 | source == nil || | |
7186 | [package source] == source | |
7187 | ) && [package visible]; | |
7188 | }]; | |
7189 | ||
7190 | [super reloadData]; | |
7191 | } | |
7192 | ||
7193 | @end | |
7194 | /* }}} */ | |
7195 | /* Sections Controller {{{ */ | |
7196 | @interface SectionsController : CyteViewController < | |
7197 | UITableViewDataSource, | |
7198 | UITableViewDelegate | |
7199 | > { | |
7200 | _transient Database *database_; | |
7201 | _H<NSString> key_; | |
7202 | _H<NSMutableArray> sections_; | |
7203 | _H<NSMutableArray> filtered_; | |
7204 | _H<UITableView, 2> list_; | |
7205 | } | |
7206 | ||
7207 | - (id) initWithDatabase:(Database *)database source:(Source *)source; | |
7208 | - (void) editButtonClicked; | |
7209 | ||
7210 | @end | |
7211 | ||
7212 | @implementation SectionsController | |
7213 | ||
7214 | - (NSURL *) navigationURL { | |
7215 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]]; | |
7216 | } | |
7217 | ||
7218 | - (Source *) source { | |
7219 | if (key_ == nil) | |
7220 | return nil; | |
7221 | return [database_ sourceWithKey:key_]; | |
7222 | } | |
7223 | ||
7224 | - (void) updateNavigationItem { | |
7225 | [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")]; | |
7226 | if ([sections_ count] == 0) { | |
7227 | [[self navigationItem] setRightBarButtonItem:nil]; | |
7228 | } else { | |
7229 | [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc] | |
7230 | initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit) | |
7231 | target:self | |
7232 | action:@selector(editButtonClicked) | |
7233 | ] animated:([[self navigationItem] rightBarButtonItem] != nil)]; | |
7234 | } | |
7235 | } | |
7236 | ||
7237 | - (void) setEditing:(BOOL)editing animated:(BOOL)animated { | |
7238 | [super setEditing:editing animated:animated]; | |
7239 | ||
7240 | if (editing) | |
7241 | [list_ reloadData]; | |
7242 | else | |
7243 | [delegate_ updateData]; | |
7244 | ||
7245 | [self updateNavigationItem]; | |
7246 | } | |
7247 | ||
7248 | - (void) viewDidAppear:(BOOL)animated { | |
7249 | [super viewDidAppear:animated]; | |
7250 | [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; | |
7251 | } | |
7252 | ||
7253 | - (void) viewWillDisappear:(BOOL)animated { | |
7254 | [super viewWillDisappear:animated]; | |
7255 | [self setEditing:NO]; | |
7256 | } | |
7257 | ||
7258 | - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath { | |
7259 | Section *section = nil; | |
7260 | int index = [indexPath row]; | |
7261 | if (![self isEditing]) { | |
7262 | index -= 1; | |
7263 | if (index >= 0) | |
7264 | section = [filtered_ objectAtIndex:index]; | |
7265 | } else { | |
7266 | section = [sections_ objectAtIndex:index]; | |
7267 | } | |
7268 | return section; | |
7269 | } | |
7270 | ||
7271 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
7272 | if ([self isEditing]) | |
7273 | return [sections_ count]; | |
7274 | else | |
7275 | return [filtered_ count] + 1; | |
7276 | } | |
7277 | ||
7278 | /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { | |
7279 | return 45.0f; | |
7280 | }*/ | |
7281 | ||
7282 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
7283 | static NSString *reuseIdentifier = @"SectionCell"; | |
7284 | ||
7285 | SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; | |
7286 | if (cell == nil) | |
7287 | cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease]; | |
7288 | ||
7289 | [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]]; | |
7290 | ||
7291 | return cell; | |
7292 | } | |
7293 | ||
7294 | - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { | |
7295 | if ([self isEditing]) | |
7296 | return; | |
7297 | ||
7298 | Section *section = [self sectionAtIndexPath:indexPath]; | |
7299 | ||
7300 | SectionController *controller = [[[SectionController alloc] | |
7301 | initWithDatabase:database_ | |
7302 | source:[self source] | |
7303 | section:[section name] | |
7304 | ] autorelease]; | |
7305 | [controller setDelegate:delegate_]; | |
7306 | ||
7307 | [[self navigationController] pushViewController:controller animated:YES]; | |
7308 | } | |
7309 | ||
7310 | - (void) loadView { | |
7311 | list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]; | |
7312 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
7313 | [list_ setRowHeight:46]; | |
7314 | [(UITableView *) list_ setDataSource:self]; | |
7315 | [list_ setDelegate:self]; | |
7316 | [self setView:list_]; | |
7317 | } | |
7318 | ||
7319 | - (void) viewDidLoad { | |
7320 | [super viewDidLoad]; | |
7321 | ||
7322 | [[self navigationItem] setTitle:UCLocalize("SECTIONS")]; | |
7323 | } | |
7324 | ||
7325 | - (void) releaseSubviews { | |
7326 | list_ = nil; | |
7327 | ||
7328 | sections_ = nil; | |
7329 | filtered_ = nil; | |
7330 | ||
7331 | [super releaseSubviews]; | |
7332 | } | |
7333 | ||
7334 | - (id) initWithDatabase:(Database *)database source:(Source *)source { | |
7335 | if ((self = [super init]) != nil) { | |
7336 | database_ = database; | |
7337 | key_ = [source key]; | |
7338 | } return self; | |
7339 | } | |
7340 | ||
7341 | - (void) reloadData { | |
7342 | [super reloadData]; | |
7343 | ||
7344 | NSArray *packages = [database_ packages]; | |
7345 | ||
7346 | sections_ = [NSMutableArray arrayWithCapacity:16]; | |
7347 | filtered_ = [NSMutableArray arrayWithCapacity:16]; | |
7348 | ||
7349 | NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]); | |
7350 | ||
7351 | Source *source([self source]); | |
7352 | ||
7353 | _trace(); | |
7354 | for (Package *package in packages) { | |
7355 | if (source != nil && [package source] != source) | |
7356 | continue; | |
7357 | ||
7358 | NSString *name([package section]); | |
7359 | NSString *key(name == nil ? @"" : name); | |
7360 | ||
7361 | Section *section; | |
7362 | ||
7363 | _profile(SectionsView$reloadData$Section) | |
7364 | section = [sections objectForKey:key]; | |
7365 | if (section == nil) { | |
7366 | _profile(SectionsView$reloadData$Section$Allocate) | |
7367 | section = [[[Section alloc] initWithName:key localize:YES] autorelease]; | |
7368 | [sections setObject:section forKey:key]; | |
7369 | _end | |
7370 | } | |
7371 | _end | |
7372 | ||
7373 | [section addToCount]; | |
7374 | ||
7375 | _profile(SectionsView$reloadData$Filter) | |
7376 | if (![package valid] || ![package visible]) | |
7377 | continue; | |
7378 | _end | |
7379 | ||
7380 | [section addToRow]; | |
7381 | } | |
7382 | _trace(); | |
7383 | ||
7384 | [sections_ addObjectsFromArray:[sections allValues]]; | |
7385 | ||
7386 | [sections_ sortUsingSelector:@selector(compareByLocalized:)]; | |
7387 | ||
7388 | for (Section *section in (id) sections_) { | |
7389 | size_t count([section row]); | |
7390 | if (count == 0) | |
7391 | continue; | |
7392 | ||
7393 | section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease]; | |
7394 | [section setCount:count]; | |
7395 | [filtered_ addObject:section]; | |
7396 | } | |
7397 | ||
7398 | [self updateNavigationItem]; | |
7399 | [list_ reloadData]; | |
7400 | _trace(); | |
7401 | } | |
7402 | ||
7403 | - (void) editButtonClicked { | |
7404 | [self setEditing:![self isEditing] animated:YES]; | |
7405 | } | |
7406 | ||
7407 | @end | |
7408 | /* }}} */ | |
7409 | ||
7410 | /* Changes Controller {{{ */ | |
7411 | @interface ChangesController : FilteredPackageListController { | |
7412 | unsigned upgrades_; | |
7413 | } | |
7414 | ||
7415 | - (id) initWithDatabase:(Database *)database; | |
7416 | ||
7417 | @end | |
7418 | ||
7419 | @implementation ChangesController | |
7420 | ||
7421 | - (NSURL *) referrerURL { | |
7422 | return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]]; | |
7423 | } | |
7424 | ||
7425 | - (NSURL *) navigationURL { | |
7426 | return [NSURL URLWithString:@"cydia://changes"]; | |
7427 | } | |
7428 | ||
7429 | - (Package *) packageAtIndexPath:(NSIndexPath *)path { | |
7430 | @synchronized (database_) { | |
7431 | if ([database_ era] != era_) | |
7432 | return nil; | |
7433 | ||
7434 | NSUInteger sectionIndex([path section]); | |
7435 | if (sectionIndex >= [sections_ count]) | |
7436 | return nil; | |
7437 | Section *section([sections_ objectAtIndex:sectionIndex]); | |
7438 | NSInteger row([path row]); | |
7439 | return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease]; | |
7440 | } } | |
7441 | ||
7442 | - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
7443 | NSString *context([alert context]); | |
7444 | ||
7445 | if ([context isEqualToString:@"norefresh"]) | |
7446 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
7447 | } | |
7448 | ||
7449 | - (void) setLeftBarButtonItem { | |
7450 | if ([delegate_ updating]) | |
7451 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
7452 | initWithTitle:UCLocalize("CANCEL") | |
7453 | style:UIBarButtonItemStyleDone | |
7454 | target:self | |
7455 | action:@selector(cancelButtonClicked) | |
7456 | ] autorelease] animated:YES]; | |
7457 | else | |
7458 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
7459 | initWithTitle:UCLocalize("REFRESH") | |
7460 | style:UIBarButtonItemStylePlain | |
7461 | target:self | |
7462 | action:@selector(refreshButtonClicked) | |
7463 | ] autorelease] animated:YES]; | |
7464 | } | |
7465 | ||
7466 | - (void) refreshButtonClicked { | |
7467 | if ([delegate_ requestUpdate]) | |
7468 | [self setLeftBarButtonItem]; | |
7469 | } | |
7470 | ||
7471 | - (void) cancelButtonClicked { | |
7472 | [delegate_ cancelUpdate]; | |
7473 | } | |
7474 | ||
7475 | - (void) upgradeButtonClicked { | |
7476 | [delegate_ distUpgrade]; | |
7477 | [[self navigationItem] setRightBarButtonItem:nil animated:YES]; | |
7478 | } | |
7479 | ||
7480 | - (bool) shouldYield { | |
7481 | return true; | |
7482 | } | |
7483 | ||
7484 | - (bool) shouldBlock { | |
7485 | return true; | |
7486 | } | |
7487 | ||
7488 | - (void) useFilter { | |
7489 | @synchronized (self) { | |
7490 | [self setFilter:[](Package *package) { | |
7491 | return [package upgradableAndEssential:YES] || [package visible]; | |
7492 | }]; | |
7493 | ||
7494 | [self setSorter:[](NSMutableArray *packages) { | |
7495 | [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL]; | |
7496 | }]; | |
7497 | } } | |
7498 | ||
7499 | - (id) initWithDatabase:(Database *)database { | |
7500 | if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) { | |
7501 | [self useFilter]; | |
7502 | } return self; | |
7503 | } | |
7504 | ||
7505 | - (void) viewDidLoad { | |
7506 | [super viewDidLoad]; | |
7507 | [self setLeftBarButtonItem]; | |
7508 | } | |
7509 | ||
7510 | - (void) viewWillAppear:(BOOL)animated { | |
7511 | [super viewWillAppear:animated]; | |
7512 | [self setLeftBarButtonItem]; | |
7513 | } | |
7514 | ||
7515 | - (void) reloadData { | |
7516 | [self setLeftBarButtonItem]; | |
7517 | [super reloadData]; | |
7518 | } | |
7519 | ||
7520 | - (NSArray *) sectionsForPackages:(NSMutableArray *)packages { | |
7521 | NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]); | |
7522 | ||
7523 | Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease]; | |
7524 | Section *ignored = nil; | |
7525 | Section *section = nil; | |
7526 | time_t last = 0; | |
7527 | ||
7528 | upgrades_ = 0; | |
7529 | bool unseens = false; | |
7530 | ||
7531 | CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle)); | |
7532 | ||
7533 | for (size_t offset = 0, count = [packages count]; offset != count; ++offset) { | |
7534 | Package *package = [packages objectAtIndex:offset]; | |
7535 | ||
7536 | BOOL uae = [package upgradableAndEssential:YES]; | |
7537 | ||
7538 | if (!uae) { | |
7539 | unseens = true; | |
7540 | time_t seen([package seen]); | |
7541 | ||
7542 | if (section == nil || last != seen) { | |
7543 | last = seen; | |
7544 | ||
7545 | NSString *name; | |
7546 | name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]); | |
7547 | [name autorelease]; | |
7548 | ||
7549 | _profile(ChangesController$reloadData$Allocate) | |
7550 | name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name]; | |
7551 | section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease]; | |
7552 | [sections addObject:section]; | |
7553 | _end | |
7554 | } | |
7555 | ||
7556 | [section addToCount]; | |
7557 | } else if ([package ignored]) { | |
7558 | if (ignored == nil) { | |
7559 | ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease]; | |
7560 | } | |
7561 | [ignored addToCount]; | |
7562 | } else { | |
7563 | ++upgrades_; | |
7564 | [upgradable addToCount]; | |
7565 | } | |
7566 | } | |
7567 | _trace(); | |
7568 | ||
7569 | CFRelease(formatter); | |
7570 | ||
7571 | if (unseens) { | |
7572 | Section *last = [sections lastObject]; | |
7573 | size_t count = [last count]; | |
7574 | [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)]; | |
7575 | [sections removeLastObject]; | |
7576 | } | |
7577 | ||
7578 | if ([ignored count] != 0) | |
7579 | [sections insertObject:ignored atIndex:0]; | |
7580 | if (upgrades_ != 0) | |
7581 | [sections insertObject:upgradable atIndex:0]; | |
7582 | ||
7583 | [list_ reloadData]; | |
7584 | ||
7585 | [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc] | |
7586 | initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]] | |
7587 | style:UIBarButtonItemStylePlain | |
7588 | target:self | |
7589 | action:@selector(upgradeButtonClicked) | |
7590 | ] autorelease]) animated:YES]; | |
7591 | ||
7592 | return sections; | |
7593 | } | |
7594 | ||
7595 | @end | |
7596 | /* }}} */ | |
7597 | /* Search Controller {{{ */ | |
7598 | @interface SearchController : FilteredPackageListController < | |
7599 | UISearchBarDelegate | |
7600 | > { | |
7601 | _H<UISearchBar, 1> search_; | |
7602 | BOOL searchloaded_; | |
7603 | bool summary_; | |
7604 | } | |
7605 | ||
7606 | - (id) initWithDatabase:(Database *)database query:(NSString *)query; | |
7607 | - (void) reloadData; | |
7608 | ||
7609 | @end | |
7610 | ||
7611 | @implementation SearchController | |
7612 | ||
7613 | - (NSURL *) referrerURL { | |
7614 | return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]]; | |
7615 | } | |
7616 | ||
7617 | - (NSURL *) navigationURL { | |
7618 | if ([search_ text] == nil || [[search_ text] isEqualToString:@""]) | |
7619 | return [NSURL URLWithString:@"cydia://search"]; | |
7620 | else | |
7621 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]]; | |
7622 | } | |
7623 | ||
7624 | - (NSArray *) termsForQuery:(NSString *)query { | |
7625 | NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]); | |
7626 | for (NSString *component in [query componentsSeparatedByString:@" "]) | |
7627 | if ([component length] != 0) | |
7628 | [terms addObject:component]; | |
7629 | ||
7630 | return terms; | |
7631 | } | |
7632 | ||
7633 | - (void) useSearch { | |
7634 | _H<NSArray> query([self termsForQuery:[search_ text]]); | |
7635 | summary_ = false; | |
7636 | ||
7637 | @synchronized (self) { | |
7638 | [self setFilter:[=](Package *package) { | |
7639 | if (![package unfiltered]) | |
7640 | return false; | |
7641 | if (![package matches:query]) | |
7642 | return false; | |
7643 | return true; | |
7644 | }]; | |
7645 | ||
7646 | [self setSorter:[](NSMutableArray *packages) { | |
7647 | [packages radixSortUsingSelector:@selector(rank)]; | |
7648 | }]; | |
7649 | } | |
7650 | ||
7651 | [self clearData]; | |
7652 | [self reloadData]; | |
7653 | } | |
7654 | ||
7655 | - (void) usePrefix:(NSString *)prefix { | |
7656 | _H<NSString> query(prefix); | |
7657 | summary_ = true; | |
7658 | ||
7659 | @synchronized (self) { | |
7660 | [self setFilter:[=](Package *package) { | |
7661 | if ([query length] == 0) | |
7662 | return false; | |
7663 | if (![package unfiltered]) | |
7664 | return false; | |
7665 | if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame) | |
7666 | return false; | |
7667 | return true; | |
7668 | }]; | |
7669 | ||
7670 | [self setSorter:nullptr]; | |
7671 | } | |
7672 | ||
7673 | [self reloadData]; | |
7674 | } | |
7675 | ||
7676 | - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar { | |
7677 | [self clearData]; | |
7678 | [self usePrefix:[search_ text]]; | |
7679 | } | |
7680 | ||
7681 | - (void) searchBarButtonClicked:(UISearchBar *)searchBar { | |
7682 | [search_ resignFirstResponder]; | |
7683 | [self useSearch]; | |
7684 | } | |
7685 | ||
7686 | - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar { | |
7687 | [search_ setText:@""]; | |
7688 | [self searchBarButtonClicked:searchBar]; | |
7689 | } | |
7690 | ||
7691 | - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar { | |
7692 | [self searchBarButtonClicked:searchBar]; | |
7693 | } | |
7694 | ||
7695 | - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text { | |
7696 | [self usePrefix:text]; | |
7697 | } | |
7698 | ||
7699 | - (bool) shouldYield { | |
7700 | return YES; | |
7701 | } | |
7702 | ||
7703 | - (bool) shouldBlock { | |
7704 | return !summary_; | |
7705 | } | |
7706 | ||
7707 | - (bool) isSummarized { | |
7708 | return summary_; | |
7709 | } | |
7710 | ||
7711 | - (bool) showsSections { | |
7712 | return false; | |
7713 | } | |
7714 | ||
7715 | - (id) initWithDatabase:(Database *)database query:(NSString *)query { | |
7716 | if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) { | |
7717 | search_ = [[[UISearchBar alloc] init] autorelease]; | |
7718 | [search_ setPlaceholder:UCLocalize("SEARCH_EX")]; | |
7719 | [search_ setDelegate:self]; | |
7720 | ||
7721 | UITextField *textField; | |
7722 | if ([search_ respondsToSelector:@selector(searchField)]) | |
7723 | textField = [search_ searchField]; | |
7724 | else | |
7725 | textField = MSHookIvar<UITextField *>(search_, "_searchField"); | |
7726 | ||
7727 | [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; | |
7728 | [textField setEnablesReturnKeyAutomatically:NO]; | |
7729 | [[self navigationItem] setTitleView:textField]; | |
7730 | ||
7731 | if (query != nil) | |
7732 | [search_ setText:query]; | |
7733 | [self useSearch]; | |
7734 | } return self; | |
7735 | } | |
7736 | ||
7737 | - (void) viewDidAppear:(BOOL)animated { | |
7738 | [super viewDidAppear:animated]; | |
7739 | ||
7740 | if (!searchloaded_) { | |
7741 | searchloaded_ = YES; | |
7742 | [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)]; | |
7743 | [search_ layoutSubviews]; | |
7744 | } | |
7745 | ||
7746 | if ([self isSummarized]) | |
7747 | [search_ becomeFirstResponder]; | |
7748 | } | |
7749 | ||
7750 | - (void) reloadData { | |
7751 | [self resetCursor]; | |
7752 | [super reloadData]; | |
7753 | } | |
7754 | ||
7755 | - (void) didSelectPackage:(Package *)package { | |
7756 | [search_ resignFirstResponder]; | |
7757 | [super didSelectPackage:package]; | |
7758 | } | |
7759 | ||
7760 | @end | |
7761 | /* }}} */ | |
7762 | /* Package Settings Controller {{{ */ | |
7763 | @interface PackageSettingsController : CyteViewController < | |
7764 | UITableViewDataSource, | |
7765 | UITableViewDelegate | |
7766 | > { | |
7767 | _transient Database *database_; | |
7768 | _H<NSString> name_; | |
7769 | _H<Package> package_; | |
7770 | _H<UITableView, 2> table_; | |
7771 | _H<UISwitch> subscribedSwitch_; | |
7772 | _H<UISwitch> ignoredSwitch_; | |
7773 | _H<UITableViewCell> subscribedCell_; | |
7774 | _H<UITableViewCell> ignoredCell_; | |
7775 | } | |
7776 | ||
7777 | - (id) initWithDatabase:(Database *)database package:(NSString *)package; | |
7778 | ||
7779 | @end | |
7780 | ||
7781 | @implementation PackageSettingsController | |
7782 | ||
7783 | - (NSURL *) navigationURL { | |
7784 | return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]]; | |
7785 | } | |
7786 | ||
7787 | - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { | |
7788 | if (package_ == nil) | |
7789 | return 0; | |
7790 | ||
7791 | if ([package_ installed] == nil) | |
7792 | return 1; | |
7793 | else | |
7794 | return 2; | |
7795 | } | |
7796 | ||
7797 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
7798 | if (package_ == nil) | |
7799 | return 0; | |
7800 | ||
7801 | // both sections contain just one item right now. | |
7802 | return 1; | |
7803 | } | |
7804 | ||
7805 | - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { | |
7806 | return nil; | |
7807 | } | |
7808 | ||
7809 | - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { | |
7810 | if (section == 0) | |
7811 | return UCLocalize("SHOW_ALL_CHANGES_EX"); | |
7812 | else | |
7813 | return UCLocalize("IGNORE_UPGRADES_EX"); | |
7814 | } | |
7815 | ||
7816 | - (void) onSubscribed:(id)control { | |
7817 | bool value([control isOn]); | |
7818 | if (package_ == nil) | |
7819 | return; | |
7820 | if ([package_ setSubscribed:value]) | |
7821 | [delegate_ updateData]; | |
7822 | } | |
7823 | ||
7824 | - (void) _updateIgnored { | |
7825 | const char *package([name_ UTF8String]); | |
7826 | bool on([ignoredSwitch_ isOn]); | |
7827 | ||
7828 | pid_t pid(ExecFork()); | |
7829 | if (pid == 0) { | |
7830 | FILE *dpkg(popen("dpkg --set-selections", "w")); | |
7831 | fwrite(package, strlen(package), 1, dpkg); | |
7832 | ||
7833 | if (on) | |
7834 | fwrite(" hold\n", 6, 1, dpkg); | |
7835 | else | |
7836 | fwrite(" install\n", 9, 1, dpkg); | |
7837 | ||
7838 | pclose(dpkg); | |
7839 | ||
7840 | exit(0); | |
7841 | } ReapZombie(pid); | |
7842 | } | |
7843 | ||
7844 | - (void) onIgnored:(id)control { | |
7845 | NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]); | |
7846 | [invocation setTarget:self]; | |
7847 | [invocation setSelector:@selector(_updateIgnored)]; | |
7848 | ||
7849 | [delegate_ reloadDataWithInvocation:invocation]; | |
7850 | } | |
7851 | ||
7852 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
7853 | if (package_ == nil) | |
7854 | return nil; | |
7855 | ||
7856 | switch ([indexPath section]) { | |
7857 | case 0: return subscribedCell_; | |
7858 | case 1: return ignoredCell_; | |
7859 | ||
7860 | _nodefault | |
7861 | } | |
7862 | ||
7863 | return nil; | |
7864 | } | |
7865 | ||
7866 | - (void) loadView { | |
7867 | UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]); | |
7868 | [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)]; | |
7869 | [self setView:view]; | |
7870 | ||
7871 | table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]; | |
7872 | [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
7873 | [(UITableView *) table_ setDataSource:self]; | |
7874 | [table_ setDelegate:self]; | |
7875 | [view addSubview:table_]; | |
7876 | ||
7877 | subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease]; | |
7878 | [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; | |
7879 | [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged]; | |
7880 | ||
7881 | ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease]; | |
7882 | [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; | |
7883 | [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged]; | |
7884 | ||
7885 | subscribedCell_ = [[[UITableViewCell alloc] init] autorelease]; | |
7886 | [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")]; | |
7887 | [subscribedCell_ setAccessoryView:subscribedSwitch_]; | |
7888 | [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone]; | |
7889 | ||
7890 | ignoredCell_ = [[[UITableViewCell alloc] init] autorelease]; | |
7891 | [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")]; | |
7892 | [ignoredCell_ setAccessoryView:ignoredSwitch_]; | |
7893 | [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone]; | |
7894 | } | |
7895 | ||
7896 | - (void) viewDidLoad { | |
7897 | [super viewDidLoad]; | |
7898 | ||
7899 | [[self navigationItem] setTitle:UCLocalize("SETTINGS")]; | |
7900 | } | |
7901 | ||
7902 | - (void) releaseSubviews { | |
7903 | ignoredCell_ = nil; | |
7904 | subscribedCell_ = nil; | |
7905 | table_ = nil; | |
7906 | ignoredSwitch_ = nil; | |
7907 | subscribedSwitch_ = nil; | |
7908 | ||
7909 | [super releaseSubviews]; | |
7910 | } | |
7911 | ||
7912 | - (id) initWithDatabase:(Database *)database package:(NSString *)package { | |
7913 | if ((self = [super init]) != nil) { | |
7914 | database_ = database; | |
7915 | name_ = package; | |
7916 | } return self; | |
7917 | } | |
7918 | ||
7919 | - (void) reloadData { | |
7920 | [super reloadData]; | |
7921 | ||
7922 | package_ = [database_ packageWithName:name_]; | |
7923 | ||
7924 | if (package_ != nil) { | |
7925 | [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO]; | |
7926 | [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO]; | |
7927 | } // XXX: what now, G? | |
7928 | ||
7929 | [table_ reloadData]; | |
7930 | } | |
7931 | ||
7932 | @end | |
7933 | /* }}} */ | |
7934 | ||
7935 | /* Installed Controller {{{ */ | |
7936 | @interface InstalledController : FilteredPackageListController { | |
7937 | bool sectioned_; | |
7938 | } | |
7939 | ||
7940 | - (id) initWithDatabase:(Database *)database; | |
7941 | - (void) queueStatusDidChange; | |
7942 | ||
7943 | @end | |
7944 | ||
7945 | @implementation InstalledController | |
7946 | ||
7947 | - (NSURL *) referrerURL { | |
7948 | return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]]; | |
7949 | } | |
7950 | ||
7951 | - (NSURL *) navigationURL { | |
7952 | return [NSURL URLWithString:@"cydia://installed"]; | |
7953 | } | |
7954 | ||
7955 | - (void) useRecent { | |
7956 | sectioned_ = false; | |
7957 | ||
7958 | @synchronized (self) { | |
7959 | [self setFilter:[](Package *package) { | |
7960 | return ![package uninstalled] && package->role_ < 7; | |
7961 | }]; | |
7962 | ||
7963 | [self setSorter:[](NSMutableArray *packages) { | |
7964 | [packages radixSortUsingSelector:@selector(recent)]; | |
7965 | }]; | |
7966 | } } | |
7967 | ||
7968 | - (void) useFilter:(UISegmentedControl *)segmented { | |
7969 | NSInteger selected([segmented selectedSegmentIndex]); | |
7970 | if (selected == 2) | |
7971 | return [self useRecent]; | |
7972 | bool simple(selected == 0); | |
7973 | sectioned_ = true; | |
7974 | ||
7975 | @synchronized (self) { | |
7976 | [self setFilter:[=](Package *package) { | |
7977 | return ![package uninstalled] && package->role_ <= (simple ? 1 : 3); | |
7978 | }]; | |
7979 | ||
7980 | [self setSorter:nullptr]; | |
7981 | } } | |
7982 | ||
7983 | - (NSArray *) sectionsForPackages:(NSMutableArray *)packages { | |
7984 | if (sectioned_) | |
7985 | return [super sectionsForPackages:packages]; | |
7986 | ||
7987 | CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle)); | |
7988 | ||
7989 | NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]); | |
7990 | Section *section(nil); | |
7991 | time_t last(0); | |
7992 | ||
7993 | for (size_t offset(0), count([packages count]); offset != count; ++offset) { | |
7994 | Package *package([packages objectAtIndex:offset]); | |
7995 | ||
7996 | time_t upgraded([package upgraded]); | |
7997 | upgraded -= upgraded % (60 * 60 * 24); | |
7998 | ||
7999 | if (section == nil || upgraded != last) { | |
8000 | last = upgraded; | |
8001 | ||
8002 | NSString *name; | |
8003 | name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]); | |
8004 | [name autorelease]; | |
8005 | ||
8006 | section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease]; | |
8007 | [sections addObject:section]; | |
8008 | } | |
8009 | ||
8010 | [section addToCount]; | |
8011 | } | |
8012 | ||
8013 | CFRelease(formatter); | |
8014 | return sections; | |
8015 | } | |
8016 | ||
8017 | - (id) initWithDatabase:(Database *)database { | |
8018 | if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) { | |
8019 | UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]); | |
8020 | [segmented setSelectedSegmentIndex:0]; | |
8021 | [segmented setSegmentedControlStyle:UISegmentedControlStyleBar]; | |
8022 | [[self navigationItem] setTitleView:segmented]; | |
8023 | ||
8024 | [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged]; | |
8025 | [self useFilter:segmented]; | |
8026 | ||
8027 | [self queueStatusDidChange]; | |
8028 | } return self; | |
8029 | } | |
8030 | ||
8031 | #if !AlwaysReload | |
8032 | - (void) queueButtonClicked { | |
8033 | [delegate_ queue]; | |
8034 | } | |
8035 | #endif | |
8036 | ||
8037 | - (void) queueStatusDidChange { | |
8038 | #if !AlwaysReload | |
8039 | if (Queuing_) { | |
8040 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
8041 | initWithTitle:UCLocalize("QUEUE") | |
8042 | style:UIBarButtonItemStyleDone | |
8043 | target:self | |
8044 | action:@selector(queueButtonClicked) | |
8045 | ] autorelease]]; | |
8046 | } else { | |
8047 | [[self navigationItem] setLeftBarButtonItem:nil]; | |
8048 | } | |
8049 | #endif | |
8050 | } | |
8051 | ||
8052 | - (void) modeChanged:(UISegmentedControl *)segmented { | |
8053 | [self useFilter:segmented]; | |
8054 | [self reloadData]; | |
8055 | } | |
8056 | ||
8057 | @end | |
8058 | /* }}} */ | |
8059 | ||
8060 | /* Source Cell {{{ */ | |
8061 | @interface SourceCell : CyteTableViewCell < | |
8062 | CyteTableViewCellDelegate, | |
8063 | SourceDelegate | |
8064 | > { | |
8065 | _H<Source, 1> source_; | |
8066 | _H<NSURL> url_; | |
8067 | _H<UIImage> icon_; | |
8068 | _H<NSString> origin_; | |
8069 | _H<NSString> label_; | |
8070 | _H<UIActivityIndicatorView> indicator_; | |
8071 | } | |
8072 | ||
8073 | - (void) setSource:(Source *)source; | |
8074 | - (void) setFetch:(NSNumber *)fetch; | |
8075 | ||
8076 | @end | |
8077 | ||
8078 | @implementation SourceCell | |
8079 | ||
8080 | - (void) _setImage:(NSArray *)data { | |
8081 | if ([url_ isEqual:[data objectAtIndex:0]]) { | |
8082 | icon_ = [data objectAtIndex:1]; | |
8083 | [content_ setNeedsDisplay]; | |
8084 | } | |
8085 | } | |
8086 | ||
8087 | - (void) _setSource:(NSURL *) url { | |
8088 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
8089 | ||
8090 | if (NSData *data = [NSURLConnection | |
8091 | sendSynchronousRequest:[NSURLRequest | |
8092 | requestWithURL:url | |
8093 | cachePolicy:NSURLRequestUseProtocolCachePolicy | |
8094 | timeoutInterval:10 | |
8095 | ] | |
8096 | ||
8097 | returningResponse:NULL | |
8098 | error:NULL | |
8099 | ]) | |
8100 | if (UIImage *image = [UIImage imageWithData:data]) | |
8101 | [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO]; | |
8102 | ||
8103 | [pool release]; | |
8104 | } | |
8105 | ||
8106 | - (void) setSource:(Source *)source { | |
8107 | source_ = source; | |
8108 | [source_ setDelegate:self]; | |
8109 | ||
8110 | [self setFetch:[NSNumber numberWithBool:[source_ fetch]]]; | |
8111 | ||
8112 | icon_ = [UIImage applicationImageNamed:@"unknown.png"]; | |
8113 | ||
8114 | origin_ = [source name]; | |
8115 | label_ = [source rooturi]; | |
8116 | ||
8117 | [content_ setNeedsDisplay]; | |
8118 | ||
8119 | url_ = [source iconURL]; | |
8120 | [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_]; | |
8121 | } | |
8122 | ||
8123 | - (void) setAllSource { | |
8124 | source_ = nil; | |
8125 | [indicator_ stopAnimating]; | |
8126 | ||
8127 | icon_ = [UIImage applicationImageNamed:@"folder.png"]; | |
8128 | origin_ = UCLocalize("ALL_SOURCES"); | |
8129 | label_ = UCLocalize("ALL_SOURCES_EX"); | |
8130 | [content_ setNeedsDisplay]; | |
8131 | } | |
8132 | ||
8133 | - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { | |
8134 | if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) { | |
8135 | UIView *content([self contentView]); | |
8136 | CGRect bounds([content bounds]); | |
8137 | ||
8138 | content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease]; | |
8139 | [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
8140 | [content_ setBackgroundColor:[UIColor whiteColor]]; | |
8141 | [content addSubview:content_]; | |
8142 | ||
8143 | [content_ setDelegate:self]; | |
8144 | [content_ setOpaque:YES]; | |
8145 | ||
8146 | indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease]; | |
8147 | [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin]; | |
8148 | [content addSubview:indicator_]; | |
8149 | ||
8150 | [[content_ layer] setContentsGravity:kCAGravityTopLeft]; | |
8151 | } return self; | |
8152 | } | |
8153 | ||
8154 | - (void) layoutSubviews { | |
8155 | [super layoutSubviews]; | |
8156 | ||
8157 | UIView *content([self contentView]); | |
8158 | CGRect bounds([content bounds]); | |
8159 | ||
8160 | CGRect frame([indicator_ frame]); | |
8161 | frame.origin.x = bounds.size.width - frame.size.width; | |
8162 | frame.origin.y = (bounds.size.height - frame.size.height) / 2; | |
8163 | ||
8164 | if (kCFCoreFoundationVersionNumber < 800) | |
8165 | frame.origin.x -= 8; | |
8166 | [indicator_ setFrame:frame]; | |
8167 | } | |
8168 | ||
8169 | - (NSString *) accessibilityLabel { | |
8170 | return origin_; | |
8171 | } | |
8172 | ||
8173 | - (void) drawContentRect:(CGRect)rect { | |
8174 | bool highlighted(highlighted_); | |
8175 | float width(rect.size.width); | |
8176 | ||
8177 | if (icon_ != nil) { | |
8178 | CGRect rect; | |
8179 | rect.size = [(UIImage *) icon_ size]; | |
8180 | ||
8181 | while (rect.size.width > 32 || rect.size.height > 32) { | |
8182 | rect.size.width /= 2; | |
8183 | rect.size.height /= 2; | |
8184 | } | |
8185 | ||
8186 | rect.origin.x = 26 - rect.size.width / 2; | |
8187 | rect.origin.y = 26 - rect.size.height / 2; | |
8188 | ||
8189 | [icon_ drawInRect:rect]; | |
8190 | } | |
8191 | ||
8192 | if (highlighted && kCFCoreFoundationVersionNumber < 800) | |
8193 | UISetColor(White_); | |
8194 | ||
8195 | if (!highlighted) | |
8196 | UISetColor(Black_); | |
8197 | [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
8198 | ||
8199 | if (!highlighted) | |
8200 | UISetColor(Gray_); | |
8201 | [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail]; | |
8202 | } | |
8203 | ||
8204 | - (void) setFetch:(NSNumber *)fetch { | |
8205 | if ([fetch boolValue]) | |
8206 | [indicator_ startAnimating]; | |
8207 | else | |
8208 | [indicator_ stopAnimating]; | |
8209 | } | |
8210 | ||
8211 | @end | |
8212 | /* }}} */ | |
8213 | /* Sources Controller {{{ */ | |
8214 | @interface SourcesController : CyteViewController < | |
8215 | UITableViewDataSource, | |
8216 | UITableViewDelegate | |
8217 | > { | |
8218 | _transient Database *database_; | |
8219 | unsigned era_; | |
8220 | ||
8221 | _H<UITableView, 2> list_; | |
8222 | _H<NSMutableArray> sources_; | |
8223 | int offset_; | |
8224 | ||
8225 | _H<NSString> href_; | |
8226 | _H<UIProgressHUD> hud_; | |
8227 | _H<NSError> error_; | |
8228 | ||
8229 | NSURLConnection *trivial_bz2_; | |
8230 | NSURLConnection *trivial_gz_; | |
8231 | ||
8232 | BOOL cydia_; | |
8233 | } | |
8234 | ||
8235 | - (id) initWithDatabase:(Database *)database; | |
8236 | - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated; | |
8237 | ||
8238 | @end | |
8239 | ||
8240 | @implementation SourcesController | |
8241 | ||
8242 | - (void) _releaseConnection:(NSURLConnection *)connection { | |
8243 | if (connection != nil) { | |
8244 | [connection cancel]; | |
8245 | //[connection setDelegate:nil]; | |
8246 | [connection release]; | |
8247 | } | |
8248 | } | |
8249 | ||
8250 | - (void) dealloc { | |
8251 | [self _releaseConnection:trivial_gz_]; | |
8252 | [self _releaseConnection:trivial_bz2_]; | |
8253 | ||
8254 | [super dealloc]; | |
8255 | } | |
8256 | ||
8257 | - (NSURL *) navigationURL { | |
8258 | return [NSURL URLWithString:@"cydia://sources"]; | |
8259 | } | |
8260 | ||
8261 | - (void) viewDidAppear:(BOOL)animated { | |
8262 | [super viewDidAppear:animated]; | |
8263 | [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated]; | |
8264 | } | |
8265 | ||
8266 | - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { | |
8267 | return 2; | |
8268 | } | |
8269 | ||
8270 | - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { | |
8271 | if (section == 1) | |
8272 | return UCLocalize("INDIVIDUAL_SOURCES"); | |
8273 | return nil; | |
8274 | } | |
8275 | ||
8276 | - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { | |
8277 | switch (section) { | |
8278 | case 0: return 1; | |
8279 | case 1: return [sources_ count]; | |
8280 | default: return 0; | |
8281 | } | |
8282 | } | |
8283 | ||
8284 | - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath { | |
8285 | @synchronized (database_) { | |
8286 | if ([database_ era] != era_) | |
8287 | return nil; | |
8288 | if ([indexPath section] != 1) | |
8289 | return nil; | |
8290 | NSUInteger index([indexPath row]); | |
8291 | if (index >= [sources_ count]) | |
8292 | return nil; | |
8293 | return [sources_ objectAtIndex:index]; | |
8294 | } } | |
8295 | ||
8296 | - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { | |
8297 | static NSString *cellIdentifier = @"SourceCell"; | |
8298 | ||
8299 | SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; | |
8300 | if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease]; | |
8301 | [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; | |
8302 | ||
8303 | Source *source([self sourceAtIndexPath:indexPath]); | |
8304 | if (source == nil) | |
8305 | [cell setAllSource]; | |
8306 | else | |
8307 | [cell setSource:source]; | |
8308 | ||
8309 | return cell; | |
8310 | } | |
8311 | ||
8312 | - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { | |
8313 | SectionsController *controller([[[SectionsController alloc] | |
8314 | initWithDatabase:database_ | |
8315 | source:[self sourceAtIndexPath:indexPath] | |
8316 | ] autorelease]); | |
8317 | ||
8318 | [controller setDelegate:delegate_]; | |
8319 | [[self navigationController] pushViewController:controller animated:YES]; | |
8320 | } | |
8321 | ||
8322 | - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { | |
8323 | if ([indexPath section] != 1) | |
8324 | return false; | |
8325 | Source *source = [self sourceAtIndexPath:indexPath]; | |
8326 | return [source record] != nil; | |
8327 | } | |
8328 | ||
8329 | - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { | |
8330 | _assert([indexPath section] == 1); | |
8331 | if (editingStyle == UITableViewCellEditingStyleDelete) { | |
8332 | Source *source = [self sourceAtIndexPath:indexPath]; | |
8333 | if (source == nil) return; | |
8334 | ||
8335 | [Sources_ removeObjectForKey:[source key]]; | |
8336 | Changed_ = true; | |
8337 | ||
8338 | [delegate_ _saveConfig]; | |
8339 | [delegate_ reloadDataWithInvocation:nil]; | |
8340 | } | |
8341 | } | |
8342 | ||
8343 | - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath { | |
8344 | [self updateButtonsForEditingStatusAnimated:YES]; | |
8345 | } | |
8346 | ||
8347 | - (void) complete { | |
8348 | [delegate_ addTrivialSource:href_]; | |
8349 | href_ = nil; | |
8350 | ||
8351 | [delegate_ syncData]; | |
8352 | } | |
8353 | ||
8354 | - (NSString *) getWarning { | |
8355 | NSString *href(href_); | |
8356 | NSRange colon([href rangeOfString:@"://"]); | |
8357 | if (colon.location != NSNotFound) | |
8358 | href = [href substringFromIndex:(colon.location + 3)]; | |
8359 | href = [href stringByAddingPercentEscapes]; | |
8360 | href = [CydiaURL(@"api/repotag/") stringByAppendingString:href]; | |
8361 | ||
8362 | NSURL *url([NSURL URLWithString:href]); | |
8363 | ||
8364 | NSStringEncoding encoding; | |
8365 | NSError *error(nil); | |
8366 | ||
8367 | if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error]) | |
8368 | return [warning length] == 0 ? nil : warning; | |
8369 | return nil; | |
8370 | } | |
8371 | ||
8372 | - (void) _endConnection:(NSURLConnection *)connection { | |
8373 | // XXX: the memory management in this method is horribly awkward | |
8374 | ||
8375 | NSURLConnection **field = NULL; | |
8376 | if (connection == trivial_bz2_) | |
8377 | field = &trivial_bz2_; | |
8378 | else if (connection == trivial_gz_) | |
8379 | field = &trivial_gz_; | |
8380 | _assert(field != NULL); | |
8381 | [connection release]; | |
8382 | *field = nil; | |
8383 | ||
8384 | if ( | |
8385 | trivial_bz2_ == nil && | |
8386 | trivial_gz_ == nil | |
8387 | ) { | |
8388 | NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil); | |
8389 | ||
8390 | [delegate_ releaseNetworkActivityIndicator]; | |
8391 | ||
8392 | [delegate_ removeProgressHUD:hud_]; | |
8393 | hud_ = nil; | |
8394 | ||
8395 | if (cydia_) { | |
8396 | if (warning != nil) { | |
8397 | UIAlertView *alert = [[[UIAlertView alloc] | |
8398 | initWithTitle:UCLocalize("SOURCE_WARNING") | |
8399 | message:warning | |
8400 | delegate:self | |
8401 | cancelButtonTitle:UCLocalize("CANCEL") | |
8402 | otherButtonTitles: | |
8403 | UCLocalize("ADD_ANYWAY"), | |
8404 | nil | |
8405 | ] autorelease]; | |
8406 | ||
8407 | [alert setContext:@"warning"]; | |
8408 | [alert setNumberOfRows:1]; | |
8409 | [alert show]; | |
8410 | ||
8411 | // XXX: there used to be this great mechanism called yieldToPopup... who deleted it? | |
8412 | error_ = nil; | |
8413 | return; | |
8414 | } | |
8415 | ||
8416 | [self complete]; | |
8417 | } else if (error_ != nil) { | |
8418 | UIAlertView *alert = [[[UIAlertView alloc] | |
8419 | initWithTitle:UCLocalize("VERIFICATION_ERROR") | |
8420 | message:[error_ localizedDescription] | |
8421 | delegate:self | |
8422 | cancelButtonTitle:UCLocalize("OK") | |
8423 | otherButtonTitles:nil | |
8424 | ] autorelease]; | |
8425 | ||
8426 | [alert setContext:@"urlerror"]; | |
8427 | [alert show]; | |
8428 | ||
8429 | href_ = nil; | |
8430 | } else { | |
8431 | UIAlertView *alert = [[[UIAlertView alloc] | |
8432 | initWithTitle:UCLocalize("NOT_REPOSITORY") | |
8433 | message:UCLocalize("NOT_REPOSITORY_EX") | |
8434 | delegate:self | |
8435 | cancelButtonTitle:UCLocalize("OK") | |
8436 | otherButtonTitles:nil | |
8437 | ] autorelease]; | |
8438 | ||
8439 | [alert setContext:@"trivial"]; | |
8440 | [alert show]; | |
8441 | ||
8442 | href_ = nil; | |
8443 | } | |
8444 | ||
8445 | error_ = nil; | |
8446 | } | |
8447 | } | |
8448 | ||
8449 | - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { | |
8450 | switch ([response statusCode]) { | |
8451 | case 200: | |
8452 | cydia_ = YES; | |
8453 | } | |
8454 | } | |
8455 | ||
8456 | - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { | |
8457 | lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]); | |
8458 | error_ = error; | |
8459 | [self _endConnection:connection]; | |
8460 | } | |
8461 | ||
8462 | - (void) connectionDidFinishLoading:(NSURLConnection *)connection { | |
8463 | [self _endConnection:connection]; | |
8464 | } | |
8465 | ||
8466 | - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method { | |
8467 | NSURL *url([NSURL URLWithString:href]); | |
8468 | ||
8469 | NSMutableURLRequest *request = [NSMutableURLRequest | |
8470 | requestWithURL:url | |
8471 | cachePolicy:NSURLRequestUseProtocolCachePolicy | |
8472 | timeoutInterval:10 | |
8473 | ]; | |
8474 | ||
8475 | [request setHTTPMethod:method]; | |
8476 | ||
8477 | if (Machine_ != NULL) | |
8478 | [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"]; | |
8479 | ||
8480 | if (UniqueID_ != nil) | |
8481 | [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"]; | |
8482 | ||
8483 | if ([url isCydiaSecure]) { | |
8484 | if (UniqueID_ != nil) | |
8485 | [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"]; | |
8486 | } | |
8487 | ||
8488 | return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; | |
8489 | } | |
8490 | ||
8491 | - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
8492 | NSString *context([alert context]); | |
8493 | ||
8494 | if ([context isEqualToString:@"source"]) { | |
8495 | switch (button) { | |
8496 | case 1: { | |
8497 | NSString *href = [[alert textField] text]; | |
8498 | ||
8499 | static Pcre href_r("^http(s?)://[^# ]*$"); | |
8500 | if (!href_r(href)) { | |
8501 | UIAlertView *alert = [[[UIAlertView alloc] | |
8502 | initWithTitle:Error_ | |
8503 | message:UCLocalize("INVALID_URL") | |
8504 | delegate:self | |
8505 | cancelButtonTitle:UCLocalize("OK") | |
8506 | otherButtonTitles:nil | |
8507 | ] autorelease]; | |
8508 | ||
8509 | [alert setContext:@"badurl"]; | |
8510 | [alert show]; | |
8511 | ||
8512 | break; | |
8513 | } | |
8514 | ||
8515 | if (![href hasSuffix:@"/"]) | |
8516 | href_ = [href stringByAppendingString:@"/"]; | |
8517 | else | |
8518 | href_ = href; | |
8519 | ||
8520 | trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain]; | |
8521 | trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain]; | |
8522 | ||
8523 | cydia_ = false; | |
8524 | ||
8525 | // XXX: this is stupid | |
8526 | hud_ = [delegate_ addProgressHUD]; | |
8527 | [hud_ setText:UCLocalize("VERIFYING_URL")]; | |
8528 | [delegate_ retainNetworkActivityIndicator]; | |
8529 | } break; | |
8530 | ||
8531 | case 0: | |
8532 | break; | |
8533 | ||
8534 | _nodefault | |
8535 | } | |
8536 | ||
8537 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
8538 | } else if ([context isEqualToString:@"trivial"]) | |
8539 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
8540 | else if ([context isEqualToString:@"urlerror"]) | |
8541 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
8542 | else if ([context isEqualToString:@"warning"]) { | |
8543 | switch (button) { | |
8544 | case 1: | |
8545 | [self performSelector:@selector(complete) withObject:nil afterDelay:0]; | |
8546 | break; | |
8547 | ||
8548 | case 0: | |
8549 | break; | |
8550 | ||
8551 | _nodefault | |
8552 | } | |
8553 | ||
8554 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
8555 | } | |
8556 | } | |
8557 | ||
8558 | - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated { | |
8559 | BOOL editing([list_ isEditing]); | |
8560 | ||
8561 | if (editing) | |
8562 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
8563 | initWithTitle:UCLocalize("ADD") | |
8564 | style:UIBarButtonItemStylePlain | |
8565 | target:self | |
8566 | action:@selector(addButtonClicked) | |
8567 | ] autorelease] animated:animated]; | |
8568 | else if ([delegate_ updating]) | |
8569 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
8570 | initWithTitle:UCLocalize("CANCEL") | |
8571 | style:UIBarButtonItemStyleDone | |
8572 | target:self | |
8573 | action:@selector(cancelButtonClicked) | |
8574 | ] autorelease] animated:animated]; | |
8575 | else | |
8576 | [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc] | |
8577 | initWithTitle:UCLocalize("REFRESH") | |
8578 | style:UIBarButtonItemStylePlain | |
8579 | target:self | |
8580 | action:@selector(refreshButtonClicked) | |
8581 | ] autorelease] animated:animated]; | |
8582 | ||
8583 | [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] | |
8584 | initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT")) | |
8585 | style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain) | |
8586 | target:self | |
8587 | action:@selector(editButtonClicked) | |
8588 | ] autorelease] animated:animated]; | |
8589 | } | |
8590 | ||
8591 | - (void) loadView { | |
8592 | list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease]; | |
8593 | [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
8594 | [list_ setRowHeight:53]; | |
8595 | [(UITableView *) list_ setDataSource:self]; | |
8596 | [list_ setDelegate:self]; | |
8597 | [self setView:list_]; | |
8598 | } | |
8599 | ||
8600 | - (void) viewDidLoad { | |
8601 | [super viewDidLoad]; | |
8602 | ||
8603 | [[self navigationItem] setTitle:UCLocalize("SOURCES")]; | |
8604 | [self updateButtonsForEditingStatusAnimated:NO]; | |
8605 | } | |
8606 | ||
8607 | - (void) viewWillAppear:(BOOL)animated { | |
8608 | [super viewWillAppear:animated]; | |
8609 | ||
8610 | [list_ setEditing:NO]; | |
8611 | [self updateButtonsForEditingStatusAnimated:NO]; | |
8612 | } | |
8613 | ||
8614 | - (void) releaseSubviews { | |
8615 | list_ = nil; | |
8616 | ||
8617 | sources_ = nil; | |
8618 | ||
8619 | [super releaseSubviews]; | |
8620 | } | |
8621 | ||
8622 | - (id) initWithDatabase:(Database *)database { | |
8623 | if ((self = [super init]) != nil) { | |
8624 | database_ = database; | |
8625 | } return self; | |
8626 | } | |
8627 | ||
8628 | - (void) reloadData { | |
8629 | [super reloadData]; | |
8630 | [self updateButtonsForEditingStatusAnimated:YES]; | |
8631 | ||
8632 | @synchronized (database_) { | |
8633 | era_ = [database_ era]; | |
8634 | ||
8635 | sources_ = [NSMutableArray arrayWithCapacity:16]; | |
8636 | [sources_ addObjectsFromArray:[database_ sources]]; | |
8637 | _trace(); | |
8638 | [sources_ sortUsingSelector:@selector(compareByName:)]; | |
8639 | _trace(); | |
8640 | ||
8641 | int count([sources_ count]); | |
8642 | offset_ = 0; | |
8643 | for (int i = 0; i != count; i++) { | |
8644 | if ([[sources_ objectAtIndex:i] record] == nil) | |
8645 | break; | |
8646 | offset_++; | |
8647 | } | |
8648 | ||
8649 | [list_ reloadData]; | |
8650 | } } | |
8651 | ||
8652 | - (void) showAddSourcePrompt { | |
8653 | UIAlertView *alert = [[[UIAlertView alloc] | |
8654 | initWithTitle:UCLocalize("ENTER_APT_URL") | |
8655 | message:nil | |
8656 | delegate:self | |
8657 | cancelButtonTitle:UCLocalize("CANCEL") | |
8658 | otherButtonTitles: | |
8659 | UCLocalize("ADD_SOURCE"), | |
8660 | nil | |
8661 | ] autorelease]; | |
8662 | ||
8663 | [alert setContext:@"source"]; | |
8664 | ||
8665 | [alert setNumberOfRows:1]; | |
8666 | [alert addTextFieldWithValue:@"http://" label:@""]; | |
8667 | ||
8668 | UITextInputTraits *traits = [[alert textField] textInputTraits]; | |
8669 | [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone]; | |
8670 | [traits setAutocorrectionType:UITextAutocorrectionTypeNo]; | |
8671 | [traits setKeyboardType:UIKeyboardTypeURL]; | |
8672 | // XXX: UIReturnKeyDone | |
8673 | [traits setReturnKeyType:UIReturnKeyNext]; | |
8674 | ||
8675 | [alert show]; | |
8676 | } | |
8677 | ||
8678 | - (void) addButtonClicked { | |
8679 | [self showAddSourcePrompt]; | |
8680 | } | |
8681 | ||
8682 | - (void) refreshButtonClicked { | |
8683 | if ([delegate_ requestUpdate]) | |
8684 | [self updateButtonsForEditingStatusAnimated:YES]; | |
8685 | } | |
8686 | ||
8687 | - (void) cancelButtonClicked { | |
8688 | [delegate_ cancelUpdate]; | |
8689 | } | |
8690 | ||
8691 | - (void) editButtonClicked { | |
8692 | [list_ setEditing:![list_ isEditing] animated:YES]; | |
8693 | [self updateButtonsForEditingStatusAnimated:YES]; | |
8694 | } | |
8695 | ||
8696 | @end | |
8697 | /* }}} */ | |
8698 | ||
8699 | /* Stash Controller {{{ */ | |
8700 | @interface StashController : CyteViewController { | |
8701 | _H<UIActivityIndicatorView> spinner_; | |
8702 | _H<UILabel> status_; | |
8703 | _H<UILabel> caption_; | |
8704 | } | |
8705 | ||
8706 | @end | |
8707 | ||
8708 | @implementation StashController | |
8709 | ||
8710 | - (void) loadView { | |
8711 | UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]); | |
8712 | [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)]; | |
8713 | [self setView:view]; | |
8714 | ||
8715 | [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]]; | |
8716 | ||
8717 | spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease]; | |
8718 | CGRect spinrect = [spinner_ frame]; | |
8719 | spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2); | |
8720 | spinrect.origin.y = [[self view] frame].size.height - 80.0f; | |
8721 | [spinner_ setFrame:spinrect]; | |
8722 | [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin]; | |
8723 | [view addSubview:spinner_]; | |
8724 | [spinner_ startAnimating]; | |
8725 | ||
8726 | CGRect captrect; | |
8727 | captrect.size.width = [[self view] frame].size.width; | |
8728 | captrect.size.height = 40.0f; | |
8729 | captrect.origin.x = 0; | |
8730 | captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2); | |
8731 | caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease]; | |
8732 | [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")]; | |
8733 | [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; | |
8734 | [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]]; | |
8735 | [caption_ setTextColor:[UIColor whiteColor]]; | |
8736 | [caption_ setBackgroundColor:[UIColor clearColor]]; | |
8737 | [caption_ setShadowColor:[UIColor blackColor]]; | |
8738 | [caption_ setTextAlignment:NSTextAlignmentCenter]; | |
8739 | [view addSubview:caption_]; | |
8740 | ||
8741 | CGRect statusrect; | |
8742 | statusrect.size.width = [[self view] frame].size.width; | |
8743 | statusrect.size.height = 30.0f; | |
8744 | statusrect.origin.x = 0; | |
8745 | statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height; | |
8746 | status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease]; | |
8747 | [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin]; | |
8748 | [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")]; | |
8749 | [status_ setFont:[UIFont systemFontOfSize:16.0f]]; | |
8750 | [status_ setTextColor:[UIColor whiteColor]]; | |
8751 | [status_ setBackgroundColor:[UIColor clearColor]]; | |
8752 | [status_ setShadowColor:[UIColor blackColor]]; | |
8753 | [status_ setTextAlignment:NSTextAlignmentCenter]; | |
8754 | [view addSubview:status_]; | |
8755 | } | |
8756 | ||
8757 | - (void) releaseSubviews { | |
8758 | spinner_ = nil; | |
8759 | status_ = nil; | |
8760 | caption_ = nil; | |
8761 | ||
8762 | [super releaseSubviews]; | |
8763 | } | |
8764 | ||
8765 | @end | |
8766 | /* }}} */ | |
8767 | ||
8768 | @interface CYURLCache : SDURLCache { | |
8769 | } | |
8770 | ||
8771 | @end | |
8772 | ||
8773 | @implementation CYURLCache | |
8774 | ||
8775 | - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request { | |
8776 | #if !ForRelease | |
8777 | if (false); | |
8778 | else if ([event isEqualToString:@"no-cache"]) | |
8779 | event = @"!!!"; | |
8780 | else if ([event isEqualToString:@"store"]) | |
8781 | event = @">>>"; | |
8782 | else if ([event isEqualToString:@"invalid"]) | |
8783 | event = @"???"; | |
8784 | else if ([event isEqualToString:@"memory"]) | |
8785 | event = @"mem"; | |
8786 | else if ([event isEqualToString:@"disk"]) | |
8787 | event = @"ssd"; | |
8788 | else if ([event isEqualToString:@"miss"]) | |
8789 | event = @"---"; | |
8790 | ||
8791 | NSLog(@"%@: %@", event, [[request URL] absoluteString]); | |
8792 | #endif | |
8793 | } | |
8794 | ||
8795 | - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request { | |
8796 | if (NSURLResponse *response = [cached response]) | |
8797 | if (NSString *mime = [response MIMEType]) | |
8798 | if ([mime isEqualToString:@"text/cache-manifest"]) { | |
8799 | NSURL *url([response URL]); | |
8800 | ||
8801 | #if !ForRelease | |
8802 | NSLog(@"###: %@", [url absoluteString]); | |
8803 | #endif | |
8804 | ||
8805 | @synchronized (HostConfig_) { | |
8806 | [CachedURLs_ addObject:url]; | |
8807 | } | |
8808 | } | |
8809 | ||
8810 | [super storeCachedResponse:cached forRequest:request]; | |
8811 | } | |
8812 | ||
8813 | @end | |
8814 | ||
8815 | @interface Cydia : UIApplication < | |
8816 | ConfirmationControllerDelegate, | |
8817 | DatabaseDelegate, | |
8818 | CydiaDelegate, | |
8819 | UINavigationControllerDelegate, | |
8820 | UITabBarControllerDelegate | |
8821 | > { | |
8822 | _H<UIWindow> window_; | |
8823 | _H<CydiaTabBarController> tabbar_; | |
8824 | _H<CydiaLoadingViewController> emulated_; | |
8825 | ||
8826 | _H<NSMutableArray> essential_; | |
8827 | _H<NSMutableArray> broken_; | |
8828 | ||
8829 | Database *database_; | |
8830 | ||
8831 | _H<NSURL> starturl_; | |
8832 | ||
8833 | unsigned locked_; | |
8834 | unsigned activity_; | |
8835 | ||
8836 | _H<StashController> stash_; | |
8837 | ||
8838 | bool loaded_; | |
8839 | } | |
8840 | ||
8841 | - (void) loadData; | |
8842 | ||
8843 | @end | |
8844 | ||
8845 | @implementation Cydia | |
8846 | ||
8847 | - (void) lockSuspend { | |
8848 | if (locked_++ == 0) { | |
8849 | if ($SBSSetInterceptsMenuButtonForever != NULL) | |
8850 | (*$SBSSetInterceptsMenuButtonForever)(true); | |
8851 | ||
8852 | [self setIdleTimerDisabled:YES]; | |
8853 | } | |
8854 | } | |
8855 | ||
8856 | - (void) unlockSuspend { | |
8857 | if (--locked_ == 0) { | |
8858 | [self setIdleTimerDisabled:NO]; | |
8859 | ||
8860 | if ($SBSSetInterceptsMenuButtonForever != NULL) | |
8861 | (*$SBSSetInterceptsMenuButtonForever)(false); | |
8862 | } | |
8863 | } | |
8864 | ||
8865 | - (void) beginUpdate { | |
8866 | [tabbar_ beginUpdate]; | |
8867 | } | |
8868 | ||
8869 | - (void) cancelUpdate { | |
8870 | [tabbar_ cancelUpdate]; | |
8871 | } | |
8872 | ||
8873 | - (bool) requestUpdate { | |
8874 | if (IsReachable("cydia.saurik.com")) { | |
8875 | [self beginUpdate]; | |
8876 | return true; | |
8877 | } else { | |
8878 | UIAlertView *alert = [[[UIAlertView alloc] | |
8879 | initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")] | |
8880 | message:@"Host Unreachable" // XXX: Localize | |
8881 | delegate:self | |
8882 | cancelButtonTitle:UCLocalize("OK") | |
8883 | otherButtonTitles:nil | |
8884 | ] autorelease]; | |
8885 | ||
8886 | [alert setContext:@"norefresh"]; | |
8887 | [alert show]; | |
8888 | ||
8889 | return false; | |
8890 | } | |
8891 | } | |
8892 | ||
8893 | - (BOOL) updating { | |
8894 | return [tabbar_ updating]; | |
8895 | } | |
8896 | ||
8897 | - (void) _loaded { | |
8898 | if ([broken_ count] != 0) { | |
8899 | int count = [broken_ count]; | |
8900 | ||
8901 | UIAlertView *alert = [[[UIAlertView alloc] | |
8902 | initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count]) | |
8903 | message:UCLocalize("HALFINSTALLED_PACKAGE_EX") | |
8904 | delegate:self | |
8905 | cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")] | |
8906 | otherButtonTitles: | |
8907 | UCLocalize("TEMPORARY_IGNORE"), | |
8908 | nil | |
8909 | ] autorelease]; | |
8910 | ||
8911 | [alert setContext:@"fixhalf"]; | |
8912 | [alert setNumberOfRows:2]; | |
8913 | [alert show]; | |
8914 | } else if (!Ignored_ && [essential_ count] != 0) { | |
8915 | int count = [essential_ count]; | |
8916 | ||
8917 | UIAlertView *alert = [[[UIAlertView alloc] | |
8918 | initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count]) | |
8919 | message:UCLocalize("ESSENTIAL_UPGRADE_EX") | |
8920 | delegate:self | |
8921 | cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE") | |
8922 | otherButtonTitles: | |
8923 | UCLocalize("UPGRADE_ESSENTIAL"), | |
8924 | UCLocalize("COMPLETE_UPGRADE"), | |
8925 | nil | |
8926 | ] autorelease]; | |
8927 | ||
8928 | [alert setContext:@"upgrade"]; | |
8929 | [alert show]; | |
8930 | } | |
8931 | } | |
8932 | ||
8933 | - (void) returnToCydia { | |
8934 | [self _loaded]; | |
8935 | } | |
8936 | ||
8937 | - (void) _saveConfig { | |
8938 | @synchronized (database_) { | |
8939 | _trace(); | |
8940 | MetaFile_.Sync(); | |
8941 | _trace(); | |
8942 | } | |
8943 | ||
8944 | if (Changed_) { | |
8945 | NSString *error(nil); | |
8946 | ||
8947 | if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) { | |
8948 | _trace(); | |
8949 | NSError *error(nil); | |
8950 | if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error]) | |
8951 | NSLog(@"failure to save metadata data: %@", error); | |
8952 | _trace(); | |
8953 | ||
8954 | Changed_ = false; | |
8955 | } else { | |
8956 | NSLog(@"failure to serialize metadata: %@", error); | |
8957 | } | |
8958 | } | |
8959 | ||
8960 | CydiaWriteSources(); | |
8961 | } | |
8962 | ||
8963 | // Navigation controller for the queuing badge. | |
8964 | - (UINavigationController *) queueNavigationController { | |
8965 | NSArray *controllers = [tabbar_ viewControllers]; | |
8966 | return [controllers objectAtIndex:3]; | |
8967 | } | |
8968 | ||
8969 | - (void) unloadData { | |
8970 | [tabbar_ unloadData]; | |
8971 | } | |
8972 | ||
8973 | - (void) _updateData { | |
8974 | [self _saveConfig]; | |
8975 | [self unloadData]; | |
8976 | ||
8977 | UINavigationController *navigation = [self queueNavigationController]; | |
8978 | ||
8979 | id queuedelegate = nil; | |
8980 | if ([[navigation viewControllers] count] > 0) | |
8981 | queuedelegate = [[navigation viewControllers] objectAtIndex:0]; | |
8982 | ||
8983 | [queuedelegate queueStatusDidChange]; | |
8984 | [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)]; | |
8985 | } | |
8986 | ||
8987 | - (void) _refreshIfPossible:(NSDate *)update { | |
8988 | NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; | |
8989 | ||
8990 | bool recently = false; | |
8991 | if (update != nil) { | |
8992 | NSTimeInterval interval([update timeIntervalSinceNow]); | |
8993 | if (interval <= 0 && interval > -(15*60)) | |
8994 | recently = true; | |
8995 | } | |
8996 | ||
8997 | // Don't automatic refresh if: | |
8998 | // - We already refreshed recently. | |
8999 | // - We already auto-refreshed this launch. | |
9000 | // - Auto-refresh is disabled. | |
9001 | // - Cydia's server is not reachable | |
9002 | if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) { | |
9003 | // If we are cancelling, we need to make sure it knows it's already loaded. | |
9004 | loaded_ = true; | |
9005 | ||
9006 | [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO]; | |
9007 | } else { | |
9008 | // We are going to load, so remember that. | |
9009 | loaded_ = true; | |
9010 | ||
9011 | [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO]; | |
9012 | } | |
9013 | ||
9014 | [pool release]; | |
9015 | } | |
9016 | ||
9017 | - (void) refreshIfPossible { | |
9018 | [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]]; | |
9019 | } | |
9020 | ||
9021 | - (void) reloadDataWithInvocation:(NSInvocation *)invocation { | |
9022 | _profile(reloadDataWithInvocation) | |
9023 | @synchronized (self) { | |
9024 | UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil); | |
9025 | if (hud != nil) | |
9026 | [hud setText:UCLocalize("RELOADING_DATA")]; | |
9027 | ||
9028 | [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation]; | |
9029 | ||
9030 | size_t changes(0); | |
9031 | ||
9032 | [essential_ removeAllObjects]; | |
9033 | [broken_ removeAllObjects]; | |
9034 | ||
9035 | _profile(reloadDataWithInvocation$Essential) | |
9036 | NSArray *packages([database_ packages]); | |
9037 | for (Package *package in packages) { | |
9038 | if ([package half]) | |
9039 | [broken_ addObject:package]; | |
9040 | if ([package upgradableAndEssential:YES] && ![package ignored]) { | |
9041 | if ([package essential] && [package installed] != nil) | |
9042 | [essential_ addObject:package]; | |
9043 | ++changes; | |
9044 | } | |
9045 | } | |
9046 | _end | |
9047 | ||
9048 | UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem]; | |
9049 | if (changes != 0) { | |
9050 | _trace(); | |
9051 | NSString *badge([[NSNumber numberWithInt:changes] stringValue]); | |
9052 | [changesItem setBadgeValue:badge]; | |
9053 | [changesItem setAnimatedBadge:([essential_ count] > 0)]; | |
9054 | [self setApplicationIconBadgeNumber:changes]; | |
9055 | } else { | |
9056 | _trace(); | |
9057 | [changesItem setBadgeValue:nil]; | |
9058 | [changesItem setAnimatedBadge:NO]; | |
9059 | [self setApplicationIconBadgeNumber:0]; | |
9060 | } | |
9061 | ||
9062 | [self _updateData]; | |
9063 | ||
9064 | if (hud != nil) | |
9065 | [self removeProgressHUD:hud]; | |
9066 | } | |
9067 | _end | |
9068 | ||
9069 | PrintTimes(); | |
9070 | } | |
9071 | ||
9072 | - (void) updateData { | |
9073 | [self _updateData]; | |
9074 | } | |
9075 | ||
9076 | - (void) updateDataAndLoad { | |
9077 | [self _updateData]; | |
9078 | if ([database_ progressDelegate] == nil) | |
9079 | [self _loaded]; | |
9080 | } | |
9081 | ||
9082 | - (void) update_ { | |
9083 | [database_ update]; | |
9084 | [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES]; | |
9085 | } | |
9086 | ||
9087 | - (void) disemulate { | |
9088 | if (emulated_ == nil) | |
9089 | return; | |
9090 | ||
9091 | if ([window_ respondsToSelector:@selector(setRootViewController:)]) | |
9092 | [window_ setRootViewController:tabbar_]; | |
9093 | else { | |
9094 | [window_ addSubview:[tabbar_ view]]; | |
9095 | [[emulated_ view] removeFromSuperview]; | |
9096 | } | |
9097 | ||
9098 | emulated_ = nil; | |
9099 | [window_ setUserInteractionEnabled:YES]; | |
9100 | } | |
9101 | ||
9102 | - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force { | |
9103 | UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]); | |
9104 | if (IsWildcat_) | |
9105 | [navigation setModalPresentationStyle:UIModalPresentationFormSheet]; | |
9106 | ||
9107 | UIViewController *parent; | |
9108 | if (emulated_ == nil) | |
9109 | parent = tabbar_; | |
9110 | else if (!force) | |
9111 | parent = emulated_; | |
9112 | else { | |
9113 | [self disemulate]; | |
9114 | parent = tabbar_; | |
9115 | } | |
9116 | ||
9117 | [parent presentModalViewController:navigation animated:YES]; | |
9118 | } | |
9119 | ||
9120 | - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title { | |
9121 | ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]); | |
9122 | ||
9123 | if (navigation != nil) | |
9124 | [navigation pushViewController:progress animated:YES]; | |
9125 | else | |
9126 | [self presentModalViewController:progress force:YES]; | |
9127 | ||
9128 | [progress invoke:invocation withTitle:title]; | |
9129 | return progress; | |
9130 | } | |
9131 | ||
9132 | - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title { | |
9133 | [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title]; | |
9134 | } | |
9135 | ||
9136 | - (void) repairWithInvocation:(NSInvocation *)invocation { | |
9137 | _trace(); | |
9138 | [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"]; | |
9139 | _trace(); | |
9140 | } | |
9141 | ||
9142 | - (void) repairWithSelector:(SEL)selector { | |
9143 | [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES]; | |
9144 | } | |
9145 | ||
9146 | - (void) reloadData { | |
9147 | [self reloadDataWithInvocation:nil]; | |
9148 | if ([database_ progressDelegate] == nil) | |
9149 | [self _loaded]; | |
9150 | } | |
9151 | ||
9152 | - (void) syncData { | |
9153 | [self _saveConfig]; | |
9154 | [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"]; | |
9155 | } | |
9156 | ||
9157 | - (void) addSource:(NSDictionary *) source { | |
9158 | CydiaAddSource(source); | |
9159 | } | |
9160 | ||
9161 | - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections { | |
9162 | CydiaAddSource(href, distribution, sections); | |
9163 | } | |
9164 | ||
9165 | - (void) addTrivialSource:(NSString *)href { | |
9166 | CydiaAddSource(href, @"./"); | |
9167 | } | |
9168 | ||
9169 | - (void) updateValues { | |
9170 | Changed_ = true; | |
9171 | } | |
9172 | ||
9173 | - (void) resolve { | |
9174 | pkgProblemResolver *resolver = [database_ resolver]; | |
9175 | ||
9176 | resolver->InstallProtect(); | |
9177 | if (!resolver->Resolve(true)) | |
9178 | _error->Discard(); | |
9179 | } | |
9180 | ||
9181 | - (bool) perform { | |
9182 | // XXX: this is a really crappy way of doing this. | |
9183 | // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that. | |
9184 | // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid | |
9185 | // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing. | |
9186 | if ([tabbar_ updating]) | |
9187 | [tabbar_ cancelUpdate]; | |
9188 | ||
9189 | if (![database_ prepare]) | |
9190 | return false; | |
9191 | ||
9192 | ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]); | |
9193 | [page setDelegate:self]; | |
9194 | UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]); | |
9195 | ||
9196 | if (IsWildcat_) | |
9197 | [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet]; | |
9198 | [tabbar_ presentModalViewController:confirm_ animated:YES]; | |
9199 | ||
9200 | return true; | |
9201 | } | |
9202 | ||
9203 | - (void) queue { | |
9204 | @synchronized (self) { | |
9205 | [self perform]; | |
9206 | } | |
9207 | } | |
9208 | ||
9209 | - (void) clearPackage:(Package *)package { | |
9210 | @synchronized (self) { | |
9211 | [package clear]; | |
9212 | [self resolve]; | |
9213 | [self perform]; | |
9214 | } | |
9215 | } | |
9216 | ||
9217 | - (void) installPackages:(NSArray *)packages { | |
9218 | @synchronized (self) { | |
9219 | for (Package *package in packages) | |
9220 | [package install]; | |
9221 | [self resolve]; | |
9222 | [self perform]; | |
9223 | } | |
9224 | } | |
9225 | ||
9226 | - (void) installPackage:(Package *)package { | |
9227 | @synchronized (self) { | |
9228 | [package install]; | |
9229 | [self resolve]; | |
9230 | [self perform]; | |
9231 | } | |
9232 | } | |
9233 | ||
9234 | - (void) removePackage:(Package *)package { | |
9235 | @synchronized (self) { | |
9236 | [package remove]; | |
9237 | [self resolve]; | |
9238 | [self perform]; | |
9239 | } | |
9240 | } | |
9241 | ||
9242 | - (void) distUpgrade { | |
9243 | @synchronized (self) { | |
9244 | if (![database_ upgrade]) | |
9245 | return; | |
9246 | [self perform]; | |
9247 | } | |
9248 | } | |
9249 | ||
9250 | - (void) _uicache { | |
9251 | _trace(); | |
9252 | system("su -c /usr/bin/uicache mobile"); | |
9253 | _trace(); | |
9254 | } | |
9255 | ||
9256 | - (void) uicache { | |
9257 | UIProgressHUD *hud([self addProgressHUD]); | |
9258 | [hud setText:UCLocalize("LOADING")]; | |
9259 | [self yieldToSelector:@selector(_uicache)]; | |
9260 | [self removeProgressHUD:hud]; | |
9261 | } | |
9262 | ||
9263 | - (void) perform_ { | |
9264 | [database_ perform]; | |
9265 | [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES]; | |
9266 | [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES]; | |
9267 | } | |
9268 | ||
9269 | - (void) confirmWithNavigationController:(UINavigationController *)navigation { | |
9270 | Queuing_ = false; | |
9271 | [self lockSuspend]; | |
9272 | [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"]; | |
9273 | [self unlockSuspend]; | |
9274 | } | |
9275 | ||
9276 | - (void) retainNetworkActivityIndicator { | |
9277 | if (activity_++ == 0) | |
9278 | [self setNetworkActivityIndicatorVisible:YES]; | |
9279 | ||
9280 | #if TraceLogging | |
9281 | NSLog(@"retainNetworkActivityIndicator->%d", activity_); | |
9282 | #endif | |
9283 | } | |
9284 | ||
9285 | - (void) releaseNetworkActivityIndicator { | |
9286 | if (--activity_ == 0) | |
9287 | [self setNetworkActivityIndicatorVisible:NO]; | |
9288 | ||
9289 | #if TraceLogging | |
9290 | NSLog(@"releaseNetworkActivityIndicator->%d", activity_); | |
9291 | #endif | |
9292 | ||
9293 | } | |
9294 | ||
9295 | - (void) cancelAndClear:(bool)clear { | |
9296 | @synchronized (self) { | |
9297 | if (clear) { | |
9298 | [database_ clear]; | |
9299 | Queuing_ = false; | |
9300 | } else { | |
9301 | Queuing_ = true; | |
9302 | } | |
9303 | ||
9304 | [self _updateData]; | |
9305 | } | |
9306 | } | |
9307 | ||
9308 | - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button { | |
9309 | NSString *context([alert context]); | |
9310 | ||
9311 | if ([context isEqualToString:@"conffile"]) { | |
9312 | FILE *input = [database_ input]; | |
9313 | if (button == [alert cancelButtonIndex]) | |
9314 | fprintf(input, "N\n"); | |
9315 | else if (button == [alert firstOtherButtonIndex]) | |
9316 | fprintf(input, "Y\n"); | |
9317 | fflush(input); | |
9318 | ||
9319 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
9320 | } else if ([context isEqualToString:@"fixhalf"]) { | |
9321 | if (button == [alert cancelButtonIndex]) { | |
9322 | @synchronized (self) { | |
9323 | for (Package *broken in (id) broken_) { | |
9324 | [broken remove]; | |
9325 | ||
9326 | NSString *id = [broken id]; | |
9327 | unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]); | |
9328 | unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]); | |
9329 | unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]); | |
9330 | unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]); | |
9331 | } | |
9332 | ||
9333 | [self resolve]; | |
9334 | [self perform]; | |
9335 | } | |
9336 | } else if (button == [alert firstOtherButtonIndex]) { | |
9337 | [broken_ removeAllObjects]; | |
9338 | [self _loaded]; | |
9339 | } | |
9340 | ||
9341 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
9342 | } else if ([context isEqualToString:@"upgrade"]) { | |
9343 | if (button == [alert firstOtherButtonIndex]) { | |
9344 | @synchronized (self) { | |
9345 | for (Package *essential in (id) essential_) | |
9346 | [essential install]; | |
9347 | ||
9348 | [self resolve]; | |
9349 | [self perform]; | |
9350 | } | |
9351 | } else if (button == [alert firstOtherButtonIndex] + 1) { | |
9352 | [self distUpgrade]; | |
9353 | } else if (button == [alert cancelButtonIndex]) { | |
9354 | Ignored_ = YES; | |
9355 | } | |
9356 | ||
9357 | [alert dismissWithClickedButtonIndex:-1 animated:YES]; | |
9358 | } | |
9359 | } | |
9360 | ||
9361 | - (void) system:(NSString *)command { | |
9362 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
9363 | ||
9364 | _trace(); | |
9365 | system([command UTF8String]); | |
9366 | _trace(); | |
9367 | ||
9368 | [pool release]; | |
9369 | } | |
9370 | ||
9371 | - (void) applicationWillSuspend { | |
9372 | [database_ clean]; | |
9373 | [super applicationWillSuspend]; | |
9374 | } | |
9375 | ||
9376 | - (BOOL) isSafeToSuspend { | |
9377 | if (locked_ != 0) { | |
9378 | #if !ForRelease | |
9379 | NSLog(@"isSafeToSuspend: locked_ != 0"); | |
9380 | #endif | |
9381 | return false; | |
9382 | } | |
9383 | ||
9384 | if ([tabbar_ modalViewController] != nil) | |
9385 | return false; | |
9386 | ||
9387 | // Use external process status API internally. | |
9388 | // This is probably a really bad idea. | |
9389 | // XXX: what is the point of this? does this solve anything at all? | |
9390 | uint64_t status = 0; | |
9391 | int notify_token; | |
9392 | if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) { | |
9393 | notify_get_state(notify_token, &status); | |
9394 | notify_cancel(notify_token); | |
9395 | } | |
9396 | ||
9397 | if (status != 0) { | |
9398 | #if !ForRelease | |
9399 | NSLog(@"isSafeToSuspend: status != 0"); | |
9400 | #endif | |
9401 | return false; | |
9402 | } | |
9403 | ||
9404 | #if !ForRelease | |
9405 | NSLog(@"isSafeToSuspend: -> true"); | |
9406 | #endif | |
9407 | return true; | |
9408 | } | |
9409 | ||
9410 | - (void) applicationSuspend:(__GSEvent *)event { | |
9411 | if ([self isSafeToSuspend]) | |
9412 | [super applicationSuspend:event]; | |
9413 | } | |
9414 | ||
9415 | - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 { | |
9416 | if ([self isSafeToSuspend]) | |
9417 | [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3]; | |
9418 | } | |
9419 | ||
9420 | - (void) _setSuspended:(BOOL)value { | |
9421 | if ([self isSafeToSuspend]) | |
9422 | [super _setSuspended:value]; | |
9423 | } | |
9424 | ||
9425 | - (UIProgressHUD *) addProgressHUD { | |
9426 | UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]); | |
9427 | [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth]; | |
9428 | ||
9429 | [window_ setUserInteractionEnabled:NO]; | |
9430 | ||
9431 | UIViewController *target(tabbar_); | |
9432 | if (UIViewController *modal = [target modalViewController]) | |
9433 | target = modal; | |
9434 | ||
9435 | [hud showInView:[target view]]; | |
9436 | ||
9437 | [self lockSuspend]; | |
9438 | return hud; | |
9439 | } | |
9440 | ||
9441 | - (void) removeProgressHUD:(UIProgressHUD *)hud { | |
9442 | [self unlockSuspend]; | |
9443 | [hud hide]; | |
9444 | [hud removeFromSuperview]; | |
9445 | [window_ setUserInteractionEnabled:YES]; | |
9446 | } | |
9447 | ||
9448 | - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer { | |
9449 | return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease]; | |
9450 | } | |
9451 | ||
9452 | - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer { | |
9453 | NSString *scheme([[url scheme] lowercaseString]); | |
9454 | if ([[url absoluteString] length] <= [scheme length] + 3) | |
9455 | return nil; | |
9456 | NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]); | |
9457 | NSArray *components([path componentsSeparatedByString:@"/"]); | |
9458 | ||
9459 | if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) { | |
9460 | CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]); | |
9461 | if (controller != nil) | |
9462 | [controller setDelegate:self]; | |
9463 | return controller; | |
9464 | } | |
9465 | ||
9466 | if ([components count] < 1 || ![scheme isEqualToString:@"cydia"]) | |
9467 | return nil; | |
9468 | ||
9469 | NSString *base([components objectAtIndex:0]); | |
9470 | ||
9471 | CyteViewController *controller = nil; | |
9472 | ||
9473 | if ([base isEqualToString:@"url"]) { | |
9474 | // This kind of URL can contain slashes in the argument, so we can't parse them below. | |
9475 | NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])]; | |
9476 | controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease]; | |
9477 | } else if (!external && [components count] == 1) { | |
9478 | if ([base isEqualToString:@"sources"]) { | |
9479 | controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease]; | |
9480 | } | |
9481 | ||
9482 | if ([base isEqualToString:@"home"]) { | |
9483 | controller = [[[HomeController alloc] init] autorelease]; | |
9484 | } | |
9485 | ||
9486 | if ([base isEqualToString:@"sections"]) { | |
9487 | controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease]; | |
9488 | } | |
9489 | ||
9490 | if ([base isEqualToString:@"search"]) { | |
9491 | controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease]; | |
9492 | } | |
9493 | ||
9494 | if ([base isEqualToString:@"changes"]) { | |
9495 | controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease]; | |
9496 | } | |
9497 | ||
9498 | if ([base isEqualToString:@"installed"]) { | |
9499 | controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease]; | |
9500 | } | |
9501 | } else if ([components count] == 2) { | |
9502 | NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
9503 | ||
9504 | if ([base isEqualToString:@"package"]) { | |
9505 | controller = [self pageForPackage:argument withReferrer:referrer]; | |
9506 | } | |
9507 | ||
9508 | if (!external && [base isEqualToString:@"search"]) { | |
9509 | controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease]; | |
9510 | } | |
9511 | ||
9512 | if (!external && [base isEqualToString:@"sections"]) { | |
9513 | if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"]) | |
9514 | argument = nil; | |
9515 | controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease]; | |
9516 | } | |
9517 | ||
9518 | if (!external && [base isEqualToString:@"sources"]) { | |
9519 | if ([argument isEqualToString:@"add"]) { | |
9520 | controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease]; | |
9521 | [(SourcesController *)controller showAddSourcePrompt]; | |
9522 | } else { | |
9523 | Source *source([database_ sourceWithKey:argument]); | |
9524 | controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease]; | |
9525 | } | |
9526 | } | |
9527 | ||
9528 | if (!external && [base isEqualToString:@"launch"]) { | |
9529 | [self launchApplicationWithIdentifier:argument suspended:NO]; | |
9530 | return nil; | |
9531 | } | |
9532 | } else if (!external && [components count] == 3) { | |
9533 | NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
9534 | NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; | |
9535 | ||
9536 | if ([base isEqualToString:@"package"]) { | |
9537 | if ([arg2 isEqualToString:@"settings"]) { | |
9538 | controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease]; | |
9539 | } else if ([arg2 isEqualToString:@"files"]) { | |
9540 | if (Package *package = [database_ packageWithName:arg1]) { | |
9541 | controller = [[[FileTable alloc] initWithDatabase:database_] autorelease]; | |
9542 | [(FileTable *)controller setPackage:package]; | |
9543 | } | |
9544 | } | |
9545 | } | |
9546 | ||
9547 | if ([base isEqualToString:@"sections"]) { | |
9548 | Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]); | |
9549 | NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2); | |
9550 | controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease]; | |
9551 | } | |
9552 | } | |
9553 | ||
9554 | [controller setDelegate:self]; | |
9555 | return controller; | |
9556 | } | |
9557 | ||
9558 | - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external { | |
9559 | CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]); | |
9560 | ||
9561 | if (page != nil) | |
9562 | [tabbar_ setUnselectedViewController:page]; | |
9563 | ||
9564 | return page != nil; | |
9565 | } | |
9566 | ||
9567 | - (void) applicationOpenURL:(NSURL *)url { | |
9568 | [super applicationOpenURL:url]; | |
9569 | ||
9570 | if (!loaded_) | |
9571 | starturl_ = url; | |
9572 | else | |
9573 | [self openCydiaURL:url forExternal:YES]; | |
9574 | } | |
9575 | ||
9576 | - (void) applicationWillResignActive:(UIApplication *)application { | |
9577 | // Stop refreshing if you get a phone call or lock the device. | |
9578 | if ([tabbar_ updating]) | |
9579 | [tabbar_ cancelUpdate]; | |
9580 | ||
9581 | if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)]) | |
9582 | [super applicationWillResignActive:application]; | |
9583 | } | |
9584 | ||
9585 | - (void) saveState { | |
9586 | [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"]; | |
9587 | [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"]; | |
9588 | [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"]; | |
9589 | Changed_ = true; | |
9590 | ||
9591 | [self _saveConfig]; | |
9592 | } | |
9593 | ||
9594 | - (void) applicationWillTerminate:(UIApplication *)application { | |
9595 | [self saveState]; | |
9596 | } | |
9597 | ||
9598 | - (void) setConfigurationData:(NSString *)data { | |
9599 | static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$"); | |
9600 | ||
9601 | if (!conffile_r(data)) { | |
9602 | lprintf("E:invalid conffile\n"); | |
9603 | return; | |
9604 | } | |
9605 | ||
9606 | NSString *ofile = conffile_r[1]; | |
9607 | //NSString *nfile = conffile_r[2]; | |
9608 | ||
9609 | UIAlertView *alert = [[[UIAlertView alloc] | |
9610 | initWithTitle:UCLocalize("CONFIGURATION_UPGRADE") | |
9611 | message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile] | |
9612 | delegate:self | |
9613 | cancelButtonTitle:UCLocalize("KEEP_OLD_COPY") | |
9614 | otherButtonTitles: | |
9615 | UCLocalize("ACCEPT_NEW_COPY"), | |
9616 | // XXX: UCLocalize("SEE_WHAT_CHANGED"), | |
9617 | nil | |
9618 | ] autorelease]; | |
9619 | ||
9620 | [alert setContext:@"conffile"]; | |
9621 | [alert setNumberOfRows:2]; | |
9622 | [alert show]; | |
9623 | } | |
9624 | ||
9625 | - (void) addStashController { | |
9626 | [self lockSuspend]; | |
9627 | stash_ = [[[StashController alloc] init] autorelease]; | |
9628 | [window_ addSubview:[stash_ view]]; | |
9629 | } | |
9630 | ||
9631 | - (void) removeStashController { | |
9632 | [[stash_ view] removeFromSuperview]; | |
9633 | stash_ = nil; | |
9634 | [self unlockSuspend]; | |
9635 | } | |
9636 | ||
9637 | - (void) stash { | |
9638 | [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque]; | |
9639 | UpdateExternalStatus(1); | |
9640 | [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"]; | |
9641 | UpdateExternalStatus(0); | |
9642 | ||
9643 | [self removeStashController]; | |
9644 | ||
9645 | pid_t pid(ExecFork()); | |
9646 | if (pid == 0) { | |
9647 | execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL); | |
9648 | perror("launchctl stop"); | |
9649 | ||
9650 | exit(0); | |
9651 | } ReapZombie(pid); | |
9652 | } | |
9653 | ||
9654 | - (void) setupViewControllers { | |
9655 | tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease]; | |
9656 | ||
9657 | NSMutableArray *items; | |
9658 | if (kCFCoreFoundationVersionNumber < 800) { | |
9659 | items = [NSMutableArray arrayWithObjects: | |
9660 | [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease], | |
9661 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease], | |
9662 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease], | |
9663 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease], | |
9664 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease], | |
9665 | nil]; | |
9666 | } else { | |
9667 | items = [NSMutableArray arrayWithObjects: | |
9668 | [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease], | |
9669 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease], | |
9670 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease], | |
9671 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease], | |
9672 | [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease], | |
9673 | nil]; | |
9674 | } | |
9675 | ||
9676 | NSMutableArray *controllers([NSMutableArray array]); | |
9677 | for (UITabBarItem *item in items) { | |
9678 | UINavigationController *controller([[[UINavigationController alloc] init] autorelease]); | |
9679 | [controller setTabBarItem:item]; | |
9680 | [controllers addObject:controller]; | |
9681 | } | |
9682 | [tabbar_ setViewControllers:controllers]; | |
9683 | ||
9684 | [tabbar_ setUpdateDelegate:self]; | |
9685 | } | |
9686 | ||
9687 | - (void) _sendMemoryWarningNotification { | |
9688 | if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0? | |
9689 | [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]]; | |
9690 | else | |
9691 | [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]]; | |
9692 | } | |
9693 | ||
9694 | - (void) _sendMemoryWarningNotifications { | |
9695 | while (true) { | |
9696 | [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO]; | |
9697 | sleep(2); | |
9698 | //usleep(2000000); | |
9699 | } | |
9700 | } | |
9701 | ||
9702 | - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application { | |
9703 | NSLog(@"--"); | |
9704 | [[NSURLCache sharedURLCache] removeAllCachedResponses]; | |
9705 | } | |
9706 | ||
9707 | - (void) applicationDidFinishLaunching:(id)unused { | |
9708 | //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil]; | |
9709 | ||
9710 | _trace(); | |
9711 | if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)]) | |
9712 | [self setApplicationSupportsShakeToEdit:NO]; | |
9713 | ||
9714 | @synchronized (HostConfig_) { | |
9715 | [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]]; | |
9716 | } | |
9717 | ||
9718 | [NSURLCache setSharedURLCache:[[[CYURLCache alloc] | |
9719 | initWithMemoryCapacity:524288 | |
9720 | diskCapacity:10485760 | |
9721 | diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_] | |
9722 | ] autorelease]]; | |
9723 | ||
9724 | [CydiaWebViewController _initialize]; | |
9725 | ||
9726 | [NSURLProtocol registerClass:[CydiaURLProtocol class]]; | |
9727 | ||
9728 | // this would disallow http{,s} URLs from accessing this data | |
9729 | //[WebView registerURLSchemeAsLocal:@"cydia"]; | |
9730 | ||
9731 | Font12_ = [UIFont systemFontOfSize:12]; | |
9732 | Font12Bold_ = [UIFont boldSystemFontOfSize:12]; | |
9733 | Font14_ = [UIFont systemFontOfSize:14]; | |
9734 | Font18_ = [UIFont systemFontOfSize:18]; | |
9735 | Font18Bold_ = [UIFont boldSystemFontOfSize:18]; | |
9736 | Font22Bold_ = [UIFont boldSystemFontOfSize:22]; | |
9737 | ||
9738 | essential_ = [NSMutableArray arrayWithCapacity:4]; | |
9739 | broken_ = [NSMutableArray arrayWithCapacity:4]; | |
9740 | ||
9741 | // XXX: I really need this thing... like, seriously... I'm sorry | |
9742 | [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData]; | |
9743 | ||
9744 | window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; | |
9745 | [window_ orderFront:self]; | |
9746 | [window_ makeKey:self]; | |
9747 | [window_ setHidden:NO]; | |
9748 | ||
9749 | if (false) stash: { | |
9750 | [self addStashController]; | |
9751 | // XXX: this would be much cleaner as a yieldToSelector: | |
9752 | // that way the removeStashController could happen right here inline | |
9753 | // we also could no longer require the useless stash_ field anymore | |
9754 | [self performSelector:@selector(stash) withObject:nil afterDelay:0]; | |
9755 | return; | |
9756 | } | |
9757 | ||
9758 | struct stat root; | |
9759 | int error(stat("/", &root)); | |
9760 | _assert(error != -1); | |
9761 | ||
9762 | #define Stash_(path) do { \ | |
9763 | struct stat folder; \ | |
9764 | int error(lstat((path), &folder)); \ | |
9765 | if (error != -1 && ( \ | |
9766 | folder.st_dev == root.st_dev && \ | |
9767 | S_ISDIR(folder.st_mode) \ | |
9768 | ) || error == -1 && ( \ | |
9769 | errno == ENOENT || \ | |
9770 | errno == ENOTDIR \ | |
9771 | )) goto stash; \ | |
9772 | } while (false) | |
9773 | ||
9774 | Stash_("/Applications"); | |
9775 | Stash_("/Library/Ringtones"); | |
9776 | Stash_("/Library/Wallpaper"); | |
9777 | //Stash_("/usr/bin"); | |
9778 | Stash_("/usr/include"); | |
9779 | Stash_("/usr/lib/pam"); | |
9780 | Stash_("/usr/share"); | |
9781 | //Stash_("/var/lib"); | |
9782 | ||
9783 | database_ = [Database sharedInstance]; | |
9784 | [database_ setDelegate:self]; | |
9785 | ||
9786 | [window_ setUserInteractionEnabled:NO]; | |
9787 | [self setupViewControllers]; | |
9788 | ||
9789 | emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease]; | |
9790 | if ([window_ respondsToSelector:@selector(setRootViewController:)]) | |
9791 | [window_ setRootViewController:emulated_]; | |
9792 | else | |
9793 | [window_ addSubview:[emulated_ view]]; | |
9794 | ||
9795 | [self performSelector:@selector(loadData) withObject:nil afterDelay:0]; | |
9796 | _trace(); | |
9797 | } | |
9798 | ||
9799 | - (NSArray *) defaultStartPages { | |
9800 | NSMutableArray *standard = [NSMutableArray array]; | |
9801 | [standard addObject:[NSArray arrayWithObject:@"cydia://home"]]; | |
9802 | [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]]; | |
9803 | [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]]; | |
9804 | [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]]; | |
9805 | [standard addObject:[NSArray arrayWithObject:@"cydia://search"]]; | |
9806 | return standard; | |
9807 | } | |
9808 | ||
9809 | - (void) loadData { | |
9810 | _trace(); | |
9811 | if ([emulated_ modalViewController] != nil) | |
9812 | [emulated_ dismissModalViewControllerAnimated:YES]; | |
9813 | [window_ setUserInteractionEnabled:NO]; | |
9814 | ||
9815 | [self reloadDataWithInvocation:nil]; | |
9816 | [self refreshIfPossible]; | |
9817 | [self disemulate]; | |
9818 | ||
9819 | int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue]; | |
9820 | NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease]; | |
9821 | int standardIndex = 0; | |
9822 | NSArray *standard = [self defaultStartPages]; | |
9823 | ||
9824 | BOOL valid = YES; | |
9825 | ||
9826 | if (saved == nil) | |
9827 | valid = NO; | |
9828 | ||
9829 | NSDate *closed = [Metadata_ objectForKey:@"LastClosed"]; | |
9830 | if (valid && closed != nil) { | |
9831 | NSTimeInterval interval([closed timeIntervalSinceNow]); | |
9832 | // XXX: Is 30 minutes the optimal time here? | |
9833 | if (interval <= -(30*60)) | |
9834 | valid = NO; | |
9835 | } | |
9836 | ||
9837 | if (valid && [saved count] != [standard count]) | |
9838 | valid = NO; | |
9839 | ||
9840 | if (valid) { | |
9841 | for (unsigned int i = 0; i < [standard count]; i++) { | |
9842 | NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i]; | |
9843 | // XXX: The "hasPrefix" sanity check here could be, in theory, fooled, | |
9844 | // but it's good enough for now. | |
9845 | if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) { | |
9846 | valid = NO; | |
9847 | break; | |
9848 | } | |
9849 | } | |
9850 | } | |
9851 | ||
9852 | NSArray *items = nil; | |
9853 | if (valid) { | |
9854 | [tabbar_ setSelectedIndex:savedIndex]; | |
9855 | items = saved; | |
9856 | } else { | |
9857 | [tabbar_ setSelectedIndex:standardIndex]; | |
9858 | items = standard; | |
9859 | } | |
9860 | ||
9861 | for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) { | |
9862 | NSArray *stack = [items objectAtIndex:tab]; | |
9863 | UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab]; | |
9864 | NSMutableArray *current = [NSMutableArray array]; | |
9865 | ||
9866 | for (unsigned int nav = 0; nav < [stack count]; nav++) { | |
9867 | NSString *addr = [stack objectAtIndex:nav]; | |
9868 | NSURL *url = [NSURL URLWithString:addr]; | |
9869 | CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil]; | |
9870 | if (page != nil) | |
9871 | [current addObject:page]; | |
9872 | } | |
9873 | ||
9874 | [navigation setViewControllers:current]; | |
9875 | } | |
9876 | ||
9877 | // (Try to) show the startup URL. | |
9878 | if (starturl_ != nil) { | |
9879 | [self openCydiaURL:starturl_ forExternal:YES]; | |
9880 | starturl_ = nil; | |
9881 | } | |
9882 | } | |
9883 | ||
9884 | - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item { | |
9885 | if (item != nil && IsWildcat_) { | |
9886 | [sheet showFromBarButtonItem:item animated:YES]; | |
9887 | } else { | |
9888 | [sheet showInView:window_]; | |
9889 | } | |
9890 | } | |
9891 | ||
9892 | - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task { | |
9893 | id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]); | |
9894 | [progress setTitle:task]; | |
9895 | [progress addProgressEvent:event]; | |
9896 | } | |
9897 | ||
9898 | - (void) addProgressEventForTask:(NSArray *)data { | |
9899 | CydiaProgressEvent *event([data objectAtIndex:0]); | |
9900 | NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]); | |
9901 | [self addProgressEvent:event forTask:task]; | |
9902 | } | |
9903 | ||
9904 | - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task { | |
9905 | [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES]; | |
9906 | } | |
9907 | ||
9908 | @end | |
9909 | ||
9910 | /*IMP alloc_; | |
9911 | id Alloc_(id self, SEL selector) { | |
9912 | id object = alloc_(self, selector); | |
9913 | lprintf("[%s]A-%p\n", self->isa->name, object); | |
9914 | return object; | |
9915 | }*/ | |
9916 | ||
9917 | /*IMP dealloc_; | |
9918 | id Dealloc_(id self, SEL selector) { | |
9919 | id object = dealloc_(self, selector); | |
9920 | lprintf("[%s]D-%p\n", self->isa->name, object); | |
9921 | return object; | |
9922 | }*/ | |
9923 | ||
9924 | static NSSet *MobilizedFiles_; | |
9925 | ||
9926 | static NSURL *MobilizeURL(NSURL *url) { | |
9927 | NSString *path([url path]); | |
9928 | if ([path hasPrefix:@"/var/root/"]) { | |
9929 | NSString *file([path substringFromIndex:10]); | |
9930 | if ([MobilizedFiles_ containsObject:file]) | |
9931 | url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO]; | |
9932 | } | |
9933 | ||
9934 | return url; | |
9935 | } | |
9936 | ||
9937 | Class $CFXPreferencesPropertyListSource; | |
9938 | @class CFXPreferencesPropertyListSource; | |
9939 | ||
9940 | MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) { | |
9941 | NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url); | |
9942 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
9943 | ||
9944 | url = MobilizeURL(url); | |
9945 | BOOL value; @try { | |
9946 | value = _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd); | |
9947 | //NSLog(@"CFX %@ %s", [url absoluteString], value ? "YES" : "NO"); | |
9948 | } @finally { | |
9949 | url = old; | |
9950 | } | |
9951 | ||
9952 | [pool release]; | |
9953 | return value; | |
9954 | } | |
9955 | ||
9956 | MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) { | |
9957 | NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url); | |
9958 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
9959 | ||
9960 | url = MobilizeURL(url); | |
9961 | void *value; @try { | |
9962 | value = _CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd); | |
9963 | //NSLog(@"CFX %@ %@", [url absoluteString], value); | |
9964 | } @finally { | |
9965 | url = old; | |
9966 | } | |
9967 | ||
9968 | [pool release]; | |
9969 | return value; | |
9970 | } | |
9971 | ||
9972 | Class $NSURLConnection; | |
9973 | ||
9974 | MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) { | |
9975 | NSMutableURLRequest *copy([[request mutableCopy] autorelease]); | |
9976 | ||
9977 | NSURL *url([copy URL]); | |
9978 | ||
9979 | NSString *host([url host]); | |
9980 | NSString *scheme([[url scheme] lowercaseString]); | |
9981 | ||
9982 | NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]); | |
9983 | ||
9984 | @synchronized (HostConfig_) { | |
9985 | if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)]) | |
9986 | if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound]) | |
9987 | [copy setHTTPShouldUsePipelining:YES]; | |
9988 | ||
9989 | if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"]) | |
9990 | if ([control isEqualToString:@"max-age=0"]) | |
9991 | if ([CachedURLs_ containsObject:url]) { | |
9992 | #if !ForRelease | |
9993 | NSLog(@"~~~: %@", url); | |
9994 | #endif | |
9995 | ||
9996 | [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; | |
9997 | ||
9998 | [copy setValue:nil forHTTPHeaderField:@"Cache-Control"]; | |
9999 | [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"]; | |
10000 | [copy setValue:nil forHTTPHeaderField:@"If-None-Match"]; | |
10001 | } | |
10002 | } | |
10003 | ||
10004 | if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) { | |
10005 | } return self; | |
10006 | } | |
10007 | ||
10008 | Class $WAKWindow; | |
10009 | ||
10010 | static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) { | |
10011 | CGSize size([[UIScreen mainScreen] bounds].size); | |
10012 | /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)]) | |
10013 | if ([$WAKWindow hasLandscapeOrientation]) | |
10014 | std::swap(size.width, size.height);*/ | |
10015 | return size; | |
10016 | } | |
10017 | ||
10018 | Class $NSUserDefaults; | |
10019 | ||
10020 | MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) { | |
10021 | if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"]) | |
10022 | return [NSString stringWithFormat:@"%@/LocalStorage", Cache_]; | |
10023 | return _NSUserDefaults$objectForKey$(self, _cmd, key); | |
10024 | } | |
10025 | ||
10026 | int main(int argc, char *argv[]) { | |
10027 | NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]); | |
10028 | ||
10029 | _trace(); | |
10030 | ||
10031 | UpdateExternalStatus(0); | |
10032 | ||
10033 | UIScreen *screen([UIScreen mainScreen]); | |
10034 | if ([screen respondsToSelector:@selector(scale)]) | |
10035 | ScreenScale_ = [screen scale]; | |
10036 | else | |
10037 | ScreenScale_ = 1; | |
10038 | ||
10039 | UIDevice *device([UIDevice currentDevice]); | |
10040 | if ([device respondsToSelector:@selector(userInterfaceIdiom)]) { | |
10041 | UIUserInterfaceIdiom idiom([device userInterfaceIdiom]); | |
10042 | if (idiom == UIUserInterfaceIdiomPad) | |
10043 | IsWildcat_ = true; | |
10044 | } | |
10045 | ||
10046 | Idiom_ = IsWildcat_ ? @"ipad" : @"iphone"; | |
10047 | ||
10048 | Pcre pattern("^([0-9]+\\.[0-9]+)"); | |
10049 | ||
10050 | if (pattern([device systemVersion])) | |
10051 | Firmware_ = pattern[1]; | |
10052 | if (pattern(Cydia_)) | |
10053 | Major_ = pattern[1]; | |
10054 | ||
10055 | SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4]; | |
10056 | ||
10057 | HostConfig_ = [[[NSObject alloc] init] autorelease]; | |
10058 | @synchronized (HostConfig_) { | |
10059 | BridgedHosts_ = [NSMutableSet setWithCapacity:4]; | |
10060 | TokenHosts_ = [NSMutableSet setWithCapacity:4]; | |
10061 | InsecureHosts_ = [NSMutableSet setWithCapacity:4]; | |
10062 | PipelinedHosts_ = [NSMutableSet setWithCapacity:4]; | |
10063 | CachedURLs_ = [NSMutableSet setWithCapacity:32]; | |
10064 | } | |
10065 | ||
10066 | NSString *ui(@"ui/ios"); | |
10067 | if (Idiom_ != nil) | |
10068 | ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]]; | |
10069 | ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]]; | |
10070 | UI_ = CydiaURL(ui); | |
10071 | ||
10072 | PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname)))); | |
10073 | ||
10074 | MobilizedFiles_ = [NSMutableSet setWithObjects: | |
10075 | @"Library/Preferences/.GlobalPreferences.plist", | |
10076 | @"Library/Preferences/com.apple.Accessibility.plist", | |
10077 | @"Library/Preferences/com.apple.preferences.sounds.plist", | |
10078 | nil]; | |
10079 | ||
10080 | /* Library Hacks {{{ */ | |
10081 | class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16"); | |
10082 | ||
10083 | $WAKWindow = objc_getClass("WAKWindow"); | |
10084 | if ($WAKWindow != NULL) | |
10085 | if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize))) | |
10086 | method_setImplementation(method, (IMP) &$WAKWindow$screenSize); | |
10087 | ||
10088 | $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSourceSynchronizer"); | |
10089 | if ($CFXPreferencesPropertyListSource == Nil) | |
10090 | $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource"); | |
10091 | ||
10092 | Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync))); | |
10093 | if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) { | |
10094 | _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync)); | |
10095 | method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync)); | |
10096 | } | |
10097 | ||
10098 | Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk))); | |
10099 | if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) { | |
10100 | _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk)); | |
10101 | method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk)); | |
10102 | } | |
10103 | ||
10104 | $NSURLConnection = objc_getClass("NSURLConnection"); | |
10105 | Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:))); | |
10106 | if (NSURLConnection$init$ != NULL) { | |
10107 | _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$)); | |
10108 | method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$)); | |
10109 | } | |
10110 | ||
10111 | $NSUserDefaults = objc_getClass("NSUserDefaults"); | |
10112 | Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:))); | |
10113 | if (NSUserDefaults$objectForKey$ != NULL) { | |
10114 | _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$)); | |
10115 | method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$)); | |
10116 | } | |
10117 | /* }}} */ | |
10118 | /* Set Locale {{{ */ | |
10119 | Locale_ = CFLocaleCopyCurrent(); | |
10120 | Languages_ = [NSLocale preferredLanguages]; | |
10121 | ||
10122 | //CFStringRef locale(CFLocaleGetIdentifier(Locale_)); | |
10123 | //NSLog(@"%@", [Languages_ description]); | |
10124 | ||
10125 | const char *lang; | |
10126 | if (Locale_ != NULL) | |
10127 | lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]; | |
10128 | else if (Languages_ != nil && [Languages_ count] != 0) | |
10129 | lang = [[Languages_ objectAtIndex:0] UTF8String]; | |
10130 | else | |
10131 | // XXX: consider just setting to C and then falling through? | |
10132 | lang = NULL; | |
10133 | ||
10134 | if (lang != NULL) { | |
10135 | Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$"); | |
10136 | lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String]; | |
10137 | } | |
10138 | ||
10139 | NSLog(@"Setting Language: %s", lang); | |
10140 | ||
10141 | if (lang != NULL) { | |
10142 | setenv("LANG", lang, true); | |
10143 | std::setlocale(LC_ALL, lang); | |
10144 | } | |
10145 | /* }}} */ | |
10146 | /* Index Collation {{{ */ | |
10147 | if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { | |
10148 | NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]); | |
10149 | NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]); | |
10150 | //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist"; | |
10151 | NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]); | |
10152 | _H<UILocalizedIndexedCollation> collation([[[UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]); | |
10153 | ||
10154 | CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale"); | |
10155 | ||
10156 | CollationThumbs_ = [collation sectionIndexTitles]; | |
10157 | for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index) | |
10158 | CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]); | |
10159 | ||
10160 | CollationTitles_ = [collation sectionTitles]; | |
10161 | CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings"); | |
10162 | ||
10163 | NSString *&transform(MSHookIvar<NSString *>(collation, "_transform")); | |
10164 | if (&transform != NULL && transform != nil) { | |
10165 | /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)]) | |
10166 | CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/ | |
10167 | const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding])); | |
10168 | UErrorCode code(U_ZERO_ERROR); | |
10169 | CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code); | |
10170 | if (!U_SUCCESS(code)) | |
10171 | NSLog(@"%s", u_errorName(code)); | |
10172 | } | |
10173 | } else { | |
10174 | CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease]; | |
10175 | ||
10176 | CollationThumbs_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil]; | |
10177 | for (NSInteger offset(0); offset != 28; ++offset) | |
10178 | CollationOffset_.push_back(offset); | |
10179 | ||
10180 | CollationTitles_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil]; | |
10181 | CollationStarts_ = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"ʒ",nil]; | |
10182 | } | |
10183 | /* }}} */ | |
10184 | ||
10185 | apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL); | |
10186 | ||
10187 | /* Parse Arguments {{{ */ | |
10188 | bool substrate(false); | |
10189 | ||
10190 | if (argc != 0) { | |
10191 | char **args(argv); | |
10192 | int arge(1); | |
10193 | ||
10194 | for (int argi(1); argi != argc; ++argi) | |
10195 | if (strcmp(argv[argi], "--") == 0) { | |
10196 | arge = argi; | |
10197 | argv[argi] = argv[0]; | |
10198 | argv += argi; | |
10199 | argc -= argi; | |
10200 | break; | |
10201 | } | |
10202 | ||
10203 | for (int argi(1); argi != arge; ++argi) | |
10204 | if (strcmp(args[argi], "--substrate") == 0) | |
10205 | substrate = true; | |
10206 | else | |
10207 | fprintf(stderr, "unknown argument: %s\n", args[argi]); | |
10208 | } | |
10209 | /* }}} */ | |
10210 | ||
10211 | App_ = [[NSBundle mainBundle] bundlePath]; | |
10212 | Advanced_ = YES; | |
10213 | ||
10214 | setuid(0); | |
10215 | setgid(0); | |
10216 | ||
10217 | if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0) | |
10218 | system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/"); | |
10219 | ||
10220 | Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain]; | |
10221 | ||
10222 | /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc)); | |
10223 | alloc_ = alloc->method_imp; | |
10224 | alloc->method_imp = (IMP) &Alloc_;*/ | |
10225 | ||
10226 | /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc)); | |
10227 | dealloc_ = dealloc->method_imp; | |
10228 | dealloc->method_imp = (IMP) &Dealloc_;*/ | |
10229 | ||
10230 | void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY)); | |
10231 | $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer")); | |
10232 | ||
10233 | /* System Information {{{ */ | |
10234 | size_t size; | |
10235 | ||
10236 | int maxproc; | |
10237 | size = sizeof(maxproc); | |
10238 | if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1) | |
10239 | perror("sysctlbyname(\"kern.maxproc\", ?)"); | |
10240 | else if (maxproc < 64) { | |
10241 | maxproc = 64; | |
10242 | if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1) | |
10243 | perror("sysctlbyname(\"kern.maxproc\", #)"); | |
10244 | } | |
10245 | ||
10246 | sysctlbyname("kern.osversion", NULL, &size, NULL, 0); | |
10247 | char *osversion = new char[size]; | |
10248 | if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1) | |
10249 | perror("sysctlbyname(\"kern.osversion\", ?)"); | |
10250 | else | |
10251 | System_ = [NSString stringWithUTF8String:osversion]; | |
10252 | ||
10253 | sysctlbyname("hw.machine", NULL, &size, NULL, 0); | |
10254 | char *machine = new char[size]; | |
10255 | if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1) | |
10256 | perror("sysctlbyname(\"hw.machine\", ?)"); | |
10257 | else | |
10258 | Machine_ = machine; | |
10259 | ||
10260 | SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber"); | |
10261 | ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString]; | |
10262 | BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false); | |
10263 | ||
10264 | UniqueID_ = UniqueIdentifier(device); | |
10265 | ||
10266 | if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) { | |
10267 | Product_ = [info objectForKey:@"SafariProductVersion"]; | |
10268 | Safari_ = [info objectForKey:@"CFBundleVersion"]; | |
10269 | } | |
10270 | ||
10271 | NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]); | |
10272 | ||
10273 | if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_)) | |
10274 | agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent]; | |
10275 | if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_)) | |
10276 | agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent]; | |
10277 | if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_)) | |
10278 | agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent]; | |
10279 | ||
10280 | UserAgent_ = agent; | |
10281 | /* }}} */ | |
10282 | /* Load Database {{{ */ | |
10283 | _trace(); | |
10284 | Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]; | |
10285 | _trace(); | |
10286 | SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease]; | |
10287 | ||
10288 | if (Metadata_ == NULL) | |
10289 | Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2]; | |
10290 | else { | |
10291 | Settings_ = [Metadata_ objectForKey:@"Settings"]; | |
10292 | ||
10293 | Packages_ = [Metadata_ objectForKey:@"Packages"]; | |
10294 | ||
10295 | Values_ = [Metadata_ objectForKey:@"Values"]; | |
10296 | Sections_ = [Metadata_ objectForKey:@"Sections"]; | |
10297 | Sources_ = [Metadata_ objectForKey:@"Sources"]; | |
10298 | ||
10299 | Token_ = [Metadata_ objectForKey:@"Token"]; | |
10300 | ||
10301 | Version_ = [Metadata_ objectForKey:@"Version"]; | |
10302 | } | |
10303 | ||
10304 | if (Values_ == nil) { | |
10305 | Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease]; | |
10306 | [Metadata_ setObject:Values_ forKey:@"Values"]; | |
10307 | } | |
10308 | ||
10309 | if (Sections_ == nil) { | |
10310 | Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease]; | |
10311 | [Metadata_ setObject:Sections_ forKey:@"Sections"]; | |
10312 | } | |
10313 | ||
10314 | if (Sources_ == nil) { | |
10315 | Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease]; | |
10316 | [Metadata_ setObject:Sources_ forKey:@"Sources"]; | |
10317 | } | |
10318 | ||
10319 | if (Version_ == nil) { | |
10320 | Version_ = [NSNumber numberWithUnsignedInt:0]; | |
10321 | [Metadata_ setObject:Version_ forKey:@"Version"]; | |
10322 | } | |
10323 | ||
10324 | if ([Version_ unsignedIntValue] == 0) { | |
10325 | CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]); | |
10326 | CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]); | |
10327 | CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]); | |
10328 | CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./"); | |
10329 | ||
10330 | Version_ = [NSNumber numberWithUnsignedInt:1]; | |
10331 | [Metadata_ setObject:Version_ forKey:@"Version"]; | |
10332 | ||
10333 | [Metadata_ removeObjectForKey:@"LastUpdate"]; | |
10334 | ||
10335 | Changed_ = true; | |
10336 | } | |
10337 | ||
10338 | _H<NSMutableArray> broken([NSMutableArray array]); | |
10339 | for (NSString *key in (id) Sources_) | |
10340 | if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound) | |
10341 | [broken addObject:key]; | |
10342 | if ([broken count] != 0) { | |
10343 | for (NSString *key in (id) broken) | |
10344 | [Sources_ removeObjectForKey:key]; | |
10345 | Changed_ = true; | |
10346 | } broken = nil; | |
10347 | /* }}} */ | |
10348 | ||
10349 | CydiaWriteSources(); | |
10350 | ||
10351 | _trace(); | |
10352 | MetaFile_.Open("/var/lib/cydia/metadata.cb0"); | |
10353 | _trace(); | |
10354 | ||
10355 | if (Packages_ != nil) { | |
10356 | bool fail(false); | |
10357 | CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail); | |
10358 | _trace(); | |
10359 | ||
10360 | if (!fail) { | |
10361 | [Metadata_ removeObjectForKey:@"Packages"]; | |
10362 | Packages_ = nil; | |
10363 | Changed_ = true; | |
10364 | } | |
10365 | } | |
10366 | ||
10367 | Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil]; | |
10368 | ||
10369 | #define MobileSubstrate_(name) \ | |
10370 | if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \ | |
10371 | void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \ | |
10372 | if (handle == NULL) \ | |
10373 | NSLog(@"%s", dlerror()); \ | |
10374 | } | |
10375 | ||
10376 | MobileSubstrate_(Activator) | |
10377 | MobileSubstrate_(libstatusbar) | |
10378 | MobileSubstrate_(SimulatedKeyEvents) | |
10379 | MobileSubstrate_(WinterBoard) | |
10380 | ||
10381 | /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0) | |
10382 | dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/ | |
10383 | ||
10384 | int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]); | |
10385 | ||
10386 | if (access("/User", F_OK) != 0 || version != 6) { | |
10387 | _trace(); | |
10388 | system("/usr/libexec/cydia/firmware.sh"); | |
10389 | _trace(); | |
10390 | } | |
10391 | ||
10392 | _assert([[NSFileManager defaultManager] | |
10393 | createDirectoryAtPath:@"/var/cache/apt/archives/partial" | |
10394 | withIntermediateDirectories:YES | |
10395 | attributes:nil | |
10396 | error:NULL | |
10397 | ]); | |
10398 | ||
10399 | if (access("/tmp/cydia.chk", F_OK) == 0) { | |
10400 | if (unlink("/var/cache/apt/pkgcache.bin") == -1) | |
10401 | _assert(errno == ENOENT); | |
10402 | if (unlink("/var/cache/apt/srcpkgcache.bin") == -1) | |
10403 | _assert(errno == ENOENT); | |
10404 | } | |
10405 | ||
10406 | /* APT Initialization {{{ */ | |
10407 | _assert(pkgInitConfig(*_config)); | |
10408 | _assert(pkgInitSystem(*_config, _system)); | |
10409 | ||
10410 | if (lang != NULL) | |
10411 | _config->Set("APT::Acquire::Translation", lang); | |
10412 | ||
10413 | // XXX: this timeout might be important :( | |
10414 | //_config->Set("Acquire::http::Timeout", 15); | |
10415 | ||
10416 | _config->Set("Acquire::http::MaxParallel", 3); | |
10417 | /* }}} */ | |
10418 | /* Color Choices {{{ */ | |
10419 | space_ = CGColorSpaceCreateDeviceRGB(); | |
10420 | ||
10421 | Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0); | |
10422 | Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0); | |
10423 | Black_.Set(space_, 0.0, 0.0, 0.0, 1.0); | |
10424 | Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0); | |
10425 | Off_.Set(space_, 0.9, 0.9, 0.9, 1.0); | |
10426 | White_.Set(space_, 1.0, 1.0, 1.0, 1.0); | |
10427 | Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0); | |
10428 | Green_.Set(space_, 0.0, 0.5, 0.0, 1.0); | |
10429 | Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0); | |
10430 | Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0); | |
10431 | ||
10432 | InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f]; | |
10433 | RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f]; | |
10434 | /* }}}*/ | |
10435 | /* UIKit Configuration {{{ */ | |
10436 | // XXX: I have a feeling this was important | |
10437 | //UIKeyboardDisableAutomaticAppearance(); | |
10438 | /* }}} */ | |
10439 | ||
10440 | $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever")); | |
10441 | ||
10442 | const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability"); | |
10443 | BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol)); | |
10444 | bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7")); | |
10445 | ||
10446 | PulseInterval_ = fast ? 50000 : 500000; | |
10447 | ||
10448 | Colon_ = UCLocalize("COLON_DELIMITED"); | |
10449 | Elision_ = UCLocalize("ELISION"); | |
10450 | Error_ = UCLocalize("ERROR"); | |
10451 | Warning_ = UCLocalize("WARNING"); | |
10452 | ||
10453 | _trace(); | |
10454 | int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia")); | |
10455 | ||
10456 | CGColorSpaceRelease(space_); | |
10457 | CFRelease(Locale_); | |
10458 | ||
10459 | [pool release]; | |
10460 | return value; | |
10461 | } |