/
JotView.m
2047 lines (1666 loc) · 79.2 KB
/
JotView.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
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Shortcut.h
// JotSDKLibrary
//
// Created by Adam Wulf on 11/19/12.
// Copyright (c) 2012 Adonit. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import <OpenGLES/EAGLDrawable.h>
#import <mach/mach_time.h> // for mach_absolute_time() and friends
#import "JotView.h"
#import "JotStrokeManager.h"
#import "AbstractBezierPathElement.h"
#import "AbstractBezierPathElement-Protected.h"
#import "CurveToPathElement.h"
#import "UIColor+JotHelper.h"
#import "JotGLTexture.h"
#import "JotGLTextureBackedFrameBuffer.h"
#import "JotDefaultBrushTexture.h"
#import "JotTrashManager.h"
#import "JotViewState.h"
#import "JotViewImmutableState.h"
#import "SegmentSmoother.h"
#import "JotFilledPathStroke.h"
#import "MMWeakTimerTarget.h"
#import "JotTextureCache.h"
#import "NSMutableArray+RemoveSingle.h"
#import "JotDiskAssetManager.h"
#import <JotTouchSDK/JotStylusManager.h>
#import "JotGLLayerBackedFrameBuffer.h"
#import "UIScreen+PortraitBounds.h"
#define kJotValidateUndoTimer .06
dispatch_queue_t importExportImageQueue;
dispatch_queue_t importExportStateQueue;
@interface JotView (){
__weak NSObject<JotViewDelegate>* delegate;
JotGLContext *context;
@private
JotGLLayerBackedFrameBuffer* viewFramebuffer;
//
// these 4 properties help with our performance when writing
// large strokes to the backing texture. the timer will continually
// try to validate our undo state. if a stroke needs to be pushed
// off the undo stack, then it's added to the strokesBeingWrittenToBackingTexture
// array, and then progressively written to the backing texture over
// numerous calls by the Timer.
//
// this prevents an entire stroke from being written to the texture
// in just 1 go, and spreads that work out over time.
//
// if our export method gets called while we're writing to the texture,
// then we add that to a queue and will re-call that export method
// after all the strokes have been written to disk
NSTimer* validateUndoStateTimer;
AbstractBezierPathElement* prevElementForTextureWriting;
NSMutableArray* exportLaterInvocations;
NSUInteger isCurrentlyExporting;
// a handle to the image used as the current brush texture
JotViewStateProxy* state;
CGSize initialFrameSize;
// the maximum stroke size in bytes before a new stroke
// is created
NSInteger maxStrokeSize;
NSLock* inkTextureLock;
NSLock* imageTextureLock;
}
@end
@implementation JotView
@synthesize delegate;
@synthesize context;
@synthesize maxStrokeSize;
@synthesize state;
#pragma mark - Initialization
static JotGLContext *mainThreadContext;
+(JotGLContext*) mainThreadContext{
return mainThreadContext;
}
/**
* Implement this to override the default layer class (which is [CALayer class]).
* We do this so that our view will be backed by a layer that is capable of OpenGL ES rendering.
*/
+ (Class) layerClass{
return [CAEAGLLayer class];
}
/**
* The GL view is stored in the nib file. When it's unarchived it's sent -initWithCoder:
*/
- (id)initWithCoder:(NSCoder*)coder {
if ((self = [super initWithCoder:coder])) {
return [self finishInit];
}
return self;
}
/**
* initialize a new view for the given frame
*/
- (id) initWithFrame:(CGRect)frame{
frame.size.width = ceilf(frame.size.width);
frame.size.height = ceilf(frame.size.height);
if((self = [super initWithFrame:frame])){
return [self finishInit];
}
return self;
}
-(id) finishInit{
CheckMainThread;
inkTextureLock = [[NSLock alloc] init];
imageTextureLock = [[NSLock alloc] init];
// strokes have a max of .5Mb each
self.maxStrokeSize = 512*1024;
CADisplayLink* displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkPresentRenderBuffer:)];
displayLink.frameInterval = 2;
[displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
initialFrameSize = self.bounds.size;
prevElementForTextureWriting = nil;
exportLaterInvocations = [NSMutableArray array];
MMWeakTimerTarget* weakTimerTarget = [[MMWeakTimerTarget alloc] initWithTarget:self andSelector:@selector(validateUndoState:)];
validateUndoStateTimer = [NSTimer scheduledTimerWithTimeInterval:kJotValidateUndoTimer
target:weakTimerTarget
selector:@selector(timerDidFire:)
userInfo:nil
repeats:YES];
//
// this view should accept Jot stylus touch events
[[JotTrashManager sharedInstance] setMaxTickDuration:kJotValidateUndoTimer * 1 / 20];
// create a default empty state
state = nil;
// allow more than 1 finger/stylus to draw at a time
self.multipleTouchEnabled = YES;
//
// the remainder is OpenGL initialization
CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
eaglLayer.opaque = NO;
// In this application, we want to retain the EAGLDrawable contents after a call to presentRenderbuffer.
eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
if(!mainThreadContext){
context = [[JotGLContext alloc] initWithName:@"JotViewMainThreadContext" andAPI:kEAGLRenderingAPIOpenGLES1 andValidateThreadWith:^BOOL{
return [NSThread isMainThread];
}];
mainThreadContext = context;
[[JotTrashManager sharedInstance] setGLContext:mainThreadContext];
}else{
context = [[JotGLContext alloc] initWithName:@"JotViewMainThreadContext" andAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:mainThreadContext.sharegroup andValidateThreadWith:^BOOL{
return [NSThread isMainThread];
}];
}
if (!context) {
return nil;
}
[context runBlock:^{
// Set the view's scale factor
self.contentScaleFactor = [[UIScreen mainScreen] scale];
[context glMatrixModeProjection];
// Setup the view port in Pixels
[context glMatrixModeModelView];
[context glDisableDither];
[context glEnableTextures];
[context glEnableBlend];
[context glEnablePointSprites];
[self destroyFramebuffer];
[self createFramebuffer];
}];
[JotGLContext validateEmptyContextStack];
return self;
}
#pragma mark - Dispatch Queues
static const void *const kImportExportImageQueueIdentifier = &kImportExportImageQueueIdentifier;
static const void *const kImportExportStateQueueIdentifier = &kImportExportStateQueueIdentifier;
+(dispatch_queue_t) importExportImageQueue{
if(!importExportImageQueue){
importExportImageQueue = dispatch_queue_create("com.milestonemade.looseleaf.importExportImageQueue", DISPATCH_QUEUE_SERIAL);
dispatch_queue_set_specific(importExportImageQueue, kImportExportImageQueueIdentifier, (void *)kImportExportImageQueueIdentifier, NULL);
}
return importExportImageQueue;
}
+(BOOL) isImportExportImageQueue{
return dispatch_get_specific(kImportExportImageQueueIdentifier) != NULL;
}
+(dispatch_queue_t) importExportStateQueue{
if(!importExportStateQueue){
importExportStateQueue = dispatch_queue_create("com.milestonemade.looseleaf.importExportStateQueue", DISPATCH_QUEUE_SERIAL);
dispatch_queue_set_specific(importExportStateQueue, kImportExportStateQueueIdentifier, (void *)kImportExportStateQueueIdentifier, NULL);
}
return importExportStateQueue;
}
+(BOOL) isImportExportStateQueue{
return dispatch_get_specific(kImportExportStateQueueIdentifier) != NULL;
}
#pragma mark - OpenGL Init
/**
* this will create the framebuffer and related
* render and depth buffers that we'll use for
* drawing
*/
- (BOOL)createFramebuffer{
CheckMainThread;
viewFramebuffer = [[JotGLLayerBackedFrameBuffer alloc] initForLayer:(CALayer<EAGLDrawable>*)self.layer];
[self clear:NO];
return YES;
}
/**
* Clean up any buffers we have allocated.
*/
- (void)destroyFramebuffer{
JotGLContext* destroyContext = context;
if(!destroyContext){
// crash log from: https://crashlytics.com/milestonemade/ios/apps/com.milestonemade.looseleaf/issues/545172eae3de5099ba29598d/sessions/545171c803d1000153d9653633633632
// shows a nil context at this point.
// this code will generate a new context
// that can be used to clean up any
// GL assets.
destroyContext = [[JotGLContext alloc] initWithName:@"JotViewDestroyFBOContext" andAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:mainThreadContext.sharegroup andValidateThreadWith:^BOOL{
return YES;
}];
}
[destroyContext runBlock:^{
viewFramebuffer = nil;
[destroyContext flush];
}];
}
#pragma mark - Import and Export
/**
* This method will load the input image into the drawable view
* and will stretch it as appropriate to fill the area. For best results,
* use an image that is the same size as the view's frame.
*
* This method will also reset the undo state of the view.
*
* This method must be called at least one time after initialization
*/
-(void) loadState:(JotViewStateProxy*)newState{
CheckMainThread;
if(state != newState){
state = newState;
[self renderAllStrokesToContext:context inFramebuffer:viewFramebuffer andPresentBuffer:YES inRect:CGRectZero];
if([state hasEditsToSave]){
// be explicit about not letting us change the state of
// the drawable view if there are saves pending.
@throw [NSException exceptionWithName:@"JotViewException" reason:@"Changing JotView state with saves pending" userInfo:nil];
}
// at this point, we know that we've saved 100% of our
// state to disk, but for some reason still have saves
// pending.
//
// empty out this array - otherwise we'll try to save our
// new state during this old invocation.
//
// https://github.com/adamwulf/loose-leaf/issues/533
[exportLaterInvocations removeAllObjects];
}
}
-(void) exportImageTo:(NSString*)inkPath
andThumbnailTo:(NSString*)thumbnailPath
andStateTo:(NSString*)plistPath
withThumbnailScale:(CGFloat)thumbScale
onComplete:(void(^)(UIImage* ink, UIImage* thumb, JotViewImmutableState* state))exportFinishBlock{
// ask to save, and send in our state object
// incase we need to defer saving until later
[self exportImageTo:inkPath andThumbnailTo:thumbnailPath andStateTo:plistPath andJotState:state withThumbnailScale:@(thumbScale) onComplete:exportFinishBlock];
}
/**
* i need to send out nil for the ink and thumbnail
* if i can determine that either/both do not have any
* user drawn content on them
*
* https://github.com/adamwulf/loose-leaf/issues/226
*/
-(void) exportImageTo:(NSString*)inkPath
andThumbnailTo:(NSString*)thumbnailPath
andStateTo:(NSString*)plistPath
andJotState:(JotViewStateProxy*)stateToBeSaved
withThumbnailScale:(NSNumber*)thumbScale
onComplete:(void(^)(UIImage* ink, UIImage* thumb, JotViewImmutableState* state))exportFinishBlock{
CheckMainThread;
if(stateToBeSaved != state){
@throw [NSException exceptionWithName:@"InvalidJotViewStateDuringSaveException" reason:@"JotView is asked to save with the wrong state object" userInfo:nil];
}
if(!stateToBeSaved){
@throw [NSException exceptionWithName:@"InvalidJotViewStateDuringSaveException" reason:@"JotView is asked to save without a state object" userInfo:nil];
}
if(!state){
exportFinishBlock(nil, nil, nil);
return;
}
if(state.isForgetful){
DebugLog(@"forget: skipping export for forgetful jotview");
exportFinishBlock(nil, nil, nil);
return;
}
if((![state isReadyToExport] || isCurrentlyExporting)){
if(isCurrentlyExporting == [state undoHash]){
//
// we're already currently saving this undo hash,
// so we don't need to add another save to the
// exportLaterInvocation list
exportFinishBlock(nil, nil, nil);
}else if(![exportLaterInvocations count]){
//
// the issue here is that we want to export the drawn image to a file, but we're
// also in the middle of writing all the strokes to the backing texture.
//
// instead of try to be super smart, and export while we draw (yikes!), we're going to
// wait for all of the strokes to be written to the texture that need to be.
//
// then, the [validateUndoState] will re-call this export method with the same parameters
// when it's done, and we'll bypass this block and finish the export.
//
// copy block to heap
void(^block)(UIImage* ink, UIImage* thumb, NSDictionary* state) = [exportFinishBlock copy];
SEL exportMethodSelector = @selector(exportImageTo:andThumbnailTo:andStateTo:andJotState:withThumbnailScale:onComplete:);
NSMethodSignature * mySignature = [JotView instanceMethodSignatureForSelector:exportMethodSelector];
NSInvocation* saveInvocation = [NSInvocation invocationWithMethodSignature:mySignature];
[saveInvocation setTarget:self];
[saveInvocation setSelector:exportMethodSelector];
[saveInvocation setArgument:&inkPath atIndex:2];
[saveInvocation setArgument:&thumbnailPath atIndex:3];
[saveInvocation setArgument:&plistPath atIndex:4];
[saveInvocation setArgument:&state atIndex:5];
[saveInvocation setArgument:&thumbScale atIndex:6];
[saveInvocation setArgument:&block atIndex:7];
[saveInvocation retainArguments];
[exportLaterInvocations addObject:saveInvocation];
}else{
// we have to call the export finish block, no matter what.
// so call the block and send nil b/c we're not actually done
// exporting.
exportFinishBlock(nil, nil, nil);
}
return;
}
@synchronized(self){
isCurrentlyExporting = [state undoHash];
// DebugLog(@"export begins: %p hash:%d", self, (int) state.undoHash);
}
dispatch_semaphore_t sema1 = dispatch_semaphore_create(0);
dispatch_semaphore_t sema2 = dispatch_semaphore_create(0);
__block UIImage* thumb = nil;
__block UIImage* ink = nil;
//
// we need to save a version of the state at this exact
// moment. after this method ends the state and/or strokes
// inside the state may change.
//
// this immutable state will ensure that we have a handle
// to the exact strokes that are visible + not yet written
// to the backing texture
JotViewImmutableState* immutableState = [state immutableState];
[self exportInkTextureOnComplete:^(UIImage* image){
ink = image;
dispatch_semaphore_signal(sema2);
}];
// now grab the bits of the rendered thumbnail
// and backing texture
[self exportToImageOnComplete:^(UIImage* image){
thumb = image;
dispatch_semaphore_signal(sema1);
} withScale:[thumbScale floatValue]];
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
//
// ok, right here we're halfway done with the export.
// we have all of the information we need in memory,
// and our next step is to write it to disk.
//
// we'll do the disk writing on a background thread
// below. this will take the rendered items and
// generate PNGs, and it will take our state and
// serialize it out as a plist.
//
//
// ok, here i walk off of the main thread,
// and my state arrays might get changed while
// i wait (yikes!).
//
// i need an immutable state that i can hold onto
// while i wait + write to disk in the background
//
dispatch_async([JotView importExportStateQueue], ^(void) {
@autoreleasepool {
dispatch_semaphore_wait(sema1, DISPATCH_TIME_FOREVER);
// i could notify about the thumbnail here
// which would let the UI swap to the cached thumbnail
// from the full JotUI if needed... (?)
// probably an over optimization at this point,
// but may be useful once multiple JotViews are
// on screen at a time + being exported simultaneously
dispatch_semaphore_wait(sema2, DISPATCH_TIME_FOREVER);
dispatch_release(sema1);
dispatch_release(sema2);
exportFinishBlock(ink, thumb, immutableState);
if(state.isForgetful){
@synchronized(self){
isCurrentlyExporting = 0;
}
DebugLog(@"forget: skipping export write to disk for forgetful jotview");
return;
}
if(ink){
// we have the backing ink texture to save
// so write it to disk
[[JotDiskAssetManager sharedManager] writeImage:ink toPath:inkPath];
// DebugLog(@"writing ink to disk");
}else{
// the backing texture either hasn't changed, or
// doesn't have anything written to it at all
// so skip writing a blank PNG to disk
// DebugLog(@"skipping writing ink, nothing changed");
}
[[JotDiskAssetManager sharedManager] writeImage:thumb toPath:thumbnailPath];
// this call will both serialize the state
// and write it to disk
[immutableState writeToDisk:plistPath];
// DebugLog(@"export complete");
@synchronized(self){
// we only ever want to export one at a time.
// if anything has changed while we've been exporting
// then that'll be held in the exportLaterInvocations
// and will fire after we're done. (from validateUndoState).
isCurrentlyExporting = 0;
}
// DebugLog(@"export ends: %p", self);
}
});
}
#pragma mark Export Helpers
/**
* export an image from the openGL render buffer to a UIImage
* @param backgroundColor an optional background color for the image. pass nil for a transparent background.
* @param backgroundImage an optional image to use as the background behind this view's content
*
* code modified from http://developer.apple.com/library/ios/#qa/qa1704/_index.html
*
* If you plan to save the returned image to the photo library,
* then you can maintain transparency by reformatting as a PNG:
* [UIImage imageWithData:UIImagePNGRepresentation(imageReturnedByThisMethod)];
*
* If you don't reformat as a PNG, then you may lose transparency
* when saving/loading from the Photo Library, as described here:
* http://stackoverflow.com/questions/1489250/uiimagewritetosavedphotosalbum-save-as-png-with-transparency
* and
* http://stackoverflow.com/questions/1379274/uiimagewritetosavedphotosalbum-saves-to-wrong-size-and-quality
*/
-(void) exportToImageOnComplete:(void(^)(UIImage*) )exportFinishBlock withScale:(CGFloat)outputScale{
CheckMainThread;
if(!exportFinishBlock) return;
if(![imageTextureLock tryLock]){
DebugLog(@"gotcha");
// save failed, just exit and our
// caller can retry later
exportFinishBlock(nil);
return;
}
// [JotGLContext pushCurrentContext:context];
//
// JotGLTexture* fullTexture = [self generateTexture];
// [fullTexture bind];
// CGSize usefulTextureSize = CGSizeMake(ceilf(initialViewport.width), ceilf(initialViewport.height));
// CGSize exportSize = CGSizeMake(ceilf(initialViewport.width / 2), ceilf(initialViewport.height / 2));
// [context flush];
// [fullTexture unbind];
// [JotGLContext popCurrentContext];
NSArray* strokesAtTimeOfExport = [state everyVisibleStroke];
//
// the rest can be done in Core Graphics in a background thread
dispatch_async([JotView importExportImageQueue], ^{
@autoreleasepool {
if(state.isForgetful){
DebugLog(@"forget: skipping export for forgetful jotview");
exportFinishBlock(nil);
[imageTextureLock unlock];
return;
}
JotGLContext* secondSubContext = [[JotGLContext alloc] initWithName:@"JotViewExportToImageContext" andAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:mainThreadContext.sharegroup andValidateThreadWith:^BOOL{
return [JotView isImportExportImageQueue];
}];
[secondSubContext runBlock:^{
// // finish current gl calls
// glFinish();
// Setup OpenGL states
[secondSubContext glMatrixModeProjection];
// Setup the view port in Pixels
[secondSubContext glMatrixModeModelView];
[secondSubContext glDisableDither];
[secondSubContext glEnableTextures];
[secondSubContext glEnableBlend];
// Set a blending function appropriate for premultiplied alpha pixel data
[secondSubContext prepOpenGLBlendModeForColor:[UIColor whiteColor]];
[context glEnablePointSprites];
GLSize fullSize = GLSizeFromCGSize(viewFramebuffer.initialViewport);
CGSize exportSize = CGSizeMake(ceilf(fullSize.width * outputScale), ceilf(fullSize.height * outputScale));;
// create the texture
// maxTextureSize
CGSize maxTextureSize = [UIScreen mainScreen].portraitBounds.size;
maxTextureSize.width *= [UIScreen mainScreen].scale;
maxTextureSize.height *= [UIScreen mainScreen].scale;
JotGLTexture* canvasTexture = [[JotTextureCache sharedManager] generateTextureForContext:secondSubContext ofSize:maxTextureSize];
JotGLTextureBackedFrameBuffer* exportFramebuffer = [[JotGLTextureBackedFrameBuffer alloc] initForTexture:canvasTexture forSize:fullSize];
// step 1:
// Clear the buffer
[exportFramebuffer clear];
// step 2:
// load a texture and draw it into a quad
// that fills the screen
[state.backgroundTexture drawInContext:secondSubContext];
// reset our viewport
[secondSubContext glViewportWithX:0 y:0 width:viewFramebuffer.initialViewport.width height:viewFramebuffer.initialViewport.height];
// we have to flush here to push all
// the pixels to the texture so they're
// available in the background thread's
// context
[secondSubContext flush];
// now render strokes
[exportFramebuffer bind];
[secondSubContext disableTextureCoordArray];
for(JotStroke* stroke in strokesAtTimeOfExport){
[stroke lock];
// make sure our texture is the correct one for this stroke
[stroke.texture bind];
// draw each stroke element
AbstractBezierPathElement* prevElement = nil;
for(AbstractBezierPathElement* element in stroke.segments){
[self renderElement:element fromPreviousElement:prevElement includeOpenGLPrepForFBO:nil toContext:secondSubContext];
prevElement = element;
}
[stroke.texture unbind];
[stroke unlock];
}
[exportFramebuffer unbind];
////////////////////////////////
// render to texture is done,
// now read its contents
//
[secondSubContext flush];
[canvasTexture bind];
[secondSubContext glOrthof:0 right:(GLsizei) fullSize.width bottom:0 top:(GLsizei) fullSize.height zNear:-1 zFar:1];
[secondSubContext glViewportWithX:0 y:0 width:(GLsizei) fullSize.width height:(GLsizei) fullSize.height];
[secondSubContext flush];
// step 3:
// read the image from OpenGL and push it into a data buffer
NSInteger dataLength = fullSize.width * fullSize.height * 4;
GLubyte *data = calloc(fullSize.height * fullSize.width, 4);
if(!data){
@throw [NSException exceptionWithName:@"Memory Exception" reason:@"can't malloc" userInfo:nil];
}
// Read pixel data from the framebuffer
[secondSubContext readPixelsInto:data ofSize:fullSize];
// now we're done, delete our buffers
[canvasTexture unbind];
[[JotTextureCache sharedManager] returnTextureForReuse:canvasTexture];
// Create a CGImage with the pixel data from OpenGL
// If your OpenGL ES content is opaque, use kCGImageAlphaNoneSkipLast to ignore the alpha channel
// otherwise, use kCGImageAlphaPremultipliedLast
CGDataProviderRef ref = CGDataProviderCreateWithData(NULL, data, dataLength, NULL);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGImageRef iref = CGImageCreate(fullSize.width, fullSize.height, 8, 32, fullSize.width * 4, colorspace, kCGBitmapByteOrderDefault |
kCGImageAlphaPremultipliedLast,
ref, NULL, true, kCGRenderingIntentDefault);
// ok, now we have the pixel data from the OpenGL frame buffer.
// next we need to setup the image context to composite the
// background color, background image, and opengl image
// OpenGL ES measures data in PIXELS
// Create a graphics context with the target size measured in POINTS
CGContextRef bitmapContext = CGBitmapContextCreate(NULL, exportSize.width, exportSize.height, 8, exportSize.width * 4, colorspace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast);
if(!bitmapContext){
@throw [NSException exceptionWithName:@"CGContext Exception" reason:@"can't create new context" userInfo:nil];
}
// can I clear less stuff and still be ok?
CGContextClearRect(bitmapContext, CGRectMake(0, 0, exportSize.width, exportSize.height));
if(!bitmapContext){
DebugLog(@"oh no1");
}
// flip vertical for our drawn content, since OpenGL is opposite core graphics
CGContextTranslateCTM(bitmapContext, 0, exportSize.height);
CGContextScaleCTM(bitmapContext, 1.0, -1.0);
//
// ok, now render our actual content
CGContextDrawImage(bitmapContext, CGRectMake(0.0, 0.0, exportSize.width, exportSize.height), iref);
// Retrieve the UIImage from the current context
CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
if(!cgImage){
@throw [NSException exceptionWithName:@"CGContext Exception" reason:@"can't create new context" userInfo:nil];
}
UIImage* image = [UIImage imageWithCGImage:cgImage scale:self.contentScaleFactor orientation:UIImageOrientationUp];
// Clean up
free(data);
CFRelease(ref);
CFRelease(colorspace);
CGImageRelease(iref);
CGContextRelease(bitmapContext);
// ok, we're done exporting and cleaning up
// so pass the newly generated image to the completion block
exportFinishBlock(image);
CGImageRelease(cgImage);
}];
[JotGLContext validateEmptyContextStack];
dispatch_async(dispatch_get_main_queue(), ^{
// can't do this sync()
// because the main thread + the importExportImageQueue
// could deadlock
[imageTextureLock unlock];
});
}
});
}
/**
* export an image from the openGL render buffer to a UIImage
* @param backgroundColor an optional background color for the image. pass nil for a transparent background.
* @param backgroundImage an optional image to use as the background behind this view's content
*
* code modified from http://developer.apple.com/library/ios/#qa/qa1704/_index.html
*
* If you plan to save the returned image to the photo library,
* then you can maintain transparency by reformatting as a PNG:
* [UIImage imageWithData:UIImagePNGRepresentation(imageReturnedByThisMethod)];
*
* If you don't reformat as a PNG, then you may lose transparency
* when saving/loading from the Photo Library, as described here:
* http://stackoverflow.com/questions/1489250/uiimagewritetosavedphotosalbum-save-as-png-with-transparency
* and
* http://stackoverflow.com/questions/1379274/uiimagewritetosavedphotosalbum-saves-to-wrong-size-and-quality
*/
-(void) exportInkTextureOnComplete:(void(^)(UIImage*) )exportFinishBlock{
CheckMainThread;
if(!state){
if(exportFinishBlock) exportFinishBlock(nil);
return;
}
if(!exportFinishBlock) return;
if(![inkTextureLock tryLock]){
DebugLog(@"gotcha");
// save failed, just exit and our
// caller can retry later
exportFinishBlock(nil);
return;
}
// the rest can be done in Core Graphics in a background thread
dispatch_async([JotView importExportImageQueue], ^{
@autoreleasepool {
if(state.isForgetful){
DebugLog(@"forget: skipping export for forgetful jotview");
exportFinishBlock(nil);
[inkTextureLock unlock];
return;
}
JotGLContext* secondSubContext = [[JotGLContext alloc] initWithName:@"JotViewExportInkTextureContext" andAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:mainThreadContext.sharegroup andValidateThreadWith:^BOOL{
return [JotView isImportExportImageQueue];
}];
[secondSubContext runBlock:^{
// finish current gl calls
// glFinish();
// Setup OpenGL states
[secondSubContext glMatrixModeProjection];
// Setup the view port in Pixels
[secondSubContext glMatrixModeModelView];
[secondSubContext glDisableDither];
[secondSubContext glEnableTextures];
[secondSubContext glEnableBlend];
// Set a blending function appropriate for premultiplied alpha pixel data
[secondSubContext prepOpenGLBlendModeForColor:[UIColor whiteColor]];
[context glEnablePointSprites];
CGSize initialViewport = viewFramebuffer.initialViewport;
[secondSubContext glOrthof:0 right:(GLsizei) initialViewport.width bottom:0 top:(GLsizei) initialViewport.height zNear:-1 zFar:1];
[secondSubContext glViewportWithX:0 y:0 width:(GLsizei) initialViewport.width height:(GLsizei) initialViewport.height];
GLSize fullSize = GLSizeFromCGSize(initialViewport);
CGSize exportSize = CGSizeMake(ceilf(initialViewport.width), ceilf(initialViewport.height));
// create the texture
// maxTextureSize
CGSize maxTextureSize = [UIScreen mainScreen].portraitBounds.size;
maxTextureSize.width *= [UIScreen mainScreen].scale;
maxTextureSize.height *= [UIScreen mainScreen].scale;
JotGLTexture* canvasTexture = [[JotTextureCache sharedManager] generateTextureForContext:secondSubContext ofSize:maxTextureSize];
JotGLTextureBackedFrameBuffer* exportFramebuffer = [[JotGLTextureBackedFrameBuffer alloc] initForTexture:canvasTexture forSize:fullSize];
// step 1:
// Clear the buffer
[exportFramebuffer bind];
[secondSubContext assertCheckFramebuffer];
[secondSubContext clear];
// step 2:
// load a texture and draw it into a quad
// that fills the screen
[state.backgroundTexture drawInContext:secondSubContext];
[exportFramebuffer unbind];
// reset our viewport
[secondSubContext glViewportWithX:0 y:0 width:initialViewport.width height:initialViewport.height];
// we have to flush here to push all
// the pixels to the texture so they're
// available in the background thread's
// context
[secondSubContext flush];
// now read its contents
[secondSubContext flush];
[canvasTexture bind];
[secondSubContext glViewportWithX:0 y:0 width:fullSize.width height:fullSize.height];
[secondSubContext flush];
// step 3:
// read the image from OpenGL and push it into a data buffer
NSInteger dataLength = fullSize.width * fullSize.height * 4;
GLubyte *data = calloc(fullSize.height * fullSize.width, 4);
if(!data){
@throw [NSException exceptionWithName:@"Memory Exception" reason:@"can't malloc" userInfo:nil];
}
// Read pixel data from the framebuffer
[secondSubContext readPixelsInto:data ofSize:fullSize];
// now we're done, delete our buffers
[canvasTexture unbind];
[[JotTextureCache sharedManager] returnTextureForReuse:canvasTexture];
// Create a CGImage with the pixel data from OpenGL
// If your OpenGL ES content is opaque, use kCGImageAlphaNoneSkipLast to ignore the alpha channel
// otherwise, use kCGImageAlphaPremultipliedLast
CGDataProviderRef ref = CGDataProviderCreateWithData(NULL, data, dataLength, NULL);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGImageRef iref = CGImageCreate(fullSize.width, fullSize.height, 8, 32, fullSize.width * 4, colorspace, kCGBitmapByteOrderDefault |
kCGImageAlphaPremultipliedLast,
ref, NULL, true, kCGRenderingIntentDefault);
// ok, now we have the pixel data from the OpenGL frame buffer.
// next we need to setup the image context to composite the
// background color, background image, and opengl image
// OpenGL ES measures data in PIXELS
// Create a graphics context with the target size measured in POINTS
CGContextRef bitmapContext = CGBitmapContextCreate(NULL, exportSize.width, exportSize.height, 8, exportSize.width * 4, colorspace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast);
if(!bitmapContext){
@throw [NSException exceptionWithName:@"CGContext Exception" reason:@"can't create new context" userInfo:nil];
}
// can I clear less stuff and still be ok?
CGContextClearRect(bitmapContext, CGRectMake(0, 0, exportSize.width, exportSize.height));
if(!bitmapContext){
DebugLog(@"oh no1");
}
// flip vertical for our drawn content, since OpenGL is opposite core graphics
CGContextTranslateCTM(bitmapContext, 0, exportSize.height);
CGContextScaleCTM(bitmapContext, 1.0, -1.0);
//
// ok, now render our actual content
CGContextDrawImage(bitmapContext, CGRectMake(0.0, 0.0, exportSize.width, exportSize.height), iref);
// Retrieve the UIImage from the current context
CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
if(!cgImage){
@throw [NSException exceptionWithName:@"CGContext Exception" reason:@"can't create new context" userInfo:nil];
}
UIImage* image = [UIImage imageWithCGImage:cgImage scale:self.contentScaleFactor orientation:UIImageOrientationUp];
// Clean up
free(data);
CFRelease(ref);
CFRelease(colorspace);
CGImageRelease(iref);
CGContextRelease(bitmapContext);
// ok, we're done exporting and cleaning up
// so pass the newly generated image to the completion block
exportFinishBlock(image);
CGImageRelease(cgImage);
}];
[JotGLContext validateEmptyContextStack];
dispatch_async(dispatch_get_main_queue(), ^{
// can't do this sync()
// because the main thread + the importExportImageQueue
// could deadlock
[inkTextureLock unlock];
});
}
});
}
#pragma mark - Rendering
/**
* this method will re-render all of the strokes that
* we have in our undo-able buffer.
*
* this can be used if a user cancells a stroke or undos
* a stroke. it will clear the screen and re-draw all
* strokes except for that undone/cancelled stroke
*/
-(void) renderAllStrokesToContext:(JotGLContext*)renderContext inFramebuffer:(AbstractJotGLFrameBuffer*)theFramebuffer andPresentBuffer:(BOOL)shouldPresent inRect:(CGRect)scissorRect{
@autoreleasepool {
CheckMainThread;
if(!state) return;
// set our current OpenGL context
[renderContext runBlock:^{
[theFramebuffer bind];
//
// step 1:
// Clear the buffer
[renderContext clear];
//
// step 2:
// load a texture and draw it into a quad
// that fills the screen
[state.backgroundTexture drawInContext:renderContext];
if(!state.backgroundTexture){
DebugLog(@"what5");