File: NSPrintOperation.m

package info (click to toggle)
gnustep-gui 0.25.0-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 13,088 kB
  • ctags: 3,417
  • sloc: objc: 153,800; ansic: 18,239; cpp: 579; yacc: 462; makefile: 143; sh: 5
file content (1234 lines) | stat: -rw-r--r-- 36,674 bytes parent folder | download | duplicates (7)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
/* 
   NSPrintOperation.m

   Controls operations generating print jobs.

   Copyright (C) 1996,2004 Free Software Foundation, Inc.

   Author:  Scott Christley <scottc@net-community.com>
   Date: 1996
   Author: Fred Kiefer <FredKiefer@gmx.de>
   Date: November 2000
   Started implementation.
   Modified for Printing Backend Support
   Author: Chad Hardin <cehardin@mac.com>
   Date: June 2004

   This file is part of the GNUstep GUI Library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; see the file COPYING.LIB.
   If not, see <http://www.gnu.org/licenses/> or write to the 
   Free Software Foundation, 51 Franklin Street, Fifth Floor, 
   Boston, MA 02110-1301, USA.
*/ 

#include <limits.h>
#include <math.h>
#include "config.h"
#import <Foundation/NSString.h>
#import <Foundation/NSDebug.h>
#import <Foundation/NSData.h>
#import <Foundation/NSFileManager.h>
#import <Foundation/NSException.h>
#import <Foundation/NSPathUtilities.h>
#import <Foundation/NSTask.h>
#import <Foundation/NSThread.h>
#import <Foundation/NSUserDefaults.h>
#import <Foundation/NSValue.h>
#import "AppKit/AppKitExceptions.h"
#import "AppKit/NSAffineTransform.h"
#import "AppKit/NSApplication.h"
#import "AppKit/NSGraphicsContext.h"
#import "AppKit/NSView.h"
#import "AppKit/NSPrinter.h"
#import "AppKit/NSPrintPanel.h"
#import "AppKit/NSPrintInfo.h"
#import "AppKit/NSPrintOperation.h"
#import "AppKit/NSWorkspace.h"
#import "AppKit/PSOperators.h"
#import "GNUstepGUI/GSEPSPrintOperation.h"
#import "GNUstepGUI/GSPDFPrintOperation.h"
#import "GNUstepGUI/GSPrintOperation.h"
#import "GSGuiPrivate.h"

#define NSNUMBER(a) [NSNumber numberWithInt: (a)]
#define NSFNUMBER(a) [NSNumber numberWithDouble: (a)]

/*
 * When a view gets printed it may need to be split up into segments, if the 
 * views printed rectangle (after scaling) is bigger than the used area on the page.
 * In this case we set xpages and ypages to the number of segments needed per 
 * dimension. This pre-calculated value may not be accurate, as the view may 
 * adjust the rect for each printed page.
 * An independent concept is that multuple pages may be put on one sheet of paper.
 * This is taken care of by nup and nupScale. Here we currently only allow even 
 * values (or 1, when we don't use multiple pages). If we ever change this be 
 * sure to change [NSView beginPageInRect:atPlacement:], perhaps by moving that 
 * code to here?
 * We always end up printing two rows per page, this is fine for 2, 4, 6, 8 and 10, 
 * but starting from there it would be better to use three or four rows.
 */
/* Local pagination variables needed while printing */
typedef struct _page_info_t {
  NSRect scaledBounds;       /* View's rect scaled by the user specified scale
                                and page fitting */
  NSRect paperBounds;        /* Print area of a page in default user space, possibly
                                rotated if printing Landscape */
  NSRect sheetBounds;        /* Print area of a sheet in default user space */
  NSSize paperSize;          /* Size of the paper */
  int xpages, ypages;        /* number of page segments for the view in both dimensions */
  int first, last;           /* first and last page to print */
  double pageScale;          /* Scaling determined from page fitting */
  double printScale;         /* User specified scaling */
  double nupScale;           /* Scale required to fit nup pages on the sheet */
  int    nup;                /* Number of pages to print on a sheet */
  double lastWidth, lastHeight; /* max. values of last printed page (scaled) */
  NSPrintingOrientation orient;
  int    pageDirection;      /* NSPrintPageDirection */
} page_info_t;


@interface NSPrintOperation (TrulyPrivate)
- (BOOL) _runOperation;
- (void) _setupPrintInfo;
- (void)_printOperationDidRun:(NSPrintOperation *)printOperation 
                   returnCode:(int)returnCode
                  contextInfo:(void *)contextInfo;
- (void) _printPaginateWithInfo: (page_info_t *)info 
                     knowsRange: (BOOL)knowsRange;
- (NSRect) _rectForPage: (int)page info: (page_info_t *)info 
                  xpage: (int *)xptr
                  ypage: (int *)yptr;
- (NSRect) _adjustPagesFirst: (int)first 
                        last: (int)last
                        info: (page_info_t *)info;
- (void) _print;
@end






@interface NSView (NSPrintOperation)
- (void) _displayPageInRect: (NSRect)pageRect
                   withInfo: (page_info_t)info
	     knowsPageRange: (BOOL)knowsPageRange;
@end

@interface NSView (NPrintOperationPrivate)
- (void) _endSheet;
- (void) _cleanupPrinting;
@end



static NSString *NSPrintOperationThreadKey = @"NSPrintOperationThreadKey";

/**
  <unit>
  <heading>Class Description</heading>
  <p>
  NSPrintOperation controls printing of an NSView. When invoked normally
  it will (optionally) display a standard print panel (NSPrintPanel), and
  based on the information entered by the user here as well as information
  about page layout (see NSPageLayout) tells the NSView to print it's 
  contents. NSPrintOperation works with the NSView to paginate the output
  into appropriately sized and oriented pages and finally delivers the result
  to the appropriate place, whether it be a printer, and PostScript file,
  or another output.
  </p>
  </unit>
*/ 
@implementation NSPrintOperation

//
// Class methods
//
+ (void)initialize
{
  if (self == [NSPrintOperation class])
    {
      // Initial version
      [self setVersion:1];
    }
}

//
// Creating and Initializing an NSPrintOperation Object
//
+ (NSPrintOperation *)EPSOperationWithView:(NSView *)aView
                                insideRect:(NSRect)rect
                                    toData:(NSMutableData *)data
{
  return [self EPSOperationWithView: aView        
               insideRect: rect
               toData: data
               printInfo: nil];
}

+ (NSPrintOperation *)EPSOperationWithView:(NSView *)aView        
                                insideRect:(NSRect)rect
                                    toData:(NSMutableData *)data
                                 printInfo:(NSPrintInfo *)aPrintInfo
{
  return AUTORELEASE([[GSEPSPrintOperation alloc] initWithView: aView
                                                  insideRect: rect
                                                  toData: data
                                                  printInfo: aPrintInfo]);
}

+ (NSPrintOperation *)EPSOperationWithView:(NSView *)aView        
                                insideRect:(NSRect)rect
                                    toPath:(NSString *)path
                                 printInfo:(NSPrintInfo *)aPrintInfo
{
  return AUTORELEASE([[GSEPSPrintOperation alloc] initWithView: aView        
                                                  insideRect: rect
                                                  toPath: path
                                                  printInfo: aPrintInfo]);
}

+ (NSPrintOperation *)printOperationWithView:(NSView *)aView
{
  return [self printOperationWithView: aView
               printInfo: nil];
}

+ (NSPrintOperation *)printOperationWithView:(NSView *)aView
                                   printInfo:(NSPrintInfo *)aPrintInfo
{
  return AUTORELEASE([[GSPrintOperation alloc] initWithView: aView
                                               printInfo: aPrintInfo]);
}

+ (NSPrintOperation *)PDFOperationWithView:(NSView *)aView 
                                insideRect:(NSRect)rect 
                                    toData:(NSMutableData *)data
{
  return [self PDFOperationWithView: aView 
               insideRect: rect 
               toData: data 
               printInfo: nil];
}

+ (NSPrintOperation *)PDFOperationWithView:(NSView *)aView 
                                insideRect:(NSRect)rect 
                                    toData:(NSMutableData *)data 
                                 printInfo:(NSPrintInfo*)aPrintInfo
{
  return AUTORELEASE([[GSPDFPrintOperation alloc] 
                         initWithView: aView 
                         insideRect: rect 
                         toData: data 
                         printInfo: aPrintInfo]);
}

+ (NSPrintOperation *)PDFOperationWithView:(NSView *)aView 
                                insideRect:(NSRect)rect 
                                    toPath:(NSString *)path 
                                 printInfo:(NSPrintInfo*)aPrintInfo
{
  return AUTORELEASE([[GSPDFPrintOperation alloc] 
                         initWithView: aView 
                         insideRect: rect 
                         toPath: path 
                         printInfo: aPrintInfo]);
}

//
// Setting the Print Operation
//
/** Returns the NSPrintOperation object that is currently performing
    a print operation (if any).
*/
+ (NSPrintOperation *)currentOperation
{
  NSMutableDictionary *dict = [[NSThread currentThread] threadDictionary];

  return (NSPrintOperation*)[dict objectForKey: NSPrintOperationThreadKey];
}

/** Set the current NSPrintOperation to the supplied operation
    object. As this is currently implemented, if a NSPrintOperation
    is currently running, that operation is lost (along with any
    associated context), so be careful to call this only when there is
    no current operation.
*/
+ (void)setCurrentOperation:(NSPrintOperation *)operation
{
  NSMutableDictionary *dict = [[NSThread currentThread] threadDictionary];

  if (operation == nil)
    [dict removeObjectForKey: NSPrintOperationThreadKey];
  else
    [dict setObject: operation forKey: NSPrintOperationThreadKey];
}

//
// Instance methods
//
//
// Creating and Initializing an NSPrintOperation Object
//

- (id)initEPSOperationWithView:(NSView *)aView
                    insideRect:(NSRect)rect
                        toData:(NSMutableData *)data
                     printInfo:(NSPrintInfo *)aPrintInfo
{
  RELEASE(self);
  
  return [[GSEPSPrintOperation alloc] initWithView: aView        
                                      insideRect: rect
                                      toData: data
                                      printInfo: aPrintInfo];
}

- (id)initWithView:(NSView *)aView
         printInfo:(NSPrintInfo *)aPrintInfo
{
  RELEASE(self);
  
  return [[GSPrintOperation alloc] initWithView: aView
                                   printInfo: aPrintInfo];
}

- (void) dealloc
{
  RELEASE(_print_info);
  RELEASE(_view);  
  RELEASE(_data);
  TEST_RELEASE(_context);
  TEST_RELEASE(_print_panel);  
  TEST_RELEASE(_accessory_view);  
  TEST_RELEASE(_path);  
  TEST_RELEASE(_job_style_hint);  

  [super dealloc];
}

//
// Determining the Type of Operation
//
/** Returns YES if the receiver is performing an operation whose output
    is EPS format.
*/
- (BOOL)isEPSOperation
{
  return NO;
}

- (BOOL)isCopyingOperation
{
  return NO;
}

//
// Controlling the User Interface
//
/** Returns the NSPrintPanel associated with the receiver.
 */
- (NSPrintPanel *)printPanel
{
  if (_print_panel == nil)
    ASSIGN(_print_panel, [NSPrintPanel printPanel]); 

  return _print_panel;
}

/** Returns YES if the reciever display an NSPrintPanel and other information
    when running a print operation. */
- (BOOL)showPanels
{
  return [self showsPrintPanel] && [self showsProgressPanel];
}

/** Sets the NSPrintPanel used by the receiver obtaining and displaying
    printing information from/to the user.
*/
- (void)setPrintPanel:(NSPrintPanel *)panel
{
  ASSIGN(_print_panel, panel);
}

/** Use this to set whether a print panel is displayed during a printing
    operation. If set to NO, then the receiver uses information that
    was previously set and does not display any status information about the
    progress of the printing operation.
*/
- (void)setShowPanels:(BOOL)flag
{
  [self setShowsPrintPanel: flag];
  [self setShowsProgressPanel: flag];
}

- (BOOL)showsPrintPanel
{
  return _flags.show_print_panel;
}

- (void)setShowsPrintPanel:(BOOL)flag
{
  _flags.show_print_panel = flag;
}

- (BOOL)showsProgressPanel
{
  return _flags.show_progress_panel;
}

- (void)setShowsProgressPanel:(BOOL)flag
{
  _flags.show_progress_panel = flag;
}


/** Returns the accessory view used by the NSPrintPanel associated with
    the receiver.
*/
- (NSView *)accessoryView
{
  return _accessory_view;
}

/** Set the accessory view used by the NSPrintPanel associated with the
    receiver.
*/
- (void)setAccessoryView:(NSView *)aView
{
  ASSIGN(_accessory_view, aView);
}

//
// Managing the drawing Context
//
/** This method is used by the print operation to create a special
   graphics context for use while running the print operation.
*/
- (NSGraphicsContext*)createContext
{
  [self subclassResponsibility: _cmd];
  return nil;
}

/** Returns the graphic contexts used by the print operation.
*/
- (NSGraphicsContext *)context
{
  return _context;
}

/** This method is used by the print operation to destroy the special
    graphic context used while running the print operation.
*/
- (void)destroyContext
{
  DESTROY(_context);
}

//
// Page Information
//
/** Returns the page currently being printing. Returns 0 if no page
    is currently being printed
*/
- (int)currentPage
{
  return _currentPage;
}

/** Returns the page order of printing.
*/
- (NSPrintingPageOrder)pageOrder
{
  return _page_order;
}

/** Set the page order used when printing.
 */
- (void)setPageOrder:(NSPrintingPageOrder)order
{
  _page_order = order;
}

//
// Running a Print Operation
//
/** Called by the print operation after it has finished running a printing
    operation.
*/
- (void)cleanUpOperation
{
  [[self printPanel] orderOut: self];
  _currentPage = 0;
  [NSPrintOperation setCurrentOperation: nil];
}

/** Called by the print operation to deliver the results of the printing
    operation. This might include sending the output to a printer, a file
    or a previewing program. Returns YES if the output was delivered 
    sucessfully.
*/
- (BOOL)deliverResult
{
  return NO;
}


/** Call this message to run the print operation on a view. This includes
    (optionally) displaying a print panel and working with the NSView to
    paginate and draw the contents of the view.
*/
- (BOOL)runOperation
{
  BOOL result;

  if ([self showsPrintPanel])
    {
      NSPrintPanel *panel = [self printPanel];
      int button;
      
      [panel setAccessoryView: _accessory_view];
      [self _setupPrintInfo];
      button = [panel runModalWithPrintInfo: _print_info];
      [panel setAccessoryView: nil];

      if (button != NSOKButton)
        {
          [self cleanUpOperation];
          return NO;
        }
    }

  result = NO;
  if ([self _runOperation])
    result = [self deliverResult];
  [self cleanUpOperation];

  return result;
}



/** Run a print operation modally with respect to a window.
 */
- (void)runOperationModalForWindow: (NSWindow *)docWindow 
                          delegate: (id)delegate 
                    didRunSelector: (SEL)didRunSelector 
                       contextInfo:(void *)contextInfo
{
  NSMutableDictionary *dict;
  NSPrintPanel *panel = [self printPanel];

  if (delegate != nil && didRunSelector != NULL)
    {
      /* Save the selector so we can use it later */
      dict = [_print_info dictionary];
      [dict setObject: [NSValue value: &didRunSelector withObjCType: @encode(SEL)]
               forKey: @"GSModalRunSelector"];
      [dict setObject: delegate
               forKey: @"GSModalRunDelegate"];
    }

  /* Assume we want to show the panel regardless of the value
     of _showPanels 
  */
  [panel setAccessoryView: _accessory_view];
  [self _setupPrintInfo];
  [panel beginSheetWithPrintInfo: _print_info 
                  modalForWindow: docWindow 
                        delegate: self 
                  didEndSelector: 
                          @selector(_printOperationDidRun:returnCode:contextInfo:)
                      contextInfo: contextInfo];
  [panel setAccessoryView: nil];
}

- (BOOL)canSpawnSeparateThread
{
  return _flags.can_spawn_separate_thread;
}

- (void)setCanSpawnSeparateThread:(BOOL)flag
{
  _flags.can_spawn_separate_thread = flag;
}

- (NSString *) jobStyleHint
{
  return _job_style_hint;
}

- (void)setJobStyleHint:(NSString *)hint
{
  ASSIGN(_job_style_hint, hint);
}

//
// Getting the NSPrintInfo Object
//
/** Returns the NSPrintInfo object associated with the receiver.
*/
- (NSPrintInfo *)printInfo
{
  return _print_info;
}

/** Set the NSPrintInfo object associated with the receiver.
 */
- (void)setPrintInfo:(NSPrintInfo *)aPrintInfo
{
  if (aPrintInfo == nil)
    aPrintInfo = [NSPrintInfo sharedPrintInfo];

  ASSIGNCOPY(_print_info, aPrintInfo);
}

//
// Getting the NSView Object
//
/** Return the view that is the being printed.
*/
- (NSView *)view
{
  return _view;
}

@end


@implementation NSPrintOperation (Private)

- (id) initWithView:(NSView *)aView
         insideRect:(NSRect)rect
             toData:(NSMutableData *)data
          printInfo:(NSPrintInfo *)aPrintInfo
{
  if ([NSPrintOperation currentOperation] != nil)
    {
      [NSException raise: NSPrintOperationExistsException
                   format: @"There is already a printoperation for this thread"];
    }

  ASSIGN(_view, aView);
  _rect = rect;
  ASSIGN(_data, data);
  _page_order = NSUnknownPageOrder;
  [self setShowsPrintPanel: NO];
  [self setShowsProgressPanel: NO];
  [self setPrintInfo: aPrintInfo];
  _path = nil;
  _currentPage = 0;

  [NSPrintOperation setCurrentOperation: self];
  return self;
}
@end

@implementation NSPrintOperation (TrulyPrivate)


/* Private method to run the printing operation. Needs to create an
   autoreleaes pool to make sure the print context is destroyed before
   returning (which closes the print file.) */
- (BOOL) _runOperation
{
  BOOL result;
  CREATE_AUTORELEASE_POOL(pool);
  NSGraphicsContext *oldContext = [NSGraphicsContext currentContext];

  [self createContext];
  if (_context == nil)
    return NO;

  result = NO;
  if (_page_order == NSUnknownPageOrder)
    {
      if ([[[_print_info dictionary] objectForKey: NSPrintReversePageOrder] 
            boolValue] == YES)
        _page_order = NSDescendingPageOrder;
      else
        _page_order = NSAscendingPageOrder;
    }

  [NSGraphicsContext setCurrentContext: _context];
  NS_DURING
    {
      [self _print];
      result = YES;
      [NSGraphicsContext setCurrentContext: oldContext];
    }
  NS_HANDLER
    {
      [_view _cleanupPrinting];
      [NSGraphicsContext setCurrentContext: oldContext];
      NSRunAlertPanel(_(@"Error"), _(@"Printing error: %@"), 
                      _(@"OK"), NULL, NULL, localException);
    }
  NS_ENDHANDLER
  [self destroyContext];
  RELEASE(pool);
  return result;
}

- (void) _setupPrintInfo
{
  BOOL knowsPageRange;
  NSRange viewPageRange = NSMakeRange(1, 0);
  NSMutableDictionary *dict = [_print_info dictionary];

  knowsPageRange = [_view knowsPageRange: &viewPageRange]; 
  if (knowsPageRange == YES)
    {
      int first = viewPageRange.location;
      int last = NSMaxRange(viewPageRange) - 1;
      [dict setObject: NSNUMBER(first) forKey: NSPrintFirstPage];
      [dict setObject: NSNUMBER(last) forKey: NSPrintLastPage];
    }
}

- (void)_printOperationDidRun:(NSPrintOperation *)printOperation 
                   returnCode:(int)returnCode  
                  contextInfo:(void *)contextInfo
{
  id delegate;
  SEL didRunSelector;
  BOOL success = NO;
  NSMutableDictionary *dict;
  void (*didRun)(id, SEL, BOOL, id);

  if (returnCode == NSOKButton)
    {
      if ([self _runOperation])
        success = [self deliverResult];
    }
  [self cleanUpOperation];
  dict = [_print_info dictionary];
  [[dict objectForKey: @"GSModalRunSelector"] getValue: &didRunSelector];
  delegate = [dict objectForKey: @"GSModalRunDelegate"];
  if (delegate != nil && didRunSelector != NULL)
    {
      didRun = (void (*)(id, SEL, BOOL, id))[delegate methodForSelector: 
                                                          didRunSelector];
      didRun (delegate, didRunSelector, success, contextInfo);
    }
}




/*
static NSSize
scaleSize(NSSize size, double scale)
{
  size.height *= scale;
  size.width  *= scale;
  return size;
}
*/

static NSRect
scaleRect(NSRect rect, double scale)
{
  return NSMakeRect(NSMinX(rect) * scale,
                    NSMinY(rect) * scale,
                    NSWidth(rect) * scale,
                    NSHeight(rect) * scale);
}

/* 
 * Pagination - guess how many pages we need to print. This could be off
 * in both X and Y because of the view's ability to adjust the width and 
 * height of the printRect during printing. 
 * Also set up a bunch of other information needed for printing.
 */
- (void) _printPaginateWithInfo: (page_info_t *)info knowsRange: (BOOL)knowsRange
{
  NSMutableDictionary *dict;
  NSNumber *value;

  dict = [_print_info dictionary];
  info->paperSize = [_print_info paperSize];
  info->orient = [_print_info orientation];
  value = [dict objectForKey: NSPrintScalingFactor];
  if (value != nil)
    info->printScale = [value doubleValue];
  else
    info->printScale = 1.0;

  info->nup = [[dict objectForKey: NSPrintPagesPerSheet] intValue];
  info->nupScale = 1;
  if (info->nup < 1 || (info->nup > 1 && (((info->nup) & 0x1) == 1)))
    {
      /* Bad nup value */
      info->nup = 1;
      [dict setObject: NSNUMBER(1) forKey: NSPrintPagesPerSheet];
    }

  /* Subtract the margins from the paper size to get print boundary */
  info->paperBounds.size = info->paperSize;
  info->paperBounds.origin.x = [_print_info leftMargin];
  info->paperBounds.origin.y = [_print_info bottomMargin];
  info->paperBounds.size.width -= 
    ([_print_info rightMargin]+[_print_info leftMargin]);
  info->paperBounds.size.height -= 
    ([_print_info topMargin]+[_print_info bottomMargin]);

  if (info->orient == NSLandscapeOrientation)
    {
      /* Bounding box needs to be in default user space, but the bbox
         we get is rotated */
      info->sheetBounds = NSMakeRect(NSMinY(info->paperBounds), 
                                     NSMinX(info->paperBounds), 
                                     NSHeight(info->paperBounds), 
                                     NSWidth(info->paperBounds));
    }
  else
    {
      info->sheetBounds = info->paperBounds;
    }

  /* Save this for the view to look at */
  [dict setObject: [NSValue valueWithRect: info->paperBounds]
            forKey: @"NSPrintPaperBounds"];
  [dict setObject: [NSValue valueWithRect: info->sheetBounds]
            forKey: @"NSPrintSheetBounds"];

   /* Scale bounds by the user specified scaling */
  info->scaledBounds = scaleRect(_rect, info->printScale);
  info->pageScale = 1; // default

  if (knowsRange == NO)
    {
      /* Now calculate page fitting to get page scale */
      if ([_print_info horizontalPagination] == NSFitPagination)
        info->pageScale  = info->paperBounds.size.width 
          / NSWidth(info->scaledBounds);
      if ([_print_info verticalPagination] == NSFitPagination)
        info->pageScale = MIN(info->pageScale,
          NSHeight(info->paperBounds)/NSHeight(info->scaledBounds));
      /* Scale bounds by pageScale */
      info->scaledBounds = scaleRect(info->scaledBounds, info->pageScale);

      /* Now find out how many pages */
      info->xpages = ceil(NSWidth(info->scaledBounds)/NSWidth(info->paperBounds));
      info->ypages = ceil(NSHeight(info->scaledBounds)/NSHeight(info->paperBounds));
      if ([_print_info horizontalPagination] == NSClipPagination)
        info->xpages = 1;
      if ([_print_info verticalPagination] == NSClipPagination)
        info->ypages = 1;
    }

  /*
   * Calculate nup. If nup is an odd multiple of two, secretly change the
   * page orientation to it's complement to make pages fit better.
   */
  if (((int)(info->nup / 2) & 0x1) == 1)
    {
      CGFloat tmp;
      if (info->orient == NSLandscapeOrientation)
        info->nupScale = 
          info->paperSize.width/(2*info->paperSize.height);
      else
        info->nupScale = 
          info->paperSize.height/(2*info->paperSize.width);
      info->nupScale /= (info->nup / 2);
      info->orient = (info->orient == NSPortraitOrientation) ? 
        NSLandscapeOrientation : NSPortraitOrientation;
      tmp = info->paperSize.width;
      info->paperSize.width = info->paperSize.height;
      info->paperSize.height = tmp;
      [dict setObject: NSNUMBER(info->orient) forKey: NSPrintOrientation];
    }
  else if (info->nup > 1)
    {
      info->nupScale = 2.0 / (CGFloat)info->nup;
    }

  if ([[dict objectForKey: NSPrintPageDirection] isEqual: @"Columns"])
    info->pageDirection = 1;
  else
    info->pageDirection = 0;
}

/* Our personnel method to calculate the print rect for the specified page.
   Note, we assume this function is called in order from our first to last
   page. The returned pageRect is in the view's coordinate system
*/
- (NSRect) _rectForPage: (int)page info: (page_info_t *)info 
                  xpage: (int *)xptr
                  ypage: (int *)yptr
{
  int xpage, ypage;
  NSRect pageRect;

  if (info->pageDirection == 1)
    {
      xpage = (page - 1) / info->ypages;
      ypage = (page - 1) % info->ypages;
    }
  else
    {
      xpage = (page - 1) % info->xpages;
      ypage = (page - 1) / info->xpages;
    }
  *xptr = xpage;
  *yptr = ypage;
  if (xpage == 0)
    info->lastWidth = 0;
  if (ypage == 0)
    info->lastHeight = 0;
  pageRect = NSMakeRect(info->lastWidth, info->lastHeight,
                        NSWidth(info->paperBounds), NSHeight(info->paperBounds));
  pageRect = NSIntersectionRect(pageRect, info->scaledBounds);
  /* Scale to view's coordinate system */
  return scaleRect(pageRect, 1/(info->pageScale*info->printScale));
  
}

/* Let the view adjust the page rect we calculated. See assumptions for
   _rectForPage:
*/
- (NSRect) _adjustPagesFirst: (int)first 
                        last: (int)last 
                        info: (page_info_t *)info
{
  int i, xpage, ypage;
  double hlimit, wlimit;
  NSRect pageRect = NSZeroRect; /* Silence compiler warning.  */
  hlimit = [_view heightAdjustLimit];
  wlimit = [_view widthAdjustLimit];
  for (i = first; i <= last; i++)
    {
      CGFloat newVal, limitVal;
      pageRect = [self _rectForPage: i info: info xpage: &xpage ypage: &ypage];
      limitVal = NSMaxY(pageRect) - hlimit * NSHeight(pageRect);
      [_view adjustPageHeightNew: &newVal
                             top: NSMinY(pageRect)
                          bottom: NSMaxY(pageRect)
                           limit: limitVal];
      if (newVal < NSMaxY(pageRect))
        pageRect.size.height = MAX(newVal, limitVal) - NSMinY(pageRect);
      limitVal = NSMaxX(pageRect) - wlimit * NSWidth(pageRect);
      [_view adjustPageWidthNew: &newVal
                           left: NSMinX(pageRect)
                          right: NSMaxX(pageRect)
                           limit: limitVal];
      if (newVal < NSMaxX(pageRect))
        pageRect.size.width = MAX(newVal, limitVal) - NSMinX(pageRect);
      if (info->pageDirection == 0 || ypage == info->ypages - 1)
        info->lastWidth = NSMaxX(pageRect)*(info->pageScale*info->printScale);
      if (info->pageDirection == 1 || xpage == info->xpages - 1)
        info->lastHeight = NSMaxY(pageRect)*(info->pageScale*info->printScale);
    }
  return pageRect;
}

- (void) _print
{
  int i, dir;
  BOOL knowsPageRange, allPages;
  NSRange viewPageRange = NSMakeRange(1, 0);
  NSMutableDictionary *dict;
  NSNumber *value;
  page_info_t info;
  
  dict = [_print_info dictionary];

  /* Setup pagination */
  knowsPageRange = [_view knowsPageRange: &viewPageRange]; 
  [self _printPaginateWithInfo: &info knowsRange: knowsPageRange];
  if (knowsPageRange == NO)
    {
      viewPageRange = NSMakeRange(1, (info.xpages * info.ypages));
    }
  else
    {
      // These values never get used
      info.xpages = 1;
      info.ypages = viewPageRange.length;
    }

  [dict setObject: NSNUMBER(NSMaxRange(viewPageRange))
           forKey: @"NSPrintTotalPages"];
  value = [dict objectForKey: NSPrintAllPages];
  if (value != nil)
    allPages = [value boolValue];
  else
    allPages = YES;
  if (allPages == YES)
    {
      info.first = viewPageRange.location;
      info.last = NSMaxRange(viewPageRange) - 1;
    }
  else
    {
      value = [dict objectForKey: NSPrintFirstPage];
      if (value != nil)
	info.first = [value intValue];
      else 
	info.first = 1;

      value = [dict objectForKey: NSPrintLastPage];
      if (value != nil)
	info.last  = [value intValue];
      else
	info.last  = INT_MAX;

      info.first = MAX(info.first, (int)viewPageRange.location);
      info.first = MIN(info.first, (int)(NSMaxRange(viewPageRange) - 1));
      info.last = MAX(info.last, info.first);
      info.last = MIN(info.last, (int)(NSMaxRange(viewPageRange) - 1));
      viewPageRange = NSMakeRange(info.first, (info.last-info.first)+1);
    }
  [dict setObject: NSFNUMBER(info.nupScale) forKey: @"NSNupScale"];
  [dict setObject: NSNUMBER(info.first) forKey: NSPrintFirstPage];
  if (allPages == YES && knowsPageRange == NO)
    [dict setObject: NSNUMBER(info.first-1) forKey: NSPrintLastPage];
  else
    [dict setObject: NSNUMBER(info.last) forKey: NSPrintLastPage];
  NSDebugLLog(@"NSPrinting", @"Printing pages %d to %d", 
              info.first, info.last);
  NSDebugLLog(@"NSPrinting", @"Printing rect %@, scaled %@",
              NSStringFromRect(_rect),
              NSStringFromRect(info.scaledBounds));

  if (_page_order == NSDescendingPageOrder)
    {
      _currentPage = info.last;
      dir = -1;
    }
  else
    {
      _currentPage = info.first;
      dir = 1;
    }

  /*
   * FIXME: Independent of the page order we could pre-calculate the
   * pageRects for all pages up to last (including clipping adjustment) 
   * and use them when printing. 
   */
  info.lastWidth = info.lastHeight = 0;
  if (!knowsPageRange && dir > 0 && _currentPage != 1)
    {
      /* Calculate page rects we aren't processing to catch up to the
         first page we are */
      [self _adjustPagesFirst: 1
                         last: _currentPage - 1 
                         info: &info];
    }

  /* Print the header information */
  [_view beginDocument];

  /* Print each page */
  i = 0;
  while (i < (info.last - info.first + 1))
    {
      NSRect pageRect;

      if (knowsPageRange == YES)
        {
          pageRect = [_view rectForPage: _currentPage];
        }
      else
        {
          if (dir < 0)
            pageRect = [self _adjustPagesFirst: 1 
                                          last: _currentPage 
                                          info: &info];
          else
            pageRect = [self _adjustPagesFirst: _currentPage 
                                          last: _currentPage 
                                          info: &info];
        }

      NSDebugLLog(@"NSPrinting", @" current page %d, rect %@", 
                  _currentPage, NSStringFromRect(pageRect));
      if (NSIsEmptyRect(pageRect))
        break;

      /* Draw using our special view routine */
      [_view _displayPageInRect: pageRect
	     withInfo: info
	     knowsPageRange: knowsPageRange];
             
      // We could end up in this case for each row/column not just the lase page.
      if (!knowsPageRange && dir > 0 && _currentPage == info.last && allPages == YES)
        {
          /* Check if adjust pages forced part of the bounds onto 
             another page */
          if (NSMaxX(pageRect) < NSMaxX(_rect) 
              && [_print_info horizontalPagination] != NSClipPagination)
            {
              info.xpages++;
            }
          if (NSMaxY(pageRect) < NSMaxY(_rect)
              && [_print_info verticalPagination] != NSClipPagination)
            {
              info.ypages++;
            }
          viewPageRange = NSMakeRange(1, (info.xpages * info.ypages));
          info.last = NSMaxRange(viewPageRange) - 1;
        }
      i++;
      _currentPage += dir;
    } /* Print each page */
  
  /* Make sure we end the sheet */
  if (info.nup > 1 && (info.last - info.first) % info.nup != info.nup - 1)
    {
      [_view drawSheetBorderWithSize: info.sheetBounds.size];
      [_view _endSheet];
      DPSgrestore([self context]);
    }
  [_view endDocument];

  /* Setup/reset for next time */
  [dict setObject: NSNUMBER(info.last) forKey: NSPrintLastPage];
  if (((int)(info.nup / 2) & 0x1) == 1)
    {
      info.orient = (info.orient == NSPortraitOrientation) ? 
        NSLandscapeOrientation : NSPortraitOrientation;
      [dict setObject: NSNUMBER(info.orient) forKey: NSPrintOrientation];
    }
}

@end

@implementation NSView (NSPrintOperation)

- (void) _displayPageInRect: (NSRect)pageRect
                   withInfo: (page_info_t)info
	     knowsPageRange: (BOOL)knowsPageRange
{
  int currentPage;
  int numberOnSheet;
  CGFloat xoffset, yoffset, scale;
  NSPoint location;
  NSPrintOperation *printOp = [NSPrintOperation currentOperation];
  NSGraphicsContext *ctxt = [printOp context];

  currentPage = [printOp currentPage];
  numberOnSheet = (currentPage - info.first) % info.nup;

  /* Begin a sheet (i.e. a physical page in Postscript terms). If 
     nup > 1 then this occurs only once every nup pages */
  if (numberOnSheet == 0)
    {
      NSString *label;
      NSRect boundsForPage = info.sheetBounds;

      if (knowsPageRange)
	{
	  boundsForPage = pageRect;
	}

      label = nil;
      if (info.nup == 1)
        label = [NSString stringWithFormat: @"%d", currentPage];

      DPSgsave(ctxt);
      [self beginPage: floor((currentPage - info.first)/info.nup)+1
            label: label
            bBox: boundsForPage
            fonts: nil];
      if (info.orient == NSLandscapeOrientation)
        {
          DPSrotate(ctxt, 90);
          DPStranslate(ctxt, 0, -info.paperSize.height);
        }
      
      if (!knowsPageRange)
	{
	  /* Also offset by margins */
	  DPStranslate(ctxt, NSMinX(info.paperBounds), NSMinY(info.paperBounds));
	}

      /* End page setup for multi page */
      if (info.nup != 1)
        {
          [self addToPageSetup];
          [self endPageSetup];
        }
    }

  scale = info.pageScale * info.printScale;
  location = [self locationOfPrintRect: scaleRect(pageRect, scale)];

  /* Begin a logical page */
  [self beginPageInRect: pageRect atPlacement: location];
  if (scale != 1.0)
    DPSscale(ctxt, scale, scale);

  /* FIXME: Why is this needed? Shouldn't the flip be handled by the lockFocus method? */
  if ([self isFlipped])
    {
      NSAffineTransformStruct ats = { 1, 0, 0, -1, 0, NSHeight(_bounds) };
      NSAffineTransform *matrix, *flip;

      flip = [NSAffineTransform new];
      matrix = [NSAffineTransform new];
      if (_boundsMatrix != nil)
        {
          [matrix prependTransform: _boundsMatrix];
        }
      /*
       * The flipping process must result in a coordinate system that
       * exactly overlays the original. To do that, we must translate
       * the origin by the height of the view.
       */
      [flip setTransformStruct: ats];
      [matrix prependTransform: flip];
      [matrix concat];
      RELEASE(flip);
      RELEASE(matrix);
      yoffset = NSHeight(_frame) - NSMaxY(pageRect);
    }
  else
    yoffset = 0 - NSMinY(pageRect);

  /* Translate so the rect we're printing is on the page */
  xoffset = 0 - NSMinX(pageRect);
  DPStranslate(ctxt, xoffset, yoffset);

  /* End page setup for single page */
  if (info.nup == 1)
    {
      [self addToPageSetup];
      [self endPageSetup];
    }

  /* Do the actual drawing */
  [self displayRectIgnoringOpacity: pageRect inContext: ctxt];

  /* End a logical page */
  // FIXME: Attempt to get the coordinates of the page border correct.
  DPSgrestore(ctxt);
  DPSgsave(ctxt);
  [self drawPageBorderWithSize: info.paperBounds.size];
  [self endPage];

  /* End a physical page */
  if (numberOnSheet == info.nup - 1)
    {
      [self drawSheetBorderWithSize: info.sheetBounds.size];
      [self _endSheet];
      DPSgrestore(ctxt);
    }
}

@end