forked from eBookProjects/uChmViewer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
1579 lines (1289 loc) · 42.7 KB
/
Copy pathmainwindow.cpp
File metadata and controls
1579 lines (1289 loc) · 42.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Kchmviewer - a CHM and EPUB file viewer with broad language support
* Copyright (C) 2004-2014 George Yunaev, gyunaev@ulduzsoft.com
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <QAction>
#include <QActionGroup>
#include <QApplication>
#include <QByteArray>
#include <QCoreApplication>
#include <QDesktopServices>
#include <QDialog>
#include <QDir>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QEvent>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QIODevice>
#include <QIcon>
#include <QKeySequence>
#include <QLabel>
#include <QList>
#include <QMenu>
#include <QMenuBar>
#include <QMessageBox>
#include <QMimeData>
#include <QObject>
#include <QPixmap>
#include <QPrinter>
#include <QPrintDialog>
#include <QProcess>
#include <QProgressDialog>
#include <QSharedMemory>
#include <QShortcut>
#include <QSize>
#include <QStatusBar>
#include <QString>
#include <QStringList>
#include <QTemporaryFile>
#include <QTextEdit>
#include <QTimer>
#include <QToolBar>
#include <QUrl>
#include <QVariant>
#include <QWhatsThis>
#include <Qt>
#include <QtGlobal>
class QCloseEvent;
#include <browser-types.hpp>
#include <ebook.h>
#include "config.h"
#include "dialog_setup.h"
#include "i18n.h"
#include "navigationpanel.h"
#include "recentfiles.h"
#include "settings.h"
#include "textencodings.h"
#include "toolbarmanager.h"
#include "ui_dialog_about.h"
#include "version.h"
#include "viewwindow.h"
#include "viewwindowmgr.h"
#include "mainwindow.h"
// Maximum memory size for inter-application communication
static const int SHARED_MEMORY_SIZE = 4096;
static const unsigned int WINDOW_DEFAULT_X_SIZE = 900;
static const unsigned int WINDOW_DEFAULT_Y_SIZE = 700;
MainWindow::MainWindow( const QStringList& arguments )
: QMainWindow( 0 ), Ui::MainWindow()
{
const unsigned int SPLT_X_SIZE = 300;
m_arguments = arguments;
// Delete the pointer when the window is closed
setAttribute( Qt::WA_DeleteOnClose );
// UIC stuff
setupUi( this );
setAcceptDrops( true );
// Set up layout direction
if ( pConfig->m_advLayoutDirectionRL )
qApp->setLayoutDirection( Qt::RightToLeft );
else
qApp->setLayoutDirection( Qt::LeftToRight );
m_ebookFile = 0;
m_autoteststate = STATE_OFF;
m_sharedMemory = 0;
m_currentSettings = new Settings();
// Create the view window, which is a central widget
m_viewWindowMgr = new ViewWindowMgr( this );
setCentralWidget( m_viewWindowMgr );
// Create a navigation panel
m_navPanel = new NavigationPanel( this );
connect( m_viewWindowMgr,
SIGNAL( historyChanged() ),
this,
SLOT( onHistoryChanged() ) );
connect( m_viewWindowMgr, &ViewWindowMgr::browserChanged,
this, &MainWindow::browserChanged );
connect( m_viewWindowMgr, &ViewWindowMgr::urlChanged,
this, &MainWindow::onUrlChanged );
connect( m_viewWindowMgr, &ViewWindowMgr::linkClicked,
this, &MainWindow::onLinkClicked );
connect( m_viewWindowMgr, &ViewWindowMgr::contextMenuRequested,
this, &MainWindow::showBrowserContextMenu );
// Add navigation dock
m_navPanel->setAllowedAreas( Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea );
addDockWidget( Qt::LeftDockWidgetArea, m_navPanel, Qt::Vertical );
// Set up toolbar manager
m_toolbarMgr = new ToolbarManager( this );
m_toolbarMgr->queryAvailableActions( this );
m_toolbarMgr->addManaged( mainToolbar );
m_toolbarMgr->addManaged( navToolbar );
m_toolbarMgr->addManaged( viewToolbar );
m_toolbarMgr->load();
// Set up other things
setupActions();
updateToolbars();
setupLangEncodingMenu();
// Resize main window and dock
resize( WINDOW_DEFAULT_X_SIZE, WINDOW_DEFAULT_Y_SIZE );
m_navPanel->resize( SPLT_X_SIZE, m_navPanel->height() );
statusBar()->show();
qApp->setWindowIcon( QPixmap( ":/images/uchmviewer.png" ) );
if ( pConfig->m_numOfRecentFiles > 0 )
{
m_recentFiles = new RecentFiles( menu_File, file_exit_action, pConfig->m_numOfRecentFiles );
connect( m_recentFiles, SIGNAL( openRecentFile( QString ) ), this, SLOT( actionOpenRecentFile( QString ) ) );
}
else
m_recentFiles = 0;
// Basically disable everything
updateActions();
}
MainWindow::~MainWindow()
{
if ( m_recentFiles )
delete m_recentFiles;
// Temporary files cleanup
while ( !m_tempFileKeeper.isEmpty() )
delete m_tempFileKeeper.takeFirst();
delete m_sharedMemory;
delete m_currentSettings;
}
void MainWindow::launch()
{
QTimer::singleShot( 0, this, SLOT( firstShow() ) );
}
bool MainWindow::hasSameTokenInstance()
{
// Find out if token has been specified as this would mean we're running in a single instance mode
QString token;
// argv[0] in Qt is still a program name
for ( int i = 1; i < m_arguments.size(); i++ )
{
// This is not bulletproof (think -showPage -token) but this is not likely to happen
if ( m_arguments[i] == "-token" )
{
token = m_arguments[++i];
break;
}
}
if ( token.isEmpty() )
return false;
m_sharedMemory = new QSharedMemory( token );
// If we can attach to it, the segment already exists
if ( m_sharedMemory->attach() )
{
// Another instance exists; send the command-line there
QByteArray args = m_arguments.join( "|" ).toLocal8Bit();
if ( args.size() < SHARED_MEMORY_SIZE - 2 )
{
// Write the size first, then the string
if ( m_sharedMemory->lock() )
{
char* data = ( char* ) m_sharedMemory->data();
*( ( short* )data ) = args.size();
memcpy( data + 2, args.data(), args.size() );
m_sharedMemory->unlock();
}
else
qDebug( "failed to lock" );
}
// Clean up
delete m_sharedMemory;
m_sharedMemory = 0;
return true;
}
// Create a new segment
if ( !m_sharedMemory->create( SHARED_MEMORY_SIZE ) )
{
QMessageBox::critical( 0,
i18n( "Shared memory segment failed" ),
i18n( "Failed to create a shared memory segment: %1" ).arg( m_sharedMemory->errorString() ) );
return false;
}
// Set it up so our checker knows there's no data yet
*( ( short* ) m_sharedMemory->data() ) = 0;
// Recheck every second
QTimer* timer = new QTimer( this );
connect( timer, SIGNAL( timeout() ), this, SLOT( checkForSharedMemoryMessage() ) );
timer->start( 1000 );
return false;
}
void MainWindow::checkForSharedMemoryMessage()
{
QStringList args;
m_sharedMemory->lock();
// Is there any data?
char* data = ( char* ) m_sharedMemory->data();
if ( data[0] != 0 || data[1] != 0 )
{
// Get the message length and the message
short len = *( ( short* ) data );
args = QString::fromLocal8Bit( data + 2, len ).split( "|" );
// Clean up
*( ( short* ) data ) = 0;
}
m_sharedMemory->unlock();
// And process it if we find anything
if ( !args.isEmpty() )
parseCmdLineArgs( args, true );
}
bool MainWindow::loadFile( const QString& loadFileName, bool call_open_page )
{
QString fileName = loadFileName;
// Strip file:// prefix if any
if ( fileName.startsWith( "file://" ) )
fileName.remove( 0, 7 );
EBook* new_ebook = EBook::loadFile( fileName );
if ( new_ebook )
{
// The new file is opened, so we can close the old one
if ( m_ebookFile )
{
closeFile( );
delete m_ebookFile;
}
m_ebookFile = new_ebook;
updateActions();
// Show current encoding in status bar
if ( m_ebookFile->hasFeature( EBook::FEATURE_ENCODING ) )
showInStatusBar( i18n( "Detected file encoding: %1 ( %2 )" )
.arg( TextEncodings::languageForCodec( m_ebookFile->currentEncoding() ) )
.arg( m_ebookFile->currentEncoding() ) );
// Make the file name absolute; we'll need it later
QDir qd;
qd.setPath( fileName );
m_ebookFilename = qd.absolutePath();
// Qt's 'dirname' does not work well
QFileInfo qf( m_ebookFilename );
pConfig->m_lastOpenedDir = qf.dir().path();
m_ebookFileBasename = qf.fileName();
// Apply settings to the navigation dock
m_navPanel->updateTabs( m_ebookFile );
// and to navigation buttons
nav_actionPreviousPage->setEnabled( hasTableOfContents() );
nav_actionNextPageToc->setEnabled( hasTableOfContents() );
navSetBackEnabled( false );
navSetForwardEnabled( false );
m_viewWindowMgr->invalidate();
// If the e-book supports encodings, below will be a call to setTextEncoding,
// which in turn will call refreshCurrentBrowser.
if ( !m_ebookFile->hasFeature( EBook::FEATURE_ENCODING ) )
refreshCurrentBrowser();
if ( m_currentSettings->loadSettings( fileName ) )
{
if ( m_ebookFile->hasFeature( EBook::FEATURE_ENCODING ) )
setTextEncoding( m_currentSettings->m_activeEncoding );
m_navPanel->applySettings( m_currentSettings );
if ( call_open_page )
{
m_viewWindowMgr->restoreSettings( m_currentSettings->m_viewwindows );
m_viewWindowMgr->setCurrentPage( m_currentSettings->m_activetabwindow );
if ( m_ebookFile->hasFeature( EBook::FEATURE_TOC ) )
actionLocateInContentsTab();
}
// Restore the main window size
resize( m_currentSettings->m_window_size_x, m_currentSettings->m_window_size_y );
m_navPanel->resize( m_currentSettings->m_window_size_splitter, m_navPanel->height() );
m_navPanel->setActive( NavigationPanel::TAB_CONTENTS );
}
else
{
m_navPanel->setActive( NavigationPanel::TAB_CONTENTS );
if ( m_ebookFile->hasFeature( EBook::FEATURE_ENCODING ) )
setTextEncoding( m_ebookFile->currentEncoding() );
if ( call_open_page )
openPage( m_ebookFile->homeUrl() );
}
// Disable the menu if ebook format doesn't support encoding changes
view_Set_encoding_action->setEnabled( m_ebookFile->hasFeature( EBook::FEATURE_ENCODING ) );
if ( m_recentFiles )
m_recentFiles->setCurrentFile( m_ebookFilename );
return true;
}
else
{
QMessageBox mbox(
i18n( "%1 - failed to load file" ) . arg( QCoreApplication::applicationName() ),
i18n( "Unable to load file %1" ) . arg( fileName ),
QMessageBox::Critical,
QMessageBox::Ok,
Qt::NoButton,
Qt::NoButton );
mbox.exec();
statusBar()->showMessage(
i18n( "Could not load file %1" ).arg( fileName ),
2000 );
return false;
}
}
void MainWindow::refreshCurrentBrowser( )
{
QString title = m_ebookFile->title();
if ( title.isEmpty() )
title = QCoreApplication::applicationName();
else
title = ( QString ) QCoreApplication::applicationName() + " - " + title;
setWindowTitle( title );
currentBrowser()->invalidate();
m_navPanel->refresh();
}
void MainWindow::showBrowserContextMenu( ViewWindow* browser,
const QPoint& globalPos,
const QUrl& link )
{
Q_UNUSED( browser )
QMenu* m = new QMenu( this );
if ( !link.isEmpty() )
{
QAction* newTab = m->addAction( i18n( "Open Link in a new tab\tShift+LMB" ) );
connect( newTab, &QAction::triggered,
[this, link]() { openPage( link, UBrowser::OPEN_IN_NEW ); } );
QAction* bckgTab = m->addAction( i18n( "Open Link in a new background tab\tCtrl+LMB" ) );
connect( bckgTab, &QAction::triggered,
[this, link]() { openPage( link, UBrowser::OPEN_IN_BACKGROUND ); } );
m->addSeparator();
}
setupPopupMenu( m );
m->exec( globalPos );
m->deleteLater();
}
void MainWindow::activateUrl( const QUrl& link )
{
if ( link.isEmpty() )
return;
Qt::KeyboardModifiers mods = QApplication::keyboardModifiers();
if ( mods & Qt::ShiftModifier )
openPage( link, UBrowser::OPEN_IN_NEW );
else if ( mods & Qt::ControlModifier )
openPage( link, UBrowser::OPEN_IN_BACKGROUND );
else
openPage( link, UBrowser::OPEN_IN_CURRENT );
}
bool MainWindow::openPage( const QUrl& url, UBrowser::OpenMode mode )
{
return onLinkClicked( currentBrowser(), url, mode );
}
bool MainWindow::onLinkClicked( ViewWindow* browser, const QUrl& url, UBrowser::OpenMode mode )
{
QString otherlink;
// Feed to the browser all non-internal URLs
if ( !m_ebookFile->isSupportedUrl( url ) )
{
switch ( pConfig->m_onExternalLinkClick )
{
case Config::ACTION_DONT_OPEN:
break;
case Config::ACTION_ASK_USER:
if ( QMessageBox::question( this,
i18n( "%1 - remote link clicked - %2" ) . arg( QCoreApplication::applicationName() ) . arg( otherlink ),
i18n( "A remote link %1 will start the external program to open it.\n\nDo you want to continue?" ).arg( url.toString() ),
i18n( "&Yes" ), i18n( "&No" ),
QString(), 0, 1 ) )
return false;
// no break! should continue to open.
//-fallthrough
case Config::ACTION_ALWAYS_OPEN:
QDesktopServices::openUrl( url );
break;
}
return false; // do not change the current page.
}
if ( mode == UBrowser::OPEN_IN_NEW || mode == UBrowser::OPEN_IN_BACKGROUND )
{
qreal zoom = currentBrowser()->zoomFactor();
browser = m_viewWindowMgr->addNewTab( mode != UBrowser::OPEN_IN_BACKGROUND );
browser->setZoomFactor( zoom );
}
browser->load( url );
if ( mode != UBrowser::OPEN_IN_BACKGROUND )
{
// Open all the tree items to show current item (if needed)
m_navPanel->findUrlInContents( url );
// Focus on the view window so keyboard scroll works; do not do it for the background tabs
browser->setFocus( Qt::OtherFocusReason );
}
return true;
}
void MainWindow::firstShow()
{
if ( !parseCmdLineArgs( m_arguments ) )
{
if ( m_recentFiles && pConfig->m_startupMode == Config::STARTUP_LOAD_LAST_FILE && !m_recentFiles->latestFile().isEmpty() )
{
loadFile( m_recentFiles->latestFile() );
return;
}
if ( pConfig->m_startupMode == Config::STARTUP_POPUP_OPENFILE )
actionOpenFile();
}
}
void MainWindow::setTextEncoding( const QString& encoding )
{
m_ebookFile->setCurrentEncoding( qPrintable( encoding ) );
// Find the appropriate encoding item in "Set encodings" menu
const QList<QAction*> encodings = m_encodingActions->actions();
for ( QList<QAction*>::const_iterator it = encodings.begin();
it != encodings.end();
++it )
{
if ( ( *it )->data().toString() == encoding )
{
if ( !( *it )->isChecked() )
( *it )->setChecked( true );
break;
}
}
// Because updateView() will call view->invalidate(), which clears the view->url(),
// we have to make a copy of it.
QUrl url = currentBrowser()->url();
// Regenerate the content and index trees
refreshCurrentBrowser();
currentBrowser()->load( url );
}
void MainWindow::closeFile( )
{
// Prepare the settings
if ( pConfig->m_HistoryStoreExtra )
{
if ( m_ebookFile->hasFeature( EBook::FEATURE_ENCODING ) )
m_currentSettings->m_activeEncoding = m_ebookFile->currentEncoding();
m_currentSettings->m_activetabwindow = m_viewWindowMgr->currentPageIndex( );
m_currentSettings->m_window_size_x = width();
m_currentSettings->m_window_size_y = height();
#ifdef Q_OS_WIN
// On Windows if the window is maximised or minimized, the WM will not restore positions/state,
// so we reset to default size
if ( isMaximized() || isMinimized() )
{
m_currentSettings->m_window_size_x = WINDOW_DEFAULT_X_SIZE;
m_currentSettings->m_window_size_y = WINDOW_DEFAULT_Y_SIZE;
}
#endif
m_currentSettings->m_window_size_splitter = m_navPanel->width();
m_navPanel->getSettings( m_currentSettings );
m_viewWindowMgr->saveSettings( m_currentSettings->m_viewwindows );
m_currentSettings->saveSettings( );
}
pConfig->save();
}
void MainWindow::closeEvent( QCloseEvent* e )
{
// Save the settings if we have something opened
if ( m_ebookFile )
{
closeFile( );
delete m_ebookFile;
m_ebookFile = 0;
}
// Save toolbars
m_toolbarMgr->save();
QMainWindow::closeEvent( e );
}
void MainWindow::dragEnterEvent( QDragEnterEvent* e )
{
if ( e->mimeData()->hasUrls() )
{
QUrl url = e->mimeData()->urls().first();
if ( url.isLocalFile() )
{
QString fileName = url.toLocalFile();
if ( fileName.endsWith( ".chm", Qt::CaseInsensitive ) || fileName.endsWith( ".epub", Qt::CaseInsensitive ) )
{
e->acceptProposedAction();
return;
}
}
}
e->ignore();
}
void MainWindow::dropEvent( QDropEvent* e )
{
if ( e->mimeData()->hasUrls() )
{
QUrl url = e->mimeData()->urls().first();
if ( url.isLocalFile() )
{
QString fileName = url.toLocalFile();
if ( fileName.endsWith( ".chm", Qt::CaseInsensitive ) || fileName.endsWith( ".epub", Qt::CaseInsensitive ) )
loadFile( fileName );
}
e->acceptProposedAction();
}
}
void MainWindow::printHelpAndExit()
{
fprintf( stderr, "Usage: %s [options] [helpfile]\n"
" The following options supported:\n"
" -showPage <url> opens the url in the help file\n"
" -index <text> searches for text in the Index tab\n"
" -search <query> searches for query in the Search tab, and activate the first entry if found\n"
" -token <token> specifies the application token; see the integration reference\n"
" -background start minimized\n"
, qPrintable( m_arguments[0] ) );
exit( 1 );
}
bool MainWindow::parseCmdLineArgs( const QStringList& args, bool from_another_app )
{
QString filename, search_query, search_index, open_url, search_toc;
bool do_autotest = false, force_background = false;
// argv[0] in Qt is still a program name
for ( int i = 1; i < args.size(); i++ )
{
if ( args[i] == "-h" || args[i] == "--help" )
printHelpAndExit();
else if ( args[i] == "--autotestmode" || args[i] == "--shortautotestmode" )
do_autotest = true;
else if ( args[i] == "--search" || args[i] == "-search" )
search_query = args[++i];
else if ( args[i] == "--sindex" || args[i] == "-index" )
search_index = args[++i];
else if ( args[i] == "--stoc" )
search_toc = args[++i];
else if ( args[i] == "-token" )
i++; // ignore
else if ( args[i] == "-background" )
force_background = true;
else if ( args[i] == "-v" || args[i] == "--version" )
{
printf( "uChmViewer version %s built at %s %s\n", APP_VERSION, __DATE__, __TIME__ );
exit( 0 );
}
else if ( args[i] == "--url" || args[i] == "-showPage" )
open_url = args[++i];
else
{
if ( filename.isEmpty() )
filename = args[i];
else
{
// Don't quit just because wrong CL was passed
if ( from_another_app )
return false;
fprintf( stderr, "Invalid command-line option %s (ebook filename is already specified as %s)\n",
qPrintable( filename ), qPrintable( args[i] ) );
printHelpAndExit();
}
}
}
// Opening the file?
if ( !filename.isEmpty() )
{
// If we have already opened the same file, no need to reopen it again
if ( !m_ebookFile || QDir( m_ebookFilename ) != QDir( filename ) )
{
if ( !loadFile( filename ) )
return true; // skip the latest checks, but do not exit from the program
}
if ( !open_url.isEmpty() )
{
QStringList event_args;
event_args.push_back( m_ebookFile->pathToUrl( open_url ).toString() );
qApp->postEvent( this, new UserEvent( "openPage", event_args ) );
}
else if ( !search_index.isEmpty() )
{
QStringList event_args;
event_args.push_back( search_index );
qApp->postEvent( this, new UserEvent( "findInIndex", event_args ) );
}
else if ( !search_query.isEmpty() )
{
QStringList event_args;
event_args.push_back( search_query );
qApp->postEvent( this, new UserEvent( "searchQuery", event_args ) );
}
else if ( !search_toc.isEmpty() )
{
QStringList event_args;
event_args.push_back( search_toc );
qApp->postEvent( this, new UserEvent( "findInToc", event_args ) );
}
if ( do_autotest )
{
if ( filename.isEmpty() )
qFatal( "Could not use Auto Test mode without a chm file!" );
m_autoteststate = STATE_INITIAL;
showMinimized();
runAutoTest();
}
if ( force_background )
showMinimized();
else if ( from_another_app )
{
// On Windows it is not possible to activate the window of a non-active process. From MSDN:
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms633539%28v=vs.85%29.aspx
//
// An application cannot force a window to the foreground while the user is working with another window.
// Instead, Windows flashes the taskbar button of the window to notify the user.
activateWindow();
raise();
show();
}
return true;
}
return false;
}
ViewWindow* MainWindow::currentBrowser( ) const
{
return m_viewWindowMgr->current();
}
void MainWindow::setNewTabLink( const QUrl& link )
{
m_newTabLink = link;
}
QUrl MainWindow::getNewTabLink() const
{
return m_newTabLink;
}
void MainWindow::onOpenPageInNewTab( )
{
openPage( getNewTabLink(), UBrowser::OPEN_IN_NEW );
}
void MainWindow::onOpenPageInNewBackgroundTab( )
{
openPage( getNewTabLink(), UBrowser::OPEN_IN_BACKGROUND );
}
void MainWindow::browserChanged( ViewWindow* browser )
{
m_navPanel->findUrlInContents( browser->url() );
}
bool MainWindow::event( QEvent* e )
{
if ( e->type() == QEvent::User )
return handleUserEvent( ( UserEvent* ) e );
return QMainWindow::event( e );
}
bool MainWindow::handleUserEvent( const UserEvent* event )
{
if ( event->m_action == "loadAndOpen" )
{
if ( event->m_args.size() != 1 && event->m_args.size() != 2 )
qFatal( "handleUserEvent: event loadAndOpen must receive 1 or 2 args" );
QString chmfile = event->m_args[0];
QString openurl = event->m_args.size() > 1 ? event->m_args[1] : "/";
return loadFile( chmfile, false ) && openPage( openurl );
}
else if ( event->m_action == "openPage" )
{
if ( event->m_args.size() != 1 )
qFatal( "handleUserEvent: event openPage must receive 1 arg" );
return openPage( event->m_args[0] );
}
else if ( event->m_action == "findInIndex" )
{
if ( event->m_args.size() != 1 )
qFatal( "handleUserEvent: event findInIndex must receive 1 arg" );
if ( !hasIndex() )
return false;
actionSwitchToIndexTab();
m_navPanel->findInIndex( event->m_args[0] );
return true;
}
else if ( event->m_action == "findInToc" )
{
if ( event->m_args.size() != 1 )
qFatal( "handleUserEvent: event findInToc must receive 1 arg" );
if ( !hasTableOfContents() )
return false;
actionSwitchToContentTab();
m_navPanel->findTextInContents( event->m_args[0] );
return true;
}
else if ( event->m_action == "searchQuery" )
{
if ( event->m_args.size() != 1 )
qFatal( "handleUserEvent: event searchQuery must receive 1 arg" );
actionSwitchToSearchTab();
m_navPanel->executeQueryInSearch( event->m_args[0] );
return true;
}
else
qWarning( "Unknown user event received: %s", qPrintable( event->m_action ) );
return false;
}
void MainWindow::runAutoTest()
{
switch ( m_autoteststate )
{
case STATE_INITIAL:
m_autoteststate = STATE_OPEN_INDEX;
QTimer::singleShot( 500, this, SLOT( runAutoTest() ) );
break; // allow to finish the initialization sequence
case STATE_OPEN_INDEX:
if ( hasIndex() )
m_navPanel->setActive( NavigationPanel::TAB_INDEX );
m_autoteststate = STATE_SHUTDOWN;
QTimer::singleShot( 500, this, SLOT( runAutoTest() ) );
break;
case STATE_SHUTDOWN:
qApp->quit();
break;
default:
break;
}
}
void MainWindow::showInStatusBar( const QString& text )
{
statusBar()->showMessage( text, 2000 );
}
void MainWindow::actionNavigateBack()
{
currentBrowser()->back();
}
void MainWindow::actionNavigateForward()
{
currentBrowser()->forward();
}
void MainWindow::actionNavigateHome()
{
if ( chmFile() )
openPage( chmFile()->homeUrl() );
}
void MainWindow::actionNavigatePrev()
{
if ( m_ebookFile == nullptr )
return;
QUrl url = m_ebookFile->navigatorPrev( currentBrowser()->url() );
if ( ! url.isEmpty() )
openPage( url );
}
void MainWindow::actionNavigateNext()
{
if ( m_ebookFile == nullptr )
return;
QUrl url = m_ebookFile->navigatorNext( currentBrowser()->url() );
if ( ! url.isEmpty() )
openPage( url );
}
void MainWindow::actionOpenFile()
{
QString fn = QFileDialog::getOpenFileName( this,
i18n( "Open a chm file" ),
pConfig->m_lastOpenedDir,
i18n( "Electronic books (*.chm *.epub)" ),
0,
QFileDialog::DontResolveSymlinks );
if ( !fn.isEmpty() )
loadFile( fn );
}
void MainWindow::actionPrint()
{
QPrinter* printer = new QPrinter( QPrinter::HighResolution );
QPrintDialog dlg( printer, this );
if ( dlg.exec() != QDialog::Accepted )
{
showInStatusBar( i18n( "Printing aborted" ) );
return;
}
currentBrowser()->print( printer, [ = ]( bool success )
{
Q_UNUSED( success );
showInStatusBar( i18n( "Printing finished" ) );
delete printer;
} );
}
void MainWindow::actionEditCopy()
{
currentBrowser()->selectedCopy();
}
void MainWindow::actionEditSelectAll()
{
currentBrowser()->selectAll();
}
void MainWindow::actionFindInPage()
{
m_viewWindowMgr->onActivateFind();
}
void MainWindow::actionChangeSettings()
{
DialogSetup dlg( this );
dlg.exec();
}
void MainWindow::actionExtractCHM()
{