This repository has been archived by the owner on Mar 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 143
/
DemoAppController.m
241 lines (189 loc) · 8.08 KB
/
DemoAppController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
//
// DemoAppController.m
// CouchCocoa
//
// Created by Jens Alfke on 6/1/11.
// Copyright (c) 2011 Couchbase, Inc, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
#import "DemoAppController.h"
#import "DemoQuery.h"
#import "Test.h"
#import "TouchDB.h"
#import <TouchDBListener/TDListener.h>
#import <CouchCocoa/CouchCocoa.h>
#import <CouchCocoa/CouchTouchDBServer.h>
#define kChangeGlowDuration 3.0
int main (int argc, const char * argv[]) {
RunTestCases(argc,argv);
return NSApplicationMain(argc, argv);
}
@implementation DemoAppController
@synthesize query = _query;
- (void) applicationDidFinishLaunching: (NSNotification*)n {
//gRESTLogLevel = kRESTLogRequestURLs;
//gCouchLogLevel = 1;
NSDictionary* bundleInfo = [[NSBundle mainBundle] infoDictionary];
NSString* dbName = [bundleInfo objectForKey: @"DemoDatabase"];
if (!dbName) {
NSLog(@"FATAL: Please specify a CouchDB database name in the app's Info.plist under the 'DemoDatabase' key");
exit(1);
}
CouchTouchDBServer* server = [CouchTouchDBServer sharedInstance];
NSAssert(!server.error, @"Error initializing TouchDB: %@", server.error);
_database = [[server databaseNamed: dbName] retain];
RESTOperation* op = [_database create];
if (![op wait]) {
NSAssert(op.error.code == 412, @"Error creating db: %@", op.error);
}
// Create a CouchDB 'view' containing list items sorted by date
TDDatabase* tdb = [server.touchServer existingDatabaseNamed: dbName];
NSAssert(tdb, @"Failed to open or create TouchDB database");
[[tdb viewNamed: @"byDate"] setMapBlock: ^(NSDictionary* doc, TDMapEmitBlock emit) {
id date = [doc objectForKey: @"created_at"];
if (date) emit(date, doc);
} reduceBlock: NULL version: @"1"];
// ...and a validation function requiring parseable dates:
[tdb addValidation: ^(TDRevision* newRevision, id<TDValidationContext>context) {
if (newRevision.deleted)
return YES;
id date = [newRevision.properties objectForKey: @"created_at"];
if (date && ! [RESTBody dateWithJSONObject: date]) {
context.errorMessage = [@"invalid date " stringByAppendingString: date];
return NO;
}
return YES;
}];
CouchQuery* q = [[_database designDocumentWithName: @"default"] queryViewNamed: @"byDate"];
q.descending = YES;
self.query = [[[DemoQuery alloc] initWithQuery: q] autorelease];
self.query.modelClass =_tableController.objectClass;
// Enable continuous sync:
[self startContinuousSyncWith: self.syncURL];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(replicationProgressChanged:)
name: TDReplicatorProgressChangedNotification
object: nil];
// Start a listener socket:
[[[TDListener alloc] initWithTDServer: server.touchServer port: 8888] start];
}
#pragma mark - SYNC:
- (NSURL*) syncURL {
NSString* urlStr = [[NSUserDefaults standardUserDefaults] stringForKey: @"SyncURL"];
return urlStr ? [NSURL URLWithString: urlStr] : nil;
}
- (void) setSyncURL:(NSURL *)url {
NSURL* currentURL = self.syncURL;
if (url != currentURL && ![url isEqual: currentURL]) {
[[NSUserDefaults standardUserDefaults] setObject: url.absoluteString
forKey: @"SyncURL"];
[self startContinuousSyncWith: url];
}
}
- (NSURL*) currentURLFromField {
NSString* urlStr = _syncURLField.stringValue;
NSURL* url = nil;
if (urlStr.length > 0) {
url = [NSURL URLWithString: urlStr];
if (![url.scheme hasPrefix: @"http"])
url = nil;
}
return url;
}
- (IBAction) configureSync: (id)sender {
_syncURLField.objectValue = self.syncURL.absoluteString;
[NSApp beginSheet: _syncConfigSheet modalForWindow: _window
modalDelegate: self
didEndSelector:@selector(configureSyncFinished:returnCode:)
contextInfo: NULL];
}
- (IBAction) dismissSyncConfigSheet:(id)sender {
NSInteger returnCode = [sender tag];
if (returnCode == NSOKButton
&& _syncURLField.stringValue.length > 0 && !self.currentURLFromField) {
NSBeep();
return;
}
[NSApp endSheet: _syncConfigSheet returnCode: returnCode];
}
- (void) configureSyncFinished:(NSWindow *)sheet returnCode:(NSInteger)returnCode {
[sheet orderOut: self];
if (returnCode == NSOKButton)
self.syncURL = self.currentURLFromField;
}
- (void) stopReplication: (CouchReplication**)repl {
[*repl removeObserver: self forKeyPath: @"completed"];
[*repl stop];
[*repl release];
*repl = nil;
}
- (void) startContinuousSyncWith: (NSURL*)otherDbURL {
[self stopReplication: &_pull];
[self stopReplication: &_push];
if (otherDbURL) {
_pull = [[_database pullFromDatabaseAtURL: otherDbURL options: kCouchReplicationContinuous]
retain];
[_pull addObserver: self forKeyPath: @"completed" options: 0 context: NULL];
_push = [[_database pushToDatabaseAtURL: otherDbURL options: kCouchReplicationContinuous]
retain];
[_push addObserver: self forKeyPath: @"completed" options: 0 context: NULL];
}
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
{
if (object == _pull || object == _push) {
unsigned completed = _pull.completed + _push.completed;
unsigned total = _pull.total + _push.total;
NSLog(@"SYNC progress: %u / %u", completed, total);
if (total > 0 && completed < total) {
[_syncProgress setDoubleValue: (completed / (double)total)];
} else {
[_syncProgress setDoubleValue: 0.0];
}
_database.server.activityPollInterval = 0; // I use notifications instead
}
}
- (void) replicationProgressChanged: (NSNotification*)n {
// This is called on the TouchDB background thread, so redispatch to the main thread:
[_database.server performSelectorOnMainThread: @selector(checkActiveTasks)
withObject: nil waitUntilDone: NO];
}
#pragma mark HIGHLIGHTING NEW ITEMS:
- (void) updateTableGlows {
_glowing = NO;
[_table setNeedsDisplay: YES];
}
- (void)tableView:(NSTableView *)tableView
willDisplayCell:(id)cell
forTableColumn:(NSTableColumn *)tableColumn
row:(NSInteger)row
{
NSColor* bg = nil;
NSArray* items = _tableController.arrangedObjects;
if (row >= (NSInteger)items.count)
return; // Don't know why I get called on illegal rows, but it happens...
CouchModel* item = [items objectAtIndex: row];
NSTimeInterval changedFor = item.timeSinceExternallyChanged;
if (changedFor > 0 && changedFor < kChangeGlowDuration) {
float fraction = (float)(1.0 - changedFor / kChangeGlowDuration);
if (YES || [cell isKindOfClass: [NSButtonCell class]])
bg = [[NSColor controlBackgroundColor] blendedColorWithFraction: fraction
ofColor: [NSColor yellowColor]];
else
bg = [[NSColor yellowColor] colorWithAlphaComponent: fraction];
if (!_glowing) {
_glowing = YES;
[self performSelector: @selector(updateTableGlows) withObject: nil afterDelay: 0.1];
}
}
[cell setBackgroundColor: bg];
[cell setDrawsBackground: (bg != nil)];
}
@end