File: ImageViewBase.cpp

package info (click to toggle)
scantailor 0.9.12.2-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 7,556 kB
  • ctags: 9,057
  • sloc: cpp: 71,264; ansic: 481; sh: 121; makefile: 10
file content (1228 lines) | stat: -rw-r--r-- 34,169 bytes parent folder | download | duplicates (4)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
/*
    Scan Tailor - Interactive post-processing tool for scanned pages.
    Copyright (C)  Joseph Artsimovich <joseph.artsimovich@gmail.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 "ImageViewBase.h"
#include "ImageViewBase.h.moc"
#include "NonCopyable.h"
#include "ImagePresentation.h"
#include "OpenGLSupport.h"
#include "PixmapRenderer.h"
#include "BackgroundExecutor.h"
#include "Dpm.h"
#include "Dpi.h"
#include "ScopedIncDec.h"
#include "imageproc/PolygonUtils.h"
#include "imageproc/Transform.h"
#include "config.h"
#include <QScrollBar>
#include <QPointer>
#include <QAtomicInt>
#include <QPaintEngine>
#include <QPainter>
#include <QPainterPath>
#include <QBrush>
#include <QLineF>
#include <QPolygonF>
#include <QPalette>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QResizeEvent>
#include <QStatusTipEvent>
#include <QApplication>
#include <QSettings>
#include <QVariant>
#include <Qt>
#include <QDebug>
#include <algorithm>
#include <assert.h>
#include <math.h>

#ifdef ENABLE_OPENGL
#include <QGLWidget>
#include <QGLFormat>
#endif

using namespace imageproc;

class ImageViewBase::HqTransformTask :
	public AbstractCommand0<IntrusivePtr<AbstractCommand0<void> > >,
	public QObject
{
	DECLARE_NON_COPYABLE(HqTransformTask)
public:
	HqTransformTask(
		ImageViewBase* image_view,
		QImage const& image, QTransform const& xform,
		QSize const& target_size);
	
	void cancel() { m_ptrResult->cancel(); }
	
	bool const isCancelled() const { return m_ptrResult->isCancelled(); }
	
	virtual IntrusivePtr<AbstractCommand0<void> > operator()();
private:
	class Result : public AbstractCommand0<void>
	{
	public:
		Result(ImageViewBase* image_view);
		
		void setData(QPoint const& origin, QImage const& hq_image);
		
		void cancel() { m_cancelFlag.fetchAndStoreRelaxed(1); }
		
		bool isCancelled() const { return m_cancelFlag.fetchAndAddRelaxed(0) != 0; }
		
		virtual void operator()();
	private:
		QPointer<ImageViewBase> m_ptrImageView;
		QPoint m_origin;
		QImage m_hqImage;
		mutable QAtomicInt m_cancelFlag;
	};
	
	IntrusivePtr<Result> m_ptrResult;
	QImage m_image;
	QTransform m_xform;
	QSize m_targetSize;
};


/**
 * \brief Temporarily adjust the widget focal point, then change it back.
 *
 * When adjusting and restoring the widget focal point, the pixmap
 * focal point is recalculated accordingly.
 */
class ImageViewBase::TempFocalPointAdjuster
{
public:
	/**
	 * Change the widget focal point to obj.centeredWidgetFocalPoint().
	 */
	TempFocalPointAdjuster(ImageViewBase& obj);
	
	/**
	 * Change the widget focal point to \p temp_widget_fp
	 */
	TempFocalPointAdjuster(ImageViewBase& obj, QPointF temp_widget_fp);
	
	/**
	 * Restore the widget focal point.
	 */
	~TempFocalPointAdjuster();
private:
	ImageViewBase& m_rObj;
	QPointF m_origWidgetFP;
};


class ImageViewBase::TransformChangeWatcher
{
public:
	TransformChangeWatcher(ImageViewBase& owner);

	~TransformChangeWatcher();
private:
	ImageViewBase& m_rOwner;
	QTransform m_imageToVirtual;
	QTransform m_virtualToWidget;
	QRectF m_virtualDisplayArea;
};


ImageViewBase::ImageViewBase(
	QImage const& image, ImagePixmapUnion const& downscaled_version,
	ImagePresentation const& presentation, Margins const& margins)
:	m_image(image),
	m_virtualImageCropArea(presentation.cropArea()),
	m_virtualDisplayArea(presentation.displayArea()),
	m_imageToVirtual(presentation.transform()),
	m_virtualToImage(presentation.transform().inverted()),
	m_lastMaximumViewportSize(maximumViewportSize()),
	m_margins(margins),
	m_zoom(1.0),
	m_transformChangeWatchersActive(0),
	m_ignoreScrollEvents(0),
	m_ignoreResizeEvents(0),
	m_hqTransformEnabled(true)
{
#ifdef ENABLE_OPENGL
	if (QSettings().value("settings/use_3d_acceleration", false) != false) {
		if (OpenGLSupport::supported()) {
			QGLFormat format;
			format.setSampleBuffers(true);
			format.setStencil(true);
			format.setAlpha(true);
			format.setRgba(true);
			format.setDepth(false);

			// Most of hardware refuses to work for us with direct rendering enabled.
			format.setDirectRendering(false);

			setViewport(new QGLWidget(format));
		}
	}
#endif

	setFrameShape(QFrame::NoFrame);
	viewport()->setFocusPolicy(Qt::WheelFocus);

	if (downscaled_version.isNull()) {
		m_pixmap = QPixmap::fromImage(createDownscaledImage(image));
	} else if (downscaled_version.pixmap().isNull()) {
		m_pixmap = QPixmap::fromImage(downscaled_version.image());
	} else {
		m_pixmap = downscaled_version.pixmap();
	}
	
	m_pixmapToImage.scale(
		(double)m_image.width() / m_pixmap.width(),
		(double)m_image.height() / m_pixmap.height()
	);
	
	m_widgetFocalPoint = centeredWidgetFocalPoint();
	m_pixmapFocalPoint = m_virtualToImage.map(virtualDisplayRect().center());
	
	m_timer.setSingleShot(true);
	m_timer.setInterval(150); // msec
	connect(
		&m_timer, SIGNAL(timeout()),
		this, SLOT(initiateBuildingHqVersion())
	);
	
	updateWidgetTransformAndFixFocalPoint(CENTER_IF_FITS);

	interactionState().setDefaultStatusTip(
		tr("Use the mouse wheel or +/- to zoom.  When zoomed, dragging is possible.")
	);
	ensureStatusTip(interactionState().statusTip());

	connect(horizontalScrollBar(), SIGNAL(sliderReleased()), SLOT(updateScrollBars()));
	connect(verticalScrollBar(), SIGNAL(sliderReleased()), SLOT(updateScrollBars()));
	connect(horizontalScrollBar(), SIGNAL(valueChanged(int)), SLOT(reactToScrollBars()));
	connect(verticalScrollBar(), SIGNAL(valueChanged(int)), SLOT(reactToScrollBars()));
}

ImageViewBase::~ImageViewBase()
{
}

void
ImageViewBase::hqTransformSetEnabled(bool const enabled)
{
	if (!enabled && m_hqTransformEnabled) {
		// Turning off.
		m_hqTransformEnabled = false;
		if (m_ptrHqTransformTask.get()) {
			m_ptrHqTransformTask->cancel();
			m_ptrHqTransformTask.reset();
		}
		if (!m_hqPixmap.isNull()) {
			m_hqPixmap = QPixmap();
			update();
		}
	} else if (enabled && !m_hqTransformEnabled) {
		// Turning on.
		m_hqTransformEnabled = true;
		update();
	}
}

QImage
ImageViewBase::createDownscaledImage(QImage const& image)
{
	assert(!image.isNull());
	
	// Original and downscaled DPM.
	Dpm const o_dpm(image);
	Dpm const d_dpm(Dpi(300, 300));
	
	int const o_w = image.width();
	int const o_h = image.height();
	
	int d_w = o_w * d_dpm.horizontal() / o_dpm.horizontal();
	int d_h = o_h * d_dpm.vertical() / o_dpm.vertical();
	d_w = qBound(1, d_w, o_w);
	d_h = qBound(1, d_h, o_h);
	
	if (d_w * 1.2 > o_w || d_h * 1.2 > o_h) {
		// Sizes are close - no point in downscaling.
		return image;
	}
	
	QTransform xform;
	xform.scale((double)d_w / o_w, (double)d_h / o_h);
	return transform(
		image, xform, QRect(0, 0, d_w, d_h),
		OutsidePixels::assumeColor(Qt::white)
	);
}

QRectF
ImageViewBase::maxViewportRect() const
{
	QRectF const viewport_rect(QPointF(0, 0), maximumViewportSize());
	QRectF r(viewport_rect);
	r.adjust(
		m_margins.left(), m_margins.top(),
		-m_margins.right(), -m_margins.bottom()
	);
	if (r.isEmpty()) {
		return QRectF(viewport_rect.center(), viewport_rect.center());
	}
	return r;
}

QRectF
ImageViewBase::dynamicViewportRect() const
{
	QRectF const viewport_rect(viewport()->rect());
	QRectF r(viewport_rect);
	r.adjust(
		m_margins.left(), m_margins.top(),
		-m_margins.right(), -m_margins.bottom()
	);
	if (r.isEmpty()) {
		return QRectF(viewport_rect.center(), viewport_rect.center());
	}
	return r;
}

QRectF
ImageViewBase::getOccupiedWidgetRect() const
{
	QRectF const widget_rect(m_virtualToWidget.mapRect(virtualDisplayRect()));
	return widget_rect.intersected(dynamicViewportRect());
}

void
ImageViewBase::setWidgetFocalPoint(QPointF const& widget_fp)
{
	setNewWidgetFP(widget_fp, /*update =*/true);
}

void
ImageViewBase::adjustAndSetWidgetFocalPoint(QPointF const& widget_fp)
{
	adjustAndSetNewWidgetFP(widget_fp, /*update=*/true);
}

void
ImageViewBase::setZoomLevel(double zoom)
{
	if (m_zoom != zoom) {
		m_zoom = zoom;
		updateWidgetTransform();
		update();
	}
}

void
ImageViewBase::moveTowardsIdealPosition(double const pixel_length)
{
	if (pixel_length <= 0) {
		// The name implies we are moving *towards* the ideal position.
		return;
	}

	QPointF const ideal_widget_fp(getIdealWidgetFocalPoint(CENTER_IF_FITS));
	if (ideal_widget_fp == m_widgetFocalPoint) {
		return;
	}

	QPointF vec(ideal_widget_fp - m_widgetFocalPoint);
	double const max_length = sqrt(vec.x() * vec.x() + vec.y() * vec.y());
	if (pixel_length >= max_length) {
		m_widgetFocalPoint = ideal_widget_fp;
	} else {
		vec *= pixel_length / max_length;
		m_widgetFocalPoint += vec;
	}

	updateWidgetTransform();
	update();
}

void
ImageViewBase::updateTransform(ImagePresentation const& presentation)
{
	TransformChangeWatcher const watcher(*this);
	TempFocalPointAdjuster const temp_fp(*this);

	m_imageToVirtual = presentation.transform();
	m_virtualToImage = m_imageToVirtual.inverted();
	m_virtualImageCropArea = presentation.cropArea();
	m_virtualDisplayArea = presentation.displayArea();

	updateWidgetTransform();
	update();
}

void
ImageViewBase::updateTransformAndFixFocalPoint(
	ImagePresentation const& presentation, FocalPointMode const mode)
{
	TransformChangeWatcher const watcher(*this);
	TempFocalPointAdjuster const temp_fp(*this);
	
	m_imageToVirtual = presentation.transform();
	m_virtualToImage = m_imageToVirtual.inverted();
	m_virtualImageCropArea = presentation.cropArea();
	m_virtualDisplayArea = presentation.displayArea();

	updateWidgetTransformAndFixFocalPoint(mode);
	update();
}

void
ImageViewBase::updateTransformPreservingScale(ImagePresentation const& presentation)
{
	TransformChangeWatcher const watcher(*this);
	TempFocalPointAdjuster const temp_fp(*this);
	
	// An arbitrary line in image coordinates.
	QLineF const image_line(0.0, 0.0, 1.0, 1.0);
	
	QLineF const widget_line_before(
		(m_imageToVirtual * m_virtualToWidget).map(image_line)
	);
	
	m_imageToVirtual = presentation.transform();
	m_virtualToImage = m_imageToVirtual.inverted();
	m_virtualImageCropArea = presentation.cropArea();
	m_virtualDisplayArea = presentation.displayArea();

	updateWidgetTransform();
	
	QLineF const widget_line_after(
		(m_imageToVirtual * m_virtualToWidget).map(image_line)
	);
	
	m_zoom *= widget_line_before.length() / widget_line_after.length();
	updateWidgetTransform();
	
	update();
}

void
ImageViewBase::ensureStatusTip(QString const& status_tip)
{
	QString const cur_status_tip(statusTip());
	if (cur_status_tip.constData() == status_tip.constData()) {
		return;
	}
	if (cur_status_tip == status_tip) {
		return;
	}
	
	viewport()->setStatusTip(status_tip);
	
	if (viewport()->underMouse()) {
		// Note that setStatusTip() alone is not enough,
		// as it's only taken into account when the mouse
		// enters the widget.
		// Also note that we use postEvent() rather than sendEvent(),
		// because sendEvent() may immediately process other events.
		QApplication::postEvent(viewport(), new QStatusTipEvent(status_tip));
	}
}

void
ImageViewBase::paintEvent(QPaintEvent* event)
{
	QPainter painter(viewport());
	painter.save();

	// On X11 (except with OpenGL), SmoothPixmapTransform is too slow, so don't enable it.
	bool smooth_pixmap_ok = true;
#if defined(Q_WS_X11)
	smooth_pixmap_ok = viewport()->inherits("QGLWidget");
#endif
	if (smooth_pixmap_ok) {
		double const xscale = m_virtualToWidget.m11();

		// Width of a source pixel in mm, as it's displayed on screen.
		double const pixel_width = widthMM() * xscale / width();

		// Disable antialiasing for large zoom levels.
		painter.setRenderHint(QPainter::SmoothPixmapTransform, pixel_width < 0.5);
	}

	if (validateHqPixmap()) {
		// HQ pixmap maps one to one to screen pixels, so antialiasing is not necessary.
		painter.setRenderHint(QPainter::SmoothPixmapTransform, false);
		painter.drawPixmap(m_hqPixmapPos, m_hqPixmap);
	} else {
		scheduleHqVersionRebuild();

		painter.setWorldTransform(
			m_pixmapToImage * m_imageToVirtual * m_virtualToWidget
		);
		PixmapRenderer::drawPixmap(painter, m_pixmap);
	}

	painter.setRenderHints(QPainter::Antialiasing, true);
	painter.setWorldMatrixEnabled(false);

	// Cover parts of the image that should not be visible with background.
	// Note that because of Qt::WA_OpaquePaintEvent attribute, we need
	// to paint the whole widget, which we do here.

	QPolygonF const image_area(
		PolygonUtils::round(
			m_virtualToWidget.map(
				m_imageToVirtual.map(QRectF(m_image.rect()))
			)
		)
	);
	QPolygonF const crop_area(
		PolygonUtils::round(m_virtualToWidget.map(m_virtualImageCropArea))
	);

	QPolygonF const intersected_area(
		PolygonUtils::round(image_area.intersected(crop_area))
	);

	QPainterPath intersected_path;
	intersected_path.addPolygon(intersected_area);

	QPainterPath containing_path;
	containing_path.addRect(viewport()->rect());

	QBrush const brush(palette().color(QPalette::Window));
	QPen pen(brush, 1.0);
	pen.setCosmetic(true);

	// By using a pen with the same color as the brush, we essentially
	// expanding the area we are going to draw.  It's necessary because
	// XRender doesn't provide subpixel accuracy.

	painter.setPen(pen);
	painter.setBrush(brush);
	painter.drawPath(containing_path.subtracted(intersected_path));

	painter.restore();

	painter.setWorldTransform(m_virtualToWidget);

	m_interactionState.resetProximity();
	if (!m_interactionState.captured()) {
		m_rootInteractionHandler.proximityUpdate(
			QPointF(0.5, 0.5) + mapFromGlobal(QCursor::pos()), m_interactionState
		);
		updateStatusTipAndCursor();
	}

	m_rootInteractionHandler.paint(painter, m_interactionState);
	maybeQueueRedraw();
}

void
ImageViewBase::keyPressEvent(QKeyEvent* event)
{
	event->setAccepted(false);
	m_rootInteractionHandler.keyPressEvent(event, m_interactionState);
	event->setAccepted(true);
	updateStatusTipAndCursor();
	maybeQueueRedraw();
}

void
ImageViewBase::keyReleaseEvent(QKeyEvent* event)
{
	event->setAccepted(false);
	m_rootInteractionHandler.keyReleaseEvent(event, m_interactionState);
	event->setAccepted(true);
	updateStatusTipAndCursor();
	maybeQueueRedraw();
}

void
ImageViewBase::mousePressEvent(QMouseEvent* event)
{
	m_interactionState.resetProximity();
	if (!m_interactionState.captured()) {
		m_rootInteractionHandler.proximityUpdate(
			QPointF(0.5, 0.5) + event->pos(), m_interactionState
		);
	}

	event->setAccepted(false);
	m_rootInteractionHandler.mousePressEvent(event, m_interactionState);
	event->setAccepted(true);
	updateStatusTipAndCursor();
	void maybeQueueRedraw();
}

void
ImageViewBase::mouseReleaseEvent(QMouseEvent* event)
{
	m_interactionState.resetProximity();
	if (!m_interactionState.captured()) {
		m_rootInteractionHandler.proximityUpdate(
			QPointF(0.5, 0.5) + event->pos(), m_interactionState
		);
	}

	event->setAccepted(false);
	m_rootInteractionHandler.mouseReleaseEvent(event, m_interactionState);
	event->setAccepted(true);
	updateStatusTipAndCursor();
	maybeQueueRedraw();
}

void
ImageViewBase::mouseMoveEvent(QMouseEvent* event)
{
	m_interactionState.resetProximity();
	if (!m_interactionState.captured()) {
		m_rootInteractionHandler.proximityUpdate(
			QPointF(0.5, 0.5) + event->pos(), m_interactionState
		);
	}

	event->setAccepted(false);
	m_rootInteractionHandler.mouseMoveEvent(event, m_interactionState);
	event->setAccepted(true);
	updateStatusTipAndCursor();
	maybeQueueRedraw();
}

void
ImageViewBase::wheelEvent(QWheelEvent* event)
{
	event->setAccepted(false);
	m_rootInteractionHandler.wheelEvent(event, m_interactionState);
	event->setAccepted(true);
	updateStatusTipAndCursor();
	maybeQueueRedraw();
}

void
ImageViewBase::contextMenuEvent(QContextMenuEvent* event)
{
	event->setAccepted(false);
	m_rootInteractionHandler.contextMenuEvent(event, m_interactionState);
	event->setAccepted(true);
	updateStatusTipAndCursor();
	maybeQueueRedraw();
}

void
ImageViewBase::resizeEvent(QResizeEvent* event)
{
	QAbstractScrollArea::resizeEvent(event);

	if (m_ignoreResizeEvents) {
		return;
	}

	ScopedIncDec<int> const guard(m_ignoreScrollEvents);

	if (maximumViewportSize() != m_lastMaximumViewportSize) {
		m_lastMaximumViewportSize = maximumViewportSize();
		m_widgetFocalPoint = centeredWidgetFocalPoint();
		updateWidgetTransform();
	} else {
		TransformChangeWatcher const watcher(*this);
		TempFocalPointAdjuster const temp_fp(*this, QPointF(0, 0));
		updateTransformPreservingScale(
			ImagePresentation(m_imageToVirtual, m_virtualImageCropArea, m_virtualDisplayArea)
		);
	}
}

void
ImageViewBase::enterEvent(QEvent* event)
{
	viewport()->setFocus();
	QAbstractScrollArea::enterEvent(event);
}

/**
 * Called when any of the transformations change.
 */
void
ImageViewBase::transformChanged()
{
	updateScrollBars();
}

void
ImageViewBase::updateScrollBars()
{
	if (verticalScrollBar()->isSliderDown() || horizontalScrollBar()->isSliderDown()) {
		return;
	}

	ScopedIncDec<int> const guard1(m_ignoreScrollEvents);
	ScopedIncDec<int> const guard2(m_ignoreResizeEvents);

	QRectF const picture(m_virtualToWidget.mapRect(virtualDisplayRect()));
	QPointF const viewport_center(maxViewportRect().center());
	QPointF const picture_center(picture.center());
	QRectF viewport(maxViewportRect());

	// Introduction of one scrollbar will decrease the available size in
	// another direction, which may cause a scrollbar in that direction
	// to become necessary.  For this reason, we have a loop here.
	for (int i = 0; i < 2; ++i) {
		double const xval = picture_center.x();
		double xmin, xmax; // Minimum and maximum positions for picture center.
		if (picture_center.x() < viewport_center.x()) {
			xmin = std::min<double>(xval, viewport.right() - 0.5 * picture.width());
			xmax = std::max<double>(viewport_center.x(), viewport.left() + 0.5 * picture.width());
		} else {
			xmax = std::max<double>(xval, viewport.left() + 0.5 * picture.width());
			xmin = std::min<double>(viewport_center.x(), viewport.right() - 0.5 * picture.width());
		}

		double const yval = picture_center.y();
		double ymin, ymax; // Minimum and maximum positions for picture center.
		if (picture_center.y() < viewport_center.y()) {
			ymin = std::min<double>(yval, viewport.bottom() - 0.5 * picture.height());
			ymax = std::max<double>(viewport_center.y(), viewport.top() + 0.5 * picture.height());
		} else {
			ymax = std::max<double>(yval, viewport.top() + 0.5 * picture.height());
			ymin = std::min<double>(viewport_center.y(), viewport.bottom() - 0.5 * picture.height());
		}

		int const xrange = (int)ceil(xmax - xmin);
		int const yrange = (int)ceil(ymax - ymin);
		int const xfirst = 0;
		int const xlast = xrange - 1;
		int const yfirst = 0;
		int const ylast = yrange - 1;

		// We are going to map scrollbar coordinates to widget coordinates
		// of the central point of the display area using a linear function.
		// f(x) = ax + b

		// xmin = xa * xlast + xb
		// xmax = xa * xfirst + xb
		double const xa = (xfirst == xlast) ? 1 : (xmax - xmin) / (xfirst - xlast);
		double const xb = xmax - xa * xfirst;
		double const ya = (yfirst == ylast) ? 1 : (ymax - ymin) / (yfirst - ylast);
		double const yb = ymax - ya * yfirst;

		// Inverse transformation.
		// xlast = ixa * xmin + ixb
		// xfirst = ixa * xmax + ixb
		double const ixa = (xmax == xmin) ? 1 : (xfirst - xlast) / (xmax - xmin);
		double const ixb = xfirst - ixa * xmax;
		double const iya = (ymax == ymin) ? 1 : (yfirst - ylast) / (ymax - ymin);
		double const iyb = yfirst - iya * ymax;

		m_scrollTransform.setMatrix(xa, 0, 0, 0, ya, 0, xb, yb, 1);

		int const xcur = qRound(ixa * xval + ixb);
		int const ycur = qRound(iya * yval + iyb);

		horizontalScrollBar()->setRange(xfirst, xlast);
		verticalScrollBar()->setRange(yfirst, ylast);

		horizontalScrollBar()->setValue(xcur);
		verticalScrollBar()->setValue(ycur);

		horizontalScrollBar()->setPageStep(qRound(viewport.width()));
		verticalScrollBar()->setPageStep(qRound(viewport.height()));

		// XXX: a hack to force immediate update of viewport()->rect(),
		// which is used by dynamicViewportRect() below.
		// Note that it involves a resize event being sent not only to
		// the viewport, but for some reason also to the containing
		// QAbstractScrollArea, that is to this object.
		setHorizontalScrollBarPolicy(horizontalScrollBarPolicy());

		QRectF const old_viewport(viewport);
		viewport = dynamicViewportRect();
		if (viewport == old_viewport) {
			break;
		}
	}
}

void
ImageViewBase::reactToScrollBars()
{
	if (m_ignoreScrollEvents) {
		return;
	}

	TransformChangeWatcher const watcher(*this);

	QPointF const raw_position(
		horizontalScrollBar()->value(), verticalScrollBar()->value()
	);
	QPointF const new_fp(m_scrollTransform.map(raw_position));
	QPointF const old_fp(getWidgetFocalPoint());

	m_pixmapFocalPoint = m_virtualToImage.map(m_virtualDisplayArea.center());
	m_widgetFocalPoint = new_fp;
	updateWidgetTransform();

	setWidgetFocalPointWithoutMoving(old_fp);
}

/**
 * Updates m_virtualToWidget and m_widgetToVirtual.\n
 * To be called whenever any of the following is modified:
 * m_imageToVirt, m_widgetFocalPoint, m_pixmapFocalPoint, m_zoom.
 * Modifying both m_widgetFocalPoint and m_pixmapFocalPoint in a way
 * that doesn't cause image movement doesn't require calling this method.
 */
void
ImageViewBase::updateWidgetTransform()
{
	TransformChangeWatcher const watcher(*this);

	QRectF const virt_rect(virtualDisplayRect());
	QPointF const virt_origin(m_imageToVirtual.map(m_pixmapFocalPoint));
	QPointF const widget_origin(m_widgetFocalPoint);
	
	QSizeF zoom1_widget_size(virt_rect.size());
	zoom1_widget_size.scale(maxViewportRect().size(), Qt::KeepAspectRatio);
	
	double const zoom1_x = zoom1_widget_size.width() / virt_rect.width();
	double const zoom1_y = zoom1_widget_size.height() / virt_rect.height();
	
	QTransform xform;
	xform.translate(-virt_origin.x(), -virt_origin.y());
	xform *= QTransform().scale(zoom1_x * m_zoom, zoom1_y * m_zoom);
	xform *= QTransform().translate(widget_origin.x(), widget_origin.y());

	m_virtualToWidget = xform;
	m_widgetToVirtual = m_virtualToWidget.inverted();
}

/**
 * Updates m_virtualToWidget and m_widgetToVirtual and adjusts
 * the focal point if necessary.\n
 * To be called whenever m_imageToVirt is modified in such a way that
 * may invalidate the focal point.
 */
void
ImageViewBase::updateWidgetTransformAndFixFocalPoint(FocalPointMode const mode)
{
	TransformChangeWatcher const watcher(*this);

	// This must go before getIdealWidgetFocalPoint(), as it
	// recalculates m_virtualToWidget, that is used by
	// getIdealWidgetFocalPoint().
	updateWidgetTransform();
	
	QPointF const ideal_widget_fp(getIdealWidgetFocalPoint(mode));
	if (ideal_widget_fp != m_widgetFocalPoint) {
		m_widgetFocalPoint = ideal_widget_fp;
		updateWidgetTransform();
	}
}

/**
 * Returns a proposed value for m_widgetFocalPoint to minimize the
 * unused widget space.  Unused widget space indicates one or both
 * of the following:
 * \li The image is smaller than the display area.
 * \li Parts of the image are outside of the display area.
 *
 * \param mode If set to CENTER_IF_FITS, then the returned focal point
 *        will center the image if it completely fits into the widget.
 *        This works in horizontal and vertical directions independently.\n
 *        If \p mode is set to DONT_CENTER and the image completely fits
 *        the widget, then the returned focal point will cause a minimal
 *        move to force the whole image to be visible.
 *
 * In case there is no unused widget space, the returned focal point
 * is equal to the current focal point (m_widgetFocalPoint).  This works
 * in horizontal and vertical dimensions independently.
 */
QPointF
ImageViewBase::getIdealWidgetFocalPoint(FocalPointMode const mode) const
{
	// Widget rect reduced by margins.
	QRectF const display_area(maxViewportRect());
	
	// The virtual image rectangle in widget coordinates.
	QRectF const image_area(m_virtualToWidget.mapRect(virtualDisplayRect()));
	
	// Unused display space from each side.
	double const left_margin = image_area.left() - display_area.left();
	double const right_margin = display_area.right() - image_area.right();
	double const top_margin = image_area.top() - display_area.top();
	double const bottom_margin = display_area.bottom() - image_area.bottom();
	
	QPointF widget_focal_point(m_widgetFocalPoint);
	
	if (mode == CENTER_IF_FITS && left_margin + right_margin >= 0.0) {
		// Image fits horizontally, so center it in that direction
		// by equalizing its left and right margins.
		double const new_margins = 0.5 * (left_margin + right_margin);
		widget_focal_point.rx() += new_margins - left_margin;
	} else if (left_margin < 0.0 && right_margin > 0.0) {
		// Move image to the right so that either left_margin or
		// right_margin becomes zero, whichever requires less movement.
		double const movement = std::min(fabs(left_margin), fabs(right_margin));
		widget_focal_point.rx() += movement;
	} else if (right_margin < 0.0 && left_margin > 0.0) {
		// Move image to the left so that either left_margin or
		// right_margin becomes zero, whichever requires less movement.
		double const movement = std::min(fabs(left_margin), fabs(right_margin));
		widget_focal_point.rx() -= movement;
	}
	
	if (mode == CENTER_IF_FITS && top_margin + bottom_margin >= 0.0) {
		// Image fits vertically, so center it in that direction
		// by equalizing its top and bottom margins.
		double const new_margins = 0.5 * (top_margin + bottom_margin);
		widget_focal_point.ry() += new_margins - top_margin;
	} else if (top_margin < 0.0 && bottom_margin > 0.0) {
		// Move image down so that either top_margin or bottom_margin
		// becomes zero, whichever requires less movement.
		double const movement = std::min(fabs(top_margin), fabs(bottom_margin));
		widget_focal_point.ry() += movement;
	} else if (bottom_margin < 0.0 && top_margin > 0.0) {
		// Move image up so that either top_margin or bottom_margin
		// becomes zero, whichever requires less movement.
		double const movement = std::min(fabs(top_margin), fabs(bottom_margin));
		widget_focal_point.ry() -= movement;
	}
	
	return widget_focal_point;
}

void
ImageViewBase::setNewWidgetFP(QPointF const widget_fp, bool const update)
{
	if (widget_fp != m_widgetFocalPoint) {
		m_widgetFocalPoint = widget_fp;
		updateWidgetTransform();
		if (update) {
			this->update();
		}
	}
}

/**
 * Used when dragging the image.  It adjusts the movement to disallow
 * dragging it away from the ideal position (determined by
 * getIdealWidgetFocalPoint()).  Movement towards the ideal position
 * is permitted.  This works independently in horizontal and vertical
 * direction.
 *
 * \param proposed_widget_fp The proposed value for m_widgetFocalPoint.
 * \param update Whether to call this->update() in case the focal point
 *        has changed.
 */
void
ImageViewBase::adjustAndSetNewWidgetFP(
	QPointF const proposed_widget_fp, bool const update)
{
	// We first apply the proposed focal point, and only then
	// calculate the ideal one.  That's done because
	// the ideal focal point is the current focal point when
	// no widget space is wasted (image covers the whole widget).
	// We don't want the ideal focal point to be equal to the current
	// one, as that would disallow any movements.
	QPointF const old_widget_fp(m_widgetFocalPoint);
	setNewWidgetFP(proposed_widget_fp, update);
	
	QPointF const ideal_widget_fp(getIdealWidgetFocalPoint(CENTER_IF_FITS));
	
	QPointF const towards_ideal(ideal_widget_fp - old_widget_fp);
	QPointF const towards_proposed(proposed_widget_fp - old_widget_fp);
	
	QPointF movement(towards_proposed);
	
	// Horizontal movement.
	if (towards_ideal.x() * towards_proposed.x() < 0.0) {
		// Wrong direction - no movement at all.
		movement.setX(0.0);
	} else if (fabs(towards_proposed.x()) > fabs(towards_ideal.x())) {
		// Too much movement - limit it.
		movement.setX(towards_ideal.x());
	}
	
	// Vertical movement.
	if (towards_ideal.y() * towards_proposed.y() < 0.0) {
		// Wrong direction - no movement at all.
		movement.setY(0.0);
	} else if (fabs(towards_proposed.y()) > fabs(towards_ideal.y())) {
		// Too much movement - limit it.
		movement.setY(towards_ideal.y());
	}
	
	QPointF const adjusted_widget_fp(old_widget_fp + movement);
	if (adjusted_widget_fp != m_widgetFocalPoint) {
		m_widgetFocalPoint = adjusted_widget_fp;
		updateWidgetTransform();
		if (update) {
			this->update();
		}
	}
}

/**
 * Returns the center point of the available display area.
 */
QPointF
ImageViewBase::centeredWidgetFocalPoint() const
{
	return maxViewportRect().center();
}

void
ImageViewBase::setWidgetFocalPointWithoutMoving(QPointF const new_widget_fp)
{
	m_widgetFocalPoint = new_widget_fp;
	m_pixmapFocalPoint = m_virtualToImage.map(
		m_widgetToVirtual.map(m_widgetFocalPoint)
	);
}

/**
 * Returns true if m_hqPixmap is valid and up to date.
 */
bool
ImageViewBase::validateHqPixmap() const
{
	if (!m_hqTransformEnabled) {
		return false;
	}

	if (m_hqPixmap.isNull()) {
		return false;
	}

	if (m_hqSourceId != m_image.cacheKey()) {
		return false;
	}

	if (m_hqXform != m_imageToVirtual * m_virtualToWidget) {
		return false;
	}

	return true;
}

void
ImageViewBase::scheduleHqVersionRebuild()
{
	QTransform const xform(m_imageToVirtual * m_virtualToWidget);

	if (!m_timer.isActive() || m_potentialHqXform != xform) {
		if (m_ptrHqTransformTask.get()) {
			m_ptrHqTransformTask->cancel();
			m_ptrHqTransformTask.reset();
		}
		m_potentialHqXform = xform;
	}
	m_timer.start();
}

void
ImageViewBase::initiateBuildingHqVersion()
{
	if (validateHqPixmap()) {
		return;
	}

	m_hqPixmap = QPixmap();

	if (m_ptrHqTransformTask.get()) {
		m_ptrHqTransformTask->cancel();
		m_ptrHqTransformTask.reset();
	}

	QTransform const xform(m_imageToVirtual * m_virtualToWidget);
	IntrusivePtr<HqTransformTask> const task(
		new HqTransformTask(this, m_image, xform, viewport()->size())
	);
	
	backgroundExecutor().enqueueTask(task);
	
	m_ptrHqTransformTask = task;
	m_hqXform = xform;
	m_hqSourceId = m_image.cacheKey();
}

/**
 * Gets called from HqTransformationTask::Result.
 */
void
ImageViewBase::hqVersionBuilt(
	QPoint const& origin, QImage const& image)
{
	if (!m_hqTransformEnabled) {
		return;
	}
	
	m_hqPixmap = QPixmap::fromImage(image);
	m_hqPixmapPos = origin;
	m_ptrHqTransformTask.reset();
	update();
}

void
ImageViewBase::updateStatusTipAndCursor()
{
	updateStatusTip();
	updateCursor();
}

void
ImageViewBase::updateStatusTip()
{
	ensureStatusTip(m_interactionState.statusTip());
}

void
ImageViewBase::updateCursor()
{
	viewport()->setCursor(m_interactionState.cursor());
}

void
ImageViewBase::maybeQueueRedraw()
{
	if (m_interactionState.redrawRequested()) {
		m_interactionState.setRedrawRequested(false);
		update();
	}
}

BackgroundExecutor&
ImageViewBase::backgroundExecutor()
{
	static BackgroundExecutor executor;
	return executor;
}


/*==================== ImageViewBase::HqTransformTask ======================*/

ImageViewBase::HqTransformTask::HqTransformTask(
	ImageViewBase* image_view,
	QImage const& image, QTransform const& xform,
	QSize const& target_size)
:	m_ptrResult(new Result(image_view)),
	m_image(image),
	m_xform(xform),
	m_targetSize(target_size)
{
}

IntrusivePtr<AbstractCommand0<void> >
ImageViewBase::HqTransformTask::operator()()
{
	if (isCancelled()) {
		return IntrusivePtr<AbstractCommand0<void> >();
	}
	
	QRect const target_rect(
		m_xform.map(
			QRectF(m_image.rect())
		).boundingRect().toRect().intersected(
			QRect(QPoint(0, 0), m_targetSize)
		)
	);
	
	QImage hq_image(
		transform(
			m_image, m_xform, target_rect,
			OutsidePixels::assumeWeakColor(Qt::white), QSizeF(0.0, 0.0)
		)
	);
#if defined(Q_WS_X11)
	// ARGB32_Premultiplied is an optimal format for X11 + XRender.
	hq_image = hq_image.convertToFormat(QImage::Format_ARGB32_Premultiplied);
#endif
	m_ptrResult->setData(target_rect.topLeft(), hq_image);
	
	return m_ptrResult;
}


/*================ ImageViewBase::HqTransformTask::Result ================*/

ImageViewBase::HqTransformTask::Result::Result(
	ImageViewBase* image_view)
:	m_ptrImageView(image_view)
{
}

void
ImageViewBase::HqTransformTask::Result::setData(
	QPoint const& origin, QImage const& hq_image)
{
	m_hqImage = hq_image;
	m_origin = origin;
}

void
ImageViewBase::HqTransformTask::Result::operator()()
{
	if (m_ptrImageView && !isCancelled()) {
		m_ptrImageView->hqVersionBuilt(m_origin, m_hqImage);
	}
}


/*================= ImageViewBase::TempFocalPointAdjuster =================*/

ImageViewBase::TempFocalPointAdjuster::TempFocalPointAdjuster(ImageViewBase& obj)
:	m_rObj(obj),
	m_origWidgetFP(obj.getWidgetFocalPoint())
{
	obj.setWidgetFocalPointWithoutMoving(obj.centeredWidgetFocalPoint());
}

ImageViewBase::TempFocalPointAdjuster::TempFocalPointAdjuster(
	ImageViewBase& obj, QPointF const temp_widget_fp)
:	m_rObj(obj),
	m_origWidgetFP(obj.getWidgetFocalPoint())
{
	obj.setWidgetFocalPointWithoutMoving(temp_widget_fp);
}

ImageViewBase::TempFocalPointAdjuster::~TempFocalPointAdjuster()
{
	m_rObj.setWidgetFocalPointWithoutMoving(m_origWidgetFP);
}


/*================== ImageViewBase::TransformChangeWatcher ================*/

ImageViewBase::TransformChangeWatcher::TransformChangeWatcher(ImageViewBase& owner)
:	m_rOwner(owner),
	m_imageToVirtual(owner.m_imageToVirtual),
	m_virtualToWidget(owner.m_virtualToWidget),
	m_virtualDisplayArea(owner.m_virtualDisplayArea)
{
	++m_rOwner.m_transformChangeWatchersActive;
}

ImageViewBase::TransformChangeWatcher::~TransformChangeWatcher()
{
	if (--m_rOwner.m_transformChangeWatchersActive == 0) {
		if (m_imageToVirtual != m_rOwner.m_imageToVirtual ||
				m_virtualToWidget != m_rOwner.m_virtualToWidget ||
				m_virtualDisplayArea != m_rOwner.m_virtualDisplayArea) {
			m_rOwner.transformChanged();
		}
	}
}