1 /***************************************************************************
4 begin : Mit Okt 23 14:35:18 CEST 2002
5 copyright : (C) 2002 by Mark Kretschmann
7 ***************************************************************************/
9 /***************************************************************************
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
16 ***************************************************************************/
20 #include "amarokconfig.h"
21 #include "amarokdbushandler.h"
22 #include "atomicstring.h"
23 #include "collectiondb.h"
24 #include "CollectionManager.h"
25 #include "ConfigDialog.h"
26 #include "context/ContextView.h"
28 #include "enginebase.h"
29 #include "enginecontroller.h"
30 #include "equalizersetup.h"
31 #include "MainWindow.h"
32 #include "mediabrowser.h"
34 #include "metabundle.h"
35 #include "mountpointmanager.h"
37 #include "playlist/PlaylistModel.h"
39 #include "pluginmanager.h"
40 #include "refreshimages.h"
41 #include "scriptmanager.h"
42 #include "scrobbler.h"
43 #include "statusbar.h"
45 #include "threadmanager.h"
46 #include "tracktooltip.h" //engineNewMetaData()
47 #include "TheInstances.h"
48 #include "metadata/tplugins.h"
54 #include <KCmdLineArgs> //initCliArgs()
55 #include <KConfigDialogManager>
56 #include <KCursor> //Amarok::OverrideCursor
57 #include <KEditToolBar> //slotConfigToolbars()
58 #include <KGlobalAccel> //initGlobalShortcuts()
59 #include <KGlobalSettings> //applyColorScheme()
60 #include <KIO/CopyJob>
61 #include <KIconLoader> //amarok Icon
63 #include <KJobUiDelegate>
65 #include <KMessageBox> //applySettings(), genericEventHandler()
66 #include <KRun> //Amarok::invokeBrowser()
68 #include <KShortcutsDialog> //slotConfigShortcuts()
69 #include <KSplashScreen>
70 #include <KStandardDirs>
72 #include <QCloseEvent>
73 #include <QDBusInterface>
75 #include <QEvent> //genericEventHandler()
76 #include <QEventLoop> //applySettings()
78 #include <QPixmapCache>
79 #include <Q3PopupMenu> //genericEventHandler
80 #include <QTimer> //showHyperThreadingWarning()
81 #include <QToolTip> //default tooltip for trayicon
84 QMutex
Amarok::globalDirsMutex
;
86 int App::mainThreadId
= 0;
89 #include <CoreFoundation/CoreFoundation.h>
90 extern void setupEventHandler_mac(long);
93 AMAROK_EXPORT KAboutData
aboutData( "amarok", 0,
94 ki18n( "Amarok" ), APP_VERSION
,
95 ki18n( "The audio player for KDE" ), KAboutData::License_GPL
,
96 ki18n( "(C) 2002-2003, Mark Kretschmann\n(C) 2003-2007, The Amarok Development Squad" ),
97 ki18n( "IRC:\nirc.freenode.net - #amarok, #amarok.de, #amarok.es\n\nFeedback:\namarok@kde.org\n\n(Build Date: " __DATE__
")" ),
98 ( "http://amarok.kde.org" ) );
102 : KUniqueApplication()
107 if( AmarokConfig::showSplashscreen() )
109 QPixmap
splashpix( KStandardDirs().findResource("data", "amarok/images/splash_screen.jpg") );
110 m_splash
= new KSplashScreen( splashpix
, Qt::WindowStaysOnTopHint
);
114 registerTaglibPlugins();
116 qRegisterMetaType
<MetaBundle
>();
118 qRegisterMetaType
<Meta::DataPtr
>();
119 qRegisterMetaType
<Meta::DataList
>();
120 qRegisterMetaType
<Meta::TrackPtr
>();
121 qRegisterMetaType
<Meta::TrackList
>();
122 qRegisterMetaType
<Meta::AlbumPtr
>();
123 qRegisterMetaType
<Meta::AlbumList
>();
124 qRegisterMetaType
<Meta::ArtistPtr
>();
125 qRegisterMetaType
<Meta::ArtistList
>();
126 qRegisterMetaType
<Meta::GenrePtr
>();
127 qRegisterMetaType
<Meta::GenreList
>();
128 qRegisterMetaType
<Meta::ComposerPtr
>();
129 qRegisterMetaType
<Meta::ComposerList
>();
130 qRegisterMetaType
<Meta::YearPtr
>();
131 qRegisterMetaType
<Meta::YearList
>();
134 //make sure we have enough cache space for all our crazy svg stuff
135 QPixmapCache::setCacheLimit ( 20 * 1024 );
138 // this is inspired by OpenSceneGraph: osgDB/FilePath.cpp
140 // Start with the the Bundle PlugIns directory.
142 // Get the main bundle first. No need to retain or release it since
143 // we are not keeping a reference
144 CFBundleRef myBundle
= CFBundleGetMainBundle();
147 // CFBundleGetMainBundle will return a bundle ref even if
148 // the application isn't part of a bundle, so we need to
150 // if the path to the bundle ends in ".app" to see if it is
152 // proper application bundle. If it is, the plugins path is
154 CFURLRef urlRef
= CFBundleCopyBundleURL(myBundle
);
157 char bundlePath
[1024];
158 if( CFURLGetFileSystemRepresentation( urlRef
, true, (UInt8
*)bundlePath
, sizeof(bundlePath
) ) )
160 QByteArray
bp( bundlePath
);
161 size_t len
= bp
.length();
162 if( len
> 4 && bp
.right( 4 ) == ".app" )
164 bp
.append( "/Contents/MacOS" );
165 QByteArray path
= getenv( "PATH" );
166 if( path
.length() > 0 )
171 debug() << "setting PATH=" << path
;
172 setenv("PATH", path
, 1);
175 // docs say we are responsible for releasing CFURLRef
181 //needs to be created before the wizard
182 new Amarok::DbusPlayerHandler(); // Must be created first
183 new Amarok::DbusPlaylistHandler();
184 new Amarok::DbusPlaylistBrowserHandler();
185 new Amarok::DbusContextHandler();
186 new Amarok::DbusCollectionHandler();
187 // new Amarok::DbusMediaBrowserHandler();
188 new Amarok::DbusScriptHandler();
190 // tell AtomicString that this is the GUI thread
191 if ( !AtomicString::isMainThread() )
192 qWarning("AtomicString was initialized from a thread other than the GUI "
193 "thread. This could lead to memory leaks.");
196 setupEventHandler_mac((long)this);
198 QDBusConnection::sessionBus().registerService("org.kde.amarok");
199 QTimer::singleShot( 0, this, SLOT( continueInit() ) );
209 // Hiding the OSD before exit prevents crash
210 Amarok::OSD::instance()->hide();
212 EngineBase
* const engine
= EngineController::engine();
214 if ( AmarokConfig::resumePlayback() ) {
215 if ( engine
->state() != Engine::Empty
) {
216 AmarokConfig::setResumeTrack( EngineController::instance()->playingURL().prettyUrl() );
217 AmarokConfig::setResumeTime( engine
->position() );
219 else AmarokConfig::setResumeTrack( QString() ); //otherwise it'll play previous resume next time!
222 EngineController::instance()->endSession(); //records final statistics
223 EngineController::instance()->detach( this );
225 // do even if trayicon is not shown, it is safe
226 Amarok::config().writeEntry( "HiddenOnExit", mainWindow()->isHidden() );
228 CollectionDB::instance()->stopScan();
230 ThreadManager::deleteInstance(); //waits for jobs to finish
232 // delete mainWindow();
234 // this must be deleted before the connection to the Xserver is
235 // severed, or we risk a crash when the QApplication is exited,
236 // I asked Trolltech! *smug*
237 delete Amarok::OSD::instance();
239 AmarokConfig::setVersion( APP_VERSION
);
240 AmarokConfig::self()->writeConfig();
242 //need to unload the engine before the kapplication is destroyed
243 PluginManager::unload( engine
);
247 #include <QStringList>
251 // grabbed from KsCD source, kompatctdisk.cpp
252 QString
urlToDevice(const QString
& device
)
254 KUrl
deviceUrl(device
);
255 if (deviceUrl
.protocol() == "media" || deviceUrl
.protocol() == "system")
257 debug() << "WARNING: urlToDevice needs to be reimplemented with KDE4 technology, it's just a stub at the moment";
258 QDBusInterface
mediamanager( "org.kde.kded", "/modules/mediamanager", "org.kde.MediaManager" );
259 QDBusReply
<QStringList
> reply
= mediamanager
.call( "properties",deviceUrl
.fileName() );
260 if (!reply
.isValid()) {
261 debug() << "Invalid reply from mediamanager";
264 QStringList properties
= reply
;
265 if( properties
.count()< 6 )
267 debug() << "Reply from mediamanager " << properties
[5];
268 return properties
[5];
277 void App::handleCliArgs() //static
279 KCmdLineArgs
* const args
= KCmdLineArgs::parsedArgs();
281 if ( args
->isSet( "cwd" ) )
283 KCmdLineArgs::setCwd( args
->getOption( "cwd" ).toLocal8Bit() );
286 bool haveArgs
= false;
287 if ( args
->count() > 0 )
292 for( int i
= 0; i
< args
->count(); i
++ )
294 KUrl url
= args
->url( i
);
296 // if( url.protocol() == "itpc" || url.protocol() == "pcast" )
297 // PlaylistBrowserNS::instance()->addPodcast( url );
302 int options
= Playlist::AppendAndPlay
;
303 if( args
->isSet( "queue" ) )
304 options
= Playlist::Queue
;
305 else if( args
->isSet( "append" ) || args
->isSet( "enqueue" ) )
306 options
= Playlist::Append
;
307 else if( args
->isSet( "load" ) )
308 options
= Playlist::Replace
;
310 if( args
->isSet( "play" ) )
311 options
|= Playlist::DirectPlay
;
313 The::playlistModel()->insertMedia( list
, options
);
316 //we shouldn't let the user specify two of these since it is pointless!
317 //so we prioritise, pause > stop > play > next > prev
318 //thus pause is the least destructive, followed by stop as brakes are the most important bit of a car(!)
319 //then the others seemed sensible. Feel free to modify this order, but please leave justification in the cvs log
320 //I considered doing some sanity checks (eg only stop if paused or playing), but decided it wasn't worth it
321 else if ( args
->isSet( "pause" ) )
324 EngineController::instance()->pause();
326 else if ( args
->isSet( "stop" ) )
329 EngineController::instance()->stop();
331 else if ( args
->isSet( "play-pause" ) )
334 EngineController::instance()->playPause();
336 else if ( args
->isSet( "play" ) ) //will restart if we are playing
339 EngineController::instance()->play();
341 else if ( args
->isSet( "next" ) )
344 EngineController::instance()->next();
346 else if ( args
->isSet( "previous" ) )
349 EngineController::instance()->previous();
351 else if (args
->isSet("cdplay"))
354 QString device
= args
->getOption("cdplay");
356 if (EngineController::engine()->getAudioCDContents(device
, urls
)) {
357 Meta::TrackList tracks
= CollectionManager::instance()->tracksForUrls( urls
);
358 The::playlistModel()->insertOptioned(
359 tracks
, Playlist::Replace
|Playlist::DirectPlay
);
360 } else { // Default behaviour
362 "Sorry, the engine doesn't support direct play from AudioCD..."
367 if ( args
->isSet( "toggle-playlist-window" ) )
370 pApp
->mainWindow()->showHide();
373 Amarok::config().writeEntry( "Debug Enabled", args
->isSet( "debug" ) );
375 static bool firstTime
= true;
376 if( !firstTime
&& !haveArgs
)
377 pApp
->mainWindow()->activate();
380 args
->clear(); //free up memory
384 /////////////////////////////////////////////////////////////////////////////////////
386 /////////////////////////////////////////////////////////////////////////////////////
388 void App::initCliArgs( int argc
, char *argv
[] ) //static
390 KCmdLineArgs::reset();
391 KCmdLineArgs::init( argc
, argv
, &::aboutData
); //calls KCmdLineArgs::addStdCmdLineOptions()
393 KCmdLineOptions options
;
394 options
.add("+[URL(s)]", ki18n( "Files/URLs to open" ));
396 options
.add("previous", ki18n( "Skip backwards in playlist" ));
398 options
.add("play", ki18n( "Start playing current playlist" ));
400 options
.add("play-pause", ki18n( "Play if stopped, pause if playing" ));
401 options
.add("pause", ki18n( "Pause playback" ));
403 options
.add("stop", ki18n( "Stop playback" ));
405 options
.add("next", ki18n( "Skip forwards in playlist" ));
406 options
.add(":", ki18n("Additional options:"));
408 options
.add("append", ki18n( "Append files/URLs to playlist" ));
410 options
.add("enqueue", ki18n("See append, available for backwards compatability"));
411 options
.add("queue", ki18n("Queue URLs after the currently playing track"));
413 options
.add("load", ki18n("Load URLs, replacing current playlist"));
415 options
.add("debug", ki18n("Print verbose debugging information"));
417 options
.add("toggle-playlist-window", ki18n("Toggle the Playlist-window"));
418 options
.add("wizard", ki18n( "Run first-run wizard" ));
419 options
.add("engine <name>", ki18n( "Use the <name> engine" ));
420 options
.add("cwd <directory>", ki18n( "Base for relative filenames/URLs" ));
421 options
.add("cdplay <device>", ki18n("Play an AudioCD from <device> or system:/media/<device>"));
422 KCmdLineArgs::addCmdLineOptions( options
); //add our own options
426 void App::initGlobalShortcuts()
428 EngineController
* const ec
= EngineController::instance();
431 // m_pGlobalAccel->insert( "play", i18n( "Play" ), 0, KKey("WIN+x"), 0, ec, SLOT( play() ), true, true );
432 action
= new KAction( i18n( "Play" ), mainWindow() );
433 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::Key_X ) );
434 connect( action
, SIGNAL( triggered() ), ec
, SLOT( play() ) );
436 // m_pGlobalAccel->insert( "pause", i18n( "Pause" ), 0, 0, 0, ec, SLOT( pause() ), true, true );
437 action
= new KAction( i18n( "Pause" ), mainWindow() );
438 connect( action
, SIGNAL( triggered() ), ec
, SLOT( pause() ) );
440 // m_pGlobalAccel->insert( "play_pause", i18n( "Play/Pause" ), 0, KKey("WIN+c"), 0, ec, SLOT( playPause() ), true, true );
441 action
= new KAction( i18n( "Play/Pause" ), mainWindow() );
442 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::Key_C ) );
443 connect( action
, SIGNAL( triggered() ), ec
, SLOT( playPause() ) );
445 // m_pGlobalAccel->insert( "stop", i18n( "Stop" ), 0, KKey("WIN+v"), 0, ec, SLOT( stop() ), true, true );
446 action
= new KAction( i18n( "Stop" ), mainWindow() );
447 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::Key_V ) );
448 connect( action
, SIGNAL( triggered() ), ec
, SLOT( stop() ) );
450 // m_pGlobalAccel->insert( "stop_after_global", i18n( "Stop Playing After Current Track" ), 0, KKey("WIN+CTRL+v"), 0, Playlist::instance()->qscrollview(), SLOT( toggleStopAfterCurrentTrack() ), true, true );
451 action
= new KAction( i18n( "Stop Playing After Current Track" ), mainWindow() );
452 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::CTRL + Qt::Key_V ) );
454 // connect( action, SIGNAL( triggered() ), Playlist::instance()->qscrollview(), SLOT( toggleStopAfterCurrentTrack() ) );
456 // m_pGlobalAccel->insert( "next", i18n( "Next Track" ), 0, KKey("WIN+b"), 0, ec, SLOT( next() ), true, true );
457 action
= new KAction( i18n( "Next Track" ), mainWindow() );
458 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::Key_B ) );
459 connect( action
, SIGNAL( triggered() ), ec
, SLOT( next() ) );
461 // m_pGlobalAccel->insert( "prev", i18n( "Previous Track" ), 0, KKey("WIN+z"), 0, ec, SLOT( previous() ), true, true );
462 action
= new KAction( i18n( "Previous Track" ), mainWindow() );
463 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::Key_Z ) );
464 connect( action
, SIGNAL( triggered() ), ec
, SLOT( previous() ) );
466 // m_pGlobalAccel->insert( "volup", i18n( "Increase Volume" ), 0, KKey("WIN+KP_Add"), 0, ec, SLOT( increaseVolume() ), true, true );
467 action
= new KAction( i18n( "Increase Volume" ), mainWindow() );
468 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::Key_Plus ) );
469 connect( action
, SIGNAL( triggered() ), ec
, SLOT( increaseVolume() ) );
471 // m_pGlobalAccel->insert( "voldn", i18n( "Decrease Volume" ), 0, KKey("WIN+KP_Subtract"), 0, ec, SLOT( decreaseVolume() ), true, true );
472 action
= new KAction( i18n( "Decrease Volume" ), mainWindow() );
473 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::Key_Minus ) );
474 connect( action
, SIGNAL( triggered() ), ec
, SLOT( decreaseVolume() ) );
477 // m_pGlobalAccel->insert( "seekforward", i18n( "Seek Forward" ), 0, KKey("WIN+Shift+KP_Add"), 0, ec, SLOT( seekForward() ), true, true );
478 action
= new KAction( i18n( "Seek Forward" ), mainWindow() );
479 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::SHIFT + Qt::Key_Plus ) );
480 connect( action
, SIGNAL( triggered() ), ec
, SLOT( seekForward() ) );
483 // m_pGlobalAccel->insert( "seekbackward", i18n( "Seek Backward" ), 0, KKey("WIN+Shift+KP_Subtract"), 0, ec, SLOT( seekBackward() ), true, true );
484 action
= new KAction( i18n( "Seek Backward" ), mainWindow() );
485 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::SHIFT + Qt::Key_Minus ) );
486 connect( action
, SIGNAL( triggered() ), ec
, SLOT( seekBackward() ) );
488 // m_pGlobalAccel->insert( "playlist_add", i18n( "Add Media..." ), 0, KKey("WIN+a"), 0, mainWindow(), SLOT( slotAddLocation() ), true, true );
489 action
= new KAction( i18n( "Add Media..." ), mainWindow() );
490 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::Key_A ) );
491 connect( action
, SIGNAL( triggered() ), mainWindow(), SLOT( slotAddLocation() ) );
493 // m_pGlobalAccel->insert( "show", i18n( "Toggle Playlist Window" ), 0, KKey("WIN+p"), 0, mainWindow(), SLOT( showHide() ), true, true );
494 action
= new KAction( i18n( "Toggle Playlist Window" ), mainWindow() );
495 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::Key_P ) );
496 connect( action
, SIGNAL( triggered() ), mainWindow(), SLOT( showHide() ) );
499 // m_pGlobalAccel->insert( "osd", i18n( "Show OSD" ), 0, KKey("WIN+o"), 0, Amarok::OSD::instance(), SLOT( forceToggleOSD() ), true, true );
500 action
= new KAction( i18n( "Show OSD" ), mainWindow() );
501 // action->setGlobalShortcut( KShortcut( Qt::META + Qt::Key_O ) );
502 connect( action
, SIGNAL( triggered() ), Amarok::OSD::instance(), SLOT( forceToggleOSD() ) );
504 m_pGlobalAccel
->insert( "mute", i18n( "Mute Volume" ), 0, KKey("WIN+m"), 0,
505 ec
, SLOT( mute() ), true, true );
506 m_pGlobalAccel
->insert( "rating1", i18n( "Rate Current Track: 1" ), 0, KKey("WIN+1"), 0,
507 this, SLOT( setRating1() ), true, true );
508 m_pGlobalAccel
->insert( "rating2", i18n( "Rate Current Track: 2" ), 0, KKey("WIN+2"), 0,
509 this, SLOT( setRating2() ), true, true );
510 m_pGlobalAccel
->insert( "rating3", i18n( "Rate Current Track: 3" ), 0, KKey("WIN+3"), 0,
511 this, SLOT( setRating3() ), true, true );
512 m_pGlobalAccel
->insert( "rating4", i18n( "Rate Current Track: 4" ), 0, KKey("WIN+4"), 0,
513 this, SLOT( setRating4() ), true, true );
514 m_pGlobalAccel
->insert( "rating5", i18n( "Rate Current Track: 5" ), 0, KKey("WIN+5"), 0,
515 this, SLOT( setRating5() ), true, true );
518 // KGlobalAccel::self()->setConfigGroup( "Shortcuts" );
519 // KGlobalAccel::self()->readSettings( KGlobal::config().data() );
522 // FIXME Is this still needed with KDE4?
524 //TODO fix kde accel system so that kactions find appropriate global shortcuts
525 // and there is only one configure shortcuts dialog
527 KActionCollection
* const ac
= Amarok::actionCollection();
528 KAccelShortcutList
list( m_pGlobalAccel
);
530 for( uint i
= 0; i
< list
.count(); ++i
)
532 KAction
*action
= ac
->action( list
.name( i
).toLatin1() );
536 //this is a hack really, also it means there may be two calls to the slot for the shortcut
537 action
->setShortcutConfigurable( false );
538 action
->setShortcut( list
.shortcut( i
) );
545 /////////////////////////////////////////////////////////////////////////////////////
547 /////////////////////////////////////////////////////////////////////////////////////
549 #include <id3v1tag.h>
550 #include <tbytevector.h>
551 #include <QTextCodec>
554 //this class is only used in this module, so I figured I may as well define it
555 //here and save creating another header/source file combination
557 class ID3v1StringHandler
: public TagLib::ID3v1::StringHandler
561 virtual TagLib::String
parse( const TagLib::ByteVector
&data
) const
563 return QStringToTString( m_codec
->toUnicode( data
.data(), data
.size() ) );
566 virtual TagLib::ByteVector
render( const TagLib::String
&ts
) const
568 const QByteArray qcs
= m_codec
->fromUnicode( TStringToQString(ts
) );
569 return TagLib::ByteVector( qcs
, (uint
) qcs
.length() );
573 ID3v1StringHandler( int codecIndex
)
574 : m_codec( QTextCodec::codecForName( QTextCodec::availableCodecs().at( codecIndex
) ) )
576 debug() << "codec: " << m_codec
;
577 debug() << "codec-name: " << m_codec
->name();
580 ID3v1StringHandler( QTextCodec
*codec
)
583 debug() << "codec: " << m_codec
;
584 debug() << "codec-name: " << m_codec
->name();
587 virtual ~ID3v1StringHandler()
592 void App::applySettings( bool firstTime
)
594 ///Called when the configDialog is closed with OK or Apply
599 //probably needs to be done in TrayIcon when it receives a QEvent::ToolTip (see QSystemtrayIcon documentation)
600 //TrackToolTip::instance()->removeFromWidget( m_tray );
602 Scrobbler::instance()->applySettings();
603 Amarok::OSD::instance()->applySettings();
604 CollectionDB::instance()->applySettings();
606 m_tray
->setVisible( AmarokConfig::showTrayIcon() );
607 //TrackToolTip::instance()->addToWidget( m_tray );
611 //on startup we need to show the window, but only if it wasn't hidden on exit
612 //and always if the trayicon isn't showing
613 QWidget
* main_window
= mainWindow();
615 if( ( main_window
&& firstTime
&& !Amarok::config().readEntry( "HiddenOnExit", false ) ) || ( main_window
&& !AmarokConfig::showTrayIcon() ) )
620 //takes longer but feels shorter. Crazy eh? :)
621 kapp
->processEvents( QEventLoop::ExcludeUserInputEvents
);
626 EngineBase
*engine
= EngineController::engine();
628 if( firstTime
|| AmarokConfig::soundSystem() !=
629 PluginManager::getService( engine
)->property( "X-KDE-Amarok-name" ).toString() )
631 //will unload engine for us first if necessary
632 engine
= EngineController::instance()->loadEngine();
635 engine
->setXfadeLength( AmarokConfig::crossfade() ? AmarokConfig::crossfadeLength() : 0 );
636 engine
->setVolume( AmarokConfig::masterVolume() );
638 engine
->setEqualizerEnabled( AmarokConfig::equalizerEnabled() );
639 if ( AmarokConfig::equalizerEnabled() )
640 engine
->setEqualizerParameters( AmarokConfig::equalizerPreamp(), AmarokConfig::equalizerGains() );
642 Amarok::actionCollection()->action("play_audiocd")->setEnabled( EngineController::hasEngineProperty( "HasKIO" ) || EngineController::hasEngineProperty("HasCDDA"));
646 //PORT 2.0 CollectionView::instance()->renderView(true);
649 //PORT 2.0 ContextBrowser::instance()->renderView();
652 { // delete unneeded cover images from cache
653 const QString size
= QString::number( AmarokConfig::coverPreviewSize() ) + '@';
654 const QDir cacheDir
= Amarok::saveLocation( "albumcovers/cache/" );
655 const QStringList obsoleteCovers
= cacheDir
.entryList( QStringList("*") );
656 foreach( QString it
, obsoleteCovers
)
657 if ( !it
.startsWith( size
) && !it
.startsWith( "50@" ) )
658 QFile( cacheDir
.filePath( it
) ).remove();
662 // Bizarrely and ironically calling this causes crashes for
663 // some people! FIXME
664 //AmarokConfig::self()->writeConfig();
673 const KCmdLineArgs
* const args
= KCmdLineArgs::parsedArgs();
674 bool restoreSession
= args
->count() == 0 || args
->isSet( "append" ) || args
->isSet( "enqueue" )
675 || Amarok::config().readEntry( "AppendAsDefault", false );
677 // Make this instance so it can start receiving signals
678 MoodServer::instance();
680 // Remember old folder setup, so we can detect changes after the wizard was used
681 //const QStringList oldCollectionFolders = MountPointManager::instance()->collectionFolders();
684 // Is this needed in Amarok 2?
685 if( Amarok::config().readEntry( "First Run", true ) || args
->isSet( "wizard" ) )
687 std::cout
<< "STARTUP\n" << std::flush
; //hide the splashscreen
688 Amarok::config().writeEntry( "First Run", false );
689 Amarok::config().sync();
692 CollectionDB::instance()->checkDatabase();
694 m_mainWindow
= new MainWindow();
696 m_tray
= new Amarok::TrayIcon( mainWindow() );
698 mainWindow()->init(); //creates the playlist, browsers, etc.
699 //init playlist window as soon as the database is guaranteed to be usable
700 //connect( CollectionDB::instance(), SIGNAL( databaseUpdateDone() ), mainWindow(), SLOT( init() ) );
701 //initGlobalShortcuts();
702 //load previous playlist in separate thread
703 if ( restoreSession
&& AmarokConfig::savePlaylist() )
705 The::playlistModel()->restoreSession();
707 if( args
->isSet( "engine" ) ) {
708 // we correct some common errors (case issues, missing -engine off the end)
709 QString engine
= args
->getOption( "engine" ).toLower();
710 if( engine
.startsWith( "gstreamer" ) ) engine
= "gst-engine";
711 if( !engine
.endsWith( "engine" ) ) engine
+= "-engine";
713 AmarokConfig::setSoundSystem( engine
);
716 //create engine, show TrayIcon etc.
717 applySettings( true );
719 // Start ScriptManager. Must be created _after_ MainWindow.
720 ScriptManager::instance();
722 //notify loader application that we have started
723 std::cout
<< "STARTUP\n" << std::flush
;
725 //do after applySettings(), or the OSD will flicker and other wierdness!
726 //do before restoreSession()!
727 EngineController::instance()->attach( this );
729 //set a default interface
730 engineStateChanged( Engine::Empty
);
732 if ( AmarokConfig::resumePlayback() && restoreSession
&& !args
->isSet( "stop" ) ) {
733 //restore session as long as the user didn't specify media to play etc.
734 //do this after applySettings() so OSD displays correctly
735 EngineController::instance()->restoreSession();
738 // Refetch covers every 80 days to comply with Amazon license
741 CollectionDB
*collDB
= CollectionDB::instance();
743 // If database version is updated, the collection needs to be rescanned.
744 // Works also if the collection is empty for some other reason
745 // (e.g. deleted collection.db)
746 if ( CollectionDB::instance()->isEmpty() )
748 //connect( collDB, SIGNAL( databaseUpdateDone() ), collDB, SLOT( startScan() ) );
751 else if ( AmarokConfig::monitorChanges() )
752 //connect( collDB, SIGNAL( databaseUpdateDone() ), collDB, SLOT( scanModifiedDirs() ) );
753 collDB
->scanModifiedDirs();
762 bool Amarok::genericEventHandler( QWidget
*recipient
, QEvent
*e
)
764 //this is used as a generic event handler for widgets that want to handle
765 //typical events in an Amarok fashion
767 //to use it just pass the event eg:
769 // void Foo::barEvent( QBarEvent *e )
771 // Amarok::genericEventHandler( this, e );
776 case QEvent::DragEnter
:
777 #define e static_cast<QDropEvent*>(e)
778 e
->setAccepted( KUrl::List::canDecode( e
->mimeData() ) );
783 KUrl::List list
= KUrl::List::fromMimeData( e
->mimeData() );
784 if( !list
.isEmpty() )
787 //FIXME this isn't a good way to determine if there is a currentTrack, need playlist() function
788 const bool b
= EngineController::engine()->loaded();
790 popup
.insertItem( KIcon( Amarok::icon( "add_playlist" ) ), i18n( "&Append to Playlist" ),
792 popup
.insertItem( KIcon( Amarok::icon( "add_playlist" ) ), i18n( "Append && &Play" ),
793 Playlist::DirectPlay
| Playlist::Append
);
795 popup
.insertItem( KIcon( Amarok::icon( "fast_forward" ) ), i18n( "&Queue Track" ),
797 popup
.addSeparator();
798 popup
.insertItem( i18n( "&Cancel" ), 0 );
800 const int id
= popup
.exec( recipient
->mapToGlobal( e
->pos() ) );
803 The::playlistModel()->insertMedia( list
, id
);
811 //this like every entry in the generic event handler is used by more than one widget
812 //please don't remove!
815 #define e static_cast<QWheelEvent*>(e)
817 //this behaviour happens for the systray
818 //to override one, override it in that class
822 case Qt::ControlModifier
:
824 const bool up
= e
->delta() > 0;
826 //if this seems strange to you, please bring it up on #amarok
827 //for discussion as we can't decide which way is best!
828 if( up
) EngineController::instance()->previous();
829 else EngineController::instance()->next();
832 case Qt::ShiftModifier
:
834 EngineController::instance()->seekRelative( ( e
->delta() / 120 ) * 5000 ); //5 seconds for keyboard seeking.
838 EngineController::instance()->increaseVolume( e
->delta() / Amarok::VOLUME_SENSITIVITY
);
849 //KDE policy states we should hide to tray and not quit() when the
850 //close window button is pushed for the main widget
852 static_cast<QCloseEvent
*>(e
)->accept(); //if we don't do this the info box appears on quit()!
854 if( AmarokConfig::showTrayIcon() && !e
->spontaneous() && !kapp
->sessionSaving() )
856 KMessageBox::information( recipient
,
857 i18n( "<qt>Closing the main-window will keep Amarok running in the System Tray. "
858 "Use <B>Quit</B> from the menu, or the Amarok tray-icon to exit the application.</qt>" ),
859 i18n( "Docking in System Tray" ), "hideOnCloseInfo" );
873 void App::engineStateChanged( Engine::State state
, Engine::State oldState
)
875 Meta::TrackPtr track
= EngineController::instance()->currentTrack();
876 //track is 0 if the engien state is Empty. we check that in the switch
880 mainWindow()->setCaption( "Amarok" );
881 TrackToolTip::instance()->clear();
882 Amarok::OSD::instance()->setImage( QImage( KIconLoader().iconPath( "amarok", -KIconLoader::SizeHuge
) ) );
885 case Engine::Playing
:
886 if ( oldState
== Engine::Paused
)
887 Amarok::OSD::instance()->OSDWidget::show( i18nc( "state, as in playing", "Play" ) );
888 if ( !track
->prettyName().isEmpty() )
889 //TODO: write a utility function somewhere
890 mainWindow()->setCaption( i18n("Amarok - %1", /*bundle.veryNiceTitle()*/ track
->prettyName() ) );
894 Amarok::OSD::instance()->OSDWidget::show( i18n("Paused") );
898 mainWindow()->setCaption( "Amarok" );
906 void App::engineNewMetaData( const MetaBundle
&bundle
, bool /*trackChanged*/ )
908 Amarok::OSD::instance()->show( bundle
);
909 if ( !bundle
.prettyTitle().isEmpty() )
910 mainWindow()->setCaption( i18n("Amarok - %1", bundle
.veryNiceTitle() ) );
912 TrackToolTip::instance()->setTrack( bundle
);
915 void App::engineTrackPositionChanged( long position
, bool /*userSeek*/ )
917 TrackToolTip::instance()->setPos( position
);
920 void App::engineVolumeChanged( int newVolume
)
922 Amarok::OSD::instance()->OSDWidget::volChanged( newVolume
);
925 void App::slotConfigEqualizer() //SLOT
927 EqualizerSetup::instance()->show();
928 EqualizerSetup::instance()->raise();
932 void App::slotConfigAmarok( const QByteArray
& page
)
934 DEBUG_THREAD_FUNC_INFO
936 Amarok2ConfigDialog
* dialog
= static_cast<Amarok2ConfigDialog
*>( KConfigDialog::exists( "settings" ) );
940 //KConfigDialog didn't find an instance of this dialog, so lets create it :
941 dialog
= new Amarok2ConfigDialog( mainWindow(), "settings", AmarokConfig::self() );
943 connect( dialog
, SIGNAL(settingsChanged(const QString
&)), SLOT(applySettings()) );
946 //FIXME it seems that if the dialog is on a different desktop it gets lost
947 // what do to? detect and move it?
949 // if ( page.isNull() )
951 // dialog->showPage( AmarokConfigDialog::s_currentPage );
953 dialog
->showPageByName( page
);
957 dialog
->activateWindow();
960 void App::slotConfigShortcuts()
962 KShortcutsDialog::configure( Amarok::actionCollection(), KShortcutsEditor::LetterShortcutsAllowed
, mainWindow() );
965 void App::slotConfigToolBars()
967 KEditToolBar
dialog( mainWindow()->actionCollection(), mainWindow() );
968 dialog
.setResourceFile( mainWindow()->xmlFile() );
970 dialog
.showButton( KEditToolBar::Apply
, false );
972 // if( dialog.exec() )
974 // mainWindow()->reloadXML();
975 // mainWindow()->createGUI();
979 void App::setUseScores( bool use
)
981 AmarokConfig::setUseScores( use
);
982 emit
useScores( use
);
985 void App::setUseRatings( bool use
)
987 AmarokConfig::setUseRatings( use
);
988 emit
useRatings( use
);
991 void App::setMoodbarPrefs( bool show
, bool moodier
, int alter
, bool withMusic
)
993 AmarokConfig::setShowMoodbar( show
);
994 AmarokConfig::setMakeMoodier( moodier
);
995 AmarokConfig::setAlterMood( alter
);
996 AmarokConfig::setMoodsWithMusic( withMusic
);
997 emit
moodbarPrefs( show
, moodier
, alter
, withMusic
);
1000 KIO::Job
*App::trashFiles( const KUrl::List
&files
)
1002 KIO::Job
*job
= KIO::trash( files
);
1003 Amarok::StatusBar::instance()->newProgressOperation( job
).setDescription( i18n("Moving files to trash") );
1004 connect( job
, SIGNAL( result( KJob
* ) ), this, SLOT( slotTrashResult( KJob
* ) ) );
1008 void App::setRating( int n
)
1010 if( !AmarokConfig::useRatings() ) return;
1014 const Engine::State s
= EngineController::instance()->engine()->state();
1015 if( s
== Engine::Playing
|| s
== Engine::Paused
|| s
== Engine::Idle
)
1017 Meta::TrackPtr track
= EngineController::instance()->currentTrack();
1018 track
->setRating( n
);
1019 Amarok::OSD::instance()->OSDWidget::ratingChanged( track
->rating() );
1022 // else if( MainWindow::self()->isReallyShown() && Playlist::instance()->qscrollview()->hasFocus() )
1023 // Playlist::instance()->setSelectedRatings( n );
1026 void App::slotTrashResult( KJob
*job
)
1029 job
->uiDelegate()->showErrorMessage();
1034 emit
prepareToQuit();
1035 if( MediaBrowser::instance() && MediaBrowser::instance()->blockQuit() )
1037 // don't quit yet, as some media devices still have to finish transferring data
1038 QTimer::singleShot( 100, this, SLOT( quit() ) );
1041 KApplication::quit();
1048 //TODO remove these, they suck, do a generic getImage
1050 QPixmap
getPNG( const QString
&filename
)
1052 QString file
= !filename
.endsWith( ".png", Qt::CaseInsensitive
) ? "amarok/images/%1.png" : "amarok/images/%1";
1054 return QPixmap( KStandardDirs::locate( "data", file
.arg( filename
) ), "PNG" );
1057 QPixmap
getJPG( const QString
&filename
)
1059 QString file
= !filename
.endsWith( ".jpg", Qt::CaseInsensitive
) ? "amarok/images/%1.jpg" : "amarok/images/%1";
1061 return QPixmap( KStandardDirs::locate( "data", QString( "amarok/images/%1.jpg" ).arg( filename
) ), "JPEG" );
1064 QWidget
*mainWindow()
1066 return pApp
->mainWindow();
1069 KActionCollection
*actionCollection()
1071 return pApp
->mainWindow()->actionCollection();
1074 KConfigGroup
config( const QString
&group
)
1076 //Slightly more useful config() that allows setting the group simultaneously
1077 // KGlobal::config()->setGroup( group );
1078 KConfigGroup configGroup
= KGlobal::config()->group( group
);
1082 bool invokeBrowser( const QString
& url
)
1084 //URL can be in whatever forms KUrl understands - ie most.
1085 const QString cmd
= KShell::quoteArg(AmarokConfig::externalBrowser())
1086 + ' ' + KShell::quoteArg(KUrl( url
).url());
1087 return KRun::runCommand( cmd
, 0L ) > 0;
1090 namespace ColorScheme
1099 OverrideCursor::OverrideCursor( Qt::CursorShape cursor
)
1101 QApplication::setOverrideCursor( cursor
== Qt::WaitCursor
?
1106 OverrideCursor::~OverrideCursor()
1108 QApplication::restoreOverrideCursor();
1111 QString
saveLocation( const QString
&directory
)
1113 globalDirsMutex
.lock();
1114 QString result
= KGlobal::dirs()->saveLocation( "data", QString("amarok/") + directory
, true );
1115 globalDirsMutex
.unlock();
1119 QString
cleanPath( const QString
&path
)
1121 QString result
= path
;
1123 result
.replace( QChar(0x00e4), "ae" ).replace( QChar(0x00c4), "Ae" );
1124 result
.replace( QChar(0x00f6), "oe" ).replace( QChar(0x00d6), "Oe" );
1125 result
.replace( QChar(0x00fc), "ue" ).replace( QChar(0x00dc), "Ue" );
1126 result
.replace( QChar(0x00df), "ss" );
1128 // some strange accents
1129 result
.replace( QChar(0x00e7), "c" ).replace( QChar(0x00c7), "C" );
1130 result
.replace( QChar(0x00fd), "y" ).replace( QChar(0x00dd), "Y" );
1131 result
.replace( QChar(0x00f1), "n" ).replace( QChar(0x00d1), "N" );
1133 // czech letters with carons
1134 result
.replace( QChar(0x0161), "s" ).replace( QChar(0x0160), "S" );
1135 result
.replace( QChar(0x010d), "c" ).replace( QChar(0x010c), "C" );
1136 result
.replace( QChar(0x0159), "r" ).replace( QChar(0x0158), "R" );
1137 result
.replace( QChar(0x017e), "z" ).replace( QChar(0x017d), "Z" );
1138 result
.replace( QChar(0x0165), "t" ).replace( QChar(0x0164), "T" );
1139 result
.replace( QChar(0x0148), "n" ).replace( QChar(0x0147), "N" );
1140 result
.replace( QChar(0x010f), "d" ).replace( QChar(0x010e), "D" );
1143 QChar a
[] = { 'a', 0xe0,0xe1,0xe2,0xe3,0xe5, 0 };
1144 QChar A
[] = { 'A', 0xc0,0xc1,0xc2,0xc3,0xc5, 0 };
1145 QChar E
[] = { 'e', 0xe8,0xe9,0xea,0xeb,0x11a, 0 };
1146 QChar e
[] = { 'E', 0xc8,0xc9,0xca,0xcb,0x11b, 0 };
1147 QChar i
[] = { 'i', 0xec,0xed,0xee,0xef, 0 };
1148 QChar I
[] = { 'I', 0xcc,0xcd,0xce,0xcf, 0 };
1149 QChar o
[] = { 'o', 0xf2,0xf3,0xf4,0xf5,0xf8, 0 };
1150 QChar O
[] = { 'O', 0xd2,0xd3,0xd4,0xd5,0xd8, 0 };
1151 QChar u
[] = { 'u', 0xf9,0xfa,0xfb,0x16e, 0 };
1152 QChar U
[] = { 'U', 0xd9,0xda,0xdb,0x16f, 0 };
1153 QChar nul
[] = { 0 };
1154 QChar
*replacements
[] = { a
, A
, e
, E
, i
, I
, o
, O
, u
, U
, nul
};
1156 for( int i
= 0; i
< result
.length(); i
++ )
1158 QChar c
= result
[ i
];
1159 for( uint n
= 0; replacements
[n
][0] != QChar(0); n
++ )
1161 for( uint k
=0; replacements
[n
][k
] != QChar(0); k
++ )
1163 if( replacements
[n
][k
] == c
)
1165 c
= replacements
[n
][0];
1174 QString
asciiPath( const QString
&path
)
1176 QString result
= path
;
1177 for( int i
= 0; i
< result
.length(); i
++ )
1179 QChar c
= result
[ i
];
1180 if( c
> QChar(0x7f) || c
== QChar(0) )
1189 QString
vfatPath( const QString
&path
)
1193 for( int i
= 0; i
< s
.length(); i
++ )
1197 || c
=='*' || c
=='?' || c
=='<' || c
=='>'
1198 || c
=='|' || c
=='"' || c
==':' || c
=='/'
1204 uint len
= s
.length();
1205 if( len
== 3 || (len
> 3 && s
[3] == '.') )
1207 QString l
= s
.left(3).toLower();
1208 if( l
=="aux" || l
=="con" || l
=="nul" || l
=="prn" )
1211 else if( len
== 4 || (len
> 4 && s
[4] == '.') )
1213 QString l
= s
.left(3).toLower();
1214 QString d
= s
.mid(3,1);
1215 if( (l
=="com" || l
=="lpt") &&
1216 (d
=="0" || d
=="1" || d
=="2" || d
=="3" || d
=="4" ||
1217 d
=="5" || d
=="6" || d
=="7" || d
=="8" || d
=="9") )
1221 while( s
.startsWith( '.' ) )
1224 while( s
.endsWith( '.' ) )
1225 s
= s
.left( s
.length()-1 );
1229 if( s
[len
-1] == ' ' )
1235 QString
decapitateString( const QString
&input
, const QString
&ref
)
1237 QString t
= ref
.toUpper();
1238 int length
= t
.length();
1239 int commonLength
= 0;
1242 if ( input
.toUpper().startsWith( t
) )
1244 commonLength
= t
.length();
1245 t
= ref
.toUpper().left( t
.length() + length
/2 );
1250 t
= ref
.toUpper().left( t
.length() - length
/2 );
1254 QString clean
= input
;
1255 if( t
.endsWith( ' ' ) || !ref
.at( t
.length() ).isLetterOrNumber() ) // common part ends with a space or complete word
1256 clean
= input
.right( input
.length() - commonLength
).trimmed();
1260 void setUseScores( bool use
) { App::instance()->setUseScores( use
); }
1261 void setUseRatings( bool use
) { App::instance()->setUseRatings( use
); }
1262 void setMoodbarPrefs( bool show
, bool moodier
, int alter
, bool withMusic
)
1263 { App::instance()->setMoodbarPrefs( show
, moodier
, alter
, withMusic
); }
1264 KIO::Job
*trashFiles( const KUrl::List
&files
) { return App::instance()->trashFiles( files
); }