File: MyPluginsController.m

package info (click to toggle)
lynkeos.app 3.8%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 6,740 kB
  • sloc: objc: 40,528; ansic: 811; cpp: 150; sh: 68; makefile: 27
file content (588 lines) | stat: -rw-r--r-- 18,911 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
//
//  Lynkeos
//  $Id$
//
//  Created by Jean-Etienne LAMIAUD on Fri Mar 2, 2007.
//  Copyright (c) 2007-2023. 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.
//

#ifdef GNUSTEP

#include <GNUstepBase/GSObjCRuntime.h>

#else

#include <Carbon/Carbon.h>
#include <objc/objc-runtime.h>

#endif

#define getClassList(c,n) objc_getClassList(c, n);

#include "processing_core.h"
#include "LynkeosFileReader.h"
#include "LynkeosFileWriter.h"
#include "LynkeosProcessingView.h"
#include "MyImageListWindow.h"
#include "LynkeosPreferences.h"
#include "LynkeosInterpolator.h"
#include "LynkeosAlertPanel.h"
#include "MyCachePrefs.h"
#include "MyGuiConstants.h"
#include "MyPluginsController.h"

NSString * const MyPluginsInitializedNotification = @"MyPluginsInitialized";

NSString * const LynkeosPluginName = @"PluginName";
NSString * const LynkeosPluginHelpFile = @"PluginHelpFile";

static MyPluginsController *myInstance = nil;

@implementation LynkeosReaderRegistry
+ (void) load
{
   // Nothing to do, but the zero-linker dumps this class if it is not defined
}
@end

@implementation LynkeosProcessingViewRegistry
+ (void) load
{
   // Nothing to do, but the zero-linker dumps this class if it is not defined
}

- (id) init
{
   if ( (self = [super init]) != nil )
   {
      config = nil;
      ident = nil;
   }

   return( self );
}

- (void) dealloc
{
   if ( config != nil )
      [config release];
   if ( ident != nil )
      [ident release];
   [super dealloc];
}

- (NSComparisonResult)caseInsensitiveCompare:(LynkeosProcessingViewRegistry*)reg
{
   NSString *myName, *otherName;
   NSString *tool, *key, *tip;
   NSImage *icon;

   [controller getProcessingTitle:&myName toolTitle:&tool
                              key:&key icon:&icon tip:&tip
                        forConfig:config];
   [reg->controller getProcessingTitle:&otherName toolTitle:&tool
                                   key:&key icon:&icon tip:&tip
                        forConfig:reg->config];

   return( [myName caseInsensitiveCompare:otherName] );
}
@end

//! Comparison function for sorting writers by name
static NSComparisonResult compareWriters( id obj1, id obj2, void *ctx )
{
   return( [[obj1 writerName] caseInsensitiveCompare:[obj2 writerName]] );
}

@interface MyPluginsController(Private)
- (void) loadPlugins ;
- (void) processReaderClass:(Class)theClass;
- (void) processWriterClass:(Class)theClass;
- (void) processProcessingViewClass:(Class)theClass;
- (void) processPreferencesClass:(Class)theClass;
- (void) processInterpolatorClass:(Class)theClass;
- (void) finalizeReaders ;
- (void) finalizeWriters ;
- (void) finalizeProcessingViews ;
- (void) finalizePreferences ;
- (void) finalizeInterpolators ;
- (void) retrieveClasses ;
- (void) updateProcessMenu:(NSMenu*)procMenu forKind:(ProcessingViewKind_t)kind ;
- (void) updateGUI ;
- (void) openPluginHelp:(id)sender ;
@end

@implementation MyPluginsController(Private)
- (void) loadPlugins
{
   NSFileManager *fMgr = [NSFileManager defaultManager];
   NSMutableArray *bundleSearchPaths = [NSMutableArray array];
   NSArray *librarySearchPaths;
   NSEnumerator *searchPathEnum;
   NSString *currPath;
   NSBundle *currBundle;

#ifndef NO_FRAMEWORK_CHECK
   NSError *err;

   // Delete the LynkeosCore framework, if obsolete, from our home folder
   // It could allow obsolete plugins to load and crash Lynkeos
   NSString *framework = @"/Library/Frameworks/LynkeosCore.framework";
   NSString *homeFramework = [NSString stringWithFormat:@"%@%@",
                                 NSHomeDirectory(), framework];

   if ( [fMgr fileExistsAtPath:homeFramework] &&
       ![fMgr fileExistsAtPath:[homeFramework stringByAppendingFormat:
                                  @"/Versions/%s", FRAMEWORK_VERSION]] )
   {
      if ( ![fMgr removeItemAtPath:homeFramework error:&err] )
      {
         NSLog( @"Cannot remove obsolete LynkeosCore.framework, error : %@",
                [err localizedDescription] );
         [LynkeosAlertPanel runAlertWithTitle:NSLocalizedString(@"ObsoleteFrameworkTitle",
                                                                @"Obsolete system framework alert panel title")
                                        style:NSAlertStyleCritical
                                      message:[NSString stringWithFormat:
                                                  NSLocalizedString(@"ObsoleteFrameworkText",
                                                                    @"Obsolete system framework text"),
                                                  homeFramework]];
      }
   }

   // If an obsolete framework is present in the system folder, we can not
   // remove it. Therefore, alert the user
   if ( [fMgr fileExistsAtPath:framework] &&
        ![fMgr fileExistsAtPath:[framework stringByAppendingFormat:
                                              @"/Versions/%s", FRAMEWORK_VERSION]] )
   {
      [LynkeosAlertPanel runAlertWithTitle:NSLocalizedString(@"ObsoleteFrameworkTitle",
                                                             @"Obsolete system framework alert panel title")
                                     style:NSAlertStyleCritical
                                   message:[NSString stringWithFormat:
                                               NSLocalizedString(@"ObsoleteFrameworkText",
                                                                 @"Obsolete system framework text"),
                                               framework]];
   }
#endif

   // Build the plugins paths list
   librarySearchPaths = NSSearchPathForDirectoriesInDomains(
                NSLibraryDirectory, NSAllDomainsMask - NSSystemDomainMask, YES);

   searchPathEnum = [librarySearchPaths objectEnumerator];
   while( (currPath = [searchPathEnum nextObject]) != nil )
      [bundleSearchPaths addObject: [currPath stringByAppendingPathComponent:
                                       @"Application Support/Lynkeos/PlugIns"]];

   [bundleSearchPaths addObject: [[NSBundle mainBundle] builtInPlugInsPath]];

   // Load every plugin in each directory
   searchPathEnum = [bundleSearchPaths objectEnumerator];
   while( (currPath = [searchPathEnum nextObject]) != nil )
   {
      NSDirectoryEnumerator *bundleEnum;
      NSString *currBundlePath;

      bundleEnum = [fMgr enumeratorAtPath:currPath];

      if(bundleEnum)
      {
         while( (currBundlePath = [bundleEnum nextObject]) != nil )
         {
            if( [[currBundlePath pathExtension] isEqualToString:@"bundle"] )
            {
               currBundle = [NSBundle bundleWithPath:
                               [currPath stringByAppendingPathComponent:
                                                               currBundlePath]];
               if( currBundle != nil )
               {
                  if ( [currBundle load] )
                     [_bundlesList addObject:currBundle];
               }
            }
         }
      }
   }
}

- (void) processWriterClass:(Class)theClass
{
   // This test is to make sure we don't send conformsToProtocol to 
   // something which will assert when receiving it
   if ( class_getClassMethod(theClass,
                         @selector(writerForURL:planes:width:height:metaData:)) != NULL )
   {
      if ( [theClass conformsToProtocol:@protocol(LynkeosImageFileWriter)] )
         [_imageWritersList addObject:theClass];
      else if ( [theClass conformsToProtocol:@protocol(LynkeosMovieFileWriter)] )
         [_movieWritersList addObject:theClass];
   }
}

- (void) processProcessingViewClass:(Class)theClass
{
   // Same test to avoid assert
   if ( class_getClassMethod(theClass,
                             @selector(isStandardProcessingViewController)) != NULL
        && [theClass conformsToProtocol:@protocol(LynkeosProcessingView)] )
   {
      if ( [theClass isStandardProcessingViewController] )
         [self registerProcessingViewController:theClass
                              withConfiguration:nil
                                     identifier:nil];
   }
}

- (void) processReaderClass:(Class)theClass
{
   if ( class_getClassMethod(theClass, @selector(lynkeosFileTypes:)) != NULL )
   {
      NSArray *types;

      // Store the file types that this class handles
      [theClass lynkeosFileTypes:&types];

      if ( types != nil )
      {
         NSEnumerator *list = [types objectEnumerator];
         id item;
         NSString *oneType;

         while( (item = [list nextObject]) != nil )
         {
            LynkeosReaderRegistry *entry =
                                    [[LynkeosReaderRegistry alloc] autorelease];
            NSMutableArray *registry;

            // If a NSNumber is in the list, it is the priority of the 
            // following file type for this item
            if ( [item isKindOfClass:[NSNumber class]] )
            {
               entry->priority = [item intValue];
               oneType = [list nextObject];
            }
            else
            {
               entry->priority = 0;
               oneType = item;
            }

            entry->reader = theClass;

            // Find this file type in the right dictionary
            NSMutableDictionary *dict = nil;

            if ( [theClass conformsToProtocol:
                                            @protocol(LynkeosImageFileReader)] )
               dict = _imageReadersDict;
            else if ( [theClass conformsToProtocol:
                                            @protocol(LynkeosMovieFileReader)] )
               dict = _movieReadersDict;
            else
               NSAssert(NO,
                       @"Found a Lynkeos file reader not for image nor movie" );

            registry = [dict objectForKey:oneType];
            if ( registry == nil )
            {
               // This file type is not registered yet
               registry = [NSMutableArray arrayWithCapacity:1];
               [dict setObject:registry forKey:oneType];
            }

            // Add this reader (priorities will be sorted later)
            [registry addObject:entry];
         }
      }
   }
}

- (void) processPreferencesClass:(Class)theClass
{
   // Same test to avoid assert
   if ( class_getClassMethod(theClass, @selector(getPreferenceInstance)) != NULL
        && [theClass conformsToProtocol:@protocol(LynkeosPreferences)] )
   {
      [_preferencesList addObject:theClass];
   }
}

- (void) processInterpolatorClass:(Class)theClass
{
   // Same test to avoid assert
   if ( class_getClassMethod(theClass, @selector(isCompatibleWithScaling:withTransform:)) != NULL
       && [theClass conformsToProtocol:@protocol(LynkeosInterpolator)] )
   {
      [_interpolatorsList addObject:theClass];
   }
}

- (void) finalizeProcessingViews
{
}

- (void) finalizeReaders
{
}

- (void) finalizeWriters
{
   // Sort the writers by name
   [_imageWritersList sortUsingFunction:compareWriters context:NULL];
   [_movieWritersList sortUsingFunction:compareWriters context:NULL];
}

- (void) finalizePreferences
{
}

- (void) finalizeInterpolators
{
}

- (void) retrieveClasses
{
   int numClasses, i;
   Class * classes = NULL;

   // Iterate over every classes to find plugin classes
   numClasses = getClassList(NULL, 0);

   if( numClasses > 0 )
   {
      classes = malloc( sizeof(Class) * numClasses );

      (void)getClassList( classes, numClasses );

      for( i = 0; i < numClasses; i++ )
      {
         Class c = classes[i];

         // Retrieve every kind of helper classes we use
         @try
         {
            [self processReaderClass:c];
            [self processWriterClass:c];
            [self processProcessingViewClass:c];
            [self processPreferencesClass:c];
            [self processInterpolatorClass:c];
         }
         @catch (NSException *exception)
         {
            // This class simply cannot be used
            NSLog(@"Exception in plugin initialisation, in class %@", [c className]);
         }
      }

      free(classes);
   }

   [self finalizeReaders];
   [self finalizeWriters];
   [self finalizeProcessingViews];
   [self finalizePreferences];
   [self finalizeInterpolators];
}

- (void) updateProcessMenu:(NSMenu*)procMenu forKind:(ProcessingViewKind_t)kind
{
   NSEnumerator *list = [_processingViewsList objectEnumerator];
   LynkeosProcessingViewRegistry *reg;
   NSMutableArray *kindList = [NSMutableArray array];

   // Extract all the processing view controllers for this kind
   while ( (reg = [list nextObject]) != nil )
   {
      if ( [reg->controller processingViewKindForConfig:reg->config] == kind )
         [kindList addObject:reg];
   }

   // Add to the menu if any controller was found
   if ( [kindList count] != 0 )
   {
      if ( kind != ListManagementKind )
      {
         // Place a separator
         NSMenuItem *sep = [NSMenuItem separatorItem];
         [sep setTag:-1];     // -1 to avoid confusion with the first process
         [procMenu addItem:sep];
      }

      // Sort the controllers by name
      [kindList sortUsingSelector:@selector(caseInsensitiveCompare:)];

      // Add a menu item for each controller
      list = [kindList objectEnumerator];
      while ( (reg = [list nextObject]) != nil )
      {
         NSString *title, *tool, *key, *tip;
         NSImage *icon;

         [reg->controller getProcessingTitle:&title toolTitle:&tool
                                         key:&key icon:&icon tip:&tip
                                   forConfig:reg->config];
         NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:title
                                       action:@selector(activateProcessingView:)
                                                keyEquivalent:key];
         if ( [key length] != 0 )
            [item setKeyEquivalentModifierMask: NSEventModifierFlagCommand|NSEventModifierFlagControl];
         if ( tip != nil )
            [item setToolTip:tip];
         NSUInteger tag = [_processingViewsList indexOfObject:reg];
         NSAssert( tag != NSNotFound,
                   @"Unknown processing class for menu item" );
         [item setTag:(NSInteger)tag];
         [procMenu addItem:item];
      }
   }
}

- (void) updateGUI
{
   // Populate the process menu
   NSMenu *procMenu = [[[NSApp mainMenu] itemWithTag:K_PROCESS_MENU_TAG] submenu];
   ProcessingViewKind_t k;

   for( k = ListManagementKind; k <= OtherProcessingKind; k++ )
      [self updateProcessMenu:procMenu forKind:k];

   // And populate the plugin help menu
   NSMenu *helpMenu = [[[NSApp mainMenu] itemWithTag:K_HELP_MENU_TAG] submenu];
   NSMenuItem *pluginHelp = [helpMenu itemWithTag:K_PLUGIN_HELP_MENU_TAG];
   NSEnumerator *bundleList = [_bundlesList objectEnumerator];
   NSBundle *bundle;

   helpMenu = [pluginHelp submenu];
   while( (bundle = [bundleList nextObject]) != nil )
   {
      // Get the help if present
      NSString *helpBook = [bundle objectForInfoDictionaryKey: @"CFBundleHelpBookName"];
      if (helpBook != nil)
      {
#if !GNUSTEP
         BOOL success = [[NSHelpManager sharedHelpManager] registerBooksInBundle:bundle];
#else
         BOOL success = NO;
#endif
         if (success)
         {
            NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:
                                   [bundle objectForInfoDictionaryKey:@"CFBundleName"]
                                                          action:@selector(openPluginHelp:)
                                                   keyEquivalent:@""];

            [item setTarget:self];
            [item setRepresentedObject:helpBook];
            [helpMenu addItem:item];
         }
      }
   }
}

- (void) openPluginHelp:(id)sender
{
#if !defined GNUSTEP
   NSString *name = [sender representedObject];
   [[NSHelpManager sharedHelpManager] openHelpAnchor:name inBook:name];
#endif
}
@end

@implementation MyPluginsController

+ (MyPluginsController*) defaultPluginController
{
   if ( myInstance )
     return( myInstance );
   else
     [[self alloc] init];

   NSAssert( myInstance != nil, @"The plugin controller is not created" );
   return( myInstance );
}

- (id) init
{
   if ( (self = [super init]) != nil )
   {
      _imageReadersDict = [[NSMutableDictionary dictionary] retain];
      _movieReadersDict = [[NSMutableDictionary dictionary] retain];
      _imageWritersList = [[NSMutableArray array] retain];
      _movieWritersList = [[NSMutableArray array] retain];
      _processingViewsList = [[NSMutableArray array] retain];
      _preferencesList = [[NSMutableArray array] retain];
      _interpolatorsList = [[NSMutableArray array] retain];
      _bundlesList = [[NSMutableArray array] retain];

      // Load every plugins from their locations
      [self loadPlugins];
      // Retrieve the helpers classes, whether compiled in or a loaded plugin
      [self retrieveClasses];

      myInstance = self;
   }

   return( self );
}

- (void) dealloc
{
   myInstance = nil;

   [_imageReadersDict release];
   [_movieReadersDict release];
   [_imageWritersList release];
   [_movieWritersList release];
   [_processingViewsList release];
   [_preferencesList release];
   [_interpolatorsList release];
   [_bundlesList release];

   [super dealloc];
}

- (void) awakeFromNib
{
   // Update the main menu with processing actions
   [self updateGUI];
}

- (void) registerProcessingViewController:(Class)c
                        withConfiguration:(id)config
                               identifier:(NSString*)ident
{
   LynkeosProcessingViewRegistry *reg =
                     [[[LynkeosProcessingViewRegistry alloc] init] autorelease];

   reg->controller = c;
   reg->config = [config retain];
   reg->ident = [ident retain];

   [_processingViewsList addObject:reg];

}

- (NSDictionary*) getImageReaders { return( _imageReadersDict ); }
- (NSDictionary*) getMovieReaders { return( _movieReadersDict ); }
- (NSArray*) getImageWriters { return( _imageWritersList ); }
- (NSArray*) getMovieWriters { return( _movieWritersList ); }
- (NSArray*) getProcessingViews { return( _processingViewsList ); }
- (NSArray*) getPreferencesPanes { return( _preferencesList ); }
- (NSArray*) getInterpolators { return( _interpolatorsList ); }
- (NSArray*) getLoadedBundles { return( _bundlesList ); }

@end