File: Document.m

package info (click to toggle)
gnustep-examples 1%3A1.0.0-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,952 kB
  • ctags: 280
  • sloc: objc: 15,345; makefile: 64
file content (503 lines) | stat: -rw-r--r-- 14,894 bytes parent folder | download
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#import "Document.h"
#import "PieceView.h"

@interface Document (Private)

- (BOOL)loadError:(NSString *)msg;
- (NSWindow*) makeWindow;

@end

@implementation Document

- init
{
  [super init];
  return self;
}

- (void) dealloc
{
  [super dealloc];
}

- scramble:(id)sender
{
    NSMutableArray *allLeaves;
    int ind;
    PieceView *piece;
    BTree *cluster;
    NSSize desksize = [image size];
    int 
        width  = DESKTOPEXTRA/2+(int)desksize.width, 
        height = DESKTOPEXTRA/2+(int)desksize.height;

    if([clusters count]==px*py){
        for(ind=0; ind<[clusters count]; ind++){
            piece = [[clusters objectAtIndex:ind] leaf];
            
            [piece setFrameOrigin:
                       NSMakePoint(DESKTOPEXTRA/2+rand()%width,
                                   DESKTOPEXTRA/2+rand()%height)];
        }
    }
    else{
        allLeaves = [NSMutableArray array];
        for(ind=0; ind<[clusters count]; ind++){
            cluster = [clusters objectAtIndex:ind];
            [allLeaves addObjectsFromArray:[cluster leaves]];
            [cluster deallocAll];
        }
        // [clusters release];
        
        clusters = [NSMutableArray array];
        for(ind=0; ind<[allLeaves count]; ind++){
            piece = (PieceView *)[allLeaves objectAtIndex:ind];
            
            cluster = [[BTree alloc] 
                          initWithLeaf:piece];
            [piece setCluster:cluster];
            [clusters addObject:cluster];
            
            [piece setFrameOrigin:
                       NSMakePoint(DESKTOPEXTRA+rand()%width,
                                   DESKTOPEXTRA+rand()%height)];
        }
        [clusters retain];
    }

    [[view window] setDocumentEdited:YES];
    [view setNeedsDisplay:YES];

    return self;
}

#define INVALID_DISPLAY_SECS 1

- verify:(id)sender
{
    int ind;
    BTree *cluster;
    PieceView **pieces;

    for(ind=0; ind<[clusters count]; ind++){
        cluster = [clusters objectAtIndex:ind];
        if((pieces = [PieceView checkCluster:cluster]) != NULL){
            NSBeep();
            [pieces[0] showInvalid];
            [pieces[1] showInvalid];

            [NSThread 
                sleepUntilDate:
                    [NSDate 
                        dateWithTimeIntervalSinceNow:
                            INVALID_DISPLAY_SECS]];

            [pieces[0] setNeedsDisplay:YES];
            [pieces[1] setNeedsDisplay:YES];

            return self;
        }
    }
     
    NSRunAlertPanel(@"Verify", @"No conflicting pieces.", 
                    @"Ok", nil, nil);
    return self;
}


- (NSMutableArray *)clusters
{
    return clusters;
}


- (NSData *)dataRepresentationOfType:(NSString *)aType 
{
    NSString *msg;

    if([aType isEqualToString:DOCTYPE]){
        NSString *trees = @"", *pieces = @"", *all;
        int clind, pind;
        BTree *cluster; PieceView *piece;
        NSMutableArray *leaves;

        for(clind=0; clind<[clusters count]; clind++){
            cluster = [clusters objectAtIndex:clind];
            trees = [trees stringByAppendingString:
                                 [cluster toString]];
            
            leaves = [cluster leaves];
            for(pind=0; pind<[leaves count]; pind++){
                piece = [leaves objectAtIndex:pind];
                pieces = [pieces stringByAppendingString:
                                     [piece toString]];
            }
        }

        all = [NSString stringWithFormat:@"%@\n%d %d %d\n", 
                        nameOfTIFF, px, py, [clusters count]];

        all = [all stringByAppendingString:trees];
        all = [all stringByAppendingString:pieces];
        return [all dataUsingEncoding:NSASCIIStringEncoding];
    }
    else{
        msg = [NSString stringWithFormat: @"Unknown type: %@", 
                        [aType uppercaseString]];
        NSRunAlertPanel(@"Alert", msg, @"Ok", nil, nil);
        return nil;
    }
}

- (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)aType 
{
    NSString *msg;
    NSSize size;
    int x, y;
    PieceView *piece;
    BTree *cluster;

    int horizontal[DIM_MAX][DIM_MAX];
    int vertical[DIM_MAX][DIM_MAX];

    if([aType isEqualToString:DOCTYPE]){
        NSArray *lines = 
            [[NSString stringWithCString:[data bytes] 
                       length:[data length]] 
                componentsSeparatedByString:@"\n"];
        NSEnumerator *en = [lines objectEnumerator];
        NSString *line;
        NSScanner *scanner;
        int clcount, clind, lind;
        NSMutableDictionary *pdict;
        int x, y, ktag, posx, posy;
        NSPoint *loc;
        PTYPE left, right, lower, upper;

        image = nil;
        clusters = nil;

        if((line = [en nextObject])==nil){
            return [self loadError:@"File name is missing"];
        }
        if ((image = [[NSImage alloc] 
                         initWithContentsOfFile:line])==nil){
            msg = [NSString stringWithFormat: @"Load failed (TIFF)", 
                            data];
            return [self loadError:msg];
        }
        nameOfTIFF = [line copy];
        size = [image size];

        if((line = [en nextObject])==nil){
            return [self loadError:@"Image dimensions missing"];
        }
        scanner = [NSScanner scannerWithString:line];
        if([scanner scanInt:&px]==NO ||
           [scanner scanInt:&py]==NO ||
           [scanner scanInt:&clcount]==NO ||
           px<DIM_MIN || px>DIM_MAX-1 ||
           py<DIM_MIN || py>DIM_MAX-1 ||
           clcount<1 || clcount>px*py){
            return [self loadError:
                             @"Image dimensions/clusters out of range"];
        }

        clusters = [NSMutableArray arrayWithCapacity:clcount];
        for(clind=0; clind<clcount; clind++){
            if((cluster = [BTree fromLines:en])==nil){
                msg = [NSString stringWithFormat: 
                                    @"Read failure  (cluster %d/%d)", 
                                clind, clcount];
                return [self loadError:msg];
            }
            [clusters addObject:cluster];
        }

        pdict = [NSMutableDictionary dictionaryWithCapacity:px*py];
        for(lind = 0; lind<px*py; lind++){
            if((line = [en nextObject])==nil){
                msg = [NSString stringWithFormat: 
                                    @"EOF  (piece %d/%d)", 
                                lind, px*py];
                return [self loadError:msg];
            }

            scanner = [NSScanner scannerWithString:line];
            if([scanner scanInt:&ktag]==NO ||
               [scanner scanInt:&x]==NO ||
               [scanner scanInt:&y]==NO ||
               [scanner scanInt:(int *)&left]==NO ||
               [scanner scanInt:(int *)&right]==NO ||
               [scanner scanInt:(int *)&upper]==NO ||
               [scanner scanInt:(int *)&lower]==NO ||
               [scanner scanInt:&posx]==NO ||
               [scanner scanInt:&posy]==NO){
                msg = [NSString stringWithFormat: 
                                    @"missing fields  (piece %d/%d)", 
                                lind, px*py];
                return [self loadError:msg];
            }

            piece = [[PieceView alloc]
                        initWithImage:image
                        loc:NSMakePoint(posx, posy)
                        posX:x outOf:px
                        posY:y outOf:py
                        left:left
                        right:right
                        upper:upper
                        lower:lower];
            [piece setDocument:self];
            [pdict setObject:piece 
                   forKey:[NSNumber numberWithInt:ktag]];
        }

        for(clind=0; clind<[clusters count]; clind++){
            cluster = [clusters objectAtIndex:clind];
            [cluster substituteLeaves:pdict];
            [cluster
                inorderWithPointer:(void *)cluster
                sel:@selector(setCluster:)]; 
        }

        [clusters retain];

        return YES;
    }
    else if([aType isEqualToString:TIFFTYPE]){
        if (!(image = [[NSImage alloc] initWithData:data])){
            NSRunAlertPanel(@"Alert", @"Load failed (TIFF)",
                            @"Ok", nil, nil);
            return NO;
        }

        size = [image size];

        px = ((int)size.width)/PIECE_WIDTH;
        if(((int)size.width)%PIECE_WIDTH){
            px++;
        }

        py = ((int)size.height)/PIECE_HEIGHT;
        if(((int)size.height)%PIECE_HEIGHT){
            py++;
        }

        if(px<DIM_MIN || py<DIM_MIN){
            [image dealloc];
            NSRunAlertPanel(@"Alert", @"Image too small (TIFF)",
                            @"Ok", nil, nil);
            return NO;
        }
        if(px>DIM_MAX-1 || py>DIM_MAX-1){
            [image dealloc];
            NSRunAlertPanel(@"Alert", @"Image too large (TIFF)", 
                            @"Ok", nil, nil);
            return NO;
        }

        // horizontal 
        for(y=0; y<py; y++){
            horizontal[0][y] = BORDER;
            for(x=1; x<px; x++){
                horizontal[x][y] = (rand()%2 ? INNER : OUTER);
            }
            horizontal[px][y] = BORDER;
        }
        
        // vertical
        for(x=0; x<px; x++){
            vertical[x][0] = BORDER;
            for(y=1; y<py; y++){
                vertical[x][y] = (rand()%2 ? INNER : OUTER);
            }
            vertical[x][py] = BORDER;
        }

        clusters = [NSMutableArray arrayWithCapacity:px*py];
        for(y=0; y<py; y++){
            for(x=0; x<px; x++){
                piece = [[PieceView alloc]
                            initWithImage:image
                            loc:NSMakePoint(DESKTOPEXTRA+x*PIECE_WIDTH, 
                                            DESKTOPEXTRA+y*PIECE_HEIGHT)
                            posX:x outOf:px
                            posY:y outOf:py
                            left:horizontal[x][y]
                            right:(-horizontal[x+1][y])
                            upper:(-vertical[x][y+1])
                            lower:vertical[x][y]];
                [piece setDocument:self];

                cluster = [[BTree alloc] initWithLeaf:piece];
                [piece setCluster:cluster];
                [clusters addObject:cluster];
            }
        }

        [clusters retain];
        [self scramble:self];
    }
    else{
        msg = [NSString stringWithFormat: @"Unknown type: %@", 
                        [aType uppercaseString]];
        NSRunAlertPanel(@"Alert", msg, @"Ok", nil, nil);
        return NO;
    }

    return YES;
}

- (void) makeWindowControllers
{
  NSWindowController *controller;
  NSWindow *win = [self makeWindow];
  
  controller = [[NSWindowController alloc] initWithWindow: win];
  RELEASE (win);
  [self addWindowController: controller];
  RELEASE(controller);

  // We have to do this ourself, as there is currently no nib file
  [self windowControllerDidLoadNib: controller];
}

- (void)windowControllerDidLoadNib:(NSWindowController *)aController;
{
  [super windowControllerDidLoadNib:aController];
}

- (BOOL)readFromFile:(NSString *)fileName ofType:(NSString *)docType
{
    if([docType isEqual:TIFFTYPE]){
        nameOfTIFF = [fileName copy];
    }

    return [super readFromFile:fileName ofType:docType];
}

@end

@implementation Document (Private)

- (NSWindow*)makeWindow
{
  NSWindow *window;
  NSRect frame;
  int m = (NSTitledWindowMask |  NSClosableWindowMask | 
           NSMiniaturizableWindowMask);

  int clind, pieceind;
  BTree *cluster;
  NSScrollView *scroller;
  NSSize scrollSize, desktop;
  NSString *fname;

  frame.origin.x = 0;
  frame.origin.y = 0;
  frame.size = [image size];
  frame.size.width  += 2*(BOUNDARY+DESKTOPEXTRA);
  frame.size.height += 2*(BOUNDARY+DESKTOPEXTRA);

  desktop = frame.size;

  view  = [[NSView alloc] initWithFrame:frame];
  for(clind=0; clind<[clusters count]; clind++){
      cluster = [clusters objectAtIndex:clind];
      [cluster inorderWithTarget:view
               sel:@selector(addSubview:)];
  }

  scrollSize = 
      [NSScrollView frameSizeForContentSize:
                        NSMakeSize((desktop.width<DESKTOPMAX ? 
                                    desktop.width : DESKTOPMAX),
                                   (desktop.height<DESKTOPMAX ? 
                                    desktop.height : DESKTOPMAX))
                    hasHorizontalScroller:YES
                    hasVerticalScroller:YES
                    borderType:NSLineBorder];
  scroller = [[NSScrollView alloc] 
                 initWithFrame:NSMakeRect(0, 0, 
                                          scrollSize.width,
                                          scrollSize.height)];
  [scroller setHasHorizontalScroller:YES];
  [scroller setHasVerticalScroller:YES];
  [scroller setDocumentView:view];

  frame = [NSWindow frameRectForContentRect:[scroller frame] 
                    styleMask:m];

  window = [[NSWindow alloc] initWithContentRect:frame 
                             styleMask:m			       
                             backing: NSBackingStoreRetained 
                             defer:YES];
  [window setMinSize:NSMakeSize(DESKTOPEXTRA, DESKTOPEXTRA)];
  [window setReleasedWhenClosed:NO];
  [window setDelegate:self];

  [window setFrame:frame display:YES];
  [window setMaxSize:desktop];
  [window setContentView:scroller];
  [window setReleasedWhenClosed:YES];

  // RELEASE(view);

  [window center];
  [window orderFrontRegardless];
  [window makeKeyWindow];
  [window display];

  [self setFileType:DOCTYPE];
  
  fname = [self fileName];
  if([fname hasSuffix:DTIFFTYPE]){
      NSArray *docs = 
          [[NSDocumentController sharedDocumentController]
              documents];
      NSString *result, *fixIt = 
          [fname substringToIndex:
                     ([fname length]-[DTIFFTYPE length])];
      NSFileManager *manager = [NSFileManager defaultManager];
      int comp, index = 1;

      while(index){
          result = [fixIt stringByAppendingFormat:@"-%u%@", 
                          index, DDOCTYPE];

          for(comp=0; comp<[docs count]; comp++){
              if([[[docs objectAtIndex:comp] fileName]
                     isEqual:result]){
                  break;
              }
          }

          if(comp==[docs count] && 
             [manager fileExistsAtPath:result]==NO){
              break;
          }
          index++;
      }
      
      [self setFileName:result];
  }
  NSLog(@"file name %@\n",  [self fileName]);

  return window;
}

- (BOOL)loadError:(NSString *)msg
{
    if(image!=nil){
        [image dealloc];
    }
    if(clusters!=nil){
        [clusters dealloc];
    }
    NSRunAlertPanel(@"Alert", msg, @"Ok", nil, nil);
    return NO;
}

@end