shell.cpp 24.9 KB
Newer Older
1 2 3 4 5 6 7
/***************************************************************************
 *   Copyright (C) 2002 by Wilco Greven <greven@kde.org>                   *
 *   Copyright (C) 2002 by Chris Cheney <ccheney@cheney.cx>                *
 *   Copyright (C) 2003 by Benjamin Meyer <benjamin@csh.rit.edu>           *
 *   Copyright (C) 2003-2004 by Christophe Devriese                        *
 *                         <Christophe.Devriese@student.kuleuven.ac.be>    *
 *   Copyright (C) 2003 by Laurent Montel <montel@kde.org>                 *
Albert Astals Cid's avatar
Albert Astals Cid committed
8
 *   Copyright (C) 2003-2004 by Albert Astals Cid <aacid@kde.org>          *
9 10 11 12
 *   Copyright (C) 2003 by Luboš Luňák <l.lunak@kde.org>                   *
 *   Copyright (C) 2003 by Malcolm Hunter <malcolm.hunter@gmx.co.uk>       *
 *   Copyright (C) 2004 by Dominique Devriese <devriese@kde.org>           *
 *   Copyright (C) 2004 by Dirk Mueller <mueller@kde.org>                  *
13 14 15
 *   Copyright (C) 2017    Klarälvdalens Datakonsult AB, a KDAB Group      *
 *                         company, info@kdab.com. Work sponsored by the   *
 *                         LiMux project of the city of Munich             *
16 17 18 19 20 21
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/
Christophe Devriese's avatar
Christophe Devriese committed
22

Albert Astals Cid's avatar
Albert Astals Cid committed
23 24
#include "shell.h"

25
// qt/kde includes
26 27 28 29 30
#include <QDesktopWidget>
#include <QTimer>
#include <QDBusConnection>
#include <QMenuBar>
#include <QApplication>
31
#include <QFileDialog>
32 33
#include <KPluginLoader>
#include <KMessageBox>
Frederik Gladhorn's avatar
Frederik Gladhorn committed
34 35
#include <QMimeType>
#include <QMimeDatabase>
36 37 38 39 40 41 42
#include <KStandardAction>
#include <KToolBar>
#include <KRecentFilesAction>
#include <KServiceTypeTrader>
#include <KToggleFullScreenAction>
#include <KActionCollection>
#include <KWindowSystem>
Laurent Montel's avatar
Laurent Montel committed
43
#include <QTabWidget>
44
#include <KXMLGUIFactory>
45
#include <QDragMoveEvent>
Jonathan Doman's avatar
Jonathan Doman committed
46
#include <QTabBar>
47
#include <KConfigGroup>
Vishesh Handa's avatar
Vishesh Handa committed
48
#include <KUrlMimeData>
Laurent Montel's avatar
Laurent Montel committed
49 50
#include <KLocalizedString>
#include <KSharedConfig>
51
#include <KIO/Global>
52
#ifndef Q_OS_WIN
Ivan Čukić's avatar
Ivan Čukić committed
53 54 55
#include <KActivities/ResourceInstance>
#endif

56
// local includes
57
#include "kdocumentviewer.h"
58
#include "../interfaces/viewerinterface.h"
59
#include "shellutils.h"
60

61 62 63
static const char *shouldShowMenuBarComingFromFullScreen = "shouldShowMenuBarComingFromFullScreen";
static const char *shouldShowToolBarComingFromFullScreen = "shouldShowToolBarComingFromFullScreen";

64 65 66
static const char* const SESSION_URL_KEY = "Urls";
static const char* const SESSION_TAB_KEY = "ActiveTab";

67 68
Shell::Shell( const QString &serializedOptions )
  : KParts::MainWindow(), m_menuBarWasShown(true), m_toolBarWasShown(true)
69
#ifndef Q_OS_WIN
70
    , m_activityResource(nullptr)
Ivan Čukić's avatar
Ivan Čukić committed
71
#endif
72
    , m_isValid(true)
73
{
Laurent Montel's avatar
Laurent Montel committed
74
  setObjectName( QStringLiteral( "okular::Shell#" ) );
75
  setContextMenuPolicy( Qt::NoContextMenu );
76 77
  // otherwise .rc file won't be found by unit test
  setComponentName(QStringLiteral("okular"), QString());
78
  // set the shell's ui resource file
Laurent Montel's avatar
Laurent Montel committed
79
  setXMLFile(QStringLiteral("shell.rc"));
80
  m_fileformatsscanned = false;
81
  m_showMenuBarAction = nullptr;
82 83 84
  // this routine will find and load our Part.  it finds the Part by
  // name which is a bad idea usually.. but it's alright in this
  // case since our Part is made for this Shell
Laurent Montel's avatar
Laurent Montel committed
85
  KPluginLoader loader(QStringLiteral("okularpart"));
Frederik Gladhorn's avatar
Frederik Gladhorn committed
86
  m_partFactory = loader.factory();
Jonathan Doman's avatar
Jonathan Doman committed
87
  if (!m_partFactory)
88 89 90
  {
    // if we couldn't find our Part, we exit since the Shell by
    // itself can't do anything useful
91
    m_isValid = false;
Frederik Gladhorn's avatar
Frederik Gladhorn committed
92
    KMessageBox::error(this, i18n("Unable to find the Okular component: %1", loader.errorString()));
93 94
    return;
  }
95

96
  // now that the Part plugin is loaded, create the part
Jonathan Doman's avatar
Jonathan Doman committed
97 98
  KParts::ReadWritePart* const firstPart = m_partFactory->create< KParts::ReadWritePart >( this );
  if (firstPart)
99
  {
Jonathan Doman's avatar
Jonathan Doman committed
100
    // Setup tab bar
Laurent Montel's avatar
Laurent Montel committed
101
    m_tabWidget = new QTabWidget( this );
Jonathan Doman's avatar
Jonathan Doman committed
102 103
    m_tabWidget->setTabsClosable( true );
    m_tabWidget->setElideMode( Qt::ElideRight );
104
    m_tabWidget->tabBar()->hide();
Jonathan Doman's avatar
Jonathan Doman committed
105
    m_tabWidget->setDocumentMode( true );
Jonathan Doman's avatar
Jonathan Doman committed
106
    m_tabWidget->setMovable( true );
107 108 109 110

    m_tabWidget->setAcceptDrops(true);
    m_tabWidget->installEventFilter(this);

Laurent Montel's avatar
Laurent Montel committed
111 112 113
    connect( m_tabWidget, &QTabWidget::currentChanged, this, &Shell::setActiveTab );
    connect( m_tabWidget, &QTabWidget::tabCloseRequested, this, &Shell::closeTab );
    connect( m_tabWidget->tabBar(), &QTabBar::tabMoved, this, &Shell::moveTabData );
Jonathan Doman's avatar
Jonathan Doman committed
114 115 116

    setCentralWidget( m_tabWidget );

117 118
    // then, setup our actions
    setupActions();
Laurent Montel's avatar
Laurent Montel committed
119
    connect( QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &QObject::deleteLater );
120
    // and integrate the part's GUI with the shell's
121
    setupGUI(Keys | ToolBar | Save);
Jonathan Doman's avatar
Jonathan Doman committed
122 123 124 125 126
    createGUI(firstPart);
    connectPart( firstPart );

    m_tabs.append( firstPart );
    m_tabWidget->addTab( firstPart->widget(), QString() );
127

128 129
    readSettings();

130 131
    m_unique = ShellUtils::unique(serializedOptions);
    if (m_unique)
132
    {
Laurent Montel's avatar
Laurent Montel committed
133
        m_unique = QDBusConnection::sessionBus().registerService(QStringLiteral("org.kde.okular"));
134 135 136
        if (!m_unique)
            KMessageBox::information(this, i18n("There is already a unique Okular instance running. This instance won't be the unique one."));
    }
137 138 139 140 141
    else
    {
        QString serviceName = QStringLiteral("org.kde.okular-") + QString::number(qApp->applicationPid());
        QDBusConnection::sessionBus().registerService(serviceName);
    }
142
    if (ShellUtils::noRaise(serializedOptions))
143 144 145
    {
        setAttribute(Qt::WA_ShowWithoutActivating);
    }
146

Laurent Montel's avatar
Laurent Montel committed
147
    QDBusConnection::sessionBus().registerObject(QStringLiteral("/okularshell"), this, QDBusConnection::ExportScriptableSlots);
148
  }
149 150
  else
  {
151
    m_isValid = false;
152 153
    KMessageBox::error(this, i18n("Unable to find the Okular component."));
  }
154 155
}

156 157
bool Shell::eventFilter(QObject *obj, QEvent *event)
{
158 159
    Q_UNUSED(obj);

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    QDragMoveEvent* dmEvent = dynamic_cast<QDragMoveEvent*>(event);
    if (dmEvent) {
        bool accept = dmEvent->mimeData()->hasUrls();
        event->setAccepted(accept);
        return accept;
    }

    QDropEvent* dEvent = dynamic_cast<QDropEvent*>(event);
    if (dEvent) {
        const QList<QUrl> list = KUrlMimeData::urlsFromMimeData(dEvent->mimeData());
        handleDroppedUrls(list);
        dEvent->setAccepted(true);
        return true;
    }
    return false;
}

177 178 179 180 181
bool Shell::isValid() const
{
    return m_isValid;
}

182 183 184 185 186
void Shell::showOpenRecentMenu()
{
    m_recent->menu()->popup(QCursor::pos());
}

187 188
Shell::~Shell()
{
Jonathan Doman's avatar
Jonathan Doman committed
189
    if( !m_tabs.empty() )
190 191
    {
        writeSettings();
Jonathan Doman's avatar
Jonathan Doman committed
192 193 194 195
        for( QList<TabState>::iterator it = m_tabs.begin(); it != m_tabs.end(); ++it )
        {
           it->part->closeUrl( false );
        }
196
        m_tabs.clear();
197
    }
198
    if (m_unique)
Laurent Montel's avatar
Laurent Montel committed
199
        QDBusConnection::sessionBus().unregisterService(QStringLiteral("org.kde.okular"));
David Rosca's avatar
David Rosca committed
200 201

    delete m_tabWidget;
202 203
}

204 205
// Open a new document if we have space for it
// This can hang if called on a unique instance and openUrl pops a messageBox
206
bool Shell::openDocument( const QUrl& url, const QString &serializedOptions )
207 208 209 210 211 212 213
{
    if( m_tabs.size() <= 0 )
       return false;

    KParts::ReadWritePart* const part = m_tabs[0].part;

    // Return false if we can't open new tabs and the only part is occupied
214 215 216 217
    if ( !dynamic_cast<Okular::ViewerInterface*>(part)->openNewFilesInTabs()
         && !part->url().isEmpty()
         && !ShellUtils::unique(serializedOptions))
    {
218
        return false;
219
    }
220

221
    openUrl( url, serializedOptions );
222 223 224 225

    return true;
}

226 227 228 229 230
bool Shell::openDocument( const QString& urlString, const QString &serializedOptions )
{
    return openDocument(QUrl(urlString), serializedOptions);
}

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
bool Shell::canOpenDocs( int numDocs, int desktop )
{
   if( m_tabs.size() <= 0 || numDocs <= 0 || m_unique )
      return false;

   KParts::ReadWritePart* const part = m_tabs[0].part;
   const bool allowTabs = dynamic_cast<Okular::ViewerInterface*>(part)->openNewFilesInTabs();

   if( !allowTabs && (numDocs > 1 || !part->url().isEmpty()) )
      return false;

   const KWindowInfo winfo( window()->effectiveWinId(), KWindowSystem::WMDesktop );
   if( winfo.desktop() != desktop )
      return false;

   return true;
}

249
void Shell::openUrl( const QUrl & url, const QString &serializedOptions )
Laurent Montel's avatar
Laurent Montel committed
250
{
Jonathan Doman's avatar
Jonathan Doman committed
251 252
    const int activeTab = m_tabWidget->currentIndex();
    if ( activeTab < m_tabs.size() )
253
    {
254 255
        KParts::ReadWritePart* const activePart = m_tabs[activeTab].part;
        if( !activePart->url().isEmpty() )
256
        {
257 258
            if( m_unique )
            {
259 260
                applyOptionsToPart( activePart, serializedOptions );
                activePart->openUrl( url );
261
            }
262 263
            else
            {
264
                if( dynamic_cast<Okular::ViewerInterface *>(activePart)->openNewFilesInTabs() )
Jonathan Doman's avatar
Jonathan Doman committed
265
                {
266
                    openNewTab( url, serializedOptions );
Jonathan Doman's avatar
Jonathan Doman committed
267 268 269
                }
                else
                {
270
                    Shell* newShell = new Shell( serializedOptions );
Jonathan Doman's avatar
Jonathan Doman committed
271
                    newShell->show();
272
                    newShell->openUrl( url, serializedOptions );
Jonathan Doman's avatar
Jonathan Doman committed
273
                }
274
            }
275
        }
276
        else
277
        {
Jonathan Doman's avatar
Jonathan Doman committed
278
            m_tabWidget->setTabText( activeTab, url.fileName() );
279
            applyOptionsToPart( activePart, serializedOptions );
280
            bool openOk = activePart->openUrl( url );
Rohan Garg's avatar
Rohan Garg committed
281
            const bool isstdin = url.fileName() == QLatin1String( "-" );
282 283 284
            if ( !isstdin )
            {
                if ( openOk )
Ivan Čukić's avatar
Ivan Čukić committed
285
                {
286
#ifndef Q_OS_WIN
Ivan Čukić's avatar
Ivan Čukić committed
287 288 289 290 291
                    if ( !m_activityResource )
                        m_activityResource = new KActivities::ResourceInstance( window()->winId(), this );

                    m_activityResource->setUri( url );
#endif
292
                    m_recent->addUrl( url );
Ivan Čukić's avatar
Ivan Čukić committed
293
                }
294 295 296
                else
                    m_recent->removeUrl( url );
            }
297
        }
298
    }
Laurent Montel's avatar
Laurent Montel committed
299 300
}

301 302
void Shell::closeUrl()
{
Jonathan Doman's avatar
Jonathan Doman committed
303
    closeTab( m_tabWidget->currentIndex() );
304
}
Laurent Montel's avatar
Laurent Montel committed
305 306

void Shell::readSettings()
307
{
308
    m_recent->loadEntries( KSharedConfig::openConfig()->group( "Recent Files" ) );
309 310
    m_recent->setEnabled( true ); // force enabling

311
    const KConfigGroup group = KSharedConfig::openConfig()->group( "Desktop Entry" );
312
    bool fullScreen = group.readEntry( "FullScreen", false );
313
    setFullScreen( fullScreen );
314

315 316 317 318 319
    if (fullScreen)
    {
        m_menuBarWasShown = group.readEntry( shouldShowMenuBarComingFromFullScreen, true );
        m_toolBarWasShown = group.readEntry( shouldShowToolBarComingFromFullScreen, true );
    }
320 321
}

Laurent Montel's avatar
Laurent Montel committed
322 323
void Shell::writeSettings()
{
324 325
    m_recent->saveEntries( KSharedConfig::openConfig()->group( "Recent Files" ) );
    KConfigGroup group = KSharedConfig::openConfig()->group( "Desktop Entry" );
326
    group.writeEntry( "FullScreen", m_fullScreenAction->isChecked() );
327 328 329 330 331
    if (m_fullScreenAction->isChecked())
    {
        group.writeEntry( shouldShowMenuBarComingFromFullScreen, m_menuBarWasShown );
        group.writeEntry( shouldShowToolBarComingFromFullScreen, m_toolBarWasShown );
    }
332
    KSharedConfig::openConfig()->sync();
333 334
}

335
void Shell::setupActions()
336
{
Laurent Montel's avatar
Laurent Montel committed
337
  KStandardAction::open(this, SLOT(fileOpen()), actionCollection());
Rohan Garg's avatar
Rohan Garg committed
338
  m_recent = KStandardAction::openRecent( this, SLOT(openUrl(QUrl)), actionCollection() );
339
  m_recent->setToolBarMode( KRecentFilesAction::MenuMode );
Albert Vaca Cintora's avatar
Albert Vaca Cintora committed
340
  connect( m_recent, &QAction::triggered, this, &Shell::showOpenRecentMenu );
Pino Toscano's avatar
Pino Toscano committed
341
  m_recent->setToolTip( i18n("Click to open a file\nClick and hold to open a recent file") );
342
  m_recent->setWhatsThis( i18n( "<b>Click</b> to open a file or <b>Click and hold</b> to select a recent file" ) );
Jonathan Doman's avatar
Jonathan Doman committed
343
  m_printAction = KStandardAction::print( this, SLOT(print()), actionCollection() );
344
  m_printAction->setEnabled( false );
345 346
  m_closeAction = KStandardAction::close( this, SLOT(closeUrl()), actionCollection() );
  m_closeAction->setEnabled( false );
Jonathan Doman's avatar
Jonathan Doman committed
347
  KStandardAction::quit(this, SLOT(close()), actionCollection());
348

349
  setStandardToolBarMenuEnabled(true);
350

Laurent Montel's avatar
Laurent Montel committed
351 352
  m_showMenuBarAction = KStandardAction::showMenubar( this, SLOT(slotShowMenubar()), actionCollection());
  m_fullScreenAction = KStandardAction::fullScreen( this, SLOT(slotUpdateFullScreen()), this,actionCollection() );
Jonathan Doman's avatar
Jonathan Doman committed
353

Laurent Montel's avatar
Laurent Montel committed
354
  m_nextTabAction = actionCollection()->addAction(QStringLiteral("tab-next"));
Jonathan Doman's avatar
Jonathan Doman committed
355
  m_nextTabAction->setText( i18n("Next Tab") );
356
  actionCollection()->setDefaultShortcuts(m_nextTabAction, KStandardShortcut::tabNext());
Jonathan Doman's avatar
Jonathan Doman committed
357
  m_nextTabAction->setEnabled( false );
Laurent Montel's avatar
Laurent Montel committed
358
  connect( m_nextTabAction, &QAction::triggered, this, &Shell::activateNextTab );
Jonathan Doman's avatar
Jonathan Doman committed
359

Laurent Montel's avatar
Laurent Montel committed
360
  m_prevTabAction = actionCollection()->addAction(QStringLiteral("tab-previous"));
Jonathan Doman's avatar
Jonathan Doman committed
361
  m_prevTabAction->setText( i18n("Previous Tab") );
362
  actionCollection()->setDefaultShortcuts(m_prevTabAction, KStandardShortcut::tabPrev());
Jonathan Doman's avatar
Jonathan Doman committed
363
  m_prevTabAction->setEnabled( false );
Laurent Montel's avatar
Laurent Montel committed
364
  connect( m_prevTabAction, &QAction::triggered, this, &Shell::activatePrevTab );
365 366
}

Tobias Koenig's avatar
Tobias Koenig committed
367
void Shell::saveProperties(KConfigGroup &group)
368
{
369 370 371
    if ( !m_isValid ) // part couldn't be loaded, nothing to save
        return;

372 373 374 375 376 377 378 379
    // Gather lists of settings to preserve
    QStringList urls;
    for( int i = 0; i < m_tabs.size(); ++i )
    {
        urls.append( m_tabs[i].part->url().url() );
    }
    group.writePathEntry( SESSION_URL_KEY, urls );
    group.writeEntry( SESSION_TAB_KEY, m_tabWidget->currentIndex() );
380 381
}

Pino Toscano's avatar
Pino Toscano committed
382
void Shell::readProperties(const KConfigGroup &group)
383
{
384 385 386 387 388
    // Reopen documents based on saved settings
    QStringList urls = group.readPathEntry( SESSION_URL_KEY, QStringList() );

    while( !urls.isEmpty() )
    {
389
        openUrl( QUrl(urls.takeFirst()) );
390 391 392 393 394 395 396
    }

    int desiredTab = group.readEntry<int>( SESSION_TAB_KEY, 0 );
    if( desiredTab < m_tabs.size() )
    {
        setActiveTab( desiredTab );
    }
397 398
}

Pino Toscano's avatar
Pino Toscano committed
399
QStringList Shell::fileFormats() const
400
{
Pino Toscano's avatar
Pino Toscano committed
401
    QStringList supportedPatterns;
402

Laurent Montel's avatar
Laurent Montel committed
403
    QString constraint( QStringLiteral("(Library == 'okularpart')") );
404 405
    QLatin1String basePartService( "KParts/ReadOnlyPart" );
    KService::List offers = KServiceTypeTrader::self()->query( basePartService, constraint );
Laurent Montel's avatar
Laurent Montel committed
406
    KService::List::ConstIterator it = offers.constBegin(), itEnd = offers.constEnd();
407
    for ( ; it != itEnd; ++it )
Pino Toscano's avatar
Pino Toscano committed
408
    {
409
        KService::Ptr service = *it;
410
        QStringList mimeTypes = service->mimeTypes();
411 412

        supportedPatterns += mimeTypes;
413 414
    }

Pino Toscano's avatar
Pino Toscano committed
415
    return supportedPatterns;
416 417 418 419 420 421 422
}

void Shell::fileOpen()
{
	// this slot is called whenever the File->Open menu is selected,
	// the Open shortcut is pressed (usually CTRL+O) or the Open toolbar
	// button is clicked
Jonathan Doman's avatar
Jonathan Doman committed
423
    const int activeTab = m_tabWidget->currentIndex();
424
    if ( !m_fileformatsscanned )
425
    {
Jonathan Doman's avatar
Jonathan Doman committed
426 427 428
        const KDocumentViewer* const doc = qobject_cast<KDocumentViewer*>(m_tabs[activeTab].part);
        if ( doc )
            m_fileformats = doc->supportedMimeTypes();
429 430 431

        if ( m_fileformats.isEmpty() )
            m_fileformats = fileFormats();
432

433
        m_fileformatsscanned = true;
434
    }
435

Aleix Pol Gonzalez's avatar
Aleix Pol Gonzalez committed
436
    QUrl startDir;
Jonathan Doman's avatar
Jonathan Doman committed
437 438
    const KParts::ReadWritePart* const curPart = m_tabs[activeTab].part;
    if ( curPart->url().isLocalFile() )
439
        startDir = KIO::upUrl(curPart->url());
440

441 442 443
    QPointer<QFileDialog> dlg( new QFileDialog( this ));
    dlg->setDirectoryUrl( startDir );
    dlg->setAcceptMode( QFileDialog::AcceptOpen );
444 445 446 447
    dlg->setOption( QFileDialog::HideNameFilterDetails, true );

    QMimeDatabase mimeDatabase;
    QSet<QString> globPatterns;
448
    QMap<QString, QStringList> namedGlobs;
449 450
    foreach ( const QString &mimeName, m_fileformats ) {
        QMimeType mimeType = mimeDatabase.mimeTypeForName( mimeName );
451 452 453 454
        const QStringList globs( mimeType.globPatterns() );
        if ( globs.isEmpty() ) {
            continue;
        }
455

456
        globPatterns.unite( globs.toSet() ) ;
457

458
        namedGlobs[ mimeType.comment() ].append( globs );
459

460
    }
461 462 463
    QStringList namePatterns;
    foreach( const QString &name, namedGlobs.keys()) {
        namePatterns.append( name +
464
                             QStringLiteral(" (") +
465
                             namedGlobs[name].join( QLatin1Char(' ') ) +
466 467 468
                             QStringLiteral(")")
                           );
    }
469

470
    namePatterns.prepend( i18n("All files (*)") );
471
    namePatterns.prepend( i18n("All supported files (%1)", globPatterns.toList().join( QLatin1Char(' ') ) ) );
472
    dlg->setNameFilters( namePatterns );
473

474
    dlg->setWindowTitle( i18n("Open Document") );
475 476 477 478 479 480
    if ( dlg->exec() && dlg ) {
        foreach(const QUrl& url, dlg->selectedUrls())
        {
            openUrl( url );
        }
    }
481

482 483
    if ( dlg ) {
        delete dlg.data();
484
    }
Laurent Montel's avatar
Laurent Montel committed
485
}
486

487 488
void Shell::tryRaise()
{
489
    KWindowSystem::forceActiveWindow( window()->effectiveWinId() );
490 491
}

Albert Astals Cid's avatar
Albert Astals Cid committed
492
// only called when starting the program
493 494
void Shell::setFullScreen( bool useFullScreen )
{
495
    if( useFullScreen )
496
        setWindowState( windowState() | Qt::WindowFullScreen ); // set
497
    else
498
        setWindowState( windowState() & ~Qt::WindowFullScreen ); // reset
499 500
}

501 502 503 504 505 506 507 508
void Shell::setCaption( const QString &caption )
{
    bool modified = false;

    const int activeTab = m_tabWidget->currentIndex();
    if ( activeTab >= 0 && activeTab < m_tabs.size() )
    {
        KParts::ReadWritePart* const activePart = m_tabs[activeTab].part;
509 510
        QString tabCaption = activePart->url().fileName();
        if ( activePart->isModified() ) {
511
            modified = true;
512 513 514 515 516 517
            if ( !tabCaption.isEmpty() ) {
                tabCaption.append( QStringLiteral( " *" ) );
            }
        }

        m_tabWidget->setTabText( activeTab, tabCaption );
518 519 520 521 522
    }

    setCaption( caption, modified );
}

523 524
void Shell::showEvent(QShowEvent *e)
{
525
    if (!menuBar()->isNativeMenuBar() && m_showMenuBarAction)
526
        m_showMenuBarAction->setChecked( menuBar()->isVisible() );
527 528 529 530

    KParts::MainWindow::showEvent(e);
}

531 532
void Shell::slotUpdateFullScreen()
{
Albert Astals Cid's avatar
Albert Astals Cid committed
533
    if(m_fullScreenAction->isChecked())
534
    {
535
      m_menuBarWasShown = !menuBar()->isHidden();
Albert Astals Cid's avatar
Albert Astals Cid committed
536
      menuBar()->hide();
537

538
      m_toolBarWasShown = !toolBar()->isHidden();
Albert Astals Cid's avatar
Albert Astals Cid committed
539
      toolBar()->hide();
540

541
      KToggleFullScreenAction::setFullScreen(this, true);
542 543 544
    }
    else
    {
Albert Astals Cid's avatar
Albert Astals Cid committed
545 546 547 548 549 550 551 552
      if (m_menuBarWasShown)
      {
        menuBar()->show();
      }
      if (m_toolBarWasShown)
      {
        toolBar()->show();
      }
553
      KToggleFullScreenAction::setFullScreen(this, false);
554 555 556
    }
}

557 558
void Shell::slotShowMenubar()
{
559
    if ( menuBar()->isHidden() )
560 561 562 563 564
        menuBar()->show();
    else
        menuBar()->hide();
}

565 566 567 568 569
QSize Shell::sizeHint() const
{
    return QApplication::desktop()->availableGeometry( this ).size() * 0.75;
}

570 571
bool Shell::queryClose()
{
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
    if (m_tabs.count() > 1)
    {
        const QString dontAskAgainName = "ShowTabWarning";
        KMessageBox::ButtonCode dummy;
        if (shouldBeShownYesNo(dontAskAgainName, dummy))
        {
            QDialog *dialog = new QDialog(this);
            dialog->setWindowTitle(i18n("Confirm Close"));

            QDialogButtonBox *buttonBox = new QDialogButtonBox(dialog);
            buttonBox->setStandardButtons(QDialogButtonBox::Yes | QDialogButtonBox::No);
            KGuiItem::assign(buttonBox->button(QDialogButtonBox::Yes), KGuiItem(i18n("Close Tabs"), "tab-close"));
            KGuiItem::assign(buttonBox->button(QDialogButtonBox::No), KStandardGuiItem::cancel());


            bool checkboxResult = true;
            const int result = KMessageBox::createKMessageBox(dialog, buttonBox, QMessageBox::Question,
Albert Astals Cid's avatar
Albert Astals Cid committed
589
                                                i18n("You are about to close %1 tabs. Are you sure you want to continue?", m_tabs.count()), QStringList(),
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
                                                i18n("Warn me when I attempt to close multiple tabs"),
                                                &checkboxResult, KMessageBox::Notify);

            if (!checkboxResult)
            {
                saveDontShowAgainYesNo(dontAskAgainName, dummy);
            }

            if (result != QDialogButtonBox::Yes)
            {
                return false;
            }
        }
    }

Jonathan Doman's avatar
Jonathan Doman committed
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
    for( int i = 0; i < m_tabs.size(); ++i )
    {
        KParts::ReadWritePart* const part = m_tabs[i].part;

        // To resolve confusion about multiple modified docs, switch to relevant tab
        if( part->isModified() )
            setActiveTab( i );

        if( !part->queryClose() )
           return false;
    }
    return true;
}

void Shell::setActiveTab( int tab )
{
    m_tabWidget->setCurrentIndex( tab );
    createGUI( m_tabs[tab].part );
    m_printAction->setEnabled( m_tabs[tab].printEnabled );
    m_closeAction->setEnabled( m_tabs[tab].closeEnabled );
}

void Shell::closeTab( int tab )
{
    KParts::ReadWritePart* const part = m_tabs[tab].part;
    if( part->closeUrl() && m_tabs.count() > 1 )
    {
        if( part->factory() )
            part->factory()->removeClient( part );
        part->disconnect();
        part->deleteLater();
        m_tabs.removeAt( tab );
        m_tabWidget->removeTab( tab );

        if( m_tabWidget->count() == 1 )
        {
641
            m_tabWidget->tabBar()->hide();
Jonathan Doman's avatar
Jonathan Doman committed
642 643 644 645 646 647 648
            m_nextTabAction->setEnabled( false );
            m_prevTabAction->setEnabled( false );
        }
    }

}

649
void Shell::openNewTab( const QUrl& url, const QString &serializedOptions )
Jonathan Doman's avatar
Jonathan Doman committed
650 651 652 653
{
    // Tabs are hidden when there's only one, so show it
    if( m_tabs.size() == 1 )
    {
654
        m_tabWidget->tabBar()->show();
Jonathan Doman's avatar
Jonathan Doman committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668
        m_nextTabAction->setEnabled( true );
        m_prevTabAction->setEnabled( true );
    }

    const int newIndex = m_tabs.size();

    // Make new part
    m_tabs.append( m_partFactory->create<KParts::ReadWritePart>(this) );
    connectPart( m_tabs[newIndex].part );

    // Update GUI
    KParts::ReadWritePart* const part = m_tabs[newIndex].part;
    m_tabWidget->addTab( part->widget(), url.fileName() );

669 670 671 672 673
    applyOptionsToPart(part, serializedOptions);

    int previousActiveTab = m_tabWidget->currentIndex();
    setActiveTab( m_tabs.size() - 1 );

Jonathan Doman's avatar
Jonathan Doman committed
674 675
    if( part->openUrl(url) )
        m_recent->addUrl( url );
676 677 678 679 680 681 682 683 684 685 686
    else
        setActiveTab( previousActiveTab );
}

void Shell::applyOptionsToPart( QObject* part, const QString &serializedOptions )
{
    KDocumentViewer* const doc = qobject_cast<KDocumentViewer*>(part);
    if ( ShellUtils::startInPresentation(serializedOptions) )
        doc->startPresentation();
    if ( ShellUtils::showPrintDialog(serializedOptions) )
        QMetaObject::invokeMethod( part, "enableStartWithPrint" );
Dileep Sankhla's avatar
Dileep Sankhla committed
687 688
    if ( ShellUtils::showPrintDialogAndExit(serializedOptions) )
        QMetaObject::invokeMethod( part, "enableExitAfterPrint" );
Jonathan Doman's avatar
Jonathan Doman committed
689 690 691 692
}

void Shell::connectPart( QObject* part )
{
693
    connect( this, SIGNAL(moveSplitter(int)), part, SLOT(moveSplitter(int)) );
Jonathan Doman's avatar
Jonathan Doman committed
694 695
    connect( part, SIGNAL(enablePrintAction(bool)), this, SLOT(setPrintEnabled(bool)));
    connect( part, SIGNAL(enableCloseAction(bool)), this, SLOT(setCloseEnabled(bool)));
Frederik Gladhorn's avatar
Frederik Gladhorn committed
696
    connect( part, SIGNAL(mimeTypeChanged(QMimeType)), this, SLOT(setTabIcon(QMimeType)));
Vishesh Handa's avatar
Vishesh Handa committed
697
    connect( part, SIGNAL(urlsDropped(QList<QUrl>)), this, SLOT(handleDroppedUrls(QList<QUrl>)) );
698
    connect( part, SIGNAL(fitWindowToPage(QSize,QSize)), this, SLOT(slotFitWindowToPage(QSize,QSize)) );
Jonathan Doman's avatar
Jonathan Doman committed
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
}

void Shell::print()
{
    QMetaObject::invokeMethod( m_tabs[m_tabWidget->currentIndex()].part, "slotPrint" );
}

void Shell::setPrintEnabled( bool enabled )
{
    int i = findTabIndex( sender() );
    if( i != -1 )
    {
        m_tabs[i].printEnabled = enabled;
        if( i == m_tabWidget->currentIndex() )
            m_printAction->setEnabled( enabled );
    }
}

void Shell::setCloseEnabled( bool enabled )
{
    int i = findTabIndex( sender() );
    if( i != -1 )
    {
        m_tabs[i].closeEnabled = enabled;
        if( i == m_tabWidget->currentIndex() )
            m_closeAction->setEnabled( enabled );
    }
}

void Shell::activateNextTab()
{
    if( m_tabs.size() < 2 )
        return;

    const int activeTab = m_tabWidget->currentIndex();
    const int nextTab = (activeTab == m_tabs.size()-1) ? 0 : activeTab+1;

    setActiveTab( nextTab );
}

void Shell::activatePrevTab()
{
    if( m_tabs.size() < 2 )
        return;

    const int activeTab = m_tabWidget->currentIndex();
    const int prevTab = (activeTab == 0) ? m_tabs.size()-1 : activeTab-1;

    setActiveTab( prevTab );
}

Frederik Gladhorn's avatar
Frederik Gladhorn committed
750
void Shell::setTabIcon( const QMimeType& mimeType )
Jonathan Doman's avatar
Jonathan Doman committed
751 752 753 754
{
    int i = findTabIndex( sender() );
    if( i != -1 )
    {
Frederik Gladhorn's avatar
Frederik Gladhorn committed
755
        m_tabWidget->setTabIcon( i, QIcon::fromTheme(mimeType.iconName()) );
Jonathan Doman's avatar
Jonathan Doman committed
756 757 758 759 760 761 762 763 764 765 766 767 768
    }
}

int Shell::findTabIndex( QObject* sender )
{
    for( int i = 0; i < m_tabs.size(); ++i )
    {
        if( m_tabs[i].part == sender )
        {
            return i;
        }
    }
    return -1;
769 770
}

Vishesh Handa's avatar
Vishesh Handa committed
771
void Shell::handleDroppedUrls( const QList<QUrl>& urls )
772
{
Rohan Garg's avatar
Rohan Garg committed
773
    foreach( const QUrl& url, urls )
774 775 776 777 778
    {
        openUrl( url );
    }
}

Jonathan Doman's avatar
Jonathan Doman committed
779 780 781 782 783
void Shell::moveTabData( int from, int to )
{
   m_tabs.move( from, to );
}

784 785 786 787 788 789 790 791
void Shell::slotFitWindowToPage(const QSize& pageViewSize, const QSize& pageSize )
{
    const int xOffset = pageViewSize.width() - pageSize.width();
    const int yOffset = pageViewSize.height() - pageSize.height();
    showNormal();
    resize( width() - xOffset, height() - yOffset);
    moveSplitter(pageSize.width());
}
792 793

/* kate: replace-tabs on; indent-width 4; */