forked from yshui/klipper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
klipper.cpp
1009 lines (866 loc) · 32.6 KB
/
klipper.cpp
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
/* This file is part of the KDE project
Copyright (C) by Andrew Stanley-Jones <[email protected]>
Copyright (C) 2000 by Carsten Pfeiffer <[email protected]>
Copyright (C) 2004 Esben Mose Hansen <[email protected]>
Copyright (C) 2008 by Dmitry Suzdalev <[email protected]>
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.
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; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "klipper.h"
#include <zlib.h>
#include <QDebug>
#include <QDir>
#include <QDialog>
#include <QMenu>
#include <QPointer>
#include <QDBusConnection>
#include <QSaveFile>
#include <KGlobalAccel>
#include <KMessageBox>
#include <KActionCollection>
#include <KToggleAction>
#include <KTextEdit>
#include "configdialog.h"
#include "klippersettings.h"
#include "urlgrabber.h"
#include "history.h"
#include "historyitem.h"
#include "historystringitem.h"
#include "klipperpopup.h"
#ifdef HAVE_PRISON
#include <prison/BarcodeWidget>
#include <prison/DataMatrixBarcode>
#include <prison/QRCodeBarcode>
#endif
#include <config-X11.h>
#if HAVE_X11
#include <QX11Info>
#include <xcb/xcb.h>
#endif
//#define NOISY_KLIPPER
namespace {
/**
* Use this when manipulating the clipboard
* from within clipboard-related signals.
*
* This avoids issues such as mouse-selections that immediately
* disappear.
* pattern: Resource Acqusition is Initialisation (RAII)
*
* (This is not threadsafe, so don't try to use such in threaded
* applications).
*/
struct Ignore {
Ignore(int& locklevel) : locklevelref(locklevel) {
locklevelref++;
}
~Ignore() {
locklevelref--;
}
private:
int& locklevelref;
};
}
// config == KGlobal::config for process, otherwise applet
Klipper::Klipper(QObject* parent, const KSharedConfigPtr& config, KlipperMode mode)
: QObject( parent )
, m_overflowCounter( 0 )
, m_locklevel( 0 )
, m_config( config )
, m_pendingContentsCheck( false )
, m_mode(mode)
{
if (m_mode == KlipperMode::Standalone) {
setenv("KSNI_NO_DBUSMENU", "1", 1);
QDBusConnection::sessionBus().registerObject("/klipper", this, QDBusConnection::ExportScriptableSlots);
}
updateTimestamp(); // read initial X user time
m_clip = qApp->clipboard();
connect( m_clip, SIGNAL(changed(QClipboard::Mode)),
this, SLOT(newClipData(QClipboard::Mode)) );
connect( &m_overflowClearTimer, SIGNAL(timeout()), SLOT(slotClearOverflow()));
m_pendingCheckTimer.setSingleShot( true );
connect( &m_pendingCheckTimer, SIGNAL(timeout()), SLOT(slotCheckPending()));
m_history = new History( this );
m_popup = new KlipperPopup(m_history);
m_popup->setShowHelp(m_mode == KlipperMode::Standalone);
connect(m_history, &History::changed, m_popup, &KlipperPopup::slotHistoryChanged);
// we need that collection, otherwise KToggleAction is not happy :}
m_collection = new KActionCollection( this );
m_toggleURLGrabAction = new KToggleAction( this );
m_collection->addAction( "clipboard_action", m_toggleURLGrabAction );
m_toggleURLGrabAction->setText(i18n("Enable Clipboard Actions"));
m_toggleURLGrabAction->setVisible(m_mode == KlipperMode::Standalone);
KGlobalAccel::setGlobalShortcut(m_toggleURLGrabAction, QKeySequence(Qt::ALT+Qt::CTRL+Qt::Key_X));
connect( m_toggleURLGrabAction, SIGNAL(toggled(bool)),
this, SLOT(setURLGrabberEnabled(bool)));
/*
* Create URL grabber
*/
m_myURLGrabber = new URLGrabber(m_history);
connect( m_myURLGrabber, SIGNAL(sigPopup(QMenu*)),
SLOT(showPopupMenu(QMenu*)) );
connect( m_myURLGrabber, SIGNAL(sigDisablePopup()),
SLOT(disableURLGrabber()) );
/*
* Load configuration settings
*/
loadSettings();
// load previous history if configured
if (m_bKeepContents) {
loadHistory();
}
m_clearHistoryAction = m_collection->addAction( "clear-history" );
m_clearHistoryAction->setIcon( QIcon::fromTheme("edit-clear-history") );
m_clearHistoryAction->setText( i18n("C&lear Clipboard History") );
m_clearHistoryAction->setVisible(m_mode == KlipperMode::Standalone);
KGlobalAccel::setGlobalShortcut(m_clearHistoryAction, QKeySequence());
connect(m_clearHistoryAction, SIGNAL(triggered()), SLOT(slotAskClearHistory()));
m_configureAction = m_collection->addAction( "configure" );
m_configureAction->setIcon( QIcon::fromTheme("configure") );
m_configureAction->setText( i18n("&Configure Klipper...") );
m_configureAction->setVisible(m_mode == KlipperMode::Standalone);
connect(m_configureAction, SIGNAL(triggered(bool)), SLOT(slotConfigure()));
m_quitAction = m_collection->addAction( "quit" );
m_quitAction->setIcon( QIcon::fromTheme("application-exit") );
m_quitAction->setText( i18nc("@item:inmenu Quit Klipper", "&Quit") );
m_quitAction->setVisible(m_mode == KlipperMode::Standalone);
connect(m_quitAction, SIGNAL(triggered(bool)), SLOT(slotQuit()));
m_repeatAction = m_collection->addAction("repeat_action");
m_repeatAction->setText(i18n("Manually Invoke Action on Current Clipboard"));
m_repeatAction->setVisible(m_mode == KlipperMode::Standalone);
KGlobalAccel::setGlobalShortcut(m_repeatAction, QKeySequence(Qt::ALT+Qt::CTRL+Qt::Key_R));
connect(m_repeatAction, SIGNAL(triggered()), SLOT(slotRepeatAction()));
// add an edit-possibility
m_editAction = m_collection->addAction("edit_clipboard");
m_editAction->setIcon(QIcon::fromTheme("document-properties"));
m_editAction->setText(i18n("&Edit Contents..."));
m_editAction->setVisible(m_mode == KlipperMode::Standalone);
KGlobalAccel::setGlobalShortcut(m_editAction, QKeySequence());
connect(m_editAction, &QAction::triggered, this,
[this]() {
editData(m_history->first());
}
);
#ifdef HAVE_PRISON
// add barcode for mobile phones
m_showBarcodeAction = m_collection->addAction("show-barcode");
m_showBarcodeAction->setText(i18n("&Show Barcode..."));
m_showBarcodeAction->setVisible(m_mode == KlipperMode::Standalone);
KGlobalAccel::setGlobalShortcut(m_showBarcodeAction, QKeySequence());
connect(m_showBarcodeAction, &QAction::triggered, this,
[this]() {
showBarcode(m_history->first());
}
);
#endif
// Cycle through history
m_cycleNextAction = m_collection->addAction("cycleNextAction");
m_cycleNextAction->setText(i18n("Next History Item"));
KGlobalAccel::setGlobalShortcut(m_cycleNextAction, QKeySequence());
connect(m_cycleNextAction, SIGNAL(triggered(bool)), SLOT(slotCycleNext()));
m_cyclePrevAction = m_collection->addAction("cyclePrevAction");
m_cyclePrevAction->setText(i18n("Previous History Item"));
KGlobalAccel::setGlobalShortcut(m_cyclePrevAction, QKeySequence());
connect(m_cyclePrevAction, SIGNAL(triggered(bool)), SLOT(slotCyclePrev()));
// Action to show Klipper popup on mouse position
m_showOnMousePos = m_collection->addAction("show-on-mouse-pos");
m_showOnMousePos->setText(i18n("Open Klipper at Mouse Position"));
KGlobalAccel::setGlobalShortcut(m_showOnMousePos, QKeySequence());
connect(m_showOnMousePos, SIGNAL(triggered(bool)), this, SLOT(slotPopupMenu()));
connect ( history(), SIGNAL(topChanged()), SLOT(slotHistoryTopChanged()) );
connect( m_popup, SIGNAL(aboutToShow()), SLOT(slotStartShowTimer()) );
m_popup->plugAction( m_toggleURLGrabAction );
m_popup->plugAction( m_clearHistoryAction );
m_popup->plugAction( m_configureAction );
m_popup->plugAction( m_repeatAction );
m_popup->plugAction( m_editAction );
#ifdef HAVE_PRISON
m_popup->plugAction( m_showBarcodeAction );
#endif
m_popup->plugAction( m_quitAction );
// session manager interaction
if (m_mode == KlipperMode::Standalone) {
connect(qApp, &QGuiApplication::commitDataRequest, this, &Klipper::saveSession);
}
}
Klipper::~Klipper()
{
delete m_myURLGrabber;
}
// DBUS
QString Klipper::getClipboardContents()
{
return getClipboardHistoryItem(0);
}
void Klipper::showKlipperPopupMenu() {
slotPopupMenu();
}
void Klipper::showKlipperManuallyInvokeActionMenu() {
slotRepeatAction();
}
// DBUS - don't call from Klipper itself
void Klipper::setClipboardContents(QString s)
{
if (s.isEmpty())
return;
Ignore lock( m_locklevel );
updateTimestamp();
HistoryItemPtr item(HistoryItemPtr(new HistoryStringItem(s)));
setClipboard( *item, Clipboard | Selection);
history()->insert( item );
}
// DBUS - don't call from Klipper itself
void Klipper::clearClipboardContents()
{
updateTimestamp();
slotClearClipboard();
}
// DBUS - don't call from Klipper itself
void Klipper::clearClipboardHistory()
{
updateTimestamp();
slotClearClipboard();
history()->slotClear();
saveSession();
}
// DBUS - don't call from Klipper itself
void Klipper::saveClipboardHistory()
{
if ( m_bKeepContents ) { // save the clipboard eventually
saveHistory();
}
}
void Klipper::slotStartShowTimer()
{
m_showTimer.start();
}
void Klipper::loadSettings()
{
// Security bug 142882: If user has save clipboard turned off, old data should be deleted from disk
static bool firstrun = true;
if (!firstrun && m_bKeepContents && !KlipperSettings::keepClipboardContents()) {
saveHistory(true);
}
firstrun=false;
m_bKeepContents = KlipperSettings::keepClipboardContents();
m_bReplayActionInHistory = KlipperSettings::replayActionInHistory();
m_bNoNullClipboard = KlipperSettings::preventEmptyClipboard();
// 0 is the id of "Ignore selection" radiobutton
m_bIgnoreSelection = KlipperSettings::ignoreSelection();
m_bIgnoreImages = KlipperSettings::ignoreImages();
m_bSynchronize = KlipperSettings::syncClipboards();
// NOTE: not used atm - kregexpeditor is not ported to kde4
m_bUseGUIRegExpEditor = KlipperSettings::useGUIRegExpEditor();
m_bSelectionTextOnly = KlipperSettings::selectionTextOnly();
m_bURLGrabber = KlipperSettings::uRLGrabberEnabled();
// this will cause it to loadSettings too
setURLGrabberEnabled(m_bURLGrabber);
history()->setMaxSize( KlipperSettings::maxClipItems() );
// Convert 4.3 settings
if (KlipperSettings::synchronize() != 3) {
// 2 was the id of "Ignore selection" radiobutton
m_bIgnoreSelection = KlipperSettings::synchronize() == 2;
// 0 was the id of "Synchronize contents" radiobutton
m_bSynchronize = KlipperSettings::synchronize() == 0;
KConfigSkeletonItem* item = KlipperSettings::self()->findItem("SyncClipboards");
item->setProperty(m_bSynchronize);
item = KlipperSettings::self()->findItem("IgnoreSelection");
item->setProperty(m_bIgnoreSelection);
item = KlipperSettings::self()->findItem("Synchronize"); // Mark property as converted.
item->setProperty(3);
KlipperSettings::self()->save();
KlipperSettings::self()->load();
}
}
void Klipper::saveSettings() const
{
m_myURLGrabber->saveSettings();
KlipperSettings::self()->setVersion(QStringLiteral(KLIPPER_VERSION_STRING));
KlipperSettings::self()->save();
// other settings should be saved automatically by KConfigDialog
}
void Klipper::showPopupMenu( QMenu* menu )
{
Q_ASSERT( menu != 0L );
QSize size = menu->sizeHint(); // geometry is not valid until it's shown
QPoint pos = QCursor::pos();
// ### We can't know where the systray icon is (since it can be hidden or shown
// in several places), so the cursor position is the only option.
if ( size.height() < pos.y() )
pos.ry() -= size.height();
menu->popup(pos);
}
bool Klipper::loadHistory() {
static const char failed_load_warning[] =
"Failed to load history resource. Clipboard history cannot be read.";
// don't use "appdata", klipper is also a kicker applet
QFile history_file(QStandardPaths::locate(QStandardPaths::GenericDataLocation,
QStringLiteral("klipper/history2.lst")));
if ( !history_file.exists() ) {
qWarning() << failed_load_warning << ": " << "History file does not exist" ;
return false;
}
if ( !history_file.open( QIODevice::ReadOnly ) ) {
qWarning() << failed_load_warning << ": " << history_file.errorString() ;
return false;
}
QDataStream file_stream( &history_file );
if( file_stream.atEnd()) {
qWarning() << failed_load_warning << ": " << "Error in reading data" ;
return false;
}
QByteArray data;
quint32 crc;
file_stream >> crc >> data;
if( crc32( 0, reinterpret_cast<unsigned char *>( data.data() ), data.size() ) != crc ) {
qWarning() << failed_load_warning << ": " << "CRC checksum does not match" ;
return false;
}
QDataStream history_stream( &data, QIODevice::ReadOnly );
char* version;
history_stream >> version;
delete[] version;
// The list needs to be reversed, as it is saved
// youngest-first to keep the most important clipboard
// items at the top, but the history is created oldest
// first.
QList<HistoryItemPtr> reverseList;
for ( HistoryItemPtr item = HistoryItem::create( history_stream );
!item.isNull();
item = HistoryItem::create( history_stream ) )
{
reverseList.prepend( item );
}
history()->slotClear();
for ( auto it = reverseList.constBegin();
it != reverseList.constEnd();
++it )
{
history()->forceInsert(*it);
}
if ( !history()->empty() ) {
setClipboard( *history()->first(), Clipboard | Selection );
}
return true;
}
void Klipper::saveHistory(bool empty) {
static const char failed_save_warning[] =
"Failed to save history. Clipboard history cannot be saved.";
// don't use "appdata", klipper is also a kicker applet
QString history_file_name(QStandardPaths::locate(QStandardPaths::GenericDataLocation,
QStringLiteral("klipper/history2.lst")));
if ( history_file_name.isNull() || history_file_name.isEmpty() ) {
// try creating the file
QDir dir(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation));
if (!dir.mkpath(QStringLiteral("klipper"))) {
qWarning() << failed_save_warning ;
return;
}
history_file_name = dir.absoluteFilePath(QStringLiteral("klipper/history2.lst"));
}
if ( history_file_name.isNull() || history_file_name.isEmpty() ) {
qWarning() << failed_save_warning ;
return;
}
QSaveFile history_file( history_file_name );
if (!history_file.open(QIODevice::WriteOnly)) {
qWarning() << failed_save_warning ;
return;
}
QByteArray data;
QDataStream history_stream( &data, QIODevice::WriteOnly );
history_stream << KLIPPER_VERSION_STRING; // const char*
if (!empty) {
HistoryItemConstPtr item = history()->first();
if (item) {
do {
history_stream << item.data();
item = HistoryItemConstPtr(history()->find(item->next_uuid()));
} while (item != history()->first());
}
}
quint32 crc = crc32( 0, reinterpret_cast<unsigned char *>( data.data() ), data.size() );
QDataStream ds ( &history_file );
ds << crc << data;
if (!history_file.commit()) {
qWarning() << failed_save_warning ;
}
}
// save session on shutdown. Don't simply use the c'tor, as that may not be called.
void Klipper::saveSession()
{
if ( m_bKeepContents ) { // save the clipboard eventually
saveHistory();
}
saveSettings();
}
void Klipper::disableURLGrabber()
{
KMessageBox::information( 0L,
i18n( "You can enable URL actions later by left-clicking on the "
"Klipper icon and selecting 'Enable Clipboard Actions'" ) );
setURLGrabberEnabled( false );
}
void Klipper::slotConfigure()
{
if (KConfigDialog::showDialog("preferences")) {
return;
}
ConfigDialog *dlg = new ConfigDialog( 0, KlipperSettings::self(), this, m_collection );
connect(dlg, SIGNAL(settingsChanged(QString)), SLOT(loadSettings()));
dlg->show();
}
void Klipper::slotQuit()
{
// If the menu was just opened, likely the user
// selected quit by accident while attempting to
// click the Klipper icon.
if ( m_showTimer.elapsed() < 300 ) {
return;
}
saveSession();
int autoStart = KMessageBox::questionYesNoCancel(0, i18n("Should Klipper start automatically when you login?"),
i18n("Automatically Start Klipper?"), KGuiItem(i18n("Start")),
KGuiItem(i18n("Do Not Start")), KStandardGuiItem::cancel(), "StartAutomatically");
KConfigGroup config( KSharedConfig::openConfig(), "General");
if ( autoStart == KMessageBox::Yes ) {
config.writeEntry("AutoStart", true);
} else if ( autoStart == KMessageBox::No) {
config.writeEntry("AutoStart", false);
} else // cancel chosen don't quit
return;
config.sync();
qApp->quit();
}
void Klipper::slotPopupMenu() {
m_popup->ensureClean();
m_popup->slotSetTopActive();
showPopupMenu( m_popup );
}
void Klipper::slotRepeatAction()
{
auto top = qSharedPointerCast<const HistoryStringItem>( history()->first() );
if ( top ) {
m_myURLGrabber->invokeAction( top );
}
}
void Klipper::setURLGrabberEnabled( bool enable )
{
if (enable != m_bURLGrabber) {
m_bURLGrabber = enable;
m_lastURLGrabberTextSelection.clear();
m_lastURLGrabberTextClipboard.clear();
KlipperSettings::setURLGrabberEnabled(enable);
}
m_toggleURLGrabAction->setChecked( enable );
// make it update its settings
m_myURLGrabber->loadSettings();
}
void Klipper::slotHistoryTopChanged() {
if ( m_locklevel ) {
return;
}
auto topitem = history()->first();
if ( topitem ) {
setClipboard( *topitem, Clipboard | Selection );
}
if ( m_bReplayActionInHistory && m_bURLGrabber ) {
slotRepeatAction();
}
}
void Klipper::slotClearClipboard()
{
Ignore lock( m_locklevel );
m_clip->clear(QClipboard::Selection);
m_clip->clear(QClipboard::Clipboard);
}
HistoryItemPtr Klipper::applyClipChanges( const QMimeData* clipData )
{
if ( m_locklevel ) {
return HistoryItemPtr();
}
Ignore lock( m_locklevel );
HistoryItemPtr item = HistoryItem::create( clipData );
history()->insert( item );
return item;
}
void Klipper::newClipData( QClipboard::Mode mode )
{
if ( m_locklevel ) {
return;
}
if( mode == QClipboard::Selection && blockFetchingNewData())
return;
checkClipData( mode == QClipboard::Selection ? true : false );
}
// Protection against too many clipboard data changes. Lyx responds to clipboard data
// requests with setting new clipboard data, so if Lyx takes over clipboard,
// Klipper notices, requests this data, this triggers "new" clipboard contents
// from Lyx, so Klipper notices again, requests this data, ... you get the idea.
const int MAX_CLIPBOARD_CHANGES = 10; // max changes per second
bool Klipper::blockFetchingNewData()
{
#if HAVE_X11
// Hacks for #85198 and #80302.
// #85198 - block fetching new clipboard contents if Shift is pressed and mouse is not,
// this may mean the user is doing selection using the keyboard, in which case
// it's possible the app sets new clipboard contents after every change - Klipper's
// history would list them all.
// #80302 - OOo (v1.1.3 at least) has a bug that if Klipper requests its clipboard contents
// while the user is doing a selection using the mouse, OOo stops updating the clipboard
// contents, so in practice it's like the user has selected only the part which was
// selected when Klipper asked first.
// Use XQueryPointer rather than QApplication::mouseButtons()/keyboardModifiers(), because
// Klipper needs the very current state.
if (!QX11Info::isPlatformX11()) {
return false;
}
xcb_connection_t *c = QX11Info::connection();
const xcb_query_pointer_cookie_t cookie = xcb_query_pointer_unchecked(c, QX11Info::appRootWindow());
QScopedPointer<xcb_query_pointer_reply_t, QScopedPointerPodDeleter> queryPointer(xcb_query_pointer_reply(c, cookie, nullptr));
if (queryPointer.isNull()) {
return false;
}
if (((queryPointer->mask & (XCB_KEY_BUT_MASK_SHIFT | XCB_KEY_BUT_MASK_BUTTON_1)) == XCB_KEY_BUT_MASK_SHIFT) // BUG: 85198
|| ((queryPointer->mask & XCB_KEY_BUT_MASK_BUTTON_1) == XCB_KEY_BUT_MASK_BUTTON_1)) { // BUG: 80302
m_pendingContentsCheck = true;
m_pendingCheckTimer.start( 100 );
return true;
}
m_pendingContentsCheck = false;
if ( m_overflowCounter == 0 )
m_overflowClearTimer.start( 1000 );
if( ++m_overflowCounter > MAX_CLIPBOARD_CHANGES )
return true;
#endif
return false;
}
void Klipper::slotCheckPending()
{
if( !m_pendingContentsCheck )
return;
m_pendingContentsCheck = false; // blockFetchingNewData() will be called again
updateTimestamp();
newClipData( QClipboard::Selection ); // always selection
}
void Klipper::checkClipData( bool selectionMode )
{
if ( ignoreClipboardChanges() ) // internal to klipper, ignoring QSpinBox selections
{
// keep our old clipboard, thanks
// This won't quite work, but it's close enough for now.
// The trouble is that the top selection =! top clipboard
// but we don't track that yet. We will....
auto top = history()->first();
if ( top ) {
setClipboard( *top, selectionMode ? Selection : Clipboard);
}
return;
}
// debug code
#ifdef NOISY_KLIPPER
qDebug() << "Checking clip data";
if ( sender() ) {
qDebug() << "sender=" << sender()->objectName();
} else {
qDebug() << "no sender";
}
qDebug() << "\nselectionMode=" << selectionMode
<< "\nowning (sel,cli)=(" << m_clip->ownsSelection() << "," << m_clip->ownsClipboard() << ")"
<< "\ntext=" << m_clip->text( selectionMode ? QClipboard::Selection : QClipboard::Clipboard) << endl;
#endif
const QMimeData* data = m_clip->mimeData( selectionMode ? QClipboard::Selection : QClipboard::Clipboard );
if ( !data ) {
qWarning() << "No data in clipboard. This not not supposed to happen.";
return;
}
bool changed = true; // ### FIXME (only relevant under polling, might be better to simply remove polling and rely on XFixes)
bool clipEmpty = data->formats().isEmpty();
if (clipEmpty) {
// Might be a timeout. Try again
clipEmpty = data->formats().isEmpty();
#ifdef NOISY_KLIPPER
qDebug() << "was empty. Retried, now " << (clipEmpty?" still empty":" no longer empty");
#endif
}
if ( changed && clipEmpty && m_bNoNullClipboard ) {
auto top = history()->first();
if ( top ) {
// keep old clipboard after someone set it to null
#ifdef NOISY_KLIPPER
qDebug() << "Resetting clipboard (Prevent empty clipboard)";
#endif
setClipboard( *top, selectionMode ? Selection : Clipboard );
}
return;
}
// this must be below the "bNoNullClipboard" handling code!
// XXX: I want a better handling of selection/clipboard in general.
// XXX: Order sensitive code. Must die.
if ( selectionMode && m_bIgnoreSelection )
return;
if( selectionMode && m_bSelectionTextOnly && !data->hasText())
return;
if( data->hasUrls() )
; // ok
else if( data->hasText() )
; // ok
else if( data->hasImage() )
{
if( m_bIgnoreImages )
return;
}
else // unknown, ignore
return;
HistoryItemPtr item = applyClipChanges( data );
if (changed) {
#ifdef NOISY_KLIPPER
qDebug() << "Synchronize?" << m_bSynchronize;
#endif
if ( m_bSynchronize && item ) {
setClipboard( *item, selectionMode ? Clipboard : Selection );
}
}
QString& lastURLGrabberText = selectionMode
? m_lastURLGrabberTextSelection : m_lastURLGrabberTextClipboard;
if( m_bURLGrabber && item && data->hasText())
{
m_myURLGrabber->checkNewData( qSharedPointerConstCast<const HistoryItem>(item) );
// Make sure URLGrabber doesn't repeat all the time if klipper reads the same
// text all the time (e.g. because XFixes is not available and the application
// has broken TIMESTAMP target). Using most recent history item may not always
// work.
if ( item->text() != lastURLGrabberText )
{
lastURLGrabberText = item->text();
}
} else {
lastURLGrabberText.clear();
}
}
void Klipper::setClipboard( const HistoryItem& item, int mode )
{
Ignore lock( m_locklevel );
Q_ASSERT( ( mode & 1 ) == 0 ); // Warn if trying to pass a boolean as a mode.
if ( mode & Selection ) {
#ifdef NOISY_KLIPPER
qDebug() << "Setting selection to <" << item.text() << ">";
#endif
m_clip->setMimeData( item.mimeData(), QClipboard::Selection );
}
if ( mode & Clipboard ) {
#ifdef NOISY_KLIPPER
qDebug() << "Setting clipboard to <" << item.text() << ">";
#endif
m_clip->setMimeData( item.mimeData(), QClipboard::Clipboard );
}
}
void Klipper::slotClearOverflow()
{
m_overflowClearTimer.stop();
if( m_overflowCounter > MAX_CLIPBOARD_CHANGES ) {
qDebug() << "App owning the clipboard/selection is lame";
// update to the latest data - this unfortunately may trigger the problem again
newClipData( QClipboard::Selection ); // Always the selection.
}
m_overflowCounter = 0;
}
QStringList Klipper::getClipboardHistoryMenu()
{
QStringList menu;
auto item = history()->first();
if (item) {
do {
menu << item->text();
item = history()->find(item->next_uuid());
} while (item != history()->first());
}
return menu;
}
QString Klipper::getClipboardHistoryItem(int i)
{
auto item = history()->first();
if (item) {
do {
if (i-- == 0) {
return item->text();
}
item = history()->find(item->next_uuid());
} while (item != history()->first());
}
return QString();
}
//
// changing a spinbox in klipper's config-dialog causes the lineedit-contents
// of the spinbox to be selected and hence the clipboard changes. But we don't
// want all those items in klipper's history. See #41917
//
bool Klipper::ignoreClipboardChanges() const
{
QWidget *focusWidget = qApp->focusWidget();
if ( focusWidget )
{
if ( focusWidget->inherits( "QSpinBox" ) ||
(focusWidget->parentWidget() &&
focusWidget->inherits("QLineEdit") &&
focusWidget->parentWidget()->inherits("QSpinWidget")) )
{
return true;
}
}
return false;
}
void Klipper::updateTimestamp()
{
#if HAVE_X11
if (QX11Info::isPlatformX11()) {
QX11Info::setAppTime(QX11Info::getTimestamp());
}
#endif
}
void Klipper::editData(const QSharedPointer< const HistoryItem > &item)
{
QPointer<QDialog> dlg(new QDialog());
dlg->setWindowTitle( i18n("Edit Contents") );
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, dlg);
buttons->button(QDialogButtonBox::Ok)->setShortcut(Qt::CTRL | Qt::Key_Return);
connect(buttons, &QDialogButtonBox::accepted, dlg.data(), &QDialog::accept);
connect(buttons, &QDialogButtonBox::rejected, dlg.data(), &QDialog::reject);
connect(dlg.data(), &QDialog::finished, dlg.data(),
[this, dlg, item](int result) {
emit editFinished(item, result);
dlg->deleteLater();
}
);
KTextEdit *edit = new KTextEdit( dlg );
if (item) {
edit->setText( item->text() );
}
edit->setFocus();
edit->setMinimumSize( 300, 40 );
QVBoxLayout *layout = new QVBoxLayout(dlg);
layout->addWidget(edit);
layout->addWidget(buttons);
dlg->adjustSize();
connect(dlg.data(), &QDialog::accepted, this, [this, edit, item]() {
QString text = edit->toPlainText();
if (item) {
m_history->remove( item );
}
m_history->insert(HistoryItemPtr(new HistoryStringItem(text)));
if (m_myURLGrabber) {
m_myURLGrabber->checkNewData(HistoryItemConstPtr(m_history->first()));
}
});
if (m_mode == KlipperMode::Standalone) {
dlg->setModal(true);
dlg->exec();
} else if (m_mode == KlipperMode::DataEngine) {
dlg->open();
}
}
#ifdef HAVE_PRISON
void Klipper::showBarcode(const QSharedPointer< const HistoryItem > &item)
{
using namespace prison;
QPointer<QDialog> dlg(new QDialog());
dlg->setWindowTitle( i18n("Mobile Barcode") );
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok, dlg);
buttons->button(QDialogButtonBox::Ok)->setShortcut(Qt::CTRL | Qt::Key_Return);
connect(buttons, &QDialogButtonBox::accepted, dlg.data(), &QDialog::accept);
connect(dlg.data(), &QDialog::finished, dlg.data(), &QDialog::deleteLater);
QWidget* mw = new QWidget(dlg);
QHBoxLayout* layout = new QHBoxLayout(mw);
BarcodeWidget* qrcode = new BarcodeWidget(new QRCodeBarcode());
BarcodeWidget* datamatrix = new BarcodeWidget(new DataMatrixBarcode());
if (item) {
qrcode->setData( item->text() );
datamatrix->setData( item->text() );
}
layout->addWidget(qrcode);
layout->addWidget(datamatrix);
mw->setFocus();
QVBoxLayout *vBox = new QVBoxLayout(dlg);
vBox->addWidget(mw);
vBox->addWidget(buttons);
dlg->adjustSize();
if (m_mode == KlipperMode::Standalone) {
dlg->setModal(true);
dlg->exec();
} else if (m_mode == KlipperMode::DataEngine) {
dlg->open();
}
}
#endif //HAVE_PRISON
void Klipper::slotAskClearHistory()
{
int clearHist = KMessageBox::questionYesNo(0,
i18n("Really delete entire clipboard history?"),
i18n("Delete clipboard history?"),
KStandardGuiItem::yes(),
KStandardGuiItem::no(),
QString::fromUtf8("really_clear_history"),
KMessageBox::Dangerous);
if (clearHist == KMessageBox::Yes) {
history()->slotClear();
slotClearClipboard();
saveHistory();
}
}
void Klipper::slotCycleNext()
{
//do cycle and show popup only if we have something in clipboard
if (m_history->first()) {
m_history->cycleNext();
emit passivePopup(i18n("Clipboard history"), cycleText());
}
}
void Klipper::slotCyclePrev()
{
//do cycle and show popup only if we have something in clipboard
if (m_history->first()) {
m_history->cyclePrev();
emit passivePopup(i18n("Clipboard history"), cycleText());
}
}
QString Klipper::cycleText() const
{
const int WIDTH_IN_PIXEL = 400;
auto itemprev = m_history->prevInCycle();
auto item = m_history->first();
auto itemnext = m_history->nextInCycle();
QFontMetrics font_metrics(m_popup->fontMetrics());
QString result("<table>");
if (itemprev) {
result += "<tr><td>";
result += i18n("up");
result += "</td><td>";
result += font_metrics.elidedText(itemprev->text().simplified().toHtmlEscaped(), Qt::ElideMiddle, WIDTH_IN_PIXEL);
result += "</td></tr>";
}
result += "<tr><td>";
result += i18n("current");
result += "</td><td><b>";
result += font_metrics.elidedText(item->text().simplified().toHtmlEscaped(), Qt::ElideMiddle, WIDTH_IN_PIXEL);
result += "</b></td></tr>";
if (itemnext) {
result += "<tr><td>";
result += i18n("down");