part.cpp 37 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/***************************************************************************
 *   Copyright (C) 2002 by Wilco Greven <greven@kde.org>                   *
 *   Copyright (C) 2002 by Chris Cheney <ccheney@cheney.cx>                *
 *   Copyright (C) 2002 by Malcolm Hunter <malcolm.hunter@gmx.co.uk>       *
 *   Copyright (C) 2003-2004 by Christophe Devriese                        *
 *                         <Christophe.Devriese@student.kuleuven.ac.be>    *
 *   Copyright (C) 2003 by Daniel Molkentin <molkentin@kde.org>            *
 *   Copyright (C) 2003 by Andy Goossens <andygoossens@telenet.be>         *
 *   Copyright (C) 2003 by Dirk Mueller <mueller@kde.org>                  *
 *   Copyright (C) 2003 by Laurent Montel <montel@kde.org>                 *
 *   Copyright (C) 2004 by Dominique Devriese <devriese@kde.org>           *
 *   Copyright (C) 2004 by Christoph Cullmann <crossfire@babylon2k.de>     *
 *   Copyright (C) 2004 by Henrique Pinto <stampede@coltec.ufmg.br>        *
 *   Copyright (C) 2004 by Waldo Bastian <bastian@kde.org>                 *
Albert Astals Cid's avatar
Albert Astals Cid committed
15
 *   Copyright (C) 2004-2006 by Albert Astals Cid <tsdgeos@terra.es>       *
16
 *   Copyright (C) 2004 by Antti Markus <antti.markus@starman.ee>          *
17 18 19 20 21 22 23
 *                                                                         *
 *   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.                                   *
 ***************************************************************************/

24
// qt/kde includes
25
#include <qsplitter.h>
26
#include <qpainter.h>
27 28
#include <qlayout.h>
#include <qlabel.h>
Pino Toscano's avatar
porting  
Pino Toscano committed
29
#include <kvbox.h>
30
#include <qtoolbox.h>
31
#include <qpushbutton.h>
32
#include <dcopobject.h>
33 34
#include <dcopclient.h>
#include <kapplication.h>
Pino Toscano's avatar
porting  
Pino Toscano committed
35
#include <k3listviewsearchline.h>
36
#include <kaction.h>
Albert Astals Cid's avatar
Albert Astals Cid committed
37
#include <kdirwatch.h>
38
#include <kinstance.h>
39
#include <kprinter.h>
40
#include <kstdaction.h>
Enrico Ros's avatar
Enrico Ros committed
41
#include <kdeversion.h>
42
#include <kparts/genericfactory.h>
Pino Toscano's avatar
porting  
Pino Toscano committed
43
#include <k3urldrag.h>
44
#include <kfiledialog.h>
Albert Astals Cid's avatar
Albert Astals Cid committed
45
#include <kmessagebox.h>
46 47
#include <kfinddialog.h>
#include <knuminput.h>
48
#include <kiconloader.h>
49
#include <kio/netaccess.h>
Pino Toscano's avatar
porting  
Pino Toscano committed
50
#include <k3popupmenu.h>
51 52
#include <kxmlguiclient.h>
#include <kxmlguifactory.h>
53
#include <ktrader.h>
54 55 56
#include <kprocess.h>
#include <kstandarddirs.h>
#include <ktempfile.h>
Piotr Szymanski's avatar
Piotr Szymanski committed
57
#include <kio/job.h>
58

59
// local includes
60 61 62
#include "part.h"
#include "ui/pageview.h"
#include "ui/toc.h"
63 64 65
#include "ui/searchwidget.h"
#include "ui/thumbnaillist.h"
#include "ui/side_reviews.h"
66
#include "ui/minibar.h"
Enrico Ros's avatar
Enrico Ros committed
67
#include "ui/newstuff.h"
68 69 70 71 72
#include "ui/propertiesdialog.h"
#include "ui/presentationwidget.h"
#include "conf/preferencesdialog.h"
#include "conf/settings.h"
#include "core/document.h"
73
#include "core/generator.h"
74
#include "core/page.h"
Christophe Devriese's avatar
Christophe Devriese committed
75

76 77 78
// definition of searchID for this class
#define PART_SEARCH_ID 1

Albert Astals Cid's avatar
Albert Astals Cid committed
79 80
typedef KParts::GenericFactory<oKular::Part> oKularPartFactory;
K_EXPORT_COMPONENT_FACTORY(liboKularpart, oKularPartFactory)
81

Albert Astals Cid's avatar
Albert Astals Cid committed
82
using namespace oKular;
83 84 85 86

Part::Part(QWidget *parentWidget, const char *widgetName,
           QObject *parent, const char *name,
           const QStringList & /*args*/ )
Albert Astals Cid's avatar
Albert Astals Cid committed
87
	: DCOPObject("oKular"), KParts::ReadOnlyPart(parent, name), m_viewportDirty( 0 ),
88
	m_showMenuBarAction(0), m_showFullScreenAction(0), m_actionsSearched(false),
89
	m_searchStarted(false)
90
{
Piotr Szymanski's avatar
Piotr Szymanski committed
91 92
	// connect the started signal to tell the job the mimetypes we like
	connect(this, SIGNAL(started(KIO::Job *)), this, SLOT(setMimeTypes(KIO::Job *)));
93
	// load catalog for translation
Albert Astals Cid's avatar
Albert Astals Cid committed
94
	KGlobal::locale()->insertCatalogue("oKular");
95

96
	// create browser extension (for printing when embedded into browser)
97
	m_bExtension = new BrowserExtension(this);
Wilco Greven's avatar
Wilco Greven committed
98

99
	// we need an instance
Albert Astals Cid's avatar
Albert Astals Cid committed
100
	setInstance(oKularPartFactory::instance());
101

102
	// build the document
103
	m_document = new KPDFDocument(&m_loadedGenerators);
104 105
	connect( m_document, SIGNAL( linkFind() ), this, SLOT( slotFind() ) );
	connect( m_document, SIGNAL( linkGoToPage() ), this, SLOT( slotGoToPage() ) );
106 107
	connect( m_document, SIGNAL( linkPresentation() ), this, SLOT( slotShowPresentation() ) );
	connect( m_document, SIGNAL( linkEndPresentation() ), this, SLOT( slotHidePresentation() ) );
Pino Toscano's avatar
porting  
Pino Toscano committed
108
	connect( m_document, SIGNAL( openURL(const KUrl &) ), this, SLOT( openURLFromDocument(const KUrl &) ) );
Piotr Szymanski's avatar
Piotr Szymanski committed
109 110 111 112 113 114
	connect( m_document, SIGNAL( close() ), this, SLOT( close() ) );
	
	if (parent && parent->metaObject()->slotNames(true).contains("slotQuit()"))
		connect( m_document, SIGNAL( quit() ), parent, SLOT( slotQuit() ) );
	else
		connect( m_document, SIGNAL( quit() ), this, SLOT( cannotQuit() ) );
115 116 117 118 119 120 121 122
        // widgets: ^searchbar (toolbar containing label and SearchWidget)
//      m_searchToolBar = new KToolBar( parentWidget, "searchBar" );
//      m_searchToolBar->boxLayout()->setSpacing( KDialog::spacingHint() );
//      QLabel * sLabel = new QLabel( i18n( "&Search:" ), m_searchToolBar, "kde toolbar widget" );
//      m_searchWidget = new SearchWidget( m_searchToolBar, m_document );
//      sLabel->setBuddy( m_searchWidget );
//      m_searchToolBar->setStretchableWidget( m_searchWidget );

123

124
	// widgets: [] splitter []
125 126
	m_splitter = new QSplitter( parentWidget, widgetName );
	m_splitter->setOpaqueResize( true );
127
	m_splitter->setChildrenCollapsible( false );
128
	setWidget( m_splitter );
129

130
	// widgets: [left panel] | []
131 132 133 134
	m_leftPanel = new QWidget( m_splitter );
	m_leftPanel->setMinimumWidth( 90 );
	m_leftPanel->setMaximumWidth( 300 );
	QVBoxLayout * leftPanelLayout = new QVBoxLayout( m_leftPanel );
135 136

	// widgets: [left toolbox/..] | []
137
	m_toolBox = new QToolBox( m_leftPanel );
138
	leftPanelLayout->addWidget( m_toolBox );
139

Enrico Ros's avatar
Enrico Ros committed
140
	int tbIndex;
141
	// [left toolbox: Table of Contents] | []
142 143
	//QFrame * tocFrame = new QFrame( m_toolBox );
	//QVBoxLayout * tocFrameLayout = new QVBoxLayout( tocFrame );
Albert Astals Cid's avatar
Albert Astals Cid committed
144 145
	m_toc = new TOC( m_toolBox/*tocFrame*/, m_document );
	connect( m_toc, SIGNAL( hasTOC( bool ) ), this, SLOT( enableTOC( bool ) ) );
146 147 148
	//KListViewSearchLine * tocSearchLine = new KListViewSearchLine( tocFrame, toc );
	//tocFrameLayout->addWidget( tocSearchLine );
	//tocFrameLayout->addWidget( toc );
Albert Astals Cid's avatar
Albert Astals Cid committed
149
	tbIndex = m_toolBox->addItem( m_toc/*tocFrame*/, QIconSet(SmallIcon("text_left")), i18n("Contents") );
Enrico Ros's avatar
Enrico Ros committed
150
	m_toolBox->setItemToolTip( tbIndex, i18n("Contents") );
151
	enableTOC( false );
152

153
	// [left toolbox: Thumbnails and Bookmarks] | []
Pino Toscano's avatar
porting  
Pino Toscano committed
154
	KVBox * thumbsBox = new ThumbnailsBox( m_toolBox );
155
	thumbsBox->setSpacing( 4 );
156 157 158
	m_searchWidget = new SearchWidget( thumbsBox, m_document );
	m_thumbnailList = new ThumbnailList( thumbsBox, m_document );
//	ThumbnailController * m_tc = new ThumbnailController( thumbsBox, m_thumbnailList );
Pino Toscano's avatar
porting  
Pino Toscano committed
159
	connect( m_thumbnailList, SIGNAL( urlDropped( const KUrl& ) ), SLOT( openURLFromDocument( const KUrl & )) );
160
	connect( m_thumbnailList, SIGNAL( rightClick(const KPDFPage *, const QPoint &) ), this, SLOT( slotShowMenu(const KPDFPage *, const QPoint &) ) );
161
	// shrink the bottom controller toolbar (too hackish..)
162 163 164
	thumbsBox->setStretchFactor( m_searchWidget, 100 );
	thumbsBox->setStretchFactor( m_thumbnailList, 100 );
//	thumbsBox->setStretchFactor( m_tc, 1 );
Enrico Ros's avatar
Enrico Ros committed
165 166
	tbIndex = m_toolBox->addItem( thumbsBox, QIconSet(SmallIcon("thumbnail")), i18n("Thumbnails") );
	m_toolBox->setItemToolTip( tbIndex, i18n("Thumbnails") );
167
	m_toolBox->setCurrentItem( thumbsBox );
168

169 170 171
	// [left toolbox: Reviews] | []
	Reviews * reviewsWidget = new Reviews( m_toolBox, m_document );
	m_toolBox->addItem( reviewsWidget, QIconSet(SmallIcon("pencil")), i18n("Reviews") );
172

173
	// widgets: [../miniBarContainer] | []
174
	QWidget * miniBarContainer = new QWidget( m_leftPanel );
175 176 177 178 179 180 181
	leftPanelLayout->addWidget( miniBarContainer );
	QVBoxLayout * miniBarLayout = new QVBoxLayout( miniBarContainer );
	// widgets: [../[spacer/..]] | []
	QWidget * miniSpacer = new QWidget( miniBarContainer );
	miniSpacer->setFixedHeight( 6 );
	miniBarLayout->addWidget( miniSpacer );
	// widgets: [../[../MiniBar]] | []
Albert Astals Cid's avatar
Albert Astals Cid committed
182 183
	m_miniBar = new MiniBar( miniBarContainer, m_document );
	miniBarLayout->addWidget( m_miniBar );
184

185
	// widgets: [] | [right 'pageView']
186 187 188 189
//	QWidget * rightContainer = new QWidget( m_splitter );
//	QVBoxLayout * rightLayout = new QVBoxLayout( rightContainer );
//	KToolBar * rtb = new KToolBar( rightContainer, "mainToolBarSS" );
//	rightLayout->addWidget( rtb );
190
	m_pageView = new PageView( m_splitter, m_document );
191
	m_pageView->setFocus(); //usability setting
Pino Toscano's avatar
porting  
Pino Toscano committed
192
	connect( m_pageView, SIGNAL( urlDropped( const KUrl& ) ), SLOT( openURLFromDocument( const KUrl & )));
193
	connect( m_pageView, SIGNAL( rightClick(const KPDFPage *, const QPoint &) ), this, SLOT( slotShowMenu(const KPDFPage *, const QPoint &) ) );
194 195 196
    connect( m_document, SIGNAL(error(QString&,int )),m_pageView,SLOT(errorMessage(QString&,int )));
    connect( m_document, SIGNAL(warning(QString&,int )),m_pageView,SLOT(warningMessage(QString&,int )));
    connect( m_document, SIGNAL(notice(QString&,int )),m_pageView,SLOT(noticeMessage(QString&,int )));
197
//	rightLayout->addWidget( m_pageView );
198 199

	// add document observers
Albert Astals Cid's avatar
Albert Astals Cid committed
200
	m_document->addObserver( this );
201 202
	m_document->addObserver( m_thumbnailList );
	m_document->addObserver( m_pageView );
Albert Astals Cid's avatar
Albert Astals Cid committed
203 204
	m_document->addObserver( m_toc );
	m_document->addObserver( m_miniBar );
205
	m_document->addObserver( reviewsWidget );
206 207 208 209 210

	// ACTIONS
	KActionCollection * ac = actionCollection();

	// Page Traversal actions
211
	m_gotoPage = KStdAction::gotoPage( this, SLOT( slotGoToPage() ), ac, "goto_page" );
212
	m_gotoPage->setShortcut( "CTRL+G" );
213
	// dirty way to activate gotopage when pressing miniBar's button
Albert Astals Cid's avatar
Albert Astals Cid committed
214
	connect( m_miniBar, SIGNAL( gotoPage() ), m_gotoPage, SLOT( activate() ) );
215 216 217

	m_prevPage = KStdAction::prior(this, SLOT(slotPreviousPage()), ac, "previous_page");
	m_prevPage->setWhatsThis( i18n( "Moves to the previous page of the document" ) );
218
	m_prevPage->setShortcut( "Backspace" );
219
	// dirty way to activate prev page when pressing miniBar's button
Albert Astals Cid's avatar
Albert Astals Cid committed
220
	connect( m_miniBar, SIGNAL( prevPage() ), m_prevPage, SLOT( activate() ) );
221 222 223

	m_nextPage = KStdAction::next(this, SLOT(slotNextPage()), ac, "next_page" );
	m_nextPage->setWhatsThis( i18n( "Moves to the next page of the document" ) );
224
	m_nextPage->setShortcut( "Space" );
225
	// dirty way to activate next page when pressing miniBar's button
Albert Astals Cid's avatar
Albert Astals Cid committed
226
	connect( m_miniBar, SIGNAL( nextPage() ), m_nextPage, SLOT( activate() ) );
227

228
	m_firstPage = KStdAction::firstPage( this, SLOT( slotGotoFirst() ), ac, "first_page" );
229 230
	m_firstPage->setWhatsThis( i18n( "Moves to the first page of the document" ) );

231
	m_lastPage = KStdAction::lastPage( this, SLOT( slotGotoLast() ), ac, "last_page" );
232 233
	m_lastPage->setWhatsThis( i18n( "Moves to the last page of the document" ) );

234 235 236 237 238 239
	m_historyBack = KStdAction::back( this, SLOT( slotHistoryBack() ), ac, "history_back" );
	m_historyBack->setWhatsThis( i18n( "Go to the place you were before" ) );

	m_historyNext = KStdAction::forward( this, SLOT( slotHistoryNext() ), ac, "history_forward" );
	m_historyNext->setWhatsThis( i18n( "Go to the place you were after" ) );

240 241
	// Find and other actions
	m_find = KStdAction::find( this, SLOT( slotFind() ), ac, "find" );
242
	m_find->setEnabled( false );
243

244
	m_findNext = KStdAction::findNext( this, SLOT( slotFindNext() ), ac, "find_next" );
245
	m_findNext->setEnabled( false );
246

247 248
	m_saveAs = KStdAction::saveAs( this, SLOT( slotSaveFileAs() ), ac, "save" );
	m_saveAs->setEnabled( false );
Enrico Ros's avatar
Enrico Ros committed
249
	KAction * prefs = KStdAction::preferences( this, SLOT( slotPreferences() ), ac, "preferences" );
250 251 252 253 254 255 256 257 258 259
	prefs->setText( i18n( "Configure oKular..." ) ); // TODO: use "Configure PDF Viewer..." when used as part (like in konq

    QString constraint("([X-KDE-Priority] > 0) and (exist Library) and ([X-KDE-oKularHasInternalSettings])") ;
    KTrader::OfferList gens=KTrader::self()->query("oKular/Generator",constraint);
    if (gens.count() > 0)
    {
        KAction * genPrefs = KStdAction::preferences( this, SLOT( slotGeneratorPreferences() ), ac, "generator_prefs" );
        genPrefs->setText( i18n( "Configure backends..." ) );
    }

260 261
	m_printPreview = KStdAction::printPreview( this, SLOT( slotPrintPreview() ), ac );
	m_printPreview->setEnabled( false );
262

Stephan Binner's avatar
Stephan Binner committed
263
	m_showLeftPanel = new KToggleAction( i18n( "Show &Navigation Panel"), "show_side_panel", 0, this, SLOT( slotShowLeftPanel() ), ac, "show_leftpanel" );
Enrico Ros's avatar
Enrico Ros committed
264
	m_showLeftPanel->setShortcut( "CTRL+L" );
Enrico Ros's avatar
Enrico Ros committed
265
	m_showLeftPanel->setCheckedState( i18n( "Hide &Navigation Panel" ) );
Piotr Szymanski's avatar
Piotr Szymanski committed
266
	m_showLeftPanel->setChecked( KpdfSettings::showLeftPanel() );
Enrico Ros's avatar
Enrico Ros committed
267 268
	slotShowLeftPanel();

269 270 271
        QString app = KStandardDirs::findExe( "ps2pdf" );
        if ( !app.isNull() )
		KAction * importPS= new KAction(i18n("&Import Postscript as PDF..."), "psimport", 0, this, SLOT(slotImportPSFile()), ac, "import_ps");
272
	KAction * ghns = new KAction(i18n("&Get Books From Internet..."), "knewstuff", 0, this, SLOT(slotGetNewStuff()), ac, "get_new_stuff");
Enrico Ros's avatar
Enrico Ros committed
273 274
	ghns->setShortcut( "G" );  // TEMP, REMOVE ME!

275
	m_showProperties = new KAction(i18n("&Properties"), "info", 0, this, SLOT(slotShowProperties()), ac, "properties");
Albert Astals Cid's avatar
Albert Astals Cid committed
276
	m_showProperties->setEnabled( false );
277

278
	m_showPresentation = new KAction( i18n("P&resentation"), "kpresenter_kpr", "Ctrl+Shift+P", this, SLOT(slotShowPresentation()), ac, "presentation");
279
	m_showPresentation->setEnabled( false );
280

281 282
	// attach the actions of the children widgets too
	m_pageView->setupActions( ac );
283

284
	// apply configuration (both internal settings and GUI configured items)
Piotr Szymanski's avatar
Piotr Szymanski committed
285
	QValueList<int> splitterSizes = KpdfSettings::splitterSizes();
286 287 288 289 290 291 292
	if ( !splitterSizes.count() )
	{
		// the first time use 1/10 for the panel and 9/10 for the pageView
		splitterSizes.push_back( 50 );
		splitterSizes.push_back( 500 );
	}
	m_splitter->setSizes( splitterSizes );
293 294 295 296
	// get notified about splitter size changes (HACK that will be removed
	// by connecting to Qt4::QSplitter's sliderMoved())
	m_pageView->installEventFilter( this );

297
	// document watcher and reloader
Albert Astals Cid's avatar
Albert Astals Cid committed
298 299 300 301 302
	m_watcher = new KDirWatch( this );
	connect( m_watcher, SIGNAL( dirty( const QString& ) ), this, SLOT( slotFileDirty( const QString& ) ) );
	m_dirtyHandler = new QTimer( this );
	connect( m_dirtyHandler, SIGNAL( timeout() ),this, SLOT( slotDoFileDirty() ) );

303 304
	slotNewConfig();

305
	// [SPEECH] check for KTTSD presence and usability
306
	KTrader::OfferList offers = KTrader::self()->query("DCOP/Text-to-Speech", "Name == 'KTTSD'");
Piotr Szymanski's avatar
Piotr Szymanski committed
307 308
	KpdfSettings::setUseKTTSD( (offers.count() > 0) );
    KpdfSettings::writeConfig();
309

310
	// set our XML-UI resource file
311
	setXMLFile("part.rc");
312
    // 
313
	updateViewActions();
314 315
}

316
Part::~Part()
Laurent Montel's avatar
Laurent Montel committed
317
{
Albert Astals Cid's avatar
Albert Astals Cid committed
318 319 320 321 322
    delete m_toc;
    delete m_pageView;
    delete m_thumbnailList;
    delete m_miniBar;

323
    delete m_document;
Laurent Montel's avatar
Laurent Montel committed
324 325
}

Pino Toscano's avatar
porting  
Pino Toscano committed
326
void Part::openURLFromDocument(const KUrl &url)
Piotr Szymanski's avatar
Piotr Szymanski committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
{
    m_bExtension->openURLNotify();
    m_bExtension->setLocationBarURL(url.prettyURL());
    openURL(url);
}

void Part::supportedMimetypes()
{
    m_supportedMimeTypes.clear();
    QString constraint("([X-KDE-Priority] > 0) and (exist Library) ") ;
    KTrader::OfferList offers=KTrader::self()->query("oKular/Generator",QString::null,constraint, QString::null);
    KTrader::OfferList::ConstIterator iterator = offers.begin();
    KTrader::OfferList::ConstIterator end = offers.end();
    QStringList::Iterator mimeType;

    for (; iterator != end; ++iterator)
    {
        KService::Ptr service = *iterator;
345
        QStringList mimeTypes = service->serviceTypes();
Piotr Szymanski's avatar
Piotr Szymanski committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        for (mimeType=mimeTypes.begin();mimeType!=mimeTypes.end();++mimeType)
            if (! (*mimeType).contains("oKular"))
                m_supportedMimeTypes << *mimeType;
    }
}

void Part::setMimeTypes(KIO::Job *job)
{
    if (job)
    {
        if (m_supportedMimeTypes.count() <= 0)
            supportedMimetypes();
        job->addMetaData("accept", m_supportedMimeTypes.join(", ") + ", */*;q=0.5");
    }
}

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
void Part::fillGenerators()
{
    QString constraint("([X-KDE-Priority] > 0) and (exist Library) and ([X-KDE-oKularHasInternalSettings])") ;
    KTrader::OfferList offers=KTrader::self()->query("oKular/Generator",constraint);
    QString propName;
    int count=offers.count();
    if (count > 0)
    {
        for (int i=0;i<count;i++)
        {
          propName=offers[i]->property("Name").toString();
          // dont load already loaded generators
          if (! m_loadedGenerators.take( propName ) )
          {
            KLibLoader *loader = KLibLoader::self();
            if (!loader)
            {
                kdWarning() << "Could not start library loader: '" << loader->lastErrorMessage() << "'." << endl;
                return;
            }
            KLibrary *lib = loader->globalLibrary( QFile::encodeName( offers[i]->library() ) );
            if (!lib) 
            {
                kdWarning() << "Could not load '" << lib->fileName() << "' library." << endl;
            }

            Generator* (*create_plugin)(KPDFDocument* doc) = ( Generator* (*)(KPDFDocument* doc) ) lib->symbol( "create_plugin" );
            // the generator should do anything with the document if we are only configuring
            m_loadedGenerators.insert(propName,create_plugin(m_document));
            m_generatorsWithSettings << propName;
          }
        }

        m_loadedGenerators.setAutoDelete(true);
    }
}

void Part::slotGeneratorPreferences( )
{
    fillGenerators();
    //Generator* gen= m_loadedGenerators[m_generatorsWithSettings[number]];

    // an instance the dialog could be already created and could be cached,
    // in which case you want to display the cached dialog
    if ( KConfigDialog::showDialog( "generator_prefs" ) )
        return;

    // we didn't find an instance of this dialog, so lets create it
Piotr Szymanski's avatar
Piotr Szymanski committed
410
    KConfigDialog * dialog = new KConfigDialog( m_pageView, "generator_prefs", KpdfSettings::self() );
411 412 413 414 415 416 417 418 419 420 421 422

    QDictIterator<Generator> it(m_loadedGenerators);
    for( ; it.current(); ++it )
    {
        it.current()->addPages(dialog);
    }

    // (for now dont FIXME) keep us informed when the user changes settings
    // connect( dialog, SIGNAL( settingsChanged() ), this, SLOT( slotNewConfig() ) );
    dialog->show();
}

Enrico Ros's avatar
Enrico Ros committed
423
void Part::notifyViewportChanged( bool /*smoothMove*/ )
424
{
425 426 427 428 429
    // update actions if the page is changed
    static int lastPage = -1;
    int viewportPage = m_document->viewport().pageNumber;
    if ( viewportPage != lastPage )
    {
430
        updateViewActions();
431 432
        lastPage = viewportPage;
    }
433 434
}

435 436
void Part::goToPage(uint i)
{
437
    if ( i <= m_document->pages() )
438
        m_document->setViewportPage( i - 1 );
439 440
}

Pino Toscano's avatar
porting  
Pino Toscano committed
441
void Part::openDocument(KUrl doc)
442
{
Enrico Ros's avatar
Enrico Ros committed
443
    openURL(doc);
444 445 446 447
}

uint Part::pages()
{
Enrico Ros's avatar
Enrico Ros committed
448 449 450 451 452 453 454 455
    return m_document->pages();
}

uint Part::currentPage()
{
    return m_document->pages() ? m_document->currentPage() + 1 : 0;
}

Pino Toscano's avatar
porting  
Pino Toscano committed
456
KUrl Part::currentDocument()
Enrico Ros's avatar
Enrico Ros committed
457 458
{
    return m_document->currentDocument();
459 460
}

461
//this don't go anywhere but is required by genericfactory.h
462
KAboutData* Part::createAboutData()
Laurent Montel's avatar
Laurent Montel committed
463
{
464 465 466
	// the non-i18n name here must be the same as the directory in
	// which the part's rc file is installed ('partrcdir' in the
	// Makefile)
Albert Astals Cid's avatar
Albert Astals Cid committed
467
	KAboutData* aboutData = new KAboutData("oKularpart", I18N_NOOP("oKular::Part"), "0.1");
468 469
	aboutData->addAuthor("Wilco Greven", 0, "greven@kde.org");
	return aboutData;
Laurent Montel's avatar
Laurent Montel committed
470 471
}

472 473
bool Part::slotImportPSFile()
{
Pino Toscano's avatar
porting  
Pino Toscano committed
474
    KUrl url = KFileDialog::getOpenURL( QString::null, "application/postscript" );
475
    KTempFile tf( QString::null, ".pdf" );
476

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
    if ( tf.status() == 0 && url.isLocalFile())
    {
        tf.close();
        m_file = url.path();
        m_temporaryLocalFile = tf.name();
        QString app = KStandardDirs::findExe( "ps2pdf" );
        KProcess *p = new KProcess;
        *p << app;
        *p << m_file << m_temporaryLocalFile;
        m_pageView->displayMessage(i18n("Importing PS file as PDF (this may take a while)..."));
        connect(p, SIGNAL(processExited(KProcess *)), this, SLOT(psTransformEnded()));
        connect(p, SIGNAL(processExited(KProcess *)), this, SLOT(psTransformEnded()));
        p -> start();
        return true;
    }
492

493
    m_temporaryLocalFile = QString::null;
494
    return false;
495
}
Piotr Szymanski's avatar
Piotr Szymanski committed
496

497
bool Part::openFile()
Laurent Montel's avatar
Laurent Montel committed
498
{
Piotr Szymanski's avatar
Piotr Szymanski committed
499 500 501 502 503 504 505 506 507 508
    KMimeType::Ptr mime;
    if ( m_bExtension->urlArgs().serviceType.isEmpty() )
    {
        mime = KMimeType::findByPath( m_file );
    }
    else
    {
        mime = KMimeType::mimeType( m_bExtension->urlArgs().serviceType );
    }
    bool ok = m_document->openDocument( m_file, url(), mime );
509
    bool canSearch = m_document->supportsSearching();
510 511

    // update one-time actions
512 513
    m_find->setEnabled( ok && canSearch );
    m_findNext->setEnabled( ok && canSearch );
514 515
    m_saveAs->setEnabled( ok );
    m_printPreview->setEnabled( ok );
516 517
    m_showProperties->setEnabled( ok );
    m_showPresentation->setEnabled( ok );
518 519

    // update viewing actions
520
    updateViewActions();
521

522 523 524 525 526 527 528 529 530 531 532 533 534 535
    if ( !ok )
    {
        // if can't open document, update windows so they display blank contents
        m_pageView->updateContents();
        m_thumbnailList->updateContents();
        return false;
    }

    // set the file to the fileWatcher
    if ( !m_watcher->contains(m_file) )
        m_watcher->addFile(m_file);

    // if the 'StartFullScreen' flag is set, start presentation
    if ( m_document->getMetaData( "StartFullScreen" ) == "yes" )
Enrico Ros's avatar
Enrico Ros committed
536 537
    {
        KMessageBox::information( m_presentationWidget, i18n("The document is going to be launched on presentation mode because the file requested it."), QString::null, "autoPresentationWarning" );
538
        slotShowPresentation();
Enrico Ros's avatar
Enrico Ros committed
539
    }
540 541 542
/*    if (m_document->getXMLFile() != QString::null)
        setXMLFile(m_document->getXMLFile(),true);*/
    m_document->setupGUI(actionCollection(),m_toolBox);
543
    return true;
Laurent Montel's avatar
Laurent Montel committed
544 545
}

Pino Toscano's avatar
porting  
Pino Toscano committed
546
bool Part::openURL(const KUrl &url)
547
{
Enrico Ros's avatar
Enrico Ros committed
548 549 550 551
    // note: this can be the right place to check the file for gz or bz2 extension
    // if it matches then: download it (if not local) extract to a temp file using
    // KTar and proceed with the URL of the temporary file

552 553
    // this calls in sequence the 'closeURL' and 'openFile' methods
    bool openOk = KParts::ReadOnlyPart::openURL(url);
554

555
    if ( openOk )
556
        m_viewportDirty = 0;
557
    else
558
        KMessageBox::error( widget(), i18n("Could not open %1").arg( url.prettyURL() ) );
559
    return openOk;
560 561
}

562 563
bool Part::closeURL()
{
564 565 566 567 568 569
    if (!m_temporaryLocalFile.isNull())
    {
        QFile::remove( m_temporaryLocalFile );
        m_temporaryLocalFile = QString::null;
    }

Piotr Szymanski's avatar
Piotr Szymanski committed
570
    slotHidePresentation();
571 572 573 574 575 576
    m_find->setEnabled( false );
    m_findNext->setEnabled( false );
    m_saveAs->setEnabled( false );
    m_printPreview->setEnabled( false );
    m_showProperties->setEnabled( false );
    m_showPresentation->setEnabled( false );
Piotr Szymanski's avatar
Piotr Szymanski committed
577 578
    emit setWindowCaption("");
    emit enablePrintAction(false);
579 580 581
    m_searchStarted = false;
    if (!m_file.isEmpty()) m_watcher->removeFile(m_file);
    m_document->closeDocument();
Piotr Szymanski's avatar
Piotr Szymanski committed
582
    updateViewActions();
583
    m_searchWidget->clearText();
584 585 586
    return KParts::ReadOnlyPart::closeURL();
}

Piotr Szymanski's avatar
Piotr Szymanski committed
587 588 589 590 591 592 593 594 595 596 597 598 599 600
void Part::close()
{
  if (parent() && strcmp(parent()->name(), "KPDF::Shell") == 0)
  {
    closeURL();
  }
  else KMessageBox::information(widget(), i18n("This link points to a close document action that does not work when using the embedded viewer."), QString::null, "warnNoCloseIfNotInKPDF");
}

void Part::cannotQuit()
{
	KMessageBox::information(widget(), i18n("This link points to a quit application action that does not work when using the embedded viewer."), QString::null, "warnNoQuitIfNotInKPDF");
}

601 602 603 604
bool Part::eventFilter( QObject * watched, QEvent * e )
{
    // if pageView has been resized, save splitter sizes
    if ( watched == m_pageView && e->type() == QEvent::Resize )
Piotr Szymanski's avatar
Piotr Szymanski committed
605
        saveSplitterSize();
606 607 608 609 610

    // only intercept events, don't block them
    return false;
}

611
void Part::slotShowLeftPanel()
Albert Astals Cid's avatar
Albert Astals Cid committed
612
{
613
    bool showLeft = m_showLeftPanel->isChecked();
Piotr Szymanski's avatar
Piotr Szymanski committed
614 615
    KpdfSettings::setShowLeftPanel( showLeft );
    KpdfSettings::writeConfig();
Enrico Ros's avatar
Enrico Ros committed
616
    // show/hide left panel
617 618 619
    m_leftPanel->setShown( showLeft );
    // this needs to be hidden explicitly to disable thumbnails gen
    m_thumbnailList->setShown( showLeft );
Albert Astals Cid's avatar
Albert Astals Cid committed
620 621
}

Piotr Szymanski's avatar
Piotr Szymanski committed
622 623 624 625 626 627
void Part::saveSplitterSize()
{
    KpdfSettings::setSplitterSizes( m_splitter->sizes() );
    KpdfSettings::writeConfig();
}

628
void Part::slotFileDirty( const QString& fileName )
Albert Astals Cid's avatar
Albert Astals Cid committed
629 630 631 632
{
  // The beauty of this is that each start cancels the previous one.
  // This means that timeout() is only fired when there have
  // no changes to the file for the last 750 milisecs.
633 634
  // This ensures that we don't update on every other byte that gets
  // written to the file.
Albert Astals Cid's avatar
Albert Astals Cid committed
635 636 637 638 639 640
  if ( fileName == m_file )
  {
    m_dirtyHandler->start( 750, true );
  }
}

641
void Part::slotDoFileDirty()
Albert Astals Cid's avatar
Albert Astals Cid committed
642
{
643
    // do the following the first time the file is reloaded
644
    if ( m_viewportDirty.pageNumber == -1 )
645 646
    {
        // store the current viewport
647
        m_viewportDirty = DocumentViewport( m_document->viewport() );
648 649 650 651 652 653 654 655 656

        // inform the user about the operation in progress
        m_pageView->displayMessage( i18n("Reloading the document...") );
    }

    // close and (try to) reopen the document
    if ( KParts::ReadOnlyPart::openURL(m_file) )
    {
        // on successfull opening, restore the previous viewport
657 658 659 660
        if ( m_viewportDirty.pageNumber >= (int) m_document->pages() ) 
            m_viewportDirty.pageNumber = (int) m_document->pages() - 1;
        m_document->setViewport( m_viewportDirty );
        m_viewportDirty.pageNumber = -1;
Piotr Szymanski's avatar
Piotr Szymanski committed
661
        emit enablePrintAction(true);
662 663 664 665 666 667 668
    }
    else
    {
        // start watching the file again (since we dropped it on close)
        m_watcher->addFile(m_file);
        m_dirtyHandler->start( 750, true );
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
669 670
}

671
void Part::updateViewActions()
672
{
673 674
    bool opened = m_document->pages() > 0;
    if ( opened )
675 676 677 678 679 680 681 682
    {
        bool atBegin = m_document->currentPage() < 1;
        bool atEnd = m_document->currentPage() >= (m_document->pages() - 1);
        m_gotoPage->setEnabled( m_document->pages() > 1 );
        m_firstPage->setEnabled( !atBegin );
        m_prevPage->setEnabled( !atBegin );
        m_lastPage->setEnabled( !atEnd );
        m_nextPage->setEnabled( !atEnd );
683 684
        m_historyBack->setEnabled( !m_document->historyAtBegin() );
        m_historyNext->setEnabled( !m_document->historyAtEnd() );
685 686 687 688 689 690 691 692
    }
    else
    {
        m_gotoPage->setEnabled( false );
        m_firstPage->setEnabled( false );
        m_lastPage->setEnabled( false );
        m_prevPage->setEnabled( false );
        m_nextPage->setEnabled( false );
693 694
        m_historyBack->setEnabled( false );
        m_historyNext->setEnabled( false );
695
    }
696
}
Laurent Montel's avatar
Laurent Montel committed
697

698 699 700 701 702
void Part::enableTOC(bool enable)
{
	m_toolBox->setItemEnabled(0, enable);
}

703
//BEGIN go to page dialog
704
class KPDFGotoPageDialog : public KDialogBase
Laurent Montel's avatar
Laurent Montel committed
705
{
706 707 708 709
public:
	KPDFGotoPageDialog(QWidget *p, int current, int max) : KDialogBase(p, 0L, true, i18n("Go to Page"), Ok | Cancel, Ok) {
		QWidget *w = new QWidget(this);
		setMainWidget(w);
710

711 712 713 714
		QVBoxLayout *topLayout = new QVBoxLayout( w, 0, spacingHint() );
		e1 = new KIntNumInput(current, w);
		e1->setRange(1, max);
		e1->setEditFocus(true);
715

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
		QLabel *label = new QLabel( e1,i18n("&Page:"), w );
		topLayout->addWidget(label);
		topLayout->addWidget(e1);
		topLayout->addSpacing(spacingHint()); // A little bit extra space
		topLayout->addStretch(10);
		e1->setFocus();
	}

	int getPage() {
		return e1->value();
	}

  protected:
    KIntNumInput *e1;
};
731
//END go to page dialog
732 733 734

void Part::slotGoToPage()
{
735 736
    KPDFGotoPageDialog pageDialog( m_pageView, m_document->currentPage() + 1, m_document->pages() );
    if ( pageDialog.exec() == QDialog::Accepted )
737
        m_document->setViewportPage( pageDialog.getPage() - 1 );
738 739
}

740
void Part::slotPreviousPage()
741
{
Piotr Szymanski's avatar
Piotr Szymanski committed
742
    if ( m_document->isOpened() && !m_document->currentPage() < 1 )
743
        m_document->setViewportPage( m_document->currentPage() - 1 );
744 745
}

746
void Part::slotNextPage()
747
{
Piotr Szymanski's avatar
Piotr Szymanski committed
748
    if ( m_document->isOpened() && m_document->currentPage() < (m_document->pages() - 1) )
749
        m_document->setViewportPage( m_document->currentPage() + 1 );
750 751
}

752
void Part::slotGotoFirst()
753
{
Piotr Szymanski's avatar
Piotr Szymanski committed
754 755
    if ( m_document->isOpened() )
        m_document->setViewportPage( 0 );
756 757
}

758
void Part::slotGotoLast()
Laurent Montel's avatar
Laurent Montel committed
759
{
Piotr Szymanski's avatar
Piotr Szymanski committed
760 761
    if ( m_document->isOpened() )
        m_document->setViewportPage( m_document->pages() - 1 );
Laurent Montel's avatar
Laurent Montel committed
762 763
}

764 765 766 767 768 769 770 771 772 773
void Part::slotHistoryBack()
{
    m_document->setPrevViewport();
}

void Part::slotHistoryNext()
{
    m_document->setNextViewport();
}

774
void Part::slotFind()
Laurent Montel's avatar
Laurent Montel committed
775
{
776 777
    KFindDialog dlg( widget() );
    dlg.setHasCursor( false );
Enrico Ros's avatar
Enrico Ros committed
778
#if KDE_IS_VERSION(3,3,90)
779 780 781
    dlg.setSupportsBackwardsFind( false );
    dlg.setSupportsWholeWordsFind( false );
    dlg.setSupportsRegularExpressionFind( false );
Enrico Ros's avatar
Enrico Ros committed
782
#endif
783 784
    if ( dlg.exec() == QDialog::Accepted )
    {
785
        m_searchStarted = true;
786
        m_document->resetSearch( PART_SEARCH_ID );
787
        m_document->searchText( PART_SEARCH_ID, dlg.pattern(), false, dlg.options() & KFindDialog::CaseSensitive,
788
                                KPDFDocument::NextMatch, true, qRgb( 255, 255, 64 ) );
789
    }
790 791
}

792
void Part::slotFindNext()
793
{
794 795 796 797
    if ( m_searchStarted )
        m_document->continueSearch( PART_SEARCH_ID );
    else
        slotFind();
798 799
}

800
void Part::slotSaveFileAs()
801
{
Pino Toscano's avatar
porting  
Pino Toscano committed
802
    KUrl saveURL = KFileDialog::getSaveURL( url().isLocalFile() ? url().url() : url().fileName(), QString::null, widget() );
803 804
    if ( saveURL.isValid() && !saveURL.isEmpty() )
    {
Enrico Ros's avatar
Enrico Ros committed
805 806
        if ( KIO::NetAccess::exists( saveURL, false, widget() ) )
        {
Piotr Szymanski's avatar
Piotr Szymanski committed
807
            if (KMessageBox::warningContinueCancel( widget(), i18n("A file named \"%1\" already exists. Are you sure you want to overwrite it?").arg(saveURL.filename()), QString::null, i18n("Overwrite")) != KMessageBox::Continue)
Enrico Ros's avatar
Enrico Ros committed
808 809 810
                return;
        }

811
        if ( !KIO::NetAccess::file_copy( url(), saveURL, -1, true ) )
Enrico Ros's avatar
Enrico Ros committed
812
            KMessageBox::information( widget(), i18n("File could not be saved in '%1'. Try to save it to another location.").arg( saveURL.prettyURL() ) );
813
    }
Albert Astals Cid's avatar
Albert Astals Cid committed
814 815
}

Enrico Ros's avatar
Enrico Ros committed
816 817 818 819 820 821 822 823
void Part::slotGetNewStuff()
{
    // show the modal dialog over pageview and execute it
    NewStuffDialog * dialog = new NewStuffDialog( m_pageView );
    dialog->exec();
    delete dialog;
}

Enrico Ros's avatar
Enrico Ros committed
824
void Part::slotPreferences()
825
{
Enrico Ros's avatar
Enrico Ros committed
826 827 828 829 830 831
    // an instance the dialog could be already created and could be cached,
    // in which case you want to display the cached dialog
    if ( PreferencesDialog::showDialog( "preferences" ) )
        return;

    // we didn't find an instance of this dialog, so lets create it
Piotr Szymanski's avatar
Piotr Szymanski committed
832
    PreferencesDialog * dialog = new PreferencesDialog( m_pageView, KpdfSettings::self() );
Enrico Ros's avatar
Enrico Ros committed
833
    // keep us informed when the user changes settings
834
    connect( dialog, SIGNAL( settingsChanged() ), this, SLOT( slotNewConfig() ) );
Enrico Ros's avatar
Enrico Ros committed
835 836 837 838 839 840

    dialog->show();
}

void Part::slotNewConfig()
{
841 842 843
    // Apply settings here. A good policy is to check wether the setting has
    // changed before applying changes.

844
    // Watch File
Piotr Szymanski's avatar
Piotr Szymanski committed
845
    bool watchFile = KpdfSettings::watchFile();
846 847 848
    if ( watchFile && m_watcher->isStopped() )
        m_watcher->startScan();
    if ( !watchFile && !m_watcher->isStopped() )
849
    {
850 851
        m_dirtyHandler->stop();
        m_watcher->stopScan();
852
    }
853

Piotr Szymanski's avatar
Piotr Szymanski committed
854
    bool showSearch = KpdfSettings::showSearchBar();
855 856 857
    if ( m_searchWidget->isShown() != showSearch )
        m_searchWidget->setShown( showSearch );

858
    // Main View (pageView)
Piotr Szymanski's avatar
Piotr Szymanski committed
859
    QScrollView::ScrollBarMode scrollBarMode = KpdfSettings::showScrollBars() ?
860 861 862 863 864 865
        QScrollView::AlwaysOn : QScrollView::AlwaysOff;
    if ( m_pageView->hScrollBarMode() != scrollBarMode )
    {
        m_pageView->setHScrollBarMode( scrollBarMode );
        m_pageView->setVScrollBarMode( scrollBarMode );
    }
Enrico Ros's avatar
Enrico Ros committed
866

867 868 869
    // update document settings
    m_document->reparseConfig();

Enrico Ros's avatar
Enrico Ros committed
870
    // update Main View and ThumbnailList contents
Piotr Szymanski's avatar
Piotr Szymanski committed
871
    // TODO do this only when changing KpdfSettings::renderMode()
872
    m_pageView->updateContents();
Piotr Szymanski's avatar
Piotr Szymanski committed
873
    if ( KpdfSettings::showLeftPanel() && m_thumbnailList->isShown() )
874
        m_thumbnailList->updateWidgets();
875
}
876

877
void Part::slotPrintPreview()
Wilco Greven's avatar
Wilco Greven committed
878
{
879
    if (m_document->pages() == 0) return;
Wilco Greven's avatar
Wilco Greven committed
880

881 882 883
    double width, height;
    int landscape, portrait;
    KPrinter printer;
Albert Astals Cid's avatar
Albert Astals Cid committed
884
    const KPDFPage *page;
885

886
    printer.setMinMax(1, m_document->pages());
887 888
    printer.setPreviewOnly( true );
    printer.setMargins(0, 0, 0, 0);
889

Albert Astals Cid's avatar
Albert Astals Cid committed
890 891
    // if some pages are landscape and others are not the most common win as kprinter does
    // not accept a per page setting
892 893
    landscape = 0;
    portrait = 0;
894
    for (uint i = 0; i < m_document->pages(); i++)
895
    {
896
        page = m_document->page(i);
Albert Astals Cid's avatar
Albert Astals Cid committed
897 898 899 900 901 902
        width = page->width();
        height = page->height();
        if (page->rotation() == 90 || page->rotation() == 270) qSwap(width, height);
        if (width > height) landscape++;
        else portrait++;
    }
903
    if (landscape > portrait) printer.setOption("orientation-requested", "4");
904

905
    doPrint(printer);
Wilco Greven's avatar
Wilco Greven committed
906 907
}

908 909
void Part::slotShowMenu(const KPDFPage *page, const QPoint &point)
{
Albert Astals Cid's avatar
Albert Astals Cid committed
910 911