PluginLoader.cc 99 KB
Newer Older
1
/*===========================================================================*\
Jan Möbius's avatar
Jan Möbius committed
2
3
*                                                                            *
*                              OpenFlipper                                   *
Jan Möbius's avatar
Jan Möbius committed
4
*      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen       *
Jan Möbius's avatar
Jan Möbius committed
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
*                           www.openflipper.org                              *
*                                                                            *
*--------------------------------------------------------------------------- *
*  This file is part of OpenFlipper.                                         *
*                                                                            *
*  OpenFlipper is free software: you can redistribute it and/or modify       *
*  it under the terms of the GNU Lesser General Public License as            *
*  published by the Free Software Foundation, either version 3 of            *
*  the License, or (at your option) any later version with the               *
*  following exceptions:                                                     *
*                                                                            *
*  If other files instantiate templates or use macros                        *
*  or inline functions from this file, or you compile this file and          *
*  link it with other files to produce an executable, this file does         *
*  not by itself cause the resulting executable to be covered by the         *
*  GNU Lesser General Public License. This exception does not however        *
*  invalidate any other reasons why the executable file might be             *
*  covered by the GNU Lesser General Public License.                         *
*                                                                            *
*  OpenFlipper is distributed in the hope that it will be useful,            *
*  but WITHOUT ANY WARRANTY; without even the implied warranty of            *
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
*  GNU Lesser General Public License for more details.                       *
*                                                                            *
*  You should have received a copy of the GNU LesserGeneral Public           *
*  License along with OpenFlipper. If not,                                   *
*  see <http://www.gnu.org/licenses/>.                                       *
*                                                                            *
33
34
35
\*===========================================================================*/

/*===========================================================================*\
Jan Möbius's avatar
Jan Möbius committed
36
37
*                                                                            *
*   $Revision$                                                       *
38
*   $LastChangedBy$                                         *
Jan Möbius's avatar
Jan Möbius committed
39
40
*   $Date$                     *
*                                                                            *
41
\*===========================================================================*/
Jan Möbius's avatar
 
Jan Möbius committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61




//=============================================================================
//
//  CLASS Core - IMPLEMENTATION of the Plugin Loading
//
//=============================================================================


//== INCLUDES =================================================================

// -------------------- mview
#include "Core.hh"

#include <QMenuBar>
#include <QToolBox>
#include <QMessageBox>
#include <QApplication>
Jan Möbius's avatar
Jan Möbius committed
62
#include <QScrollArea>
Jan Möbius's avatar
 
Jan Möbius committed
63
64
65
66
67
68
69
70
71

#include <QPluginLoader>
#include "OpenFlipper/BasePlugin/BaseInterface.hh"
#include "OpenFlipper/BasePlugin/KeyInterface.hh"
#include "OpenFlipper/BasePlugin/BackupInterface.hh"
#include "OpenFlipper/BasePlugin/LoggingInterface.hh"
#include "OpenFlipper/BasePlugin/MouseInterface.hh"
#include "OpenFlipper/BasePlugin/PickingInterface.hh"
#include "OpenFlipper/BasePlugin/ToolboxInterface.hh"
Dirk Wilden's avatar
Dirk Wilden committed
72
#include "OpenFlipper/BasePlugin/OptionsInterface.hh"
Jan Möbius's avatar
 
Jan Möbius committed
73
74
#include "OpenFlipper/BasePlugin/ToolbarInterface.hh"
#include "OpenFlipper/BasePlugin/TextureInterface.hh"
Jan Möbius's avatar
Jan Möbius committed
75
#include "OpenFlipper/BasePlugin/RenderInterface.hh"
76
#include "OpenFlipper/BasePlugin/PostProcessorInterface.hh"
Jan Möbius's avatar
 
Jan Möbius committed
77
78
#include "OpenFlipper/BasePlugin/MenuInterface.hh"
#include "OpenFlipper/BasePlugin/ContextMenuInterface.hh"
79
#include "OpenFlipper/BasePlugin/ProcessInterface.hh"
Jan Möbius's avatar
 
Jan Möbius committed
80
#include "OpenFlipper/BasePlugin/ViewInterface.hh"
Jan Möbius's avatar
Jan Möbius committed
81
#include "OpenFlipper/BasePlugin/ViewModeInterface.hh"
Jan Möbius's avatar
 
Jan Möbius committed
82
83
84
85
86
87
#include "OpenFlipper/BasePlugin/LoadSaveInterface.hh"
#include "OpenFlipper/BasePlugin/StatusbarInterface.hh"
#include "OpenFlipper/BasePlugin/INIInterface.hh"
#include "OpenFlipper/BasePlugin/FileInterface.hh"
#include "OpenFlipper/BasePlugin/RPCInterface.hh"
#include "OpenFlipper/BasePlugin/ScriptInterface.hh"
88
#include "OpenFlipper/BasePlugin/SecurityInterface.hh"
89
#include "OpenFlipper/BasePlugin/SelectionInterface.hh"
90
#include "OpenFlipper/BasePlugin/TypeInterface.hh"
91
#include "OpenFlipper/BasePlugin/PluginConnectionInterface.hh"
Jan Möbius's avatar
 
Jan Möbius committed
92

93
#include "OpenFlipper/common/RendererInfo.hh"
94

Jan Möbius's avatar
 
Jan Möbius committed
95
96
97
98
99
100
101
102
#include "OpenFlipper/INIFile/INIFile.hh"

#include "OpenFlipper/common/GlobalOptions.hh"

#include <QMessageBox>
#include <QtScript/QScriptValueIterator>

#include <ACG/QtWidgets/QtFileDialog.hh>
Dirk Wilden's avatar
Dirk Wilden committed
103
#include "OpenFlipper/widgets/PluginDialog/PluginDialog.hh"
Jan Möbius's avatar
 
Jan Möbius committed
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
#include <deque>
#include <limits>

/**
 * The number of plugins to load simultaneously.
 *
 * FIXME: This number should not be constant but be
 * determined from the number of processor cores.
 */
static const int PRELOAD_THREADS_COUNT = 8;

class PreloadAggregator {
    public:
        PreloadAggregator() : expectedLoaders_(0) {}

        /**
         * Intended to be called by a PreloadThread
         * before count subsequent calls to loaderReady().
         * May be called multiple times in which case
         * the counts accumulate.
         *
         * @param count The number of times the calling
         * PreloadThread intents to call loaderReady().
         */
        void expectLoaders(int count) {
            QMutexLocker loadersLock(&loadersMutex_);
            expectedLoaders_ += count;
        }

        /**
         * Intended to be called by a PreloadThread.
         *
         * Transfers ownership of the supplied loader
         * to the PreloadAggregator.
         */
        void loaderReady(QPluginLoader *loader) {
            QMutexLocker loadersLock(&loadersMutex_);
            loaders_.push_back(loader);
            --expectedLoaders_;
            pluginAvailable_.wakeOne();
        }

        /**
         * If there are still loaders expected, block
         * until the next loader becomes available and return
         * it.
         *
         * Ownership of the returned object is transferred
         * to the caller. (I.e. the caller has to delete it.)
         *
         * @return Null if there are no more loaders expected.
         * The next loader, otherwise.
         */
        QPluginLoader *waitForNextLoader() {
            QMutexLocker loadersLock(&loadersMutex_);
            if (loaders_.empty()) {
                if (expectedLoaders_ > 0) {
                    pluginAvailable_.wait(&loadersMutex_);
                } else {
                    return 0;
                }
            }

            /*
             * At this point, it is guaranteed that
             * loaders_.size() > 0.
             */
            QPluginLoader *result = loaders_.front();
            loaders_.pop_front();
            return result;
        }

    protected:
        std::deque<QPluginLoader *> loaders_;
        QWaitCondition pluginAvailable_;
        QMutex loadersMutex_;

        int expectedLoaders_;
};

Jan Möbius's avatar
Jan Möbius committed
185
186
187
188
189
190
191
192
193
class PreloadThread : public QThread
{
  public: 
    
    /** \brief Preload thread constructor
    *
    * This constructor initializes the preloading thread.
    * @param _fileName Filename of the Plugin to be loaded.
    */
194
    PreloadThread(PreloadAggregator *aggregator) : aggregator_(aggregator) {
Jan Möbius's avatar
Jan Möbius committed
195
196
197
198
    }
  
  public:
    
199
200
201
202
203
204
    void addFilename(const QString &filename) {
        QMutexLocker filenamesLock(&filenamesMutex_);
        filenames_.push_back(filename);
        aggregator_->expectLoaders(1);
    }

Jan Möbius's avatar
Jan Möbius committed
205
206
207
208
209
    /** \brief preload function
    *
    * This function is used in the thread to preload a plugin. The name is given in the constructor.
    */
    void run() {
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
      for (;;) {
          QString fileName;
          {
              /*
               * Just to be on the safe side, we protect
               * filenames_. (addFilename() could be called from
               * a different thread.)
               */
              QMutexLocker filenamesLock(&filenamesMutex_);
              if (filenames_.empty()) break;
              fileName = filenames_.front();
              filenames_.pop_front();
          }

          QPluginLoader *loader = new QPluginLoader;
          loader->setFileName(fileName);
          loader->load();
          aggregator_->loaderReady(loader);
      }
Jan Möbius's avatar
Jan Möbius committed
229
230
231
    }
    
  private:
232
233
234
    std::deque<QString> filenames_;
    QMutex filenamesMutex_;
    PreloadAggregator *aggregator_;
Jan Möbius's avatar
Jan Möbius committed
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
/**
 * @brief Defines the order in which plugins have to be loaded.
 *
 * First load all type Plugins to register the dataTypes to the core
 * Than load the file plugins to load objects
 * Next is textureControl to control texture based properties
 * Then load everything else.
 */
class PluginInitializationOrder {
    public:
        int getTypeOrdinal(const QString &name) const {
            const QString basename = QFileInfo(name).baseName();
            if (basename.contains("Plugin-Type"))
                return 0;
            else if (basename.contains("Plugin-File"))
                return 1;
            else if (basename.contains("TextureControl"))
                return 2;
            else
                return 3;

        }
        bool operator() (const QString &a, const QString &b) const {
            const int typeA = getTypeOrdinal(a);
            const int typeB = getTypeOrdinal(b);
            if (typeA != typeB) { return typeA < typeB; }
            return a < b;
        }

        bool operator() (const QPluginLoader *a, const QPluginLoader *b) const {
            return operator() (a->fileName(), b->fileName());
        }
};
Jan Möbius's avatar
Jan Möbius committed
270

Jan Möbius's avatar
 
Jan Möbius committed
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//== IMPLEMENTATION ==========================================================


bool Core::checkSlot(QObject* _plugin , const char* _slotSignature) {
  const QMetaObject* meta = _plugin->metaObject();
  int id = meta->indexOfSlot( QMetaObject::normalizedSignature( _slotSignature ) );
  return ( id != -1 );
}

bool Core::checkSignal(QObject* _plugin , const char* _signalSignature) {
  const QMetaObject* meta = _plugin->metaObject();
  int id = meta->indexOfSignal( QMetaObject::normalizedSignature( _signalSignature ) );
  return ( id != -1 );
}

 /** Load plugins from dir Plugins. The plugin information gets stored, toolbox and menu entries are created and the required signals and slots are connected.
  */
void Core::loadPlugins()
{
Jan Möbius's avatar
Jan Möbius committed
290
291
292
  
  QString licenseTexts = "";
  
Dirk Wilden's avatar
Dirk Wilden committed
293
  //try to load plugins from new location
294
  QDir tempDir = QDir(OpenFlipper::Options::pluginDir());
Dirk Wilden's avatar
Dirk Wilden committed
295

296
297
298
299
300
  // Possible Plugin extensions
  QStringList filter;
  if ( OpenFlipper::Options::isWindows() )
    filter << "*.dll";
  else if ( OpenFlipper::Options::isDarwin() )
Jan Möbius's avatar
Jan Möbius committed
301
302
    filter << "*.so";
//    filter << "*.dylib";
303
304
305
  else
    filter << "*.so";
  
Jan Möbius's avatar
 
Jan Möbius committed
306
  // Get all files in the Plugin dir
307
  QStringList pluginlist = tempDir.entryList(filter,QDir::Files);
Dirk Wilden's avatar
Dirk Wilden committed
308

309
310
  // Convert local file path to absolute path
  for (int i=0; i < pluginlist.size(); i++) {
311
     pluginlist[i] = tempDir.absoluteFilePath(pluginlist[i]);
Jan Möbius's avatar
 
Jan Möbius committed
312
313
  }

314
  // get all Plugin Names which will not be loaded
315
  QStringList dontLoadPlugins = OpenFlipperSettings().value("PluginControl/DontLoadNames", QStringList()).toStringList();
316
317
318
319
320
321
  
  // Output info about additional plugins
  for ( int i = 0 ; i < dontLoadPlugins.size(); ++i) 
    emit log(LOGOUT,tr("dontLoadPlugins Plugin from ini file: %1").arg( dontLoadPlugins[i] ) );
  
  // get all Plugins which should be loaded in addition to the standard plugins 
322
  QStringList additionalPlugins = OpenFlipperSettings().value("PluginControl/AdditionalPlugins", QStringList()).toStringList();
323
324
  
  // Output info about additional plugins
Jan Möbius's avatar
Jan Möbius committed
325
  for ( int i = 0 ; i < additionalPlugins.size(); ++i) {
326
    emit log(LOGOUT,tr("Additional Plugin from file: %1").arg( additionalPlugins[i] ) );
Jan Möbius's avatar
Jan Möbius committed
327
  }
328
329
330
  
  // Prepend the additional Plugins to the plugin list
  pluginlist = additionalPlugins << pluginlist;
331
332
333
334
335
336

  /*
   * Note: This call is not necessary, anymore. Initialization order
   * is determined later.
   */
  std::sort(pluginlist.begin(), pluginlist.end(), PluginInitializationOrder());
Jan Möbius's avatar
 
Jan Möbius committed
337

338
339
  for ( int i = 0 ; i < dontLoadPlugins.size(); ++i )
    emit log(LOGWARN,tr("Skipping Plugins :\t %1").arg( dontLoadPlugins[i] ) );
Jan Möbius's avatar
 
Jan Möbius committed
340

341
  emit log(LOGOUT,"================================================================================");
Jan Möbius's avatar
 
Jan Möbius committed
342

Jan Möbius's avatar
Jan Möbius committed
343
344
345
346
  QTime time;
  
  time.start();
  
347
348
349
350
351
352
353
354
355
356
  PreloadAggregator preloadAggregator;
  std::vector< PreloadThread* > loaderThreads(PRELOAD_THREADS_COUNT);

  /*
   * Initialize loaderThreads.
   */
  for (std::vector< PreloadThread* >::iterator it = loaderThreads.begin();
          it != loaderThreads.end(); ++it) {
      *it = new PreloadThread(&preloadAggregator);
  }
Jan Möbius's avatar
Jan Möbius committed
357
  
358
359
360
361
  /*
   * Distribute plugins onto loader threads in a round robin fashion.
   * (only load them in seperate thread. Instance will be created in main thread)
   */
Jan Möbius's avatar
 
Jan Möbius committed
362
  for ( int i = 0 ; i < pluginlist.size() ; ++i) {
363
364
365
366
367
368
369
370
371
    loaderThreads[i % loaderThreads.size()]->addFilename(pluginlist[i]);
  }

  /*
   * Start plugin preloading.
   */
  for (std::vector< PreloadThread* >::iterator it = loaderThreads.begin();
          it != loaderThreads.end(); ++it) {
      (*it)->start();
Jan Möbius's avatar
Jan Möbius committed
372
373
  }
  
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
  /*
   * Wait for the plugins to get preloaded
   */
  std::vector<QPluginLoader*> loadedPlugins;
  loadedPlugins.reserve(pluginlist.size());

  for (QPluginLoader *loader = preloadAggregator.waitForNextLoader(); loader != 0;
          loader = preloadAggregator.waitForNextLoader()) {

      loadedPlugins.push_back(loader);

      if ( OpenFlipper::Options::gui() && OpenFlipperSettings().value("Core/Gui/splash",true).toBool() ) {
        splashMessage_ = tr("Loading Plugin %1/%2").arg(loadedPlugins.size()).arg(pluginlist.size()) ;
        splash_->showMessage( splashMessage_ , Qt::AlignBottom | Qt::AlignLeft , Qt::white);
      }
Jan Möbius's avatar
 
Jan Möbius committed
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
  /*
   * Finalize PreloadThreads.
   */
  for (std::vector< PreloadThread* >::iterator it = loaderThreads.begin();
          it != loaderThreads.end(); ++it) {
      (*it)->wait();
      delete *it;
  }

  /*
   * Initialize preloaded plugins in the correct order.
   */
  std::sort(loadedPlugins.begin(), loadedPlugins.end(), PluginInitializationOrder());
  for (std::vector<QPluginLoader*>::iterator it = loadedPlugins.begin();
          it != loadedPlugins.end(); ++it) {

      if ( OpenFlipper::Options::gui() && OpenFlipperSettings().value("Core/Gui/splash",true).toBool() ) {
        splashMessage_ = tr("Initializing Plugin %1/%2")
                .arg(std::distance(loadedPlugins.begin(), it) + 1)
                .arg(loadedPlugins.size());
        splash_->showMessage( splashMessage_ , Qt::AlignBottom | Qt::AlignLeft , Qt::white);
      }

      if ((*it)->instance() != 0 ) {
        QString pluginLicenseText  = "";
        loadPlugin((*it)->fileName(),true,pluginLicenseText, (*it)->instance());
        licenseTexts += pluginLicenseText;
      } else {
        emit log(LOGERR,tr("Unable to load Plugin :\t %1").arg( (*it)->fileName() ) );
        emit log(LOGERR,tr("Error was : ") + (*it)->errorString() );
        emit log(LOGOUT,"================================================================================");
      }
      delete *it;
  }

  emit log(LOGINFO, tr("Total time needed to load plugins was %1 ms.").arg(time.elapsed()));

Jan Möbius's avatar
 
Jan Möbius committed
428
  splashMessage_ = "";
Jan Möbius's avatar
Jan Möbius committed
429
430
  
  if ( licenseTexts != "" ) {
Jan Möbius's avatar
Jan Möbius committed
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
    if ( OpenFlipper::Options::gui() ) {
      
      // split for each license block
      QStringList licenseBlocks = licenseTexts.split("==");

      // Cleanup lists to get only the ones containing valid plugins.
      for ( QStringList::iterator it = licenseBlocks.begin(); it != licenseBlocks.end() ; ++it )
        if ( ! it->contains("PluginName") ) {
          licenseBlocks.erase(it);
          it = licenseBlocks.begin();
        }
      
      // sort by the contact mails
      QMap< QString , QString > contacts;
      
      for ( QStringList::iterator it = licenseBlocks.begin(); it != licenseBlocks.end() ; ++it ) {
        QStringList lines = it->split("\n");
        
        lines = lines.filter ( "Contact mail", Qt::CaseInsensitive );
        
        // Corect one found:
        if (lines.size() == 1)  {
          QString mail = lines[0].section(":",-1).simplified();
          QString list = contacts.take(mail);
          list.append(*it);
          contacts.insert(mail,list);
        } else {
          emit log(LOGWARN,tr("Can't extract mail contact from license request"));
        }
          
      }
      
      for ( QMap<QString , QString>::iterator it = contacts.begin() ; it != contacts.end() ; ++it ) {
        
        QStringList request = it.value().split("\n");
        
        // Cleanup lists to get only the relevant part
        for ( QStringList::iterator lit = request.begin(); lit != request.end() ; ++lit ) {
          
          if ( lit->contains("Message:")  ) {
            *lit = lit->section(":",-1).simplified();
          }
          
          if ( lit->contains("Contact mail:")  ) {
            *lit = lit->section(":",-1).simplified();
          }
477
           
Jan Möbius's avatar
Jan Möbius committed
478
        }
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495

        QDialog licenseBox;
          
        QTextEdit *edit = new QTextEdit(&licenseBox);
        edit->setText(request.join("\n"));

        QLabel* mailLabel = new QLabel(&licenseBox);
        mailLabel->setText(tr("The text has been copied to your clipboard. Open in Mail program?"));

        QPushButton* noButton = new QPushButton(&licenseBox);
        noButton->setText(tr("No"));
        connect( noButton, SIGNAL(clicked ()), &licenseBox, SLOT(reject()) );

        QPushButton* yesButton = new QPushButton(&licenseBox);
        yesButton->setText(tr("Yes"));
        connect( yesButton, SIGNAL(clicked ()), &licenseBox, SLOT(accept()) );

Jan Möbius's avatar
Jan Möbius committed
496
497
498
499
500
501
        QGridLayout *layout = new QGridLayout;
        layout->addWidget(edit,0,0,1,2);
        layout->addWidget(mailLabel,1,0,1,2);
        layout->addWidget(noButton,2,0);
        layout->addWidget(yesButton,2,1);
        licenseBox.setLayout(layout);
502
503
504
505
506
507

        licenseBox.resize(500,500);
        licenseBox.setModal(true);
        licenseBox.setWindowTitle(tr("Plugin License check failed, issuer is: %1").arg( it.key() ));  
        int userAnswer =licenseBox.exec();

Jan Möbius's avatar
Jan Möbius committed
508
        // set a text to the Clipboard
509
        QClipboard *cb = QApplication::clipboard();
Jan Möbius's avatar
Jan Möbius committed
510
        cb->setText(request.join("\n"));
Jan Möbius's avatar
Jan Möbius committed
511

512
        if ( userAnswer == 1 ) {
513
514
515
516
517
518
519
           QString url = "mailto:" + it.key();
           url += "?subject=License Request&body=";
#ifdef WIN32
           url += request.join(";;");
#else
           url += request.join("\n");
#endif
Jan Möbius's avatar
Jan Möbius committed
520

521
522
523
           QUrl encodedURL(url, QUrl::TolerantMode);
           QDesktopServices::openUrl(encodedURL);
        }
Jan Möbius's avatar
Jan Möbius committed
524
525
526
527
528
529
        
      }

      
    } else {
      emit log(LOGWARN,tr("Plugin License check failed: "));
Jan Möbius's avatar
Jan Möbius committed
530
531
532
      std::cerr << licenseTexts.toStdString() << std::endl;
    }
  } 
Jan Möbius's avatar
 
Jan Möbius committed
533
534
535

  emit pluginsInitialized();

Jan Möbius's avatar
Jan Möbius committed
536
  emit log(LOGOUT,tr("Loaded %n Plugin(s)","",plugins_.size()) );
Jan Möbius's avatar
 
Jan Möbius committed
537
538
539
540
541
542
543
544
545
}

/** @brief slot for loading Plugins
 */
void Core::slotLoadPlugin(){

  if ( OpenFlipper::Options::nogui() )
    return;

546
  // Setup filters for possible plugin extensions
Jan Möbius's avatar
 
Jan Möbius committed
547
548
549
  QString filter;
  if ( OpenFlipper::Options::isWindows() )
    filter = "Plugins (*.dll)";
550
  else if ( OpenFlipper::Options::isDarwin() )
Jan Möbius's avatar
Jan Möbius committed
551
552
    // filter = "Plugins (*.dylib)";
    filter = "Plugins (*.so)";
Jan Möbius's avatar
 
Jan Möbius committed
553
554
555
  else
    filter = "Plugins (*.so)";

556
  // Ask the user to select the file to load
557
  QString filename = ACG::getOpenFileName(coreWidget_,tr("Load Plugin"),filter, OpenFlipperSettings().value("Core/CurrentDir").toString() );
Jan Möbius's avatar
 
Jan Möbius committed
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578

  if (filename.isEmpty())
    return;

  // get the plugin name
  // and check if Plugin is in the dontLoad List
  QPluginLoader loader( filename );
  QObject *plugin = loader.instance();
  QString name;

  // Check if a plugin has been loaded
  if (plugin) {
    // Check if it is a BasePlugin
    BaseInterface* basePlugin = qobject_cast< BaseInterface * >(plugin);
    if ( basePlugin ) {
      name = basePlugin->name();
    }else
      return;
  }else
    return;

579
  // Ask if the plugin is on the block list
580
  QStringList dontLoadPlugins = OpenFlipperSettings().value("PluginControl/DontLoadNames", QStringList()).toStringList();
581
  if (dontLoadPlugins.contains(name)){
Jan Möbius's avatar
 
Jan Möbius committed
582
583
      int ret = QMessageBox::question(0, tr("Plugin Loading Prevention"),
                   tr("OpenFlipper is currently configured to prevent loading this plugin.\n"
584
                      "Do you want to enable this plugin permanently?"),
Jan Möbius's avatar
 
Jan Möbius committed
585
586
                   QMessageBox::Yes | QMessageBox::No,
                   QMessageBox::Yes);
587
588
589
590
591
      if (ret == QMessageBox::Yes) {
        dontLoadPlugins.removeAll(name);
        OpenFlipperSettings().setValue("PluginControl/DontLoadNames",dontLoadPlugins);
      } else
         return;
Jan Möbius's avatar
 
Jan Möbius committed
592
  }
593
594
  
  // check if the plugin is not on the additional plugin list
595
  QStringList additionalPlugins = OpenFlipperSettings().value("PluginControl/AdditionalPlugins", QStringList()).toStringList();
596
597
598
599
600
601
602
603
604
605
606
607
  if (!additionalPlugins.contains(name)){
    int ret = QMessageBox::question(0, tr("Plugin Loading ..."),
                                       tr("Should OpenFlipper load this plugin on next startup?"),
                                    QMessageBox::Yes | QMessageBox::No,
                                    QMessageBox::Yes);
    if (ret == QMessageBox::Yes) {
      additionalPlugins << filename;
      std::cerr << "Added: " << filename.toStdString() << std::endl;
      OpenFlipperSettings().setValue("PluginControl/AdditionalPlugins",additionalPlugins);
    }
  }
  
Jan Möbius's avatar
Jan Möbius committed
608
609
610
611
  QString licenseText = "";
  loadPlugin(filename,false,licenseText);
  
  if ( licenseText != "" ) {
Jan Möbius's avatar
Jan Möbius committed
612
    if ( OpenFlipper::Options::gui() ) {
Jan Möbius's avatar
Jan Möbius committed
613
      QMessageBox::warning ( 0, tr("Plugin License check failed"),  licenseText );
Jan Möbius's avatar
Jan Möbius committed
614
615
616
617
      
      std::cerr << "OpenURL: " << std::endl;
      QDesktopServices::openUrl(QUrl(tr("mailto:contact@openflipper.com?subject=License Request&body=%1").arg(licenseText), QUrl::TolerantMode));
    } else {
Jan Möbius's avatar
Jan Möbius committed
618
619
620
      std::cerr << "Plugin License check failed" << std::endl;
      std::cerr << licenseText.toStdString() << std::endl;
    }
621
  }
Jan Möbius's avatar
 
Jan Möbius committed
622
623
}

Dirk Wilden's avatar
Dirk Wilden committed
624
/** @brief slot for showing loaded Plugins
Jan Möbius's avatar
 
Jan Möbius committed
625
 */
Dirk Wilden's avatar
Dirk Wilden committed
626
void Core::slotShowPlugins(){
Jan Möbius's avatar
 
Jan Möbius committed
627

Dirk Wilden's avatar
Dirk Wilden committed
628
629
630
631
632
633
  if ( OpenFlipper::Options::gui() ){

    int ret = 0;

    while (ret == 0){

Jan Möbius's avatar
Jan Möbius committed
634
      PluginDialog* dialog = new PluginDialog(plugins_, coreWidget_);
Jan Möbius's avatar
 
Jan Möbius committed
635

Dirk Wilden's avatar
Dirk Wilden committed
636
637
638
639
640
641
642
643
644
645
      //connect signals
      connect(dialog, SIGNAL(unloadPlugin(QString)), this, SLOT(unloadPlugin(QString)));
      connect(dialog, SIGNAL( loadPlugin() ), this, SLOT( slotLoadPlugin() ));

      //if a plugin was deleted/loaded the dialog returns 0 and it needs to be loaded again
      ret = dialog->exec();

      delete dialog;
    }
  }
Jan Möbius's avatar
 
Jan Möbius committed
646
647
648
649
650
651
}

/** @brief Unload a Plugin with given name (slot)
 *  @param name plugin name
 */
void Core::unloadPlugin(QString name){
Jan Möbius's avatar
Jan Möbius committed
652
653
654
655
  for (uint i=0; i < plugins_.size(); i++)
    if (plugins_[i].rpcName == name){
      if ( checkSlot( plugins_[i].plugin , "exit()" ) )
        QMetaObject::invokeMethod(plugins_[i].plugin, "exit",  Qt::DirectConnection);
Jan Möbius's avatar
 
Jan Möbius committed
656
657
658
659

      //remove toolbox widget
      QString name_nospace = name;
      name_nospace.remove(" ");
Jan Möbius's avatar
Jan Möbius committed
660
661
      if ( coreWidget_->viewModes_[0]->visibleToolboxes.contains(name_nospace) )
        coreWidget_->viewModes_[0]->visibleToolboxes.removeAt(coreWidget_->viewModes_[0]->visibleToolboxes.indexOf(name_nospace));
Jan Möbius's avatar
Jan Möbius committed
662
663
664
665
      for ( uint j = 0 ; j < plugins_[i].toolboxWidgets.size() ; ++j )
        if (plugins_[i].toolboxWidgets[j].second ){
          plugins_[i].toolboxWidgets[j].second->setVisible(false);
          delete plugins_[i].toolboxWidgets[j].second;
Dirk Wilden's avatar
Dirk Wilden committed
666

Jan Möbius's avatar
Jan Möbius committed
667
668
          if( plugins_[i].toolboxIcons[j] != 0 )
            delete plugins_[i].toolboxIcons[j];
669
        }
Jan Möbius's avatar
 
Jan Möbius committed
670

Jan Möbius's avatar
Jan Möbius committed
671
      plugins_.erase(plugins_.begin() + i);
Jan Möbius's avatar
 
Jan Möbius committed
672

Jan Möbius's avatar
Jan Möbius committed
673
      emit log(LOGOUT,tr("Unloaded Plugin :\t\t %1").arg( name) );
Jan Möbius's avatar
 
Jan Möbius committed
674
675
676
677

      return;
    }

Jan Möbius's avatar
Jan Möbius committed
678
    log(LOGERR, tr("Unable to unload plugin '%1' (plugin wasn't found)").arg(name));
Jan Möbius's avatar
 
Jan Möbius committed
679
680
681
682
683
}

/** @brief Load a Plugin with given filename
 *  @param filename complete path + filename of the plugin
 *  @param silent if 'true': user isn't asked what to do if a plugin is already loaded
Jan Möbius's avatar
Jan Möbius committed
684
 *  @param _licenseErrors String will be epty when no license issues occured, otherwise it contains the required information for obtaining a license
Jan Möbius's avatar
Jan Möbius committed
685
 *  @param _plugin You can provide a preloaded plugin here. If this is 0 the filename will be used to load the plugin.
Jan Möbius's avatar
 
Jan Möbius committed
686
 */
Jan Möbius's avatar
Jan Möbius committed
687
void Core::loadPlugin(QString filename, bool silent, QString& _licenseErrors, QObject* _plugin){
Jan Möbius's avatar
 
Jan Möbius committed
688

Jan Möbius's avatar
Jan Möbius committed
689
690
  _licenseErrors = "";
  
Jan Möbius's avatar
 
Jan Möbius committed
691
692
693
694
695
696
697
698
699
700
701
702
703
704
  // Only load .dll under windows
  if ( OpenFlipper::Options::isWindows() ) {
    QString dllname = filename;
    if ( ! dllname.endsWith( ".dll" ) )
      return;
  }

  // Only load .so under linux
  if ( OpenFlipper::Options::isLinux() ) {
    QString soname = filename;
    if ( ! soname.endsWith( ".so" ) )
      return;
  }

Jan Möbius's avatar
Jan Möbius committed
705
706
  // This will be the reference to our plugin
  QObject *plugin = 0;
Jan Möbius's avatar
 
Jan Möbius committed
707

Jan Möbius's avatar
Jan Möbius committed
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
  // Try to open the file if we did not get a plugin,
  // Otherwise use the supplied plugin pointer
  if ( _plugin == 0 ) {
    QPluginLoader loader( filename );
    plugin = loader.instance();  
    
    if ( !plugin) {
      emit log(LOGERR,tr("Unable to load Plugin :\t %1").arg( filename ) );
      emit log(LOGERR,tr("Error was : ") + loader.errorString() );
      emit log(LOGOUT,"================================================================================");       
    }
    
  } else {
      plugin = _plugin;
  }
  
Jan Möbius's avatar
 
Jan Möbius committed
724
  // Check if a plugin has been loaded
Jan Möbius's avatar
Jan Möbius committed
725
726
  PluginInfo info;
  QString supported;
Jan Möbius's avatar
 
Jan Möbius committed
727

Jan Möbius's avatar
Jan Möbius committed
728
  emit log(LOGOUT,tr("Location : \t %1").arg(filename) );
Jan Möbius's avatar
Jan Möbius committed
729
730
731
732
733
  
  // Check if it is a BasePlugin
  BaseInterface* basePlugin = qobject_cast< BaseInterface * >(plugin);
  if ( basePlugin ) {
    emit log(LOGOUT,tr("Found Plugin : \t %1").arg(basePlugin->name()) );
Jan Möbius's avatar
 
Jan Möbius committed
734

Jan Möbius's avatar
Jan Möbius committed
735
736
737
738
    if ( OpenFlipper::Options::gui() && OpenFlipperSettings().value("Core/Gui/splash",true).toBool() ) {
      splashMessage_ = splashMessage_ + " " + basePlugin->name() ;
      splash_->sh