File: itkObjectFactoryBase.cxx

package info (click to toggle)
insighttoolkit 3.6.0-3
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 94,956 kB
  • ctags: 74,981
  • sloc: cpp: 355,621; ansic: 195,070; fortran: 28,713; python: 3,802; tcl: 1,996; sh: 1,175; java: 583; makefile: 415; csh: 184; perl: 175
file content (716 lines) | stat: -rw-r--r-- 16,831 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
/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile: itkObjectFactoryBase.cxx,v $
  Language:  C++
  Date:      $Date: 2007-12-26 17:55:49 $
  Version:   $Revision: 1.56 $

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

  Portions of this code are covered under the VTK copyright.
  See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even 
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkObjectFactoryBase.h"
#include "itkDynamicLoader.h"
#include "itkDirectory.h"
#include "itkVersion.h"
#include <stdlib.h>
#include <ctype.h>
#include <algorithm>
#include <map>

namespace
{
  
class CleanUpObjectFactory
{
public:
  inline void Use() 
    {
    }
  ~CleanUpObjectFactory()
    {
    itk::ObjectFactoryBase::UnRegisterAllFactories();
    }  
};
static CleanUpObjectFactory CleanUpObjectFactoryGlobal;
}

namespace itk
{

/**
 * Add this for the SGI compiler which does not seem
 * to provide a default implementation as it should.
 */
bool operator==(const ObjectFactoryBase::OverrideInformation& rhs, 
                const ObjectFactoryBase::OverrideInformation& lhs)
{
  return (rhs.m_Description == lhs.m_Description
       && rhs.m_OverrideWithName == lhs.m_OverrideWithName);
}

/**
 * Add this for the SGI compiler which does not seem
 * to provide a default implementation as it should.
 */
bool operator<(const ObjectFactoryBase::OverrideInformation& rhs, 
               const ObjectFactoryBase::OverrideInformation& lhs)
{
  return (rhs.m_Description < lhs.m_Description
          && rhs.m_OverrideWithName < lhs.m_OverrideWithName);
}


/** \class StringOverMap
 * \brief Internal implementation class for ObjectFactorBase.
 *
 * Create a sub class to shrink the size of the symbols
 * Also, so a forward reference can be put in ObjectFactoryBase.h
 * and a pointer member can be used.  This avoids other
 * classes including <map> and getting long symbol warnings.
 */
typedef std::multimap<std::string, ObjectFactoryBase::OverrideInformation> 
StringOverMapType;

/** \class OverRideMap
 * \brief Internal implementation class for ObjectFactorBase.
 */
class OverRideMap : public StringOverMapType
{
public:
};

/**
 * Initialize static list of factories.
 */
std::list<ObjectFactoryBase*>* 
ObjectFactoryBase::m_RegisteredFactories = 0;


/**
 * Create an instance of a named itk object using the loaded
 * factories
 */
LightObject::Pointer 
ObjectFactoryBase
::CreateInstance(const char* itkclassname)
{
  if ( !ObjectFactoryBase::m_RegisteredFactories )
    {
    ObjectFactoryBase::Initialize();
    }
  
  for ( std::list<ObjectFactoryBase*>::iterator 
          i = m_RegisteredFactories->begin();
        i != m_RegisteredFactories->end(); ++i )
    {
    LightObject::Pointer newobject = (*i)->CreateObject(itkclassname);
    if(newobject)
      {
      newobject->Register();
      return newobject;
      }
    }
  return 0;
}


std::list<LightObject::Pointer>
ObjectFactoryBase
::CreateAllInstance(const char* itkclassname)
{
  if ( !ObjectFactoryBase::m_RegisteredFactories )
    {
    ObjectFactoryBase::Initialize();
    }
  std::list<LightObject::Pointer> created;
  for ( std::list<ObjectFactoryBase*>::iterator 
          i = m_RegisteredFactories->begin();
        i != m_RegisteredFactories->end(); ++i )
    {
    LightObject::Pointer newobject = (*i)->CreateObject(itkclassname);
    if(newobject)
      {
      created.push_back(newobject);
      }
    }
  return created;
}


/**
 * A one time initialization method.
 */
void 
ObjectFactoryBase
::Initialize()
{
  CleanUpObjectFactoryGlobal.Use();
  /**
   * Don't do anything if we are already initialized
   */
  if ( ObjectFactoryBase::m_RegisteredFactories )
    {
    return;
    }
  
  ObjectFactoryBase::m_RegisteredFactories =
    new std::list<ObjectFactoryBase*>;
  ObjectFactoryBase::RegisterDefaults();
  ObjectFactoryBase::LoadDynamicFactories();
}


/**
 * Register any factories that are always present in ITK like
 * the OpenGL factory, currently this is not done.
 */
void 
ObjectFactoryBase
::RegisterDefaults()
{
}

/**
 * Load all libraries in ITK_AUTOLOAD_PATH
 */
void 
ObjectFactoryBase
::LoadDynamicFactories()
{
  /**
   * follow PATH conventions
   */
#ifdef _WIN32
  char PathSeparator = ';';
#else
  char PathSeparator = ':';
#endif
  
  std::string LoadPath;
  if (getenv("ITK_AUTOLOAD_PATH"))
    {
    LoadPath = getenv("ITK_AUTOLOAD_PATH");
    }
  else
    {
    return;
    }

  if(LoadPath.size() == 0)
    {
    return;
    }
  std::string::size_type EndSeparatorPosition = 0;
  std::string::size_type StartSeparatorPosition = 0;

  while ( StartSeparatorPosition != std::string::npos )
    {
    StartSeparatorPosition = EndSeparatorPosition;

    /**
     * find PathSeparator in LoadPath
     */
    EndSeparatorPosition = LoadPath.find(PathSeparator, 
                                         StartSeparatorPosition);
    if(EndSeparatorPosition == std::string::npos)
      {
      EndSeparatorPosition = LoadPath.size() + 1; // Add 1 to simulate
                                                  // having a separator
      }
    std::string CurrentPath = 
      LoadPath.substr(StartSeparatorPosition,
                      EndSeparatorPosition - StartSeparatorPosition);

    ObjectFactoryBase::LoadLibrariesInPath(CurrentPath.c_str());

    /**
     * Move past separator
     */
    if(EndSeparatorPosition > LoadPath.size())
      {
      StartSeparatorPosition = std::string::npos;
      }
    else
      {
      EndSeparatorPosition++; // Skip the separator
      }
    }
}


/**
 * A file scope helper function to concat path and file into
 * a full path
 */
static std::string 
CreateFullPath(const char* path, const char* file)
{
  std::string ret;
#ifdef _WIN32
  const char sep = '\\';
#else
  const char sep = '/';
#endif
  /**
   * make sure the end of path is a separator
   */
  ret = path;
  if ( !ret.empty() && ret[ret.size()-1] != sep )
    {
    ret += sep;
    }
  ret += file;
  return ret;
}


/**
 * A file scope typedef to make the cast code to the load
 * function cleaner to read.
 */
typedef ObjectFactoryBase* (* ITK_LOAD_FUNCTION)();


/**
 * A file scoped function to determine if a file has
 * the shared library extension in its name, this converts name to lower
 * case before the compare, DynamicLoader always uses
 * lower case for LibExtension values.
 */
inline bool 
NameIsSharedLibrary(const char* name)
{
  std::string extension = itksys::DynamicLoader::LibExtension();

#ifdef __APPLE__
  // possible bug: CMake generated build file on the Mac makes
  // libraries with a .dylib extension.  kwsys guesses the extension
  // should be ".so"
  extension = ".dylib";
#endif
  
  std::string sname = name;
  if ( sname.rfind(extension) == sname.size() - extension.size() )
    {
    return true;
    }
  return false;
}

/**
 *
 */
void 
ObjectFactoryBase
::LoadLibrariesInPath(const char* path)
{
  Directory::Pointer dir = Directory::New();
  if ( !dir->Load(path) )
    {
    return;
    }
  
  /**
   * Attempt to load each file in the directory as a shared library
   */
  for ( unsigned int i = 0; i < dir->GetNumberOfFiles(); i++ )
    {
    const char* file = dir->GetFile(i);
    /**
     * try to make sure the file has at least the extension
     * for a shared library in it.
     */
    if ( NameIsSharedLibrary(file) )
      {
      std::string fullpath = CreateFullPath(path, file);
      LibHandle lib = DynamicLoader::OpenLibrary(fullpath.c_str());
      if ( lib )
        {
        /**
         * Look for the symbol itkLoad in the library
         */
        ITK_LOAD_FUNCTION loadfunction
          = (ITK_LOAD_FUNCTION)DynamicLoader::GetSymbolAddress(lib, "itkLoad");
        /**
         * if the symbol is found call it to create the factory
         * from the library
         */
        if ( loadfunction )
          {
          ObjectFactoryBase* newfactory = (*loadfunction)();

          /**
           * initialize class members if load worked
           */
          newfactory->m_LibraryHandle = (void*)lib;
          newfactory->m_LibraryPath = fullpath;
          newfactory->m_LibraryDate = 0; // unused for now...
          ObjectFactoryBase::RegisterFactory(newfactory);
          }
        else
          {
          // We would really like to close the lib if it does not
          // contain the itkLoad symbol. Unfortuantely, it seems that
          // some systems crash on the call
          // DynamicLoader::CloseLibrary(lib) if the lib has symbols
          // that the current executable is using.
          }
        }
      }
    }
}


/**
 * Recheck the ITK_AUTOLOAD_PATH for new libraries
 */
void 
ObjectFactoryBase
::ReHash()
{
  ObjectFactoryBase::UnRegisterAllFactories();
  ObjectFactoryBase::Initialize();
}


/**
 * initialize class members
 */
ObjectFactoryBase::ObjectFactoryBase()
{
  m_LibraryHandle = 0;
  m_LibraryDate = 0;
  m_OverrideMap = new OverRideMap;
}


/**
 * Unload the library and free the path string
 */
ObjectFactoryBase
::~ObjectFactoryBase()
{
  m_OverrideMap->erase(m_OverrideMap->begin(), m_OverrideMap->end());
  delete m_OverrideMap;
}


/**
 * Add a factory to the registered list
 */
void 
ObjectFactoryBase
::RegisterFactory(ObjectFactoryBase* factory)
{
  if ( factory->m_LibraryHandle == 0 )
    {
    const char nonDynamicName[] = "Non-Dynamicaly loaded factory";
    factory->m_LibraryPath = nonDynamicName;
    }
  if ( strcmp(factory->GetITKSourceVersion(), 
              Version::GetITKSourceVersion()) != 0 )
    {
    itkGenericOutputMacro(<< "Possible incompatible factory load:" 
                          << "\nRunning itk version :\n" << Version::GetITKSourceVersion() 
                          << "\nLoaded factory version:\n" << factory->GetITKSourceVersion()
                          << "\nLoading factory:\n" << factory->m_LibraryPath << "\n");
    }

  ObjectFactoryBase::Initialize();
  ObjectFactoryBase::m_RegisteredFactories->push_back(factory);
  factory->Register();
}


/**
 *
 */
void 
ObjectFactoryBase
::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Factory DLL path: " << m_LibraryPath.c_str() << "\n";
  os << indent << "Factory description: " << this->GetDescription() << std::endl;

  int num = static_cast<int>( m_OverrideMap->size() );
  os << indent << "Factory overides " << num << " classes:" << std::endl;

  indent = indent.GetNextIndent();
  for(OverRideMap::iterator i = m_OverrideMap->begin();
      i != m_OverrideMap->end(); ++i)
    {
    os << indent << "Class : " <<  (*i).first.c_str() << "\n";
    os << indent << "Overriden with: " <<  (*i).second.m_OverrideWithName.c_str()
       << std::endl;
    os << indent << "Enable flag: " << (*i).second.m_EnabledFlag
       << std::endl;
    os << indent << "Create object: " << (*i).second.m_CreateObject
       << std::endl;
    os << std::endl;
    }
}


/**
 *
 */
void 
ObjectFactoryBase
::UnRegisterFactory(ObjectFactoryBase* factory)
{ 
  for ( std::list<ObjectFactoryBase*>::iterator i = 
          m_RegisteredFactories->begin();
        i != m_RegisteredFactories->end(); ++i )
    {
    if ( factory == *i )
      {
      factory->UnRegister();
      m_RegisteredFactories->remove(factory);
      return;
      }
    }
}
  

/**
 * unregister all factories and delete the RegisteredFactories list
 */
void 
ObjectFactoryBase
::UnRegisterAllFactories()
{
  
  if ( ObjectFactoryBase::m_RegisteredFactories )
    {
    // Collect up all the library handles so they can be closed
    // AFTER the factory has been deleted.
    std::list<void *> libs;
    for ( std::list<ObjectFactoryBase*>::iterator i 
            = m_RegisteredFactories->begin();
          i != m_RegisteredFactories->end(); ++i )
      {
      libs.push_back(static_cast<void *>((*i)->m_LibraryHandle));
      }
    // Unregister each factory
    for ( std::list<ObjectFactoryBase*>::iterator f 
            = m_RegisteredFactories->begin();
          f != m_RegisteredFactories->end(); ++f )
      {
      (*f)->UnRegister();
      }
    // And delete the library handles all at once
    for ( std::list<void *>::iterator lib = libs.begin();
          lib != libs.end();
          ++lib)
      {
      if((*lib))
        {
        DynamicLoader::CloseLibrary(static_cast<LibHandle>(*lib));
        }
      }
    delete ObjectFactoryBase::m_RegisteredFactories;
    ObjectFactoryBase::m_RegisteredFactories = 0;
    }
}


/**
 *
 */
void 
ObjectFactoryBase
::RegisterOverride(const char* classOverride,
                   const char* subclass,
                   const char* description,
                   bool enableFlag,
                   CreateObjectFunctionBase*
                   createFunction)
{
  ObjectFactoryBase::OverrideInformation info;
  info.m_Description = description;
  info.m_OverrideWithName = subclass;
  info.m_EnabledFlag = enableFlag;
  info.m_CreateObject = createFunction;

  m_OverrideMap->insert(OverRideMap::value_type(classOverride, info));
}


LightObject::Pointer 
ObjectFactoryBase
::CreateObject(const char* itkclassname)
{
  OverRideMap::iterator start = m_OverrideMap->lower_bound(itkclassname);
  OverRideMap::iterator end = m_OverrideMap->upper_bound(itkclassname);

  for ( OverRideMap::iterator i = start; i != end; ++i )
    {
    if ( i != m_OverrideMap->end() && (*i).second.m_EnabledFlag)
      {
      return (*i).second.m_CreateObject->CreateObject();
      }
    }
  return 0;
}


/**
 *
 */
void 
ObjectFactoryBase
::SetEnableFlag(bool flag,
                const char* className,
                const char* subclassName)
{
  OverRideMap::iterator start = m_OverrideMap->lower_bound(className);
  OverRideMap::iterator end = m_OverrideMap->upper_bound(className);
  for ( OverRideMap::iterator i = start; i != end; ++i )
    {
    if ( (*i).second.m_OverrideWithName == subclassName )
      {
      (*i).second.m_EnabledFlag = flag;
      }
    }
}


/**
 *
 */
bool 
ObjectFactoryBase
::GetEnableFlag(const char* className, const char* subclassName)
{
  OverRideMap::iterator start = m_OverrideMap->lower_bound(className);
  OverRideMap::iterator end = m_OverrideMap->upper_bound(className);
  for ( OverRideMap::iterator i = start; i != end; ++i )
    {
    if ( (*i).second.m_OverrideWithName == subclassName )
      {
      return (*i).second.m_EnabledFlag;
      }
    }
  return 0;
}


/**
 *
 */
void 
ObjectFactoryBase
::Disable(const char* className)
{
  OverRideMap::iterator start = m_OverrideMap->lower_bound(className);
  OverRideMap::iterator end = m_OverrideMap->upper_bound(className);
  for ( OverRideMap::iterator i = start; i != end; ++i )
    {
    (*i).second.m_EnabledFlag = 0;
    }
}


/**
 *
 */
std::list<ObjectFactoryBase*> 
ObjectFactoryBase
::GetRegisteredFactories()
{
  return *ObjectFactoryBase::m_RegisteredFactories;
}


/**
 * Return a list of classes that this factory overrides.
 */
std::list<std::string> 
ObjectFactoryBase
::GetClassOverrideNames()
{
  std::list<std::string> ret;
  for ( OverRideMap::iterator i = m_OverrideMap->begin();
        i != m_OverrideMap->end(); ++i )
    {
    ret.push_back((*i).first);
    }
  return ret;
}


/**
 * Return a list of the names of classes that override classes.
 */
std::list<std::string> 
ObjectFactoryBase
::GetClassOverrideWithNames()
{
  std::list<std::string> ret;
  for ( OverRideMap::iterator i = m_OverrideMap->begin();
        i != m_OverrideMap->end(); ++i )
    {
    ret.push_back((*i).second.m_OverrideWithName);
    }
  return ret;
}


/**
 * Retrun a list of descriptions for class overrides
 */
std::list<std::string> 
ObjectFactoryBase
::GetClassOverrideDescriptions()
{ 
  std::list<std::string> ret;
  for ( OverRideMap::iterator i = m_OverrideMap->begin();
        i != m_OverrideMap->end(); ++i )
    {
    ret.push_back((*i).second.m_Description);
    }
  return ret;
}


/**
 * Return a list of enable flags
 */
std::list<bool> 
ObjectFactoryBase
::GetEnableFlags()
{
  std::list<bool> ret;
  for( OverRideMap::iterator i = m_OverrideMap->begin();
       i != m_OverrideMap->end(); ++i)
    {
    ret.push_back((*i).second.m_EnabledFlag);
    }
  return ret;
}

/**
 * Return the path to a dynamically loaded factory. */
const char *
ObjectFactoryBase
::GetLibraryPath()
{
  return m_LibraryPath.c_str();
}

} // end namespace itk