File: MyImageListWindow.m

package info (click to toggle)
lynkeos.app 3.10%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,832 kB
  • sloc: objc: 41,053; ansic: 812; cpp: 151; sh: 68; makefile: 27
file content (1995 lines) | stat: -rw-r--r-- 67,463 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
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
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
//
//  Lynkeos
//  $Id$
//
//  Created by Jean-Etienne LAMIAUD on Fri Nov 28 2003.
//  Copyright (c) 2003-2025. Jean-Etienne LAMIAUD
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//

#include <limits.h>

#include "LynkeosAlertPanel.h"

#include "MyGuiConstants.h"
#include "MyImageListWindow.h"

#include "LynkeosMetadata.h"
#include "LynkeosImageBufferAdditions.h"
#include "LynkeosGammaCorrecter.h"
#include "LynkeosBasicAlignResult.h"
#include "MyUserPrefsController.h"
#include "MyImageListEnumerator.h"
#include "MyImageStacker.h"
#include "MyChromaticAlignerView.h"

#ifdef DOUBLE_PIXELS
#define powerof(x,y) pow(x,y)
#else
#define powerof(x,y) powf(x,y)
#endif

static NSString * const K_PREFERED_IMAGE_WRITER = @"Last image writer";
static NSString * const K_PREFERED_MOVIE_WRITER = @"Last movie writer";

static NSString * const K_TOOLBAR_REF = @"Processing toolbar";

static NSString * const K_WINFRAME_KEY = @"window frame";
static NSString * const K_MARGINWIDTH_KEY = @"margin width";
static NSString * const K_PROCESSHEIGHT_KEY = @"process height";
static NSString * const K_COLUMNSWIDTH_KEY = @"columns width";

#if !GNUSTEP
const CFStringRef LynkeosName = CFSTR("Lynkeos");
#else
#define NSAlertStyleCritical NSCriticalAlertStyle
#endif

static NSCursor *myWatchCursor = nil;

typedef enum { K_UP, K_DOWN } enumeration_direction_t;

static NSObject *objectFromNSValue(id v)
{
   NSObject *n = nil;

   if ([v isKindOfClass:[NSValue class]])
   {
      const char *fieldType = [v objCType];

      if (strlen(fieldType) != 1)
      {
         NSLog(@"Unsupported field type : %s", fieldType );
         return nil;
      }

      switch( *fieldType )
      {
         case 'c' :
         case 'C' :
         {
            char c;
            [v getValue:&c];
            n = [NSNumber numberWithChar:c];
         }
            break;
         case 's' :
         case 'S' :
         {
            short s;
            [v getValue:&s];
            n = [NSNumber numberWithShort:s];
         }
            break;
         case 'i' :
         case 'I' :
         {
            int i;
            [v getValue:&i];
            n = [NSNumber numberWithInt:i];
         }
            break;
         case 'l' :
         case 'L' :
         {
            long l;
            [v getValue:&l];
            n = [NSNumber numberWithLong:l];
         }
            break;
         case 'q' :
         case 'Q' :
         {
            long long l;
            [v getValue:&l];
            n = [NSNumber numberWithLongLong:l];
         }
            break;
         case 'f' :
         {
            float f;
            [v getValue:&f];
            n = [NSNumber numberWithFloat:f];
         }
            break;
         case 'd' :
         {
            double d;
            [v getValue:&d];
            n = [NSNumber numberWithDouble:d];
         }
            break;
         case 'B' :
         {
            BOOL b;
            [v getValue:&b];
            n = [NSNumber numberWithBool:b];
         }
            break;
         case '*' :
         {
            const char *s;
            [v getValue:&s];
            n = [NSString stringWithCString:s encoding:NSUTF8StringEncoding];
         }
            break;
         default :
            NSLog( @"Unsupported field type %s", fieldType );
            break;
      }
   }
   else if ( [v isKindOfClass:[NSString class]])
   {
      n = v;
   }
   else
      NSLog(@"Unsupported column data type %@", [[v class] description]);

   return n;
}

#if GNUSTEP
struct _sortCtxt
{
  LynkeosColumnDescription *desc;
  BOOL sortUp;
};

static NSComparisonResult sortFunc(id obj1, id obj2, void *ctxt)
{
  struct _sortCtxt *context = (struct _sortCtxt *)ctxt;

  LynkeosColumnDescription *desc = context->desc;
  BOOL _sortUp = context->sortUp;
  NSObject <LynkeosProcessingParameter> *param1 =
    [obj1 getProcessingParameterWithRef:desc->_parameterReference
                          forProcessing:desc->_processingRef];
  NSObject <LynkeosProcessingParameter> *param2 =
    [obj2 getProcessingParameterWithRef:desc->_parameterReference
                          forProcessing:desc->_processingRef];
  NSObject *field1 = nil, *field2 = nil;
  if (param1 != nil)
    field1 = objectFromNSValue([param1 valueForKey:desc->_fieldName]);
  if (param2 != nil)
    field2 = objectFromNSValue([param2 valueForKey:desc->_fieldName]);

  if (field1 == nil)
    {
      if (field2 == nil)
        return NSOrderedSame;
      else if (_sortUp)
        return NSOrderedAscending;
      else
        return NSOrderedDescending;
    }
  else if (field2 == nil)
    {
      if (_sortUp)
        return NSOrderedDescending;
      else
        return NSOrderedAscending;
    }
  else
    {
      if ([field1 isKindOfClass:[NSNumber class]])
        {
          NSNumber *num1 = (NSNumber*)field1;
          NSNumber *num2 = (NSNumber*)field2;
          if (_sortUp)
            return [num1 compare:num2];
          else
            return [num2 compare:num1];
        }
      else if ([field1 isKindOfClass:[NSString class]])
        {
          NSString *str1 = (NSString*)field1;
          NSString *str2 = (NSString*)field2;
          if (_sortUp)
            return [str1 localizedCompare:str2];
          else
            return [str2 localizedCompare:str1];
        }
      else
        {
          NSLog(@"Unsupported type for sorting %@", [[field1 class] description]);
          return NSOrderedSame;
        }
    }
}
#endif

/*!
 * @abstract Parameters of a processing tool
 */
@interface MyProcessViewDefinition : NSObject
{
@public
    //! The processing controller
   NSObject <LynkeosProcessingView> *_viewController;
   //! The process view
   NSView                           *_view;
   //! The current framing mode for this process
   LynkeosProcessingViewFrame_t     _currentFrame;
   //! Associated menu item (loose binding)
   NSMenuItem                       *_menuItem;
   //! Index in the processing tools
   NSInteger                         _processIndex;
   //! Processing tool title
   NSString                         *_title;
}
@end

@implementation MyProcessViewDefinition
- (id) init
{
   if ( (self = [super init]) != nil )
   {
      _viewController = nil;
      _view = nil;
      _currentFrame = BottomTab;
      _menuItem = nil;
      _processIndex = NSNotFound;
      _title = nil;
   }

   return( self );
}

- (void) dealloc
{
   [_viewController release];
   [_title release];

   [super dealloc];
}
@end

typedef struct
{
   MyImageListEnumerator *imgList;
   double                 black, white, gamma;
   u_short                nPlanes;
   LynkeosIntegerRect     cropRectangle;
   NSAffineTransform     *transform;
   LynkeosImageBuffer    *sample;
} MovieExportCtrl_t;

@interface MyImageListWindow(Private)
- (void) highlightOther:(enumeration_direction_t)sense skipUnselected:(BOOL)skip;
- (void) itemChanged:(NSNotification*)notif ;
- (void) zoomChanged:(NSNotification*)notif ;
@end

@interface MyImageListWindow(SplitView)
- (void) setProcessView:(NSView*)newView
            withDisplay:(LynkeosProcessingViewFrame_t)display ;
- (void) validateSplitControls ;
@end

@implementation MyImageListWindow(Private)
- (void) highlightOther :(enumeration_direction_t)sense skipUnselected:(BOOL)skip
{
   MyImageListItem *item;

   if (_outlineDisplay)
   {
      NSEnumerator *list;
      MyImageListItem *parent;
      list = [_currentList imageEnumeratorStartAt:_highlightedItem
                                      directSense:(sense==K_DOWN)
                                   skipUnselected:skip];

      item = [list nextObject];

      if ( item == nil )
         return;

      parent = [item getParent];
      if ( parent != nil )
         [_textView expandItem:parent];
   }
   else
   {
      const NSUInteger lastIdx = [_sortedItems count] - 1;
      NSUInteger idx = NSNotFound;

      NSAssert(_sortedItems != nil, @"Sorted items iteration without sorted array");

      item = _highlightedItem;
      do
      {
         if (item != nil)
         {
            idx = [_sortedItems indexOfObject:item];
            if (sense == K_DOWN && idx < lastIdx)
               idx ++;
            else if (sense == K_UP && idx > 0)
               idx --;
            else
               idx = NSNotFound;
         }
         else if (sense == K_DOWN)
            idx = 0;
         else
            idx =  lastIdx;

         if (idx != NSNotFound && idx <= lastIdx)
            item = [_sortedItems objectAtIndex:idx];
         else
            item = nil;
      } while (skip && item != nil && [item getSelectionState] != NSOnState);
   }

   [self highlightItem:item];
}

- (void) itemChanged:(NSNotification*)notif
{
   // Get the modified item
   MyImageListItem *item = [[notif userInfo] objectForKey:LynkeosUserInfoItem];

   if ( [item isKindOfClass:[MyImageListItem class]] )
   {
      // Redisplay it
      [_textView reloadItem:item reloadChildren:[item numberOfChildren] != 0];
      // And its parent if needed
      MyImageListItem *parent = [item getParent];
      if ( parent != nil )
         [_textView reloadItem:parent reloadChildren:NO];
      // If the display is sorted, schedule a re-sorting, after a little while,
      // in order to avoid multiple re-sortings during list processing
      if (_dataMode == ListData && !_outlineDisplay)
      {
         [[self class] cancelPreviousPerformRequestsWithTarget:self
                                                      selector:@selector(reloadData)
                                                        object:nil];
         [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.2];
      }
   }
}

- (void) zoomChanged:(NSNotification*)notif
{
   double zoom = [_imageView getZoom];

   switch( [(MyDocument*)[self document] dataMode] )
   {
      case ResultData :
         _resultZoom = zoom;
         break;
      case ListData :
         _listZoom = zoom;
         break;
      default : NSAssert( NO, @"Inconsistent data mode" );
   }
}
@end

@implementation MyImageListWindow
- (id) init
{
   if ( (self = [super init]) == nil )
      return( self );

   _highlightedItem = nil;
   _processingViewDict = [[NSMutableDictionary dictionary] retain];
   _processingAuthorization = NULL;
   _isProcessing = NO;
   _listSelectionAuthorized = YES;
   _dataModeSelectionAuthorized = YES;
   _itemSelectionAuthorized = NO;
   _itemEditionAuthorized = NO;
   _processingViewReg = nil;
   _processingViewController = nil;
   _currentProcessDisplay = BottomTab;
   _authorizedProcessDisplays = 0;
   _displayProgress = YES;
   _listMode = ImageMode;
   _dataMode = ListData;
   _outlineDisplay = YES;
   _sortedItems = nil;
   _sortColumn = nil;
   _sortUp = YES;
   _resultZoom = 1.0;
   _listZoom = 1.0;

   _toolBar = [[NSToolbar alloc] initWithIdentifier:K_TOOLBAR_REF];
   [_toolBar setAllowsUserCustomization:YES];
   [_toolBar setAutosavesConfiguration:YES];
   [_toolBar setDelegate:self];

   // Create the watch cursor
   if ( myWatchCursor == nil )
      myWatchCursor = [[NSCursor alloc] initWithImage:
                                                   [NSImage imageNamed:@"watch"]
                                              hotSpot:NSMakePoint(8,8)];

   return( [super initWithWindowNibName:@"ImageListWindow"] );
}

- (void) dealloc
{
   [[self class] cancelPreviousPerformRequestsWithTarget:self
                                                selector:@selector(reloadData)
                                                  object:nil];
   [[NSNotificationCenter defaultCenter] removeObserver:self];
   [_processingViewDict release];
   if ( _processingAuthorization != NULL )
      free( _processingAuthorization );
   [_listSubview release];
   [_processSubview release];
   [_marginSubview release];
   [_toolBar release];
   if (_sortedItems != nil)
      [_sortedItems release];

   [super dealloc];
}

- (void) windowDidLoad
{
   // Get the document contents
   _currentList = (MyImageList*)[(MyDocument*)[self document] imageList];

   NSTableColumn *tableColumn = nil;
   NSButtonCell *buttonCell = nil;

   // Initialize the buttons in the outline first column
   tableColumn = [_textView tableColumnWithIdentifier: @"select"];
   buttonCell = [[[NSButtonCell alloc] initTextCell: @""] autorelease];
   [buttonCell setEditable: YES];
   [buttonCell setButtonType: NSSwitchButton];
   [buttonCell setAllowsMixedState: YES];
   [buttonCell setControlSize:NSControlSizeSmall];
   [tableColumn setDataCell:buttonCell];
   [_textView reloadData];

   // Get the columns descriptions
   _columnsDescriptor = [LynkeosColumnDescriptor defaultColumnDescriptor];

   // Initialize dragging
   [_textView registerForDraggedTypes:
    [NSArray arrayWithObject:NSFilenamesPboardType]];

   // Initialize image view
   [_imageView setSelectionMode:NoSelection];

   // Initialize the frames
   _listSubview = [[[_listSplit subviews] objectAtIndex:0] retain];
   _processSubview = [[[_listSplit subviews] objectAtIndex:1] retain];
   _marginSubview = [[[_imageSplit subviews] objectAtIndex:0] retain];   

   // Restore the window frames
   NSDictionary *wSizes = [(MyDocument*)[self document] savedWindowSizes];
   if ( wSizes != nil )
   {
      NSString* wframe = [wSizes objectForKey:K_WINFRAME_KEY];
      if (wframe != nil )
         [[self window] setFrameFromString:wframe];
      NSSize size;
      float delta;
      NSNumber *nb = [wSizes objectForKey:K_PROCESSHEIGHT_KEY];
      if ( nb != nil )
      {
         size = [_processSubview frame].size;
         delta = [nb floatValue] - size.height;
         size.height += delta;
         [_processSubview setFrameSize:size];
         size = [_listSubview frame].size;
         size.height -= delta;
         [_listSubview setFrameSize:size];
         [_listSplit adjustSubviews];
      }
      nb = [wSizes objectForKey:K_MARGINWIDTH_KEY];
      if ( nb != nil )
      {
         size = [_marginSubview frame].size;
         delta = [nb floatValue] - size.width;
         size.width += delta;
         [_marginSubview setFrameSize:size];
         NSView *imageSubview = [[_imageSplit subviews] objectAtIndex:1];
         size = [imageSubview frame].size;
         size.width -= delta;
         [imageSubview setFrameSize:size];
         [_imageSplit adjustSubviews];
      }
      NSDictionary *colSizes = [wSizes objectForKey:K_COLUMNSWIDTH_KEY];
      if ( colSizes != nil )
      {
         NSEnumerator *sizeList = [colSizes keyEnumerator];
         id colSize;
         while( (colSize = [sizeList nextObject]) != nil )
         {
            NSTableColumn *col = [_textView tableColumnWithIdentifier:colSize];
            if ( col != nil && col != [_textView outlineTableColumn] )
               [col setWidth:[[colSizes objectForKey:colSize] floatValue]];
         }
      }
   }

   // Initialize the processing view controllers management
   NSArray *processingList =
   [[MyPluginsController defaultPluginController] getProcessingViews];
   NSUInteger i, listProcIndex = NSNotFound, nCtrl = [processingList count];
   _processingAuthorization = (unsigned int*)malloc(sizeof(unsigned int)*nCtrl);
   for( i = 0; i < nCtrl; i++ )
   {
      LynkeosProcessingViewRegistry *reg = [processingList objectAtIndex:i];
      if ( [reg->controller respondsToSelector:
            @selector(authorizedModesForConfig:)] )
         _processingAuthorization[i] = 
         [reg->controller authorizedModesForConfig:reg->config]
         | ProcessingViewAuthorized;
      else
      {
         _processingAuthorization[i] = ProcessingViewAuthorized
         |ImageMode|ListData;
         switch ( [reg->controller processingViewKindForConfig:reg->config] )
         {
            case ImageProcessingKind:
            case OtherProcessingKind:
               _processingAuthorization[i] |= ResultData;
               break;
            default: break;
         }
      }

      // Hack : use this loop to locate the registry for the list manager
      if ( reg->controller == [_listProcessing class] )
         listProcIndex = i;
   }
   [[NSNotificationCenter defaultCenter] postNotificationName:
                                              LynkeosDocumentDidOpenNotification
                                                       object:[self document]
                                                     userInfo:
    [NSDictionary dictionaryWithObject:self
                                forKey:LynkeosUserinfoWindowController]];

   // Initialize the toolbar with all the processings
   [[self window] setToolbar:_toolBar];

   // Put the list manager instance in the processing views dictionary
   MyProcessViewDefinition *def =
                           [[[MyProcessViewDefinition alloc] init] autorelease];

   // The list processing will be released with the definition, and as a Nib
   // top level object : so retain it on behalf of the definition
   def->_viewController = [_listProcessing retain];
   def->_view = [_listProcessing getProcessingView];
   def->_currentFrame = [_listProcessing preferredDisplay];
   NSAssert( listProcIndex != NSNotFound, @"List management registry not found" );
   def->_processIndex = listProcIndex;
   _processMenu = [[[NSApp mainMenu] itemWithTag:K_PROCESS_MENU_TAG] submenu];
   def->_menuItem = [_processMenu itemWithTag:def->_processIndex];
   def->_title = [[NSString stringWithString:[def->_menuItem title]] retain];

   [_processingViewDict setObject:def
                           forKey:@"LynkeosProcToolbarItem_MyListManagement"];
   _processingViewDef = def;

   // And set it as the first active view
   [self activateProcessingView:def->_menuItem];

   // Register for notifications
   NSNotificationCenter *notifCenter = [NSNotificationCenter defaultCenter];
   [notifCenter addObserver:self
                   selector:@selector(itemChanged:)
                       name: LynkeosItemChangedNotification
                     object:[self document]];
   [notifCenter addObserver:self
                   selector:@selector(zoomChanged:)
                       name: LynkeosImageViewZoomDidChangeNotification
                     object:_imageView];

   // Update initial state
   [self documentListModeChanged:[self document]];
   [self documentDataModeChanged:[self document]];
}

- (void) keyDown:(NSEvent *)theEvent
{
   unichar c = [[theEvent characters] characterAtIndex:0];

   if ( !_isProcessing )
   {
      if ( _processingViewController != nil
           && [_processingViewController respondsToSelector:
                                                      @selector(handleKeyDown:)]
           && [_processingViewController handleKeyDown:theEvent] )
         return;

      BOOL nextEnabled = [[_currentList imageArray] count] != 0;

#if !GNUSTEP
      if ((theEvent.modifierFlags & NSEventModifierFlagDeviceIndependentFlagsMask
           & ~NSEventModifierFlagNumericPad & ~NSEventModifierFlagFunction) == 0)
      {
#endif
         switch( c )
         {
            case NSLeftArrowFunctionKey:
               if ( nextEnabled )
                  [self highlightPrevious:nil];
               break;
            case NSRightArrowFunctionKey :
               if ( nextEnabled )
                  [self highlightNext:nil];
               break;
            case NSDownArrowFunctionKey:
               if ( nextEnabled )
                  [self highlightOther:K_DOWN skipUnselected:NO];
               break;
            case NSUpArrowFunctionKey:
               if ( nextEnabled )
                  [self highlightOther:K_UP skipUnselected:NO];
               break;
            case NSHomeFunctionKey :
               if ( nextEnabled )
               {
                  _highlightedItem = nil;
                  [self highlightOther:K_DOWN skipUnselected:NO];
               }
               break;
            case NSEndFunctionKey :
               if ( nextEnabled )
               {
                  _highlightedItem = nil;
                  [self highlightOther:K_UP skipUnselected:NO];
               }
               break;
            case '\r' :
            case ' ' :
               if ( _highlightedItem != nil )
                  [self toggleEntrySelection:nil];
               break;
            case NSDeleteFunctionKey :
            case '\b' :
            case 127 : // Delete char
               if ( _highlightedItem != nil )
                  [self delete:nil];
               break;
            default:
               [super keyDown:theEvent];
               break;
         }
#if !GNUSTEP
      }
      else
         [super keyDown:theEvent];
#endif
   }
   else
      [super keyDown:theEvent];
}

- (BOOL)validateMenuItem:(NSMenuItem*)menuItem
{
   NSInteger tag = [menuItem tag];
   switch ( tag )
   {
      case K_SAVE_TAG:
      case K_SAVE_AS_TAG:
      case K_REVERT_TAG:
      case K_ADD_IMAGE_TAG:
         return( ! _isProcessing );
      case K_SAVE_IMAGE_TAG:
      {
         id <LynkeosProcessableItem> item = nil;
         double b, w, g;

         switch ( _dataMode )
         {
            case ListData:
               if ( _highlightedItem != nil
                   && [_highlightedItem numberOfChildren] == 0 )
                  item = _highlightedItem;
               break;
            case ResultData: item = _currentList; break;
            default: NSAssert1( NO, @"Invalid data mode %d", _dataMode );
         }

         return( !_isProcessing && item != nil
                 && [item getBlackLevel:&b whiteLevel:&w gamma:&g] );
      }
      case K_EXPORT_MOVIE_TAG:
         return( _dataMode == ListData && !_isProcessing
                 && [[_currentList imageArray] count] != 0 );
      case K_UNDO_TAG:
      case K_REDO_TAG:
         return( !_isProcessing );
      case K_DELETE_TAG:
         return( !_isProcessing && _highlightedItem != nil );
      case K_HIDE_LIST_TAG:
         switch( _currentProcessDisplay )
      {
         case BottomTab:
            return( (_authorizedProcessDisplays & BottomTab_NoList) != 0 );
         case BottomTab_NoList:
            return( (_authorizedProcessDisplays & BottomTab) != 0 );
         case SeparateView:
            return( (_authorizedProcessDisplays & SeparateView_NoList) != 0 );
         case SeparateView_NoList:
            return( (_authorizedProcessDisplays & SeparateView) != 0 );
      }
      case K_DETACH_PROCESS_TAG:
         switch( _currentProcessDisplay )
      {
         case BottomTab:
            return( (_authorizedProcessDisplays & SeparateView) != 0 );
         case BottomTab_NoList:
            return( (_authorizedProcessDisplays & SeparateView_NoList) != 0 );
         case SeparateView:
            return( (_authorizedProcessDisplays & BottomTab) != 0 );
         case SeparateView_NoList:
            return( (_authorizedProcessDisplays & BottomTab_NoList) != 0 );
      }
         break;
      default:
         if ( [menuItem menu] == _processMenu )
         {
            unsigned int mask = ProcessingViewAuthorized|_listMode;
            return( !_isProcessing &&
                   (_processingAuthorization[tag] & mask) == mask );
         }
         break;
   }
   // Other menus sending to this controller should always be enabled
   return( YES );
}

- (BOOL)windowShouldClose:(id)sender
{
   if ( sender == _processWindow )
   {
      NSAssert1( _currentProcessDisplay == SeparateView || 
                _currentProcessDisplay == SeparateView_NoList,
                @"Process window tries to close while in display %d",
                _currentProcessDisplay );
      return( (_currentProcessDisplay == SeparateView
               && (_authorizedProcessDisplays & BottomTab) != 0) ||
             (_currentProcessDisplay == SeparateView_NoList
              && (_authorizedProcessDisplays & BottomTab_NoList) != 0) );
   }
   else
      return( YES );
}

- (void)windowWillClose:(NSNotification *)aNotification
{
   NSWindow *w = [aNotification object];
   if ( w == _processWindow )
   {
      LynkeosProcessingViewFrame_t display = 0;

      switch( _currentProcessDisplay )
      {
         case SeparateView: display = BottomTab; break;
         case SeparateView_NoList:  display = BottomTab_NoList; break;
         default: break;
      }

      if ( display != 0 )
      {
         [self setProcessView:_processingView withDisplay:display];
         _processingViewDef->_currentFrame = display;
      }
   }
   else if ( w == [self window] )
   {
      // Stop the process in progress if any
      if ( _isProcessing )
         [(id <LynkeosDocument>)[self document] stopProcess];
      // Wait for process completion
      while ( _isProcessing )
         [[NSRunLoop currentRunLoop] runUntilDate:
          [NSDate dateWithTimeIntervalSinceNow:0.2]];
      // Deactivate any remaining processing view
      if ( _processingViewController != nil )
         [_processingViewController setActiveView:NO];
      // And notify it
      [[NSNotificationCenter defaultCenter] postNotificationName:
                                            LynkeosDocumentWillCloseNotification
                                                          object:[self document]
                                                        userInfo:
           [NSDictionary dictionaryWithObject:self
                                       forKey:LynkeosUserinfoWindowController]];      
   }
}

- (NSRect)windowWillUseStandardFrame:(NSWindow *)sender
                        defaultFrame:(NSRect)defaultFrame
{
   if ( sender == _processWindow )
   {
      NSRect content = [_processingView frame];
      NSSize maxSize = [_processWindow maxSize];

      // Add some space to be sure that the srollbars don't show up
      content.size.width += 2;
      content.size.height += 2;
      if ( content.size.width > maxSize.width )
         content.size.width = maxSize.width;
      if ( content.size.height > maxSize.height )
         content.size.height = maxSize.height;
      return( [sender frameRectForContentRect:content] );
   }
   else
      return( defaultFrame );
}

- (void)windowDidBecomeMain:(NSNotification *)aNotification
{
   NSWindow *mainWindow = [self window];
   NSWindow *sender = [aNotification object];

   NSAssert1( sender == mainWindow,
              @"Unexpected window becomes main : %@", sender );

   if ( _currentProcessDisplay == SeparateView
       || _currentProcessDisplay == SeparateView_NoList )
   {
      [_processWindow makeKeyAndOrderFront:self];
      [NSApp addWindowsItem:_processWindow title:[_processWindow title]
                   filename:NO];
   }

   if ( _processingViewDef != nil )
      [_processingViewDef->_menuItem setState:NSOnState];
}

- (void)windowDidResignMain:(NSNotification *)aNotification
{
   NSWindow *mainWindow = [self window];
   NSWindow *sender = [aNotification object];

   NSAssert1( sender == mainWindow,
              @"Unexpected window becomes main : %@", sender );

   if ( _currentProcessDisplay == SeparateView
       || _currentProcessDisplay == SeparateView_NoList )
   {
      [_processWindow orderOut:self];
      [NSApp removeWindowsItem:_processWindow];
   }

   if ( _processingViewDef != nil )
      [_processingViewDef->_menuItem setState:NSOffState];
}

#pragma mark = LynkeosDocumentDelegate protocol
- (void) documentDidLoad : (id <LynkeosDocument>)document
{
   // Select the list management tool
   MyProcessViewDefinition *def = [_processingViewDict objectForKey:
                                   @"LynkeosProcToolbarItem_MyListManagement"];

   [self activateProcessingView:def->_menuItem];
   // And force it to update
   [[NSNotificationCenter defaultCenter] postNotificationName:
                                                   LynkeosListChangeNotification
                                                       object:[self document]];
}

- (void) document:(id <LynkeosDocument>)document
  processDidStart:(Class)processClass
{
   _isProcessing = YES;
   [_listMenu setEnabled: NO];
   [_dataModeRadio setEnabled: NO];
   if ( _displayProgress )
      [_progress startAnimation:self];
}

- (void) document:(id <LynkeosDocument>)document
  processHasEnded:(Class)processingClass
{
   _isProcessing = NO;
   [_listMenu setEnabled: _listSelectionAuthorized];
   [_dataModeRadio setEnabled: _dataModeSelectionAuthorized];
   [_progress stopAnimation:self];
   [[self window] update];
}

- (void) itemWasAdded:(id <LynkeosDocument>)document
{
   [self reloadData];
}

- (void) itemWasRemoved:(id <LynkeosDocument>)document
{
   [self reloadData];
   // Force update of the hilighted item in case it was deleted
   // Because outline view does not notify (the selection is at same line)
   [self outlineViewSelectionDidChange:
      [NSNotification notificationWithName:@"LynkeosItemRemoved" object:nil]];
}

- (void) documentListModeChanged:(id <LynkeosDocument>)document
{
   ListMode_t mode = [(MyDocument*)document listMode];

   if ( _listMode != mode )
   {
      _listMode = mode;
      [_listMenu selectItemWithTag:_listMode];
   }

   _currentList = [(MyDocument*)document currentList];
   // Redisplay the outline view
   [self reloadData];

   if ( _dataMode == ResultData )
      // Force selection on first and only line
      [_textView selectRowIndexes:[NSIndexSet indexSetWithIndex:0]
             byExtendingSelection:NO];
   else
      // Force notification of selection in the new list
      [self outlineViewSelectionDidChange:
         [NSNotification notificationWithName:@"LynkeosListModeChange" object:nil]];
}

- (void) documentDataModeChanged:(id <LynkeosDocument>)document
{
   DataMode_t mode = [(MyDocument*)document dataMode];

   if ( _dataMode != mode )
   {
      _dataMode = mode;
      [_dataModeRadio selectCellWithTag:_dataMode];
      // Redisplay the outline view
      [self reloadData];
      // Reset the bounds of the image view, which were adapted to the "other" mode
      [_imageView resetBounds];

      if ( _dataMode == ResultData )
         // Force selection on first and only line
         [_textView selectRowIndexes:[NSIndexSet indexSetWithIndex:0]
                byExtendingSelection:NO];

      if ( _processingViewController == nil
          || ![[_processingViewController class] respondsToSelector:
               @selector(handleImageViewZoom)]
          || ![[_processingViewController class] handleImageViewZoom] )
         [_imageView setZoom:(_dataMode == ResultData ?
                              _resultZoom : _listZoom)];

      // In case the outline view did not notify, do it ourselves
      [self outlineViewSelectionDidChange:
         [NSNotification notificationWithName:@"LynkeosDataModeChange" object:nil]];
   }
}

#pragma mark = LynkeosWindowController protocol
- (NSDictionary*) windowSizes
{
   // Get the columns
   NSArray *columns = [_textView tableColumns];
   NSMutableDictionary *columnSizes =
                   [NSMutableDictionary dictionaryWithCapacity:[columns count]];
   NSEnumerator *colList = [columns objectEnumerator];
   NSTableColumn *col;
   while ( (col = [colList nextObject]) != nil )
   {
      if ( col != [_textView outlineTableColumn] )
         [columnSizes setObject:[NSNumber numberWithFloat:[col width]]
                                                   forKey:[col identifier]];
   }

   return( [NSDictionary dictionaryWithObjectsAndKeys:
                  [[self window] stringWithSavedFrame],
                  K_WINFRAME_KEY,
                  [NSNumber numberWithFloat:[_marginSubview frame].size.width],
                  K_MARGINWIDTH_KEY,
                  [NSNumber numberWithFloat:[_processSubview frame].size.height],
                  K_PROCESSHEIGHT_KEY,
                  columnSizes,
                  K_COLUMNSWIDTH_KEY,
                  nil] );
}

- (id <LynkeosImageView>) getImageView { return( _imageView ); }
- (id <LynkeosImageView>) getRealImageView { return( _imageView ); }

// Accessors
- (id <LynkeosProcessableItem>) highlightedItem
{
   return( _highlightedItem );
}

- (void) highlightItem :(id <LynkeosProcessableItem>)item
{
   if ( item == nil )
      [_textView deselectAll:self];

   else
   {
      NSInteger row;
      MyImageListItem *parent = nil;
      if ( [item isKindOfClass:[MyImageListItem class]] )
         parent = [(MyImageListItem*)item getParent];

      // Expand father (won't do anything if already expanded)
      if ( parent != nil )
         [_textView expandItem:parent];

      row = [_textView rowForItem:item];

      // Don't change highlight if item is not in the list
      if ( row < 0 )
         return;

      // Set the hilight
      [_textView selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
      [_textView scrollRowToVisible:row];
   }
}

- (void) setListSelectionAuthorization: (BOOL)auth
{
   _listSelectionAuthorized = auth;
   [_listMenu setEnabled: (auth && !_isProcessing)];
}

- (void) setDataModeSelectionAuthorization: (BOOL)auth
{
   _dataModeSelectionAuthorized = auth;
   [_dataModeRadio setEnabled: (auth && !_isProcessing)];
}

- (void) setItemSelectionAuthorization: (BOOL)auth
{
   _itemSelectionAuthorized = auth;
}

- (void) setItemEditionAuthorization: (BOOL)auth
{
   _itemEditionAuthorized = auth;
}

- (void) setProcessing:(Class)c andIdent:(NSString*)ident
         authorization: (BOOL)auth
{
   NSEnumerator *list = [[[MyPluginsController defaultPluginController]
                                          getProcessingViews] objectEnumerator];
   LynkeosProcessingViewRegistry *reg = nil;
   NSUInteger tag = NSNotFound, i = 0;
   while( (reg = [list nextObject]) != nil )
   {
      if ( reg->controller == c && reg->ident == ident )
      {
         tag = i;
         break;
      }
      i++;
   }
   NSAssert( tag != NSNotFound, @"Unknown process to authorize" );
   if ( auth )
      _processingAuthorization[tag] |= ProcessingViewAuthorized;
   else
      _processingAuthorization[tag] &= ~ProcessingViewAuthorized;
}

- (void) getItemToProcess:(LynkeosProcessableImage**)item
             andParameter:(LynkeosImageProcessingParameter**)param
                  forView:(id <LynkeosProcessingView>)sender
{
   *item = nil;
   switch ( _dataMode )
   {
      case ListData:
         if ( [_highlightedItem numberOfChildren] == 0 )
            *item = _highlightedItem; // Movies are not really processable
         break;
      case ResultData:
         *item = (LynkeosProcessableImage*)_currentList;
         break;
      default:
         NSAssert1( NO, @"Invalid data mode %d", _dataMode );
   }

   *param = nil;  // Default value

   // Get the topmost processing if handled by this process controller
   if ( *item != nil )
   {
      NSMutableArray *stack =
                      (NSMutableArray*)[*item getProcessingParameterWithRef:
                                                             K_PROCESS_STACK_REF
                                                              forProcessing:nil
                                                                       goUp:NO];
      if ( stack != nil && [stack count] > 0 )
      {
         LynkeosImageProcessingParameter *lastParam = [stack lastObject];
         id <NSObject> dummy;
         if ( [[sender class] isViewControllingProcess:
                                                     [lastParam processingClass]
                                            withConfig:&dummy] )
         {
            *param = lastParam;
            [lastParam setExcluded:NO];   // Force it in case of reselection
         }
      }
   }
}

- (void) saveImage:(LynkeosImageBuffer*)image withBlack:(double*)black
             white:(double*)white
             gamma:(double*)gamma
          metadata:(NSDictionary*)metadata
{
   NSEnumerator *list;
   Class writerClass;
   id <LynkeosImageFileWriter> writer;
   NSInteger selectedIndex = -1;

   // Construct the writers list
   _currentWriters = [NSMutableArray array];
   if ( [_fileWritersMenu numberOfItems] != 0 )
      [_fileWritersMenu removeAllItems];
   for( list = [[[MyPluginsController defaultPluginController]
                 getImageWriters] objectEnumerator];
       (writerClass = [list nextObject]) != nil; )
   {
      if ( [writerClass canSaveDataWithPlanes:image->_nPlanes 
                                        width:image->_w height:image->_h
                                     metaData:metadata] )
      {
         [_currentWriters addObject:writerClass];
         [_fileWritersMenu addItemWithTitle:[writerClass writerName]];
      }
   }

   // Select the last used, if any ; otherwise, select the first
   NSString *prefWriter = [[NSUserDefaults standardUserDefaults] 
                           stringForKey:K_PREFERED_IMAGE_WRITER];
   if ( prefWriter != nil )
      selectedIndex = [_fileWritersMenu indexOfItemWithTitle:prefWriter];
   if ( selectedIndex == -1 )
      selectedIndex = 0;
   [_fileWritersMenu selectItemAtIndex:selectedIndex];

   _savePanel = [NSSavePanel savePanel];
   [_savePanel setTitle:NSLocalizedString(@"Save image",
                                          @"Save image window title")];
   [_savePanel setCanSelectHiddenExtension:YES];
   [_savePanel setAccessoryView:_fileWritersView];
   writerClass = [_currentWriters objectAtIndex:selectedIndex];
   [_savePanel setAllowedFileTypes:[NSArray arrayWithObject:[writerClass fileExtension]]];

   if ( [_savePanel runModal] == NSModalResponseOK )
   {
      // The user gave a filename, save the image in it
      NSURL *url = [_savePanel URL];

      selectedIndex = [_fileWritersMenu indexOfSelectedItem];
      writerClass = [_currentWriters objectAtIndex: selectedIndex];

      // Allocate a writer instance
      writer = (id <LynkeosImageFileWriter>)[writerClass 
                                             writerForURL:url 
                                             planes:image->_nPlanes 
                                             width:image->_w
                                             height:image->_h
                                             metaData:metadata];

      // Let the user fine tune the writer's options
      if ( [NSApp runModalForWindow:[writer configurationPanel]] == NSModalResponseOK )
      {
         // Set the watch cursor
         [myWatchCursor push];

         // And save at last
         LynkeosImageBuffer *copy = [image copy];
         const u_short nPlanes = copy->_nPlanes;
         u_short x, y, c;
         double vmin, vmax, a;
         a = 1.0/(white[nPlanes] - black[nPlanes]);
         [copy getMinLevel:&vmin maxLevel:&vmax];

         for( c = 0; c < nPlanes; c++ )
         {
            double ac = (vmax - vmin)/(white[c] - black[c]);
            LynkeosGammaCorrecter *gammaCorrect = 
                                 [LynkeosGammaCorrecter getCorrecterForGamma:
                                                      gamma[nPlanes]*gamma[c]];

            for( y = 0; y < copy->_h; y++ )
            {
               for( x = 0; x < copy->_w; x++ )
               {
                  colorValue(copy,x,y,c) = 
                     correctedValue( gammaCorrect,
                                       ( (colorValue(copy,x,y,c) - black[c])*ac
                                         + vmin - black[nPlanes]) * a);
               }
            }
            [gammaCorrect releaseCorrecter];
         }

         [writer saveImageAtURL:url
                       withData:(const REAL*const*const)[copy colorPlanes]
                     blackLevel:black[nPlanes] whiteLevel:white[nPlanes]
                     withPlanes:copy->_nPlanes
                          width:copy->_w lineWidth:copy->_padw
                         height:copy->_h
                       metaData:nil];
         [copy release];

         // Remember the writer's name
         [[NSUserDefaults standardUserDefaults] 
          setObject:[writerClass writerName]
          forKey:K_PREFERED_IMAGE_WRITER];

         // Revert the cursor to its normal state when we finished saving
         [NSCursor pop];
      }
   }
}

- (void) exportMovieFromList:(id<LynkeosImageList>)list withParams:(MyImageStackerParameters*)params
                   withBlack:(double)black white:(double)white gamma:(double)gamma
{
   const u_short nPlanes = list.numberOfPlanes;

   LynkeosIntegerRect rect = params->_cropRectangle;
   NSAffineTransformStruct t = [params->_transform transformStruct];
   CGFloat scale = sqrt( t.m11*t.m22 - t.m12*t.m21 );
   NSEnumerator *pluginList;
   Class writerClass;
   id <LynkeosMovieFileWriter> writer;
   NSInteger selectedIndex = -1;

   // Adjust the crop rectangle without scaling
   rect.origin.x = rect.origin.x / scale;
   rect.origin.y = rect.origin.y / scale;
   rect.size.width = rect.size.width / scale;
   rect.size.height = rect.size.height / scale;

   // Construct the writers list
   _currentWriters = [NSMutableArray array];
   if ( [_fileWritersMenu numberOfItems] != 0 )
      [_fileWritersMenu removeAllItems];
   for( pluginList = [[[MyPluginsController defaultPluginController] getMovieWriters] objectEnumerator];
       (writerClass = [pluginList nextObject]) != nil; )
   {
      if ( [writerClass canSaveDataWithPlanes:nPlanes
                                        width:rect.size.width
                                       height:rect.size.height
                                     metaData:nil] )
      {
         [_currentWriters addObject:writerClass];
         [_fileWritersMenu addItemWithTitle:[writerClass writerName]];
      }
   }
   
   // Select the last used, if any ; otherwise, select the first
   NSString *prefWriter = [[NSUserDefaults standardUserDefaults] stringForKey:K_PREFERED_MOVIE_WRITER];
   if ( prefWriter != nil )
      selectedIndex = [_fileWritersMenu indexOfItemWithTitle:prefWriter];
   if ( selectedIndex == -1 )
      selectedIndex = 0;
   [_fileWritersMenu selectItemAtIndex:selectedIndex];
   
   _savePanel = [NSSavePanel savePanel];
   [_savePanel setTitle:NSLocalizedString(@"Export sequence",
                                          @"Export sequence panel title")];
   [_savePanel setCanSelectHiddenExtension:YES];
   [_savePanel setAccessoryView:_fileWritersView];
   writerClass = [_currentWriters objectAtIndex:selectedIndex];
   [_savePanel setAllowedFileTypes:[NSArray arrayWithObject:[writerClass fileExtension]]];
   
   if ( [_savePanel runModal] == NSModalResponseOK )
   {
      // The user gave a filename, save the image in it
      NSURL *url = [_savePanel URL];

      selectedIndex = [_fileWritersMenu indexOfSelectedItem];
      writerClass = [_currentWriters objectAtIndex: selectedIndex];

      NSMutableDictionary *mDict
         = [NSMutableDictionary dictionaryWithDictionary:[list getMetaData]];
#if !GNUSTEP
      NSArray *app = [mDict objectForKey:LynkeosMD_CreatorApp()];
      if (app == nil)
         [mDict setObject:[NSArray arrayWithObject:(NSString*)LynkeosName] forKey:LynkeosMD_CreatorApp()];
      else if (![app containsObject:(NSString*)LynkeosName])
         [mDict setObject:[app arrayByAddingObject:(NSString*)LynkeosName] forKey:LynkeosMD_CreatorApp()];
#endif

      // Allocate a writer instance
      writer = (id <LynkeosMovieFileWriter>)[writerClass
                                             writerForURL:url
                                             planes:nPlanes
                                             width:rect.size.width
                                             height:rect.size.height
                                             metaData:mDict];

      // Let the user fine tune the writer's options
      NSWindow *cfgPanel = [writer configurationPanel];
      if ( cfgPanel == nil || [NSApp runModalForWindow:cfgPanel] == NSModalResponseOK )
      {
         // Set the watch cursor
         [myWatchCursor push];
         // And open the progress panel
         _exportProgressIndicator.minValue = 0.0;
         _exportProgressIndicator.maxValue = 0.0;
         _exportProgressIndicator.doubleValue = 0.0;
         _exportProgressIndicator.indeterminate = YES;
         _exportProgressIndicator.usesThreadedAnimation = YES;

         // And save at last
         MovieExportCtrl_t ctrl;
         ctrl.imgList = (MyImageListEnumerator*)[list imageEnumeratorStartAt:nil
                                                                 directSense:YES
                                                              skipUnselected:YES];
         NSAssert([ctrl.imgList isKindOfClass:[MyImageListEnumerator class]],
                  @"Wrong class for image list enumerator");
         ctrl.cropRectangle = rect;
         NSAffineTransform *transform
            = [[[NSAffineTransform alloc] initWithTransform:params->_transform] autorelease];
         [transform scaleBy:1.0/scale];
         ctrl.transform = transform;
         ctrl.black = black;
         ctrl.white = white;
         ctrl.gamma = gamma;
         ctrl.nPlanes = nPlanes;
         ctrl.sample = [LynkeosImageBuffer imageBufferWithNumberOfPlanes:nPlanes
                                                                   width:rect.size.width
                                                                  height:rect.size.height];
         _exportProgressSession = [NSApp beginModalSessionForWindow: _exportProgressPanel];
         [NSApp runModalSession:_exportProgressSession];

         // Count the number of images in the sequence, for the progress indicator
         u_long total = 0;
         while (([ctrl.imgList nextObject]) != nil)
            total += 1;
         _exportProgressIndicator.maxValue = total;
         [ctrl.imgList reset];
         [_exportProgressIndicator stopAnimation:self];
         _exportProgressIndicator.indeterminate = NO;
         [NSApp runModalSession:_exportProgressSession];

         // And save
         [writer saveMovieAtURL:url
                   withDelegate:self
                         opaque:&ctrl
                     blackLevel:black
                     whiteLevel:white
                     withPlanes:nPlanes
                          width:rect.size.width
                         height:rect.size.height
                       metaData:mDict];

         // Remember the writer's name
         [[NSUserDefaults standardUserDefaults]
            setObject:[writerClass writerName] forKey:K_PREFERED_MOVIE_WRITER];

         // Close the progress panel
         [NSApp endModalSession:_exportProgressSession];
         [_exportProgressPanel close];

         // Revert the cursor to its normal state when we finished saving
         [NSCursor pop];
      }
   }
}

- (LynkeosImageBuffer*) loadImage
{
   LynkeosImageBuffer *image = nil;
   NSOpenPanel* panel = [NSOpenPanel openPanel];
   NSDictionary *fileTypes =
   [[MyPluginsController defaultPluginController] getImageReaders];
   NSArray *files;

   [panel setAllowedFileTypes:[fileTypes allKeys]];
   if ( [panel runModal] == NSModalResponseOK )
   {
      files = [panel URLs];

      if ( [files count] != 0 )
      {
         NSURL *url = [files objectAtIndex:0];

         // Find the reader class which declares this file type, 
         // and accepts to open this file
         NSMutableArray *readers = [NSMutableArray array];
         NSEnumerator *list;
         LynkeosReaderRegistry *item;
         id <LynkeosImageFileReader> reader = nil;

         NSString *ext = [[[url path] pathExtension] lowercaseString];

         [readers addObjectsFromArray:[fileTypes objectForKey:ext]];
#if !defined GNUSTEP
         [readers addObjectsFromArray:[fileTypes objectForKey:
                                       NSHFSTypeOfFile([url path])]];
#endif

         // Try the readers until one accepts
         list = [readers objectEnumerator];
         while( (item = [list nextObject]) != nil )
         {
            if ( (reader = [[[item->reader alloc] initWithURL:url] autorelease])
                 != nil )
               // Found it
               break;
         }

         if ( reader != nil )
         {
            u_short w, h, n;
            [reader imageWidth:&w height:&h];
            n = [reader numberOfPlanes];
            image = [[[LynkeosImageBuffer alloc] initWithNumberOfPlanes:n
                                                             width:w
                                                            height:h] autorelease];
            [reader getImageSample:[image colorPlanes]
                        withPlanes:n atX:0 Y:0 W:w H:h lineWidth:image->_padw];
         }
         else
            // Bad luck
            NSLog( @"Unable to load file %@", [url absoluteString] );
      }
   }

   return( image );
}

#pragma mark = Processing views management
- (void) activateProcessingView: (id) sender
{
   NSInteger tag = [sender tag];
   NSArray *procList = [[MyPluginsController defaultPluginController] getProcessingViews];

   // Ignore activation if the process is not authorized
   const unsigned int mask = ProcessingViewAuthorized|_listMode;   
   if ( _isProcessing || (_processingAuthorization[tag] & mask) != mask )
   {
      // Reset the selection
      NSAssert( _processingViewReg != nil, @"Current process view has no registry" );
      NSMutableString *curIdent = [NSMutableString stringWithString:toolbarProcPrefix];
      [curIdent appendString: [_processingViewReg->controller className]];
      if ( _processingViewReg->ident != nil )
         [curIdent appendString:_processingViewReg->ident];
      [_toolBar setSelectedItemIdentifier:curIdent];
      return;
   }

   // Switch data mode if the current one is not compatible with the process
   if ( (_processingAuthorization[tag] & _dataMode) == 0 )
      [(MyDocument*)[self document] setDataMode: (_dataMode == ListData ? ResultData : ListData)];

   // Retrieve the controller
   LynkeosProcessingViewRegistry *reg = [procList objectAtIndex:tag];
   NSAssert( reg != nil, @"Could not find process view registry" );

   if ( _processingViewReg != nil && _processingViewReg == reg )
      // The selection did not change
      return;

   // And get the cached view controller, if any
   NSMutableString *procIdent = [NSMutableString stringWithString:toolbarProcPrefix];
   [procIdent appendString:[reg->controller className]];
   if ( reg->ident != nil )
      [procIdent appendString:reg->ident];
   MyProcessViewDefinition *def = [_processingViewDict objectForKey:procIdent];

   if ( def == nil )
   {
      // Allocate a new controller as it was not in the cache
      def = [[[MyProcessViewDefinition alloc] init] autorelease];

      def->_viewController =
               [[reg->controller alloc] initWithWindowController:self
                                                        document:[self document]
                                                   configuration:reg->config];
      def->_view = [def->_viewController getProcessingView];
      def->_currentFrame = [def->_viewController preferredDisplay];
      def->_processIndex = tag;
      def->_menuItem = [_processMenu itemWithTag: tag];
      def->_title = [[NSString stringWithString:[def->_menuItem title]] retain];

      [_processingViewDict setObject:def forKey:procIdent];
   }

   // Uncheck the previous process in the menu
   if ( _processingViewController != nil )
   {
      [_processingViewController setActiveView:NO];
      NSMenuItem *oldItem = [_processMenu itemWithTag:[procList indexOfObject: _processingViewReg]];
      [oldItem setState: NSOffState];
   }

   // Clean up any selections left by the previous controller, if any
   [_imageView removeAllSelections];
   [_imageView setSelectionMode:NoSelection];

   // Change the name of the separate window to reflect the new process
   [_processWindow setTitle: def->_title];

   // Note if we shall display the progress
   if ( [reg->controller respondsToSelector:@selector(hasProgressIndicator)]
        && [reg->controller hasProgressIndicator] )
      _displayProgress = NO;
   else
      _displayProgress = YES;

   [self setProcessView: def->_view withDisplay: def->_currentFrame];

   [def->_viewController setActiveView: YES];
   [[self window] makeFirstResponder: def->_view];

   _processingViewController = def->_viewController;
   _processingViewReg = reg;
   _processingViewDef = def;
   _authorizedProcessDisplays = [reg->controller allowedDisplaysForConfig: reg->config];
   [self validateSplitControls];

   // Set the selections
   if ( ![sender isMemberOfClass: [NSToolbarItem class]] )
      [_toolBar setSelectedItemIdentifier: procIdent];

   [[_processMenu itemWithTag:tag] setState: NSOnState];
}

#pragma mark = NIB Actions
- (void) highlightNext :(id)sender
{
   [self highlightOther:K_DOWN skipUnselected:YES];
}

- (void) highlightPrevious :(id)sender
{
   [self highlightOther:K_UP skipUnselected:YES];
}

// Buttons or menu actions
- (void) modeMenuAction :(id)sender
{
   _highlightedItem = nil; // Hilight may be inconsistent until notified back
   [(MyDocument*)[self document] setListMode:(int)[sender selectedTag]];
}

- (IBAction) dataModeAction :(id)sender
{
   _highlightedItem = nil; // Hilight may be inconsistent until notified back
   [(MyDocument*)[self document] setDataMode:(int)[sender selectedTag]];
}

- (void) addAction :(id)sender
{
   // Ask the user to choose some images/movies
   NSOpenPanel* panel = [NSOpenPanel openPanel];
   NSArray *URLs;

   [panel setAllowedFileTypes:[MyImageListItem imageListItemFileTypes]];
   [panel setAllowsMultipleSelection:YES];
   if ( [panel runModal] == NSModalResponseOK )
   {
      URLs = [panel URLs];

      // And add their objects to the document
      [self addURLs:URLs];
   }
}

#pragma mark Other
- (void) delete:(id)sender
{
   NSInteger sel = [_textView selectedRow];
   id item = [_textView itemAtRow:sel];

   [(MyDocument*)[self document] deleteEntry:item];
}

- (void) addURLs :(NSArray*)URLs
{
   NSEnumerator* list;
   NSURL *url;

   // Set the watch cursor
   [[self window] disableCursorRects];
   [myWatchCursor push];

   // Add their objects to the document
   list = [URLs objectEnumerator];
   while ( (url = [list nextObject]) != nil )
   {
      MyImageListItem *item;

      item = [MyImageListItem imageListItemWithURL: url];

      if ( item != nil )
      {
         [item setMode:_listMode];
         [(MyDocument*)[self document] addEntry: item];
      }
      else
      {
         [LynkeosAlertPanel runAlertWithTitle:NSLocalizedString(@"BadFileTitle",
                                                                @"Bad format file alert panel title")
                                        style:NSAlertStyleCritical
                                      message:[NSString stringWithFormat:NSLocalizedString(@"BadFile",
                                                                                           @"Message of bad file alert message"),
                                                                         [url absoluteString]]];
      }
   }

   // Revert the cursor to its normal state when we finished adding
   [NSCursor pop];
   [[self window] enableCursorRects];
}

- (void) reloadData
{
   if (_dataMode == ListData && !_outlineDisplay)
   { // Re-sort before reloading
      // Find the sort column description
      LynkeosColumnDescription *desc = [_columnsDescriptor objectForKey:_sortColumn];
      NSMutableArray *unsortedItems = [NSMutableArray array];
      NSEnumerator *listEnum = [_currentList imageEnumerator];
      MyImageListItem *item;
      
      while ((item = [listEnum nextObject]) != nil)
         [unsortedItems addObject:item];
      
      if (_sortedItems != nil)
         [_sortedItems release];
      if (desc != nil)
      {
#if !GNUSTEP
         _sortedItems = [unsortedItems sortedArrayUsingComparator: ^(id obj1, id obj2) {
            
            NSObject <LynkeosProcessingParameter> *param1 =
            [obj1 getProcessingParameterWithRef:desc->_parameterReference
                                  forProcessing:desc->_processingRef];
            NSObject <LynkeosProcessingParameter> *param2 =
            [obj2 getProcessingParameterWithRef:desc->_parameterReference
                                  forProcessing:desc->_processingRef];
            NSObject *field1 = nil, *field2 = nil;
            if (param1 != nil)
               field1 = objectFromNSValue([param1 valueForKey:desc->_fieldName]);
            if (param2 != nil)
               field2 = objectFromNSValue([param2 valueForKey:desc->_fieldName]);
            
            if (field1 == nil)
            {
               if (field2 == nil)
                  return NSOrderedSame;
               else if (_sortUp)
                  return NSOrderedAscending;
               else
                  return NSOrderedDescending;
            }
            else if (field2 == nil)
            {
               if (_sortUp)
                  return NSOrderedDescending;
               else
                  return NSOrderedAscending;
            }
            else
            {
               if ([field1 isKindOfClass:[NSNumber class]])
               {
                  NSNumber *num1 = (NSNumber*)field1;
                  NSNumber *num2 = (NSNumber*)field2;
                  if (_sortUp)
                     return [num1 compare:num2];
                  else
                     return [num2 compare:num1];
               }
               else if ([field1 isKindOfClass:[NSString class]])
               {
                  NSString *str1 = (NSString*)field1;
                  NSString *str2 = (NSString*)field2;
                  if (_sortUp)
                     return [str1 localizedStandardCompare:str2];
                  else
                     return [str2 localizedStandardCompare:str1];
               }
               else
               {
                  NSLog(@"Unsupported type for sorting %@", [[field1 class] description]);
                  return NSOrderedSame;
               }
            }
         }];
#else
         struct _sortCtxt context;
         context.desc = desc;
         context.sortUp = _sortUp;
         _sortedItems = [unsortedItems sortedArrayUsingFunction:sortFunc context:(void *)&context];
#endif
      }
      else
         // Best effort...
         _sortedItems = unsortedItems;
      
      [_sortedItems retain];
   }
   
   [_textView reloadData];

   // Make sure the selection follows the currently selected item
   [self highlightItem:_highlightedItem];
}

- (void) reloadItem:(id<LynkeosProcessableItem>)item
{
   [_textView reloadItem:item reloadChildren:YES];
}

- (void) toggleEntrySelection :(id)sender
{
   if( _highlightedItem != nil )
      [(MyDocument*)[self document] changeEntrySelection :_highlightedItem
                     value:([_highlightedItem getSelectionState] != NSOnState)];
}

- (void) fileWritersPopupAction : (id)sender
{
   Class writer = [_currentWriters objectAtIndex:[sender indexOfSelectedItem]];
   [_savePanel setAllowedFileTypes:[NSArray arrayWithObject:[writer fileExtension]]];
}

- (IBAction) hideImageMargin:(id)sender
{
   NSAssert1( _currentProcessDisplay != SeparateView_NoList,
             @"Hide margin pressed in display mode %d", _currentProcessDisplay );

   [self setProcessView:_processingView withDisplay:SeparateView_NoList];
   _processingViewDef->_currentFrame = SeparateView_NoList;
}

- (IBAction) shareMargin:(id)sender
{
   NSAssert1( _currentProcessDisplay == BottomTab_NoList
              || _currentProcessDisplay == SeparateView,
              @"Hide margin pressed in display mode %d",
              _currentProcessDisplay );

   [self setProcessView:_processingView withDisplay:BottomTab];
   _processingViewDef->_currentFrame = BottomTab;
}

- (void) showHideImageList:(id)sender
{
   LynkeosProcessingViewFrame_t display = BottomTab;

   switch( _currentProcessDisplay )
   {
      case BottomTab:            display = BottomTab_NoList; break;
      case BottomTab_NoList:     display = BottomTab; break;
      case SeparateView:         display = SeparateView_NoList; break;
      case SeparateView_NoList:  display = SeparateView; break;
      default:
         NSAssert( NO, @"Invalid process display state" );
   }

   [self setProcessView:_processingView withDisplay:display];
   _processingViewDef->_currentFrame = display;
}

- (void) attachDetachProcessView:(id)sender
{
   LynkeosProcessingViewFrame_t display = BottomTab;

   switch( _currentProcessDisplay )
   {
      case BottomTab:            display = SeparateView; break;
      case BottomTab_NoList:     display = SeparateView_NoList; break;
      case SeparateView:         display = BottomTab; break;
      case SeparateView_NoList:  display = BottomTab_NoList; break;
      default:
         NSAssert( NO, @"Invalid process display state" );
   }

   [self setProcessView:_processingView withDisplay:display];
   _processingViewDef->_currentFrame = display;
}

- (void) saveStackedImage :(id)sender
{
   id <LynkeosProcessableItem> item = nil;
   LynkeosImageBuffer *img;

   // Get the active item
   switch ( _dataMode )
   {
       case ListData:
          if ( _highlightedItem != nil
              && [_highlightedItem numberOfChildren] == 0 )
             item = _highlightedItem;
          break;
       case ResultData: item = _currentList; break;
       default: NSAssert1( NO, @"Invalid data mode %d", _dataMode );
   }

   NSAssert( item != nil, @"Attempt to save a nil item" );

   // Retrieve the image
   img = [item getImage];
   NSAssert( img != nil, @"Attempt to save a nil image" );
   const u_short nPlanes = [item numberOfPlanes];
   double black[nPlanes+1], white[nPlanes+1], gamma[nPlanes+1];
   u_short i;

   [item getBlackLevel:&black[nPlanes] whiteLevel:&white[nPlanes]
                 gamma:&gamma[nPlanes]];
   for( i = 0; i < nPlanes; i++ )
      [item getBlackLevel:&black[i] whiteLevel:&white[i] gamma:&gamma[i]
                 forPlane:i];

   NSMutableDictionary *mDict
      = [NSMutableDictionary dictionaryWithDictionary:[item getMetaData]];
#if !GNUSTEP
   NSArray *app = [mDict objectForKey:LynkeosMD_CreatorApp()];
   if (app == nil)
      [mDict setObject:[NSArray arrayWithObject:LynkeosName] forKey:LynkeosMD_CreatorApp()];
   else if (![app containsObject:LynkeosName])
      [mDict setObject:[app arrayByAddingObject:LynkeosName] forKey:LynkeosMD_CreatorApp()];
#endif

   // Save it
   [self saveImage:img withBlack:black white:white gamma:gamma metadata:mDict];
}

- (void) exportMovie :(id)sender
{
   NSAssert( _dataMode == ListData, @"Wrong data mode for exporting a movie");
   NSAssert( _currentList != nil, @"No list to export a movie");

   // Check that a crop rectangle was set
   MyImageStackerParameters *params
      = [_currentList getProcessingParameterWithRef:myImageStackerParametersRef
                                      forProcessing:myImageStackerRef];
   if (params == nil
       || params->_cropRectangle.size.width == 0 || params->_cropRectangle.size.height == 0)
   {
      [LynkeosAlertPanel runAlertWithTitle:NSLocalizedString(@"NoRectForExportTitle",
                                                             @"Title for movie export crop rectangle")
                                     style:NSAlertStyleCritical
                                   message:NSLocalizedString(@"NoRectForExport",
                                                             @"Text for movie export crop rectangle")];
      return;
   }

   double black, white, gamma;

   [_imageView getBlack:&black white:&white gamma:&gamma];
   
   // Save it
   [self exportMovieFromList:_currentList withParams:params
                   withBlack:black white:white gamma:gamma];
}

- (IBAction) cancelMovieExport : (id)sender
{
   [NSApp stopModalWithCode:NSModalResponseCancel];
}

#pragma mark LynkeosMovieFileWriterDelegate

- (void) getNextFrameWithData:(const REAL * const * *)planes
                    lineWidth:(u_short*)lineW
                       opaque:(void*)opaque
                     canceled:(BOOL*)canceled
{
   MovieExportCtrl_t *ctrl = (MovieExportCtrl_t*)opaque;
   LynkeosProcessableImage *img = [ctrl->imgList nextObject];

   *canceled = NO; // By default

   if (img != nil)
   {
      NSPoint offsets[3] = {{0.0}, {0.0}, {0.0}};
      LynkeosIntegerRect r = ctrl->cropRectangle;
      u_short x, y, c;

      id <LynkeosAlignResult> alignRes
         = (id <LynkeosAlignResult>)[img getProcessingParameterWithRef: LynkeosAlignResultRef
                                                         forProcessing: LynkeosAlignRef];

      if ( alignRes != nil )
      {
         NSAffineTransform *transform
            = [[[NSAffineTransform alloc] initWithTransform:[alignRes alignTransform]] autorelease];
         NSAffineTransformStruct t;

         // Take stacking transform into account, and convert to bitmap coordinate system
         [transform appendTransform:ctrl->transform];
         t = [transform transformStruct];
         const CGFloat imgHeight = [img imageSize].height;
         t.tX += t.m21*imgHeight;
         t.tY = (1.0 - t.m22)*imgHeight - t.tY;
         t.m12 *= -1.0;
         t.m21 *= -1.0;

         r.origin.y =  imgHeight - r.origin.y - r.size.height;

         // Take the chromatic dispersion correction into account
         MyChromaticAlignParameter *chroma
            = [img getProcessingParameterWithRef:myChromaticAlignerOffsetsRef
                                   forProcessing:myChromaticAlignerRef];

         // Prepare the offsets, with conversion to the bitmap coordinate system
         for( c = 0; c < ctrl->nPlanes; c++ )
         {
            if ( chroma != nil )
            {
               offsets[c].x += chroma->_offsets[c].x;
               offsets[c].y -= chroma->_offsets[c].y;
            }
         }

         [img getImageSample:&ctrl->sample inRect:r withTransform:t withOffsets:offsets];
      }
      else
         [img getImageSample:&ctrl->sample inRect:r];

      double a = 1.0/(ctrl->white - ctrl->black);

      LynkeosGammaCorrecter *gammaCorrect
         = [LynkeosGammaCorrecter getCorrecterForGamma: ctrl->gamma];

      for( c = 0; c < ctrl->nPlanes; c++ )
      {
         for( y = 0; y < ctrl->sample->_h; y++ )
         {
            for( x = 0; x < ctrl->sample->_w; x++ )
            {
               colorValue(ctrl->sample,x,y,c) =
               correctedValue( gammaCorrect,
                               (colorValue(ctrl->sample,x,y,c) - ctrl->black) * a);
            }
         }
      }
      [gammaCorrect releaseCorrecter];

      *planes = (const REAL * const *)[ctrl->sample colorPlanes];
      *lineW = ctrl->sample->_padw;

      [_exportProgressIndicator setDoubleValue:[_exportProgressIndicator doubleValue] + 1.0];
      if ([NSApp runModalSession: _exportProgressSession] == NSModalResponseCancel)
         *canceled = YES;
   }
   else
      // Finished
      *planes = NULL;
}
@end