ctkVTKMagnifyView.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.commontk.org/LICENSE
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QEvent>
  16. #include <QMouseEvent>
  17. #include <QPointF>
  18. #include <QTimerEvent>
  19. // CTK includes
  20. #include "ctkVTKMagnifyView.h"
  21. #include "ctkVTKMagnifyView_p.h"
  22. #include "ctkLogger.h"
  23. // VTK includes
  24. #include <QVTKWidget.h>
  25. #include <vtkRenderWindow.h>
  26. #include <vtkUnsignedCharArray.h>
  27. // STD includes
  28. #include <cmath>
  29. // Convenient macro
  30. #define VTK_CREATE(type, name) \
  31. vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
  32. //--------------------------------------------------------------------------
  33. static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKMagnifyView");
  34. //--------------------------------------------------------------------------
  35. // --------------------------------------------------------------------------
  36. // ctkVTKMagnifyViewPrivate methods
  37. // --------------------------------------------------------------------------
  38. ctkVTKMagnifyViewPrivate::ctkVTKMagnifyViewPrivate(ctkVTKMagnifyView& object)
  39. : QObject(&object), q_ptr(&object)
  40. {
  41. this->ObservedQVTKWidgets = QList<QVTKWidget *>();
  42. this->Magnification = 1.0;
  43. this->ObserveRenderWindowEvents = true;
  44. this->EventHandler.EventType = NoEvent;
  45. this->EventHandler.Widget = 0;
  46. this->EventHandler.Position = QPointF(0,0);
  47. this->EventHandler.UpdateInterval = 20;
  48. this->EventHandler.TimerId = 0;
  49. }
  50. // --------------------------------------------------------------------------
  51. ctkVTKMagnifyViewPrivate::~ctkVTKMagnifyViewPrivate()
  52. {
  53. if (this->EventHandler.TimerId != 0)
  54. {
  55. this->killTimer(this->EventHandler.TimerId);
  56. }
  57. }
  58. // --------------------------------------------------------------------------
  59. void ctkVTKMagnifyViewPrivate::init()
  60. {
  61. // Start by removing the pixmap
  62. this->EventHandler.EventType = RemovePixmapEvent;
  63. this->removePixmap();
  64. // Start the timer
  65. this->restartTimer();
  66. }
  67. // --------------------------------------------------------------------------
  68. void ctkVTKMagnifyViewPrivate::restartTimer()
  69. {
  70. // Kill any old timers
  71. if (this->EventHandler.TimerId != 0)
  72. {
  73. this->killTimer(this->EventHandler.TimerId);
  74. this->EventHandler.TimerId = 0;
  75. }
  76. // Start timer if appropriate
  77. if (this->EventHandler.UpdateInterval != 0)
  78. {
  79. this->EventHandler.TimerId = this->startTimer(this->EventHandler.UpdateInterval);
  80. Q_ASSERT(this->EventHandler.TimerId);
  81. }
  82. // Not using any timers, process events as they come
  83. else
  84. {
  85. this->EventHandler.TimerId = 0;
  86. }
  87. }
  88. // --------------------------------------------------------------------------
  89. void ctkVTKMagnifyViewPrivate::resetEventHandler()
  90. {
  91. this->EventHandler.EventType = NoEvent;
  92. }
  93. // --------------------------------------------------------------------------
  94. void ctkVTKMagnifyViewPrivate::timerEvent(QTimerEvent * event)
  95. {
  96. Q_ASSERT(event->timerId() == this->EventHandler.TimerId);
  97. if (this->EventHandler.EventType == UpdatePixmapEvent)
  98. {
  99. this->updatePixmap();
  100. }
  101. else if (this->EventHandler.EventType == RemovePixmapEvent)
  102. {
  103. this->removePixmap();
  104. }
  105. }
  106. // --------------------------------------------------------------------------
  107. void ctkVTKMagnifyViewPrivate::pushUpdatePixmapEvent()
  108. {
  109. Q_ASSERT(this->EventHandler.Widget);
  110. this->pushUpdatePixmapEvent(
  111. this->EventHandler.Widget->mapFromGlobal(QCursor::pos()));
  112. }
  113. // --------------------------------------------------------------------------
  114. void ctkVTKMagnifyViewPrivate::pushUpdatePixmapEvent(QPointF pos)
  115. {
  116. Q_ASSERT(this->EventHandler.Widget);
  117. // Add this event to the queue
  118. this->EventHandler.EventType = UpdatePixmapEvent;
  119. this->EventHandler.Position = pos;
  120. // Process the event if we handle all events
  121. if (this->EventHandler.UpdateInterval == 0)
  122. {
  123. this->updatePixmap();
  124. }
  125. }
  126. // --------------------------------------------------------------------------
  127. void ctkVTKMagnifyViewPrivate::pushRemovePixmapEvent()
  128. {
  129. // Add this event to the queue
  130. this->EventHandler.EventType = RemovePixmapEvent;
  131. // Process the event if we handle all events
  132. if (this->EventHandler.UpdateInterval == 0)
  133. {
  134. this->removePixmap();
  135. }
  136. }
  137. // --------------------------------------------------------------------------
  138. void ctkVTKMagnifyViewPrivate::connectRenderWindow(QVTKWidget * widget)
  139. {
  140. Q_ASSERT(widget);
  141. Q_ASSERT(this->ObserveRenderWindowEvents);
  142. vtkRenderWindow * renderWindow = widget->GetRenderWindow();
  143. if (renderWindow)
  144. {
  145. this->qvtkConnect(renderWindow, vtkCommand::EndEvent,
  146. this, SLOT(pushUpdatePixmapEvent()));
  147. }
  148. }
  149. // --------------------------------------------------------------------------
  150. void ctkVTKMagnifyViewPrivate::disconnectRenderWindow(QVTKWidget * widget)
  151. {
  152. Q_ASSERT(widget);
  153. vtkRenderWindow * renderWindow = widget->GetRenderWindow();
  154. if (renderWindow)
  155. {
  156. this->qvtkDisconnect(renderWindow, vtkCommand::EndEvent,
  157. this, SLOT(pushUpdatePixmapEvent()));
  158. }
  159. }
  160. // --------------------------------------------------------------------------
  161. void ctkVTKMagnifyViewPrivate::observe(QVTKWidget * widget)
  162. {
  163. Q_ASSERT(widget);
  164. // If we are not already observing the widget, add it to the list and install
  165. // the public implementation as the event filter to handle mousing
  166. if (!this->ObservedQVTKWidgets.contains(widget))
  167. {
  168. this->ObservedQVTKWidgets.append(widget);
  169. Q_Q(ctkVTKMagnifyView);
  170. widget->installEventFilter(q);
  171. if (this->ObserveRenderWindowEvents)
  172. {
  173. this->connectRenderWindow(widget);
  174. }
  175. }
  176. }
  177. // --------------------------------------------------------------------------
  178. void ctkVTKMagnifyViewPrivate::remove(QVTKWidget * widget)
  179. {
  180. Q_ASSERT(widget);
  181. // If we are observing the widget, remove it from the list and remove the
  182. // public implementations event filtering
  183. if (this->ObservedQVTKWidgets.contains(widget))
  184. {
  185. Q_ASSERT(this->ObservedQVTKWidgets.count(widget) == 1);
  186. this->ObservedQVTKWidgets.removeOne(widget);
  187. Q_Q(ctkVTKMagnifyView);
  188. widget->removeEventFilter(q);
  189. if (this->ObserveRenderWindowEvents)
  190. {
  191. this->disconnectRenderWindow(widget);
  192. }
  193. }
  194. }
  195. // --------------------------------------------------------------------------
  196. void ctkVTKMagnifyViewPrivate::removePixmap()
  197. {
  198. Q_ASSERT(this->EventHandler.EventType == RemovePixmapEvent);
  199. Q_Q(ctkVTKMagnifyView);
  200. QPixmap nullPixmap;
  201. q->setPixmap(nullPixmap);
  202. q->update();
  203. this->resetEventHandler();
  204. }
  205. // -------------------------------------------------------------------------
  206. void ctkVTKMagnifyViewPrivate::updatePixmap()
  207. {
  208. Q_ASSERT(this->EventHandler.EventType == UpdatePixmapEvent);
  209. Q_ASSERT(this->EventHandler.Widget);
  210. Q_Q(ctkVTKMagnifyView);
  211. // Retrieve buffer of given QVTKWidget from its render window
  212. vtkRenderWindow * renderWindow = this->EventHandler.Widget->GetRenderWindow();
  213. if (!renderWindow)
  214. {
  215. return;
  216. }
  217. // Get the window size and mouse position, and do error checking
  218. QPointF pos = this->EventHandler.Position;
  219. int * windowSize = renderWindow->GetSize();
  220. QPointF mouseWindowPos(pos.x(), static_cast<double>(windowSize[1]-1)-pos.y());
  221. if (mouseWindowPos.x() < 0 || mouseWindowPos.x() >= windowSize[0] ||
  222. mouseWindowPos.y() < 0 || mouseWindowPos.y() >= windowSize[1])
  223. {
  224. return;
  225. }
  226. // Compute indices into the render window's data array
  227. // Given a magnification and the label's widget size, compute the number of
  228. // pixels we can show. We should round to get a larger integer extent, since
  229. // we will later adjust the pixmap's location in paintEvent().
  230. // Left-right and up-down are in the render window coordinate frame.
  231. // (which is different in the y-direction compared to Qt coordinates).
  232. QSizeF sizeToMagnify = QSizeF(q->size()) / this->Magnification;
  233. double posLeft = (mouseWindowPos.x() - ((sizeToMagnify.width()-1.0) / 2.0));
  234. double posRight = (mouseWindowPos.x() + ((sizeToMagnify.width()-1.0) / 2.0));
  235. double posBottom = (mouseWindowPos.y() - ((sizeToMagnify.height()-1.0) / 2.0));
  236. double posTop = (mouseWindowPos.y() + ((sizeToMagnify.height()-1.0) / 2.0));
  237. // Round to ints, for indexing into the pixel array
  238. int indexLeft = std::floor(posLeft);
  239. int indexRight = std::ceil(posRight);
  240. int indexBottom = std::floor(posBottom);
  241. int indexTop = std::ceil(posTop);
  242. // Handle when mouse is near the border
  243. int minLeft = 0;
  244. int maxRight = windowSize[0]-1;
  245. int minBottom = 0;
  246. int maxTop = windowSize[1]-1;
  247. bool overLeft = indexLeft < minLeft;
  248. bool overRight = indexRight > maxRight;
  249. bool overBottom = indexBottom < minBottom;
  250. bool overTop = indexTop > maxTop;
  251. // Ensure we don't access nonexistant indices
  252. if (overLeft)
  253. {
  254. indexLeft = minLeft;
  255. posLeft = minLeft;
  256. }
  257. if (overRight)
  258. {
  259. indexRight = maxRight;
  260. posRight = maxRight;
  261. }
  262. if (overBottom)
  263. {
  264. indexBottom = minBottom;
  265. posBottom = minBottom;
  266. }
  267. if (overTop)
  268. {
  269. indexTop = maxTop;
  270. posTop = maxTop;
  271. }
  272. // Error case
  273. if (indexLeft > indexRight || indexBottom > indexTop)
  274. {
  275. return;
  276. }
  277. // Setup the pixelmap's position in the label
  278. Qt::Alignment alignment;
  279. if (overLeft && !overRight)
  280. {
  281. alignment = Qt::AlignRight;
  282. }
  283. else if (overRight && !overLeft)
  284. {
  285. alignment = Qt::AlignLeft;
  286. }
  287. else
  288. {
  289. alignment = Qt::AlignLeft;
  290. }
  291. if (overBottom && !overTop)
  292. {
  293. alignment = alignment | Qt::AlignTop;
  294. }
  295. else if (overTop && !overBottom)
  296. {
  297. alignment = alignment | Qt::AlignBottom;
  298. }
  299. else
  300. {
  301. alignment = alignment | Qt::AlignTop;
  302. }
  303. q->setAlignment(alignment);
  304. // Retrieve the pixel data into a QImage (flip vertically to move from render
  305. // window coordinates to Qt coordinates)
  306. QSize actualSize(indexRight-indexLeft+1, indexTop-indexBottom+1);
  307. QImage image(actualSize.width(), actualSize.height(), QImage::Format_RGB32);
  308. vtkUnsignedCharArray * pixelData = vtkUnsignedCharArray::New();
  309. pixelData->SetArray(image.bits(), actualSize.width() * actualSize.height() * 4, 1);
  310. int front = renderWindow->GetDoubleBuffer();
  311. int success = renderWindow->GetRGBACharPixelData(
  312. indexLeft, indexBottom, indexRight, indexTop, front, pixelData);
  313. if (!success)
  314. {
  315. return;
  316. }
  317. pixelData->Delete();
  318. image = image.rgbSwapped();
  319. image = image.mirrored();
  320. // Scale the image to zoom, using FastTransformation to prevent smoothing
  321. QSize imageSize = actualSize * this->Magnification;
  322. image = image.scaled(imageSize, Qt::KeepAspectRatioByExpanding,
  323. Qt::FastTransformation);
  324. // Crop the magnified image to solve the problem of magnified partial pixels
  325. double errorLeft
  326. = (posLeft - static_cast<double>(indexLeft)) * this->Magnification;
  327. double errorRight
  328. = (static_cast<double>(indexRight) - posRight) * this->Magnification;
  329. double errorBottom
  330. = (posBottom - static_cast<double>(indexBottom)) * this->Magnification;
  331. double errorTop
  332. = (static_cast<double>(indexTop) - posTop) * this->Magnification;
  333. // When cropping the Qt image, the 'adjust' variables are in Qt coordinates,
  334. // not render window coordinates (bottom and top switch).
  335. int cropIndexLeft = round(errorLeft);
  336. int cropIndexRight = imageSize.width() - round(errorRight) - 1;
  337. int cropIndexTop = round(errorTop);
  338. int cropIndexBottom = imageSize.height() - round(errorBottom) - 1;
  339. // Handle case when label size and magnification are not both even or odd
  340. // (errorLeft/errorRight/errorBottom/errorTop will have fractional component,
  341. // so cropped image wouldn't be the correct size unless we adjust further).
  342. int requiredWidth = round((posRight - posLeft + 1) * this->Magnification);
  343. int requiredHeight = round((posTop - posBottom + 1) * this->Magnification);
  344. int actualWidth = cropIndexRight - cropIndexLeft + 1;
  345. int actualHeight = cropIndexBottom - cropIndexTop + 1;
  346. int diffWidth = requiredWidth - actualWidth;
  347. int diffHeight = requiredHeight - actualHeight;
  348. // Too wide
  349. if (diffWidth < 0 && cropIndexRight != imageSize.width()-1)
  350. {
  351. Q_ASSERT(actualWidth - requiredWidth <= 1);
  352. cropIndexRight += diffWidth;
  353. }
  354. // Too narrow
  355. else if (diffWidth > 0 && cropIndexLeft != 0)
  356. {
  357. Q_ASSERT(requiredWidth - actualWidth <= 1);
  358. cropIndexLeft -= diffWidth;
  359. }
  360. // Too tall
  361. if (diffHeight < 0 && cropIndexBottom != imageSize.height()-1)
  362. {
  363. Q_ASSERT(actualHeight - requiredHeight <= 1);
  364. cropIndexBottom += diffHeight;
  365. }
  366. // Too short
  367. else if (diffHeight > 0 && cropIndexTop != 0)
  368. {
  369. Q_ASSERT(requiredHeight - actualHeight <= 1);
  370. cropIndexTop -= diffHeight;
  371. }
  372. // Finally crop the QImage for display
  373. QRect cropRect(QPoint(cropIndexLeft, cropIndexTop),
  374. QPoint(cropIndexRight, cropIndexBottom));
  375. image = image.copy(cropRect);
  376. // Finally, set the pixelmap to the new one we have created and update
  377. q->setPixmap(QPixmap::fromImage(image));
  378. q->update();
  379. this->resetEventHandler();
  380. }
  381. //---------------------------------------------------------------------------
  382. // ctkVTKMagnifyView methods
  383. // --------------------------------------------------------------------------
  384. ctkVTKMagnifyView::ctkVTKMagnifyView(QWidget* parentWidget)
  385. : Superclass(parentWidget)
  386. , d_ptr(new ctkVTKMagnifyViewPrivate(*this))
  387. {
  388. Q_D(ctkVTKMagnifyView);
  389. d->init();
  390. }
  391. // --------------------------------------------------------------------------
  392. ctkVTKMagnifyView::~ctkVTKMagnifyView()
  393. {
  394. }
  395. // --------------------------------------------------------------------------
  396. CTK_GET_CPP(ctkVTKMagnifyView, double, magnification, Magnification);
  397. // --------------------------------------------------------------------------
  398. void ctkVTKMagnifyView::setMagnification(double newMagnification)
  399. {
  400. Q_D(ctkVTKMagnifyView);
  401. if (newMagnification == d->Magnification || newMagnification <= 0)
  402. {
  403. return;
  404. }
  405. d->Magnification = newMagnification;
  406. this->update();
  407. }
  408. // --------------------------------------------------------------------------
  409. CTK_GET_CPP(ctkVTKMagnifyView, bool,
  410. observeRenderWindowEvents, ObserveRenderWindowEvents);
  411. // --------------------------------------------------------------------------
  412. void ctkVTKMagnifyView::setObserveRenderWindowEvents(bool newObserve)
  413. {
  414. Q_D(ctkVTKMagnifyView);
  415. if (newObserve == d->ObserveRenderWindowEvents)
  416. {
  417. return;
  418. }
  419. d->ObserveRenderWindowEvents = newObserve;
  420. // Connect/disconnect observations on vtkRenderWindow EndEvents, depending
  421. // on whether we are switching from not-observing to observing or from
  422. // observing to not-observing
  423. QList<QVTKWidget *>::iterator it = d->ObservedQVTKWidgets.begin();
  424. while (it != d->ObservedQVTKWidgets.end())
  425. {
  426. if (newObserve)
  427. {
  428. d->connectRenderWindow(*it);
  429. }
  430. else
  431. {
  432. d->disconnectRenderWindow(*it);
  433. }
  434. ++it;
  435. }
  436. }
  437. // --------------------------------------------------------------------------
  438. int ctkVTKMagnifyView::updateInterval() const
  439. {
  440. Q_D(const ctkVTKMagnifyView);
  441. return d->EventHandler.UpdateInterval;
  442. }
  443. // --------------------------------------------------------------------------
  444. void ctkVTKMagnifyView::setUpdateInterval(int newInterval)
  445. {
  446. Q_D(ctkVTKMagnifyView);
  447. if (newInterval == d->EventHandler.UpdateInterval || newInterval < 0)
  448. {
  449. return;
  450. }
  451. d->EventHandler.UpdateInterval = newInterval;
  452. d->restartTimer();
  453. }
  454. // --------------------------------------------------------------------------
  455. void ctkVTKMagnifyView::observe(QVTKWidget * widget)
  456. {
  457. Q_D(ctkVTKMagnifyView);
  458. if (widget)
  459. {
  460. d->observe(widget);
  461. }
  462. }
  463. // --------------------------------------------------------------------------
  464. void ctkVTKMagnifyView::observe(QList<QVTKWidget *> widgets)
  465. {
  466. foreach(QVTKWidget * widget, widgets)
  467. {
  468. this->observe(widget);
  469. }
  470. }
  471. // --------------------------------------------------------------------------
  472. bool ctkVTKMagnifyView::isObserved(QVTKWidget * widget) const
  473. {
  474. if (!widget)
  475. {
  476. return false;
  477. }
  478. Q_D(const ctkVTKMagnifyView);
  479. return d->ObservedQVTKWidgets.contains(widget);
  480. }
  481. // --------------------------------------------------------------------------
  482. int ctkVTKMagnifyView::numberObserved() const
  483. {
  484. Q_D(const ctkVTKMagnifyView);
  485. return d->ObservedQVTKWidgets.length();
  486. }
  487. // --------------------------------------------------------------------------
  488. void ctkVTKMagnifyView::remove(QVTKWidget * widget)
  489. {
  490. Q_D(ctkVTKMagnifyView);
  491. if (widget)
  492. {
  493. d->remove(widget);
  494. }
  495. }
  496. // --------------------------------------------------------------------------
  497. void ctkVTKMagnifyView::remove(QList<QVTKWidget *> widgets)
  498. {
  499. foreach(QVTKWidget * widget, widgets)
  500. {
  501. this->remove(widget);
  502. }
  503. }
  504. // --------------------------------------------------------------------------
  505. bool ctkVTKMagnifyView::eventFilter(QObject * obj, QEvent * event)
  506. {
  507. // The given object should be a QVTKWidget in our list
  508. QVTKWidget * widget = static_cast<QVTKWidget *>(obj);
  509. Q_ASSERT(widget);
  510. Q_D(ctkVTKMagnifyView);
  511. Q_ASSERT(d->ObservedQVTKWidgets.contains(widget));
  512. d->EventHandler.Widget = widget;
  513. QEvent::Type eventType = event->type();
  514. // On mouse move, update the pixmap with the zoomed image
  515. if (eventType == QEvent::MouseMove)
  516. {
  517. QMouseEvent * mouseEvent = static_cast<QMouseEvent *>(event);
  518. Q_ASSERT(mouseEvent);
  519. d->pushUpdatePixmapEvent(mouseEvent->posF());
  520. }
  521. // On enter, update the pixmap with the zoomed image (required for zooming when
  522. // widget is created with mouse already within it), and emit signal of enter event
  523. else if (eventType == QEvent::Enter)
  524. {
  525. d->pushUpdatePixmapEvent();
  526. emit enteredObservedWidget(widget);
  527. }
  528. // On leave, fill the pixmap with a solid color and emit signal of leave event
  529. else if (eventType == QEvent::Leave)
  530. {
  531. d->pushRemovePixmapEvent();
  532. emit leftObservedWidget(widget);
  533. }
  534. // For other event types, use standard event processing
  535. else
  536. {
  537. return QObject::eventFilter(obj, event);
  538. }
  539. return false;
  540. }