diff --git a/src/lib/marble/MarbleInputHandler.cpp b/src/lib/marble/MarbleInputHandler.cpp index dc4a51fa2..837f725d7 100644 --- a/src/lib/marble/MarbleInputHandler.cpp +++ b/src/lib/marble/MarbleInputHandler.cpp @@ -1,947 +1,947 @@ // // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn // Copyright 2007 Inge Wallin // Copyright 2014 Adam Dabrowski // #include "MarbleInputHandler.h" #include #include #include #include #include #include #include #include #include "kineticmodel.h" #include "MarbleGlobal.h" #include "MarbleDebug.h" #include "MarbleMap.h" #include "GeoDataCoordinates.h" #include "MarbleAbstractPresenter.h" #include "ViewportParams.h" #include "AbstractFloatItem.h" #include "AbstractDataPluginItem.h" #include "RenderPlugin.h" namespace Marble { const int TOOLTIP_START_INTERVAL = 1000; class Q_DECL_HIDDEN MarbleInputHandler::Protected { public: Protected(MarbleAbstractPresenter *marblePresenter); MarbleAbstractPresenter *const m_marblePresenter; bool m_positionSignalConnected; QTimer *m_mouseWheelTimer; Qt::MouseButtons m_disabledMouseButtons; qreal m_wheelZoomTargetDistance; bool m_panViaArrowsEnabled; bool m_inertialEarthRotation; int m_steps; const int m_discreteZoomSteps = 120; }; MarbleInputHandler::Protected::Protected(MarbleAbstractPresenter *marblePresenter) : m_marblePresenter( marblePresenter ), m_positionSignalConnected( false ), m_mouseWheelTimer( 0 ), m_disabledMouseButtons( Qt::NoButton ), m_wheelZoomTargetDistance( 0.0 ), m_panViaArrowsEnabled( true ), m_inertialEarthRotation( true ), m_steps(0) { } MarbleInputHandler::MarbleInputHandler(MarbleAbstractPresenter *marblePresenter) : d(new Protected(marblePresenter)) { d->m_mouseWheelTimer = new QTimer( this ); connect(d->m_mouseWheelTimer, SIGNAL(timeout()), this, SLOT(restoreViewContext())); connect(d->m_marblePresenter->map(), SIGNAL(renderPluginInitialized(RenderPlugin*)), this, SLOT(installPluginEventFilter(RenderPlugin*))); } MarbleInputHandler::~MarbleInputHandler() { delete d->m_mouseWheelTimer; delete d; } void MarbleInputHandler::setPositionSignalConnected(bool connected) { d->m_positionSignalConnected = connected; } bool MarbleInputHandler::isPositionSignalConnected() const { return d->m_positionSignalConnected; } void MarbleInputHandler::setMouseButtonPopupEnabled(Qt::MouseButton mouseButton, bool enabled) { if (enabled) { d->m_disabledMouseButtons &= ~Qt::MouseButtons(mouseButton); } else { d->m_disabledMouseButtons |= mouseButton; } } bool MarbleInputHandler::isMouseButtonPopupEnabled(Qt::MouseButton mouseButton) const { return !(d->m_disabledMouseButtons & mouseButton); } void MarbleInputHandler::setPanViaArrowsEnabled(bool enabled) { d->m_panViaArrowsEnabled = enabled; } bool MarbleInputHandler::panViaArrowsEnabled() const { return d->m_panViaArrowsEnabled; } void MarbleInputHandler::setInertialEarthRotationEnabled(bool enabled) { d->m_inertialEarthRotation = enabled; } bool MarbleInputHandler::inertialEarthRotationEnabled() const { return d->m_inertialEarthRotation; } class Q_DECL_HIDDEN MarbleDefaultInputHandler::Private { public: Private(); ~Private(); QPixmap m_curpmtl; QPixmap m_curpmtc; QPixmap m_curpmtr; QPixmap m_curpmcr; QPixmap m_curpmcl; QPixmap m_curpmbl; QPixmap m_curpmbc; QPixmap m_curpmbr; QCursor m_arrowCur[3][3]; // Indicates if the left mouse button has been pressed already. bool m_leftPressed; // Indicates whether the drag was started by a click above or below the visible pole. int m_leftPressedDirection; // Indicates if the middle mouse button has been pressed already. bool m_midPressed; // The mouse pointer x position when the left mouse button has been pressed. int m_leftPressedX; // The mouse pointer y position when the left mouse button has been pressed. int m_leftPressedY; // The mouse pointer y position when the middle mouse button has been pressed. int m_midPressedY; int m_startingRadius; // The center longitude in radian when the left mouse button has been pressed. qreal m_leftPressedLon; // The center latitude in radian when the left mouse button has been pressed. qreal m_leftPressedLat; int m_dragThreshold; QTimer m_lmbTimer; QTimer m_pressAndHoldTimer; // Models to handle the kinetic spinning. KineticModel m_kineticSpinning; QPoint m_selectionOrigin; QPointer m_lastToolTipItem; QTimer m_toolTipTimer; QPoint m_toolTipPosition; }; MarbleDefaultInputHandler::Private::Private() : m_leftPressed(false), m_midPressed(false), m_dragThreshold(MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen ? 15 : 3) { m_curpmtl.load(QStringLiteral(":/marble/cursor/tl.png")); m_curpmtc.load(QStringLiteral(":/marble/cursor/tc.png")); m_curpmtr.load(QStringLiteral(":/marble/cursor/tr.png")); m_curpmcr.load(QStringLiteral(":/marble/cursor/cr.png")); m_curpmcl.load(QStringLiteral(":/marble/cursor/cl.png")); m_curpmbl.load(QStringLiteral(":/marble/cursor/bl.png")); m_curpmbc.load(QStringLiteral(":/marble/cursor/bc.png")); m_curpmbr.load(QStringLiteral(":/marble/cursor/br.png")); m_arrowCur[0][0] = QCursor( m_curpmtl, 2, 2 ); m_arrowCur[1][0] = QCursor( m_curpmtc, 10, 3 ); m_arrowCur[2][0] = QCursor( m_curpmtr, 19, 2 ); m_arrowCur[0][1] = QCursor( m_curpmcl, 3, 10 ); m_arrowCur[1][1] = QCursor( Qt::OpenHandCursor ); m_arrowCur[2][1] = QCursor( m_curpmcr, 18, 10 ); m_arrowCur[0][2] = QCursor( m_curpmbl, 2, 19 ); m_arrowCur[1][2] = QCursor( m_curpmbc, 11, 18 ); m_arrowCur[2][2] = QCursor( m_curpmbr, 19, 19 ); } MarbleDefaultInputHandler::Private::~Private() { } MarbleDefaultInputHandler::MarbleDefaultInputHandler(MarbleAbstractPresenter *marblePresenter) : MarbleInputHandler(marblePresenter), d(new Private()) { d->m_toolTipTimer.setSingleShot(true); d->m_toolTipTimer.setInterval(TOOLTIP_START_INTERVAL); connect(&d->m_toolTipTimer, SIGNAL(timeout()), this, SLOT(openItemToolTip())); d->m_lmbTimer.setSingleShot(true); connect(&d->m_lmbTimer, SIGNAL(timeout()), this, SLOT(lmbTimeout())); d->m_kineticSpinning.setUpdateInterval(35); connect(&d->m_kineticSpinning, SIGNAL(positionChanged(qreal,qreal)), MarbleInputHandler::d->m_marblePresenter, SLOT(centerOn(qreal,qreal))); connect(&d->m_kineticSpinning, SIGNAL(finished()), SLOT(restoreViewContext())); // Left and right mouse button signals. connect(this, SIGNAL(rmbRequest(int,int)), this, SLOT(showRmbMenu(int,int))); connect(this, SIGNAL(lmbRequest(int,int)), this, SLOT(showLmbMenu(int,int))); d->m_pressAndHoldTimer.setInterval(800); d->m_pressAndHoldTimer.setSingleShot(true); connect(&d->m_pressAndHoldTimer, SIGNAL(timeout()), this, SLOT(handlePressAndHold())); } MarbleDefaultInputHandler::~MarbleDefaultInputHandler() { delete d; } void MarbleDefaultInputHandler::lmbTimeout() { if (!selectionRubber()->isVisible()) { qreal clickedLon = 0; qreal clickedLat = 0; bool isPointOnGlobe = MarbleInputHandler::d->m_marblePresenter->map()->geoCoordinates( d->m_leftPressedX, d->m_leftPressedY, clickedLon, clickedLat, GeoDataCoordinates::Degree ); emit lmbRequest(d->m_leftPressedX, d->m_leftPressedY); /** * emit mouse click only when the clicked * position is within the globe. */ if ( isPointOnGlobe ) { emit mouseClickGeoPosition( clickedLon, clickedLat, GeoDataCoordinates::Degree ); } } } void MarbleInputHandler::restoreViewContext() { // Needs to stop the timer since it repeats otherwise. d->m_mouseWheelTimer->stop(); // Redraw the map with the quality set for Still (if necessary). d->m_marblePresenter->setViewContext(Still); d->m_marblePresenter->map()->viewport()->resetFocusPoint(); d->m_wheelZoomTargetDistance = 0.0; } void MarbleDefaultInputHandler::hideSelectionIfCtrlReleased(QEvent *e) { if (selectionRubber()->isVisible() && e->type() == QEvent::MouseMove) { QMouseEvent *event = static_cast(e); if (!(event->modifiers() & Qt::ControlModifier)) { selectionRubber()->hide(); } } } bool MarbleDefaultInputHandler::handleDoubleClick(QMouseEvent *event) { qreal mouseLon; qreal mouseLat; const bool isMouseAboveMap = MarbleInputHandler::d->m_marblePresenter->map()->geoCoordinates(event->x(), event->y(), mouseLon, mouseLat, GeoDataCoordinates::Radian); if(isMouseAboveMap) { d->m_pressAndHoldTimer.stop(); d->m_lmbTimer.stop(); MarbleInputHandler::d->m_marblePresenter->moveTo(event->pos(), 0.67); } return acceptMouse(); } bool MarbleDefaultInputHandler::handleWheel(QWheelEvent *wheelevt) { MarbleAbstractPresenter *marblePresenter = MarbleInputHandler::d->m_marblePresenter; marblePresenter->setViewContext(Animation); if( (MarbleInputHandler::d->m_steps > 0 && wheelevt->delta() < 0) || (MarbleInputHandler::d->m_steps < 0 && wheelevt->delta() > 0) ) { MarbleInputHandler::d->m_steps = wheelevt->delta(); } else { MarbleInputHandler::d->m_steps += wheelevt->delta(); } if (marblePresenter->map()->discreteZoom()) { if(qAbs(MarbleInputHandler::d->m_steps) >= MarbleInputHandler::d->m_discreteZoomSteps) { marblePresenter->zoomAtBy(wheelevt->pos(), MarbleInputHandler::d->m_steps); MarbleInputHandler::d->m_steps = 0; } } else { qreal zoom = marblePresenter->zoom(); qreal target = MarbleInputHandler::d->m_wheelZoomTargetDistance; if (marblePresenter->animationsEnabled() && target > 0.0) { // Do not use intermediate (interpolated) distance values caused by animations zoom = marblePresenter->zoomFromDistance(target); } qreal newDistance = marblePresenter->distanceFromZoom(zoom + MarbleInputHandler::d->m_steps); MarbleInputHandler::d->m_wheelZoomTargetDistance = newDistance; marblePresenter->zoomAt(wheelevt->pos(), newDistance); if (MarbleInputHandler::d->m_inertialEarthRotation) { d->m_kineticSpinning.jumpToPosition(MarbleInputHandler::d->m_marblePresenter->centerLongitude(), MarbleInputHandler::d->m_marblePresenter->centerLatitude()); } MarbleInputHandler::d->m_steps = 0; } MarbleInputHandler::d->m_mouseWheelTimer->start(400); return true; } bool MarbleDefaultInputHandler::handlePinch(const QPointF ¢er, qreal scaleFactor, Qt::GestureState state) { qreal destLat; qreal destLon; MarbleAbstractPresenter *marblePresenter = MarbleInputHandler::d->m_marblePresenter; bool isValid = marblePresenter->map()->geoCoordinates(center.x(), center.y(), destLon, destLat, GeoDataCoordinates::Radian ); if (isValid) { marblePresenter->map()->viewport()->setFocusPoint(GeoDataCoordinates(destLon, destLat)); } qreal zoom, target, newDistance; qreal zoomDelta = scaleFactor > 1.0 ? scaleFactor : -1.0/scaleFactor; switch (state) { case Qt::NoGesture: break; case Qt::GestureStarted: marblePresenter->setViewContext(Animation); d->m_pressAndHoldTimer.stop(); d->m_lmbTimer.stop(); d->m_midPressed = false; d->m_leftPressed = false; break; case Qt::GestureUpdated: zoom = marblePresenter->zoom(); target = MarbleInputHandler::d->m_wheelZoomTargetDistance; if (marblePresenter->animationsEnabled() && target > 0.0) { // Do not use intermediate (interpolated) distance values caused by animations zoom = marblePresenter->zoomFromDistance(target); } newDistance = marblePresenter->distanceFromZoom(zoom + 20 * zoomDelta); MarbleInputHandler::d->m_wheelZoomTargetDistance = newDistance; marblePresenter->zoomAt(center.toPoint(), newDistance); break; case Qt::GestureFinished: marblePresenter->map()->viewport()->resetFocusPoint(); marblePresenter->setViewContext(Still); break; case Qt::GestureCanceled: marblePresenter->map()->viewport()->resetFocusPoint(); marblePresenter->setViewContext(Still); break; } return true; } bool MarbleDefaultInputHandler::handleGesture(QGestureEvent *ge) { QPinchGesture *pinch = static_cast(ge->gesture(Qt::PinchGesture)); if (!pinch) { return false; } qreal scaleFactor = pinch->scaleFactor(); QPointF center = pinch->centerPoint(); return handlePinch(center, scaleFactor, pinch->state()); } void MarbleDefaultInputHandler::checkReleasedMove(QMouseEvent *event) { // To prevent error from lost MouseButtonRelease events if (event->type() == QEvent::MouseMove && !(event->buttons() & Qt::LeftButton)) { if (d->m_leftPressed) { d->m_leftPressed = false; if (MarbleInputHandler::d->m_inertialEarthRotation) { d->m_kineticSpinning.start(); } else { MarbleInputHandler::d->m_marblePresenter->setViewContext(Still); } } } if (event->type() == QEvent::MouseMove && !(event->buttons() & Qt::MidButton)) { d->m_midPressed = false; } } void MarbleDefaultInputHandler::handleMouseButtonPress(QMouseEvent *event) { if (event->button() == Qt::LeftButton ) { handleLeftMouseButtonPress(event); } if ( event->button() == Qt::MidButton ) { handleMiddleMouseButtonPress(event); } if ( event->button() == Qt::RightButton ) { handleRightMouseButtonPress(event); } } void MarbleDefaultInputHandler::handleLeftMouseButtonPress(QMouseEvent *event) { // silently enable the animation context without triggering a repaint MarbleInputHandler::d->m_marblePresenter->map()->blockSignals(true); MarbleInputHandler::d->m_marblePresenter->setViewContext(Animation); MarbleInputHandler::d->m_marblePresenter->map()->blockSignals(false); if (isMouseButtonPopupEnabled(Qt::LeftButton)) { d->m_lmbTimer.start(400); } d->m_leftPressed = true; d->m_midPressed = false; selectionRubber()->hide(); // On the single event of a mouse button press these // values get stored, to enable us to e.g. calculate the // distance of a mouse drag while the mouse button is // still down. d->m_leftPressedX = event->x(); d->m_leftPressedY = event->y(); // Calculate translation of center point d->m_leftPressedLon = MarbleInputHandler::d->m_marblePresenter->centerLongitude(); d->m_leftPressedLat = MarbleInputHandler::d->m_marblePresenter->centerLatitude(); d->m_leftPressedDirection = 1; if (MarbleInputHandler::d->m_inertialEarthRotation) { d->m_kineticSpinning.stop(); d->m_kineticSpinning.setPosition(d->m_leftPressedLon, d->m_leftPressedLat); } // Choose spin direction by taking into account whether we // drag above or below the visible pole. if (MarbleInputHandler::d->m_marblePresenter->map()->projection() == Spherical) { if (d->m_leftPressedLat >= 0) { // The visible pole is the north pole qreal northPoleX, northPoleY; MarbleInputHandler::d->m_marblePresenter->map()->screenCoordinates(0.0, 90.0, northPoleX, northPoleY); if (event->y() < northPoleY) { d->m_leftPressedDirection = -1; } } else { // The visible pole is the south pole qreal southPoleX, southPoleY; MarbleInputHandler::d->m_marblePresenter->map()->screenCoordinates(0.0, -90.0, southPoleX, southPoleY); if (event->y() > southPoleY) { d->m_leftPressedDirection = -1; } } } if (event->modifiers() & Qt::ControlModifier) { mDebug() << Q_FUNC_INFO << "Starting selection"; d->m_pressAndHoldTimer.stop(); d->m_lmbTimer.stop(); d->m_selectionOrigin = event->pos(); selectionRubber()->setGeometry(QRect(d->m_selectionOrigin, QSize())); selectionRubber()->show(); } } void MarbleDefaultInputHandler::handleMiddleMouseButtonPress(QMouseEvent *event) { d->m_midPressed = true; d->m_leftPressed = false; d->m_startingRadius = MarbleInputHandler::d->m_marblePresenter->radius(); d->m_midPressedY = event->y(); if (MarbleInputHandler::d->m_inertialEarthRotation) { d->m_kineticSpinning.start(); } selectionRubber()->hide(); MarbleInputHandler::d->m_marblePresenter->setViewContext(Animation); } void MarbleDefaultInputHandler::handleRightMouseButtonPress(QMouseEvent *event) { emit rmbRequest(event->x(), event->y()); } void MarbleDefaultInputHandler::handleMouseButtonRelease(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { - //emit current coordinates to be be interpreted + //emit current coordinates to be interpreted //as requested emit mouseClickScreenPosition(d->m_leftPressedX, d->m_leftPressedY); d->m_leftPressed = false; if (MarbleInputHandler::d->m_inertialEarthRotation) { d->m_kineticSpinning.start(); } else { MarbleInputHandler::d->m_marblePresenter->setViewContext(Still); } } if (event->button() == Qt::MidButton) { d->m_midPressed = false; MarbleInputHandler::d->m_marblePresenter->setViewContext(Still); } if (event->type() == QEvent::MouseButtonRelease && event->button() == Qt::RightButton) { } if (event->type() == QEvent::MouseButtonRelease && event->button() == Qt::LeftButton && selectionRubber()->isVisible()) { mDebug() << Q_FUNC_INFO << "Leaving selection"; MarbleInputHandler::d->m_marblePresenter->setSelection(selectionRubber()->geometry()); selectionRubber()->hide(); } } void MarbleDefaultInputHandler::notifyPosition(bool isMouseAboveMap, qreal mouseLon, qreal mouseLat) { // emit the position string only if the signal got attached if (MarbleInputHandler::d->m_positionSignalConnected) { if (!isMouseAboveMap) { emit mouseMoveGeoPosition(QCoreApplication::translate( "Marble", NOT_AVAILABLE)); } else { QString position = GeoDataCoordinates(mouseLon, mouseLat).toString(); emit mouseMoveGeoPosition(position); } } } void MarbleDefaultInputHandler::adjustCursorShape(const QPoint &mousePosition, const QPoint &mouseDirection) { // Find out if there are data items and if one has defined an action QList dataItems = MarbleInputHandler::d->m_marblePresenter->map()->whichItemAt(mousePosition); bool dataAction = false; QPointer toolTipItem; QList::iterator it = dataItems.begin(); QList::iterator const end = dataItems.end(); for (; it != end && dataAction == false && toolTipItem.isNull(); ++it) { if ((*it)->action()) { dataAction = true; } if (!(*it)->toolTip().isNull() && toolTipItem.isNull()) { toolTipItem = (*it); } } if (toolTipItem.isNull()) { d->m_toolTipTimer.stop(); } else if (!( d->m_lastToolTipItem.data() == toolTipItem.data())) { d->m_toolTipTimer.start(); d->m_lastToolTipItem = toolTipItem; d->m_toolTipPosition = mousePosition; } else { if (!d->m_toolTipTimer.isActive()) { d->m_toolTipTimer.start(); } d->m_toolTipPosition = mousePosition; } if (!dataAction && !MarbleInputHandler::d->m_marblePresenter->map()->hasFeatureAt(mousePosition)) { if (!d->m_leftPressed) { d->m_arrowCur [1][1] = QCursor(Qt::OpenHandCursor); } else { d->m_arrowCur [1][1] = QCursor(Qt::ClosedHandCursor); } } else { if (!d->m_leftPressed) { d->m_arrowCur [1][1] = QCursor(Qt::PointingHandCursor); } } if (panViaArrowsEnabled()) { setCursor(d->m_arrowCur[mouseDirection.x()+1][mouseDirection.y()+1]); } else { setCursor(d->m_arrowCur[1][1]); } } QPoint MarbleDefaultInputHandler::mouseMovedOutside(QMouseEvent *event) { //Returns a 2d vector representing the direction in which the mouse left int dirX = 0; int dirY = 0; int polarity = MarbleInputHandler::d->m_marblePresenter->viewport()->polarity(); if (d->m_leftPressed) { d->m_leftPressed = false; if (MarbleInputHandler::d->m_inertialEarthRotation) { d->m_kineticSpinning.start(); } } QRect boundingRect = MarbleInputHandler::d->m_marblePresenter->viewport()->mapRegion().boundingRect(); if (boundingRect.width() != 0) { dirX = (int)( 3 * (event->x() - boundingRect.left()) / boundingRect.width()) - 1; } if (dirX > 1) { dirX = 1; } if (dirX < -1) { dirX = -1; } if (boundingRect.height() != 0) { dirY = (int)(3 * (event->y() - boundingRect.top()) / boundingRect.height()) - 1; } if (dirY > 1) { dirY = 1; } if (dirY < -1) { dirY = -1; } if (event->button() == Qt::LeftButton && event->type() == QEvent::MouseButtonPress && panViaArrowsEnabled() && !d->m_kineticSpinning.hasVelocity()) { d->m_pressAndHoldTimer.stop(); d->m_lmbTimer.stop(); qreal moveStep = MarbleInputHandler::d->m_marblePresenter->moveStep(); if (polarity < 0) { MarbleInputHandler::d->m_marblePresenter->rotateBy(-moveStep * (qreal)(+dirX), moveStep * (qreal)(+dirY)); } else { MarbleInputHandler::d->m_marblePresenter->rotateBy(-moveStep * (qreal)(-dirX), moveStep * (qreal)(+dirY)); } } if (!MarbleInputHandler::d->m_inertialEarthRotation) { MarbleInputHandler::d->m_marblePresenter->setViewContext(Still); } return QPoint(dirX, dirY); } bool MarbleDefaultInputHandler::handleMouseEvent(QMouseEvent *event) { QPoint direction; checkReleasedMove(event); // Do not handle (and therefore eat) mouse press and release events // that occur above visible float items. Mouse motion events are still // handled, however. if (event->type() != QEvent::MouseMove && !selectionRubber()->isVisible()) { auto const floatItems = MarbleInputHandler::d->m_marblePresenter->map()->floatItems(); for (AbstractFloatItem *floatItem: floatItems) { if ( floatItem->enabled() && floatItem->visible() && floatItem->contains( event->pos() ) ) { d->m_pressAndHoldTimer.stop(); d->m_lmbTimer.stop(); return false; } } } qreal mouseLon; qreal mouseLat; const bool isMouseAboveMap = MarbleInputHandler::d->m_marblePresenter->map()->geoCoordinates(event->x(), event->y(), mouseLon, mouseLat, GeoDataCoordinates::Radian); notifyPosition(isMouseAboveMap, mouseLon, mouseLat); QPoint mousePosition(event->x(), event->y()); if (isMouseAboveMap || selectionRubber()->isVisible() || MarbleInputHandler::d->m_marblePresenter->map()->hasFeatureAt(mousePosition)) { if (event->type() == QEvent::MouseButtonPress) { d->m_pressAndHoldTimer.start(); handleMouseButtonPress(event); } if (event->type() == QEvent::MouseButtonRelease) { d->m_pressAndHoldTimer.stop(); handleMouseButtonRelease(event); } // Regarding all kinds of mouse moves: if (d->m_leftPressed && !selectionRubber()->isVisible()) { qreal radius = (qreal)(MarbleInputHandler::d->m_marblePresenter->radius()); int deltax = event->x() - d->m_leftPressedX; int deltay = event->y() - d->m_leftPressedY; if (abs(deltax) > d->m_dragThreshold || abs(deltay) > d->m_dragThreshold || !d->m_lmbTimer.isActive()) { MarbleInputHandler::d->m_marblePresenter->setViewContext(Animation); d->m_pressAndHoldTimer.stop(); d->m_lmbTimer.stop(); const qreal posLon = d->m_leftPressedLon - 90.0 * d->m_leftPressedDirection * deltax / radius; const qreal posLat = d->m_leftPressedLat + 90.0 * deltay / radius; MarbleInputHandler::d->m_marblePresenter->centerOn(posLon, posLat); if (MarbleInputHandler::d->m_inertialEarthRotation) { d->m_kineticSpinning.setPosition(posLon, posLat); } } } if (d->m_midPressed) { int eventy = event->y(); int dy = d->m_midPressedY - eventy; MarbleInputHandler::d->m_marblePresenter->setRadius(d->m_startingRadius * pow(1.005, dy)); } if (selectionRubber()->isVisible()) { // We change selection. selectionRubber()->setGeometry(QRect(d->m_selectionOrigin, event->pos()).normalized()); } } else { direction = mouseMovedOutside(event); } if (MarbleInputHandler::d->m_marblePresenter->viewContext() != Animation) { adjustCursorShape(mousePosition, direction); } return acceptMouse(); } bool MarbleDefaultInputHandler::acceptMouse() { // let others, especially float items, still process the event // Note: This caused a bug in combination with oxygen, see https://bugs.kde.org/show_bug.cgi?id=242414 // and changing it a related regression, see https://bugs.kde.org/show_bug.cgi?id=324862 return false; } bool MarbleDefaultInputHandler::eventFilter(QObject* o, QEvent* e) { Q_UNUSED(o); if (layersEventFilter(o, e)) { return true; } hideSelectionIfCtrlReleased(e); switch (e->type()) { case QEvent::TouchBegin: case QEvent::TouchUpdate: case QEvent::TouchEnd: return handleTouch(static_cast(e)); case QEvent::KeyPress: return handleKeyPress(static_cast(e)); case QEvent::Gesture: return handleGesture(static_cast(e)); case QEvent::Wheel: return handleWheel(static_cast(e)); case QEvent::MouseButtonDblClick: return handleDoubleClick(static_cast(e)); case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseMove: return handleMouseEvent(static_cast(e)); default: return false; } } bool MarbleDefaultInputHandler::handleTouch(QTouchEvent*) { return false; //reimplement to handle in cases of QML and PinchArea element } bool MarbleDefaultInputHandler::handleKeyPress(QKeyEvent* event) { if ( event->type() == QEvent::KeyPress ) { MarbleAbstractPresenter *marblePresenter = MarbleInputHandler::d->m_marblePresenter; bool handled = true; switch ( event->key() ) { case Qt::Key_Left: marblePresenter->moveByStep(-1, 0); break; case Qt::Key_Right: marblePresenter->moveByStep(1, 0); break; case Qt::Key_Up: marblePresenter->moveByStep(0, -1); break; case Qt::Key_Down: marblePresenter->moveByStep(0, 1); break; case Qt::Key_Plus: marblePresenter->zoomIn(); break; case Qt::Key_Minus: marblePresenter->zoomOut(); break; case Qt::Key_Home: marblePresenter->goHome(); break; default: handled = false; break; } return handled; } return false; } void MarbleDefaultInputHandler::handleMouseButtonPressAndHold(const QPoint &) { // Default implementation does nothing } void MarbleDefaultInputHandler::handlePressAndHold() { handleMouseButtonPressAndHold(QPoint(d->m_leftPressedX, d->m_leftPressedY)); } QPointer MarbleDefaultInputHandler::lastToolTipItem() { return d->m_lastToolTipItem; } QTimer* MarbleDefaultInputHandler::toolTipTimer() { return &d->m_toolTipTimer; } QPoint MarbleDefaultInputHandler::toolTipPosition() { return d->m_toolTipPosition; } } #include "moc_MarbleInputHandler.cpp" diff --git a/src/lib/marble/MarbleZip.cpp b/src/lib/marble/MarbleZip.cpp index 5d9482da8..92519707d 100644 --- a/src/lib/marble/MarbleZip.cpp +++ b/src/lib/marble/MarbleZip.cpp @@ -1,1282 +1,1282 @@ // // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // This file is based on qzip.cpp from Qt with the original license // below, taken from // http://code.qt.io/cgit/qt/qt.git/plain/src/gui/text/qzip.cpp /**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include #ifndef QT_NO_TEXTODFWRITER #include "MarbleZipReader.h" #include "MarbleZipWriter.h" #include #include #include #include #include #include #if defined(Q_OS_WIN) # undef S_IFREG # define S_IFREG 0100000 # ifndef S_IFDIR # define S_IFDIR 0040000 # endif # ifndef S_ISDIR # define S_ISDIR(x) ((x) & S_IFDIR) > 0 # endif # ifndef S_ISREG # define S_ISREG(x) ((x) & 0170000) == S_IFREG # endif # define S_IFLNK 020000 # define S_ISLNK(x) ((x) & S_IFLNK) > 0 # ifndef S_IRUSR # define S_IRUSR 0400 # endif # ifndef S_IWUSR # define S_IWUSR 0200 # endif # ifndef S_IXUSR # define S_IXUSR 0100 # endif # define S_IRGRP 0040 # define S_IWGRP 0020 # define S_IXGRP 0010 # define S_IROTH 0004 # define S_IWOTH 0002 # define S_IXOTH 0001 #endif #if 0 #define ZDEBUG qDebug #else #define ZDEBUG if (0) qDebug #endif namespace Marble { static inline uint readUInt(const uchar *data) { return (data[0]) + (data[1]<<8) + (data[2]<<16) + (data[3]<<24); } static inline ushort readUShort(const uchar *data) { return (data[0]) + (data[1]<<8); } static inline void writeUInt(uchar *data, uint i) { data[0] = i & 0xff; data[1] = (i>>8) & 0xff; data[2] = (i>>16) & 0xff; data[3] = (i>>24) & 0xff; } static inline void writeUShort(uchar *data, ushort i) { data[0] = i & 0xff; data[1] = (i>>8) & 0xff; } static inline void copyUInt(uchar *dest, const uchar *src) { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; dest[3] = src[3]; } static inline void copyUShort(uchar *dest, const uchar *src) { dest[0] = src[0]; dest[1] = src[1]; } static void writeMSDosDate(uchar *dest, const QDateTime& dt) { if (dt.isValid()) { quint16 time = (dt.time().hour() << 11) // 5 bit hour | (dt.time().minute() << 5) // 6 bit minute | (dt.time().second() >> 1); // 5 bit double seconds dest[0] = time & 0xff; dest[1] = time >> 8; quint16 date = ((dt.date().year() - 1980) << 9) // 7 bit year 1980-based | (dt.date().month() << 5) // 4 bit month | (dt.date().day()); // 5 bit day dest[2] = char(date); dest[3] = char(date >> 8); } else { dest[0] = 0; dest[1] = 0; dest[2] = 0; dest[3] = 0; } } static quint32 permissionsToMode(QFile::Permissions perms) { quint32 mode = 0; if (perms & QFile::ReadOwner) mode |= S_IRUSR; if (perms & QFile::WriteOwner) mode |= S_IWUSR; if (perms & QFile::ExeOwner) mode |= S_IXUSR; if (perms & QFile::ReadUser) mode |= S_IRUSR; if (perms & QFile::WriteUser) mode |= S_IWUSR; if (perms & QFile::ExeUser) mode |= S_IXUSR; if (perms & QFile::ReadGroup) mode |= S_IRGRP; if (perms & QFile::WriteGroup) mode |= S_IWGRP; if (perms & QFile::ExeGroup) mode |= S_IXGRP; if (perms & QFile::ReadOther) mode |= S_IROTH; if (perms & QFile::WriteOther) mode |= S_IWOTH; if (perms & QFile::ExeOther) mode |= S_IXOTH; return mode; } static int inflate(Bytef *dest, ulong *destLen, const Bytef *source, ulong sourceLen) { z_stream stream; int err; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; err = inflateInit2(&stream, -MAX_WBITS); if (err != Z_OK) return err; err = inflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { inflateEnd(&stream); if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) return Z_DATA_ERROR; return err; } *destLen = stream.total_out; err = inflateEnd(&stream); return err; } static int deflate (Bytef *dest, ulong *destLen, const Bytef *source, ulong sourceLen) { z_stream stream; int err; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; stream.opaque = (voidpf)0; err = deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY); if (err != Z_OK) return err; err = deflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { deflateEnd(&stream); return err == Z_OK ? Z_BUF_ERROR : err; } *destLen = stream.total_out; err = deflateEnd(&stream); return err; } static QFile::Permissions modeToPermissions(quint32 mode) { QFile::Permissions ret; if (mode & S_IRUSR) ret |= QFile::ReadOwner; if (mode & S_IWUSR) ret |= QFile::WriteOwner; if (mode & S_IXUSR) ret |= QFile::ExeOwner; if (mode & S_IRUSR) ret |= QFile::ReadUser; if (mode & S_IWUSR) ret |= QFile::WriteUser; if (mode & S_IXUSR) ret |= QFile::ExeUser; if (mode & S_IRGRP) ret |= QFile::ReadGroup; if (mode & S_IWGRP) ret |= QFile::WriteGroup; if (mode & S_IXGRP) ret |= QFile::ExeGroup; if (mode & S_IROTH) ret |= QFile::ReadOther; if (mode & S_IWOTH) ret |= QFile::WriteOther; if (mode & S_IXOTH) ret |= QFile::ExeOther; return ret; } static QDateTime readMSDosDate(const uchar *src) { uint dosDate = readUInt(src); quint64 uDate; uDate = (quint64)(dosDate >> 16); uint tm_mday = (uDate & 0x1f); uint tm_mon = ((uDate & 0x1E0) >> 5); uint tm_year = (((uDate & 0x0FE00) >> 9) + 1980); uint tm_hour = ((dosDate & 0xF800) >> 11); uint tm_min = ((dosDate & 0x7E0) >> 5); uint tm_sec = ((dosDate & 0x1f) << 1); return QDateTime(QDate(tm_year, tm_mon, tm_mday), QTime(tm_hour, tm_min, tm_sec)); } struct LocalFileHeader { uchar signature[4]; // 0x04034b50 uchar version_needed[2]; uchar general_purpose_bits[2]; uchar compression_method[2]; uchar last_mod_file[4]; uchar crc_32[4]; uchar compressed_size[4]; uchar uncompressed_size[4]; uchar file_name_length[2]; uchar extra_field_length[2]; }; struct DataDescriptor { uchar crc_32[4]; uchar compressed_size[4]; uchar uncompressed_size[4]; }; struct CentralFileHeader { uchar signature[4]; // 0x02014b50 uchar version_made[2]; uchar version_needed[2]; uchar general_purpose_bits[2]; uchar compression_method[2]; uchar last_mod_file[4]; uchar crc_32[4]; uchar compressed_size[4]; uchar uncompressed_size[4]; uchar file_name_length[2]; uchar extra_field_length[2]; uchar file_comment_length[2]; uchar disk_start[2]; uchar internal_file_attributes[2]; uchar external_file_attributes[4]; uchar offset_local_header[4]; LocalFileHeader toLocalHeader() const; }; struct EndOfDirectory { uchar signature[4]; // 0x06054b50 uchar this_disk[2]; uchar start_of_directory_disk[2]; uchar num_dir_entries_this_disk[2]; uchar num_dir_entries[2]; uchar directory_size[4]; uchar dir_start_offset[4]; uchar comment_length[2]; }; struct FileHeader { CentralFileHeader h; QByteArray file_name; QByteArray extra_field; QByteArray file_comment; }; MarbleZipReader::FileInfo::FileInfo() : isDir(false), isFile(false), isSymLink(false), crc32(0), size(0) { } MarbleZipReader::FileInfo::~FileInfo() { } MarbleZipReader::FileInfo::FileInfo(const FileInfo &other) { operator=(other); } MarbleZipReader::FileInfo& MarbleZipReader::FileInfo::operator=(const FileInfo &other) { filePath = other.filePath; isDir = other.isDir; isFile = other.isFile; isSymLink = other.isSymLink; permissions = other.permissions; crc32 = other.crc32; size = other.size; lastModified = other.lastModified; return *this; } bool MarbleZipReader::FileInfo::isValid() const { return isDir || isFile || isSymLink; } class QZipPrivate { public: QZipPrivate(QIODevice *device, bool ownDev) : device(device), ownDevice(ownDev), dirtyFileTree(true), start_of_directory(0) { } ~QZipPrivate() { if (ownDevice) delete device; } void fillFileInfo(int index, MarbleZipReader::FileInfo &fileInfo) const; QIODevice *device; bool ownDevice; bool dirtyFileTree; QList fileHeaders; QByteArray comment; uint start_of_directory; }; void QZipPrivate::fillFileInfo(int index, MarbleZipReader::FileInfo &fileInfo) const { FileHeader header = fileHeaders.at(index); fileInfo.filePath = QString::fromLocal8Bit(header.file_name); const quint32 mode = (qFromLittleEndian(&header.h.external_file_attributes[0]) >> 16) & 0xFFFF; if (mode == 0) { fileInfo.isDir = false; fileInfo.isFile = true; fileInfo.isSymLink = false; fileInfo.permissions = QFile::ReadOwner; } else { fileInfo.isDir = S_ISDIR(mode); fileInfo.isFile = S_ISREG(mode); fileInfo.isSymLink = S_ISLNK(mode); fileInfo.permissions = modeToPermissions(mode); } fileInfo.crc32 = readUInt(header.h.crc_32); fileInfo.size = readUInt(header.h.uncompressed_size); fileInfo.lastModified = readMSDosDate(header.h.last_mod_file); } class MarbleZipReaderPrivate : public QZipPrivate { public: MarbleZipReaderPrivate(QIODevice *device, bool ownDev) : QZipPrivate(device, ownDev), status(MarbleZipReader::NoError) { } void scanFiles(); MarbleZipReader::Status status; }; class MarbleZipWriterPrivate : public QZipPrivate { public: MarbleZipWriterPrivate(QIODevice *device, bool ownDev) : QZipPrivate(device, ownDev), status(MarbleZipWriter::NoError), permissions(QFile::ReadOwner | QFile::WriteOwner), compressionPolicy(MarbleZipWriter::AlwaysCompress) { } MarbleZipWriter::Status status; QFile::Permissions permissions; MarbleZipWriter::CompressionPolicy compressionPolicy; enum EntryType { Directory, File, Symlink }; void addEntry(EntryType type, const QString &fileName, const QByteArray &contents); }; LocalFileHeader CentralFileHeader::toLocalHeader() const { LocalFileHeader h; writeUInt(h.signature, 0x04034b50); copyUShort(h.version_needed, version_needed); copyUShort(h.general_purpose_bits, general_purpose_bits); copyUShort(h.compression_method, compression_method); copyUInt(h.last_mod_file, last_mod_file); copyUInt(h.crc_32, crc_32); copyUInt(h.compressed_size, compressed_size); copyUInt(h.uncompressed_size, uncompressed_size); copyUShort(h.file_name_length, file_name_length); copyUShort(h.extra_field_length, extra_field_length); return h; } void MarbleZipReaderPrivate::scanFiles() { if (!dirtyFileTree) return; if (! (device->isOpen() || device->open(QIODevice::ReadOnly))) { status = MarbleZipReader::FileOpenError; return; } if ((device->openMode() & QIODevice::ReadOnly) == 0) { // only read the index from readable files. status = MarbleZipReader::FileReadError; return; } dirtyFileTree = false; uchar tmp[4]; device->read((char *)tmp, 4); if (readUInt(tmp) != 0x04034b50) { qWarning() << "QZip: not a zip file!"; return; } // find EndOfDirectory header int i = 0; int start_of_directory = -1; int num_dir_entries = 0; EndOfDirectory eod; while (start_of_directory == -1) { int pos = device->size() - sizeof(EndOfDirectory) - i; if (pos < 0 || i > 65535) { qWarning() << "QZip: EndOfDirectory not found"; return; } device->seek(pos); device->read((char *)&eod, sizeof(EndOfDirectory)); if (readUInt(eod.signature) == 0x06054b50) break; ++i; } // have the eod start_of_directory = readUInt(eod.dir_start_offset); num_dir_entries = readUShort(eod.num_dir_entries); ZDEBUG("start_of_directory at %d, num_dir_entries=%d", start_of_directory, num_dir_entries); int comment_length = readUShort(eod.comment_length); if (comment_length != i) qWarning() << "QZip: failed to parse zip file."; comment = device->read(qMin(comment_length, i)); device->seek(start_of_directory); for (i = 0; i < num_dir_entries; ++i) { FileHeader header; int read = device->read((char *) &header.h, sizeof(CentralFileHeader)); if (read < (int)sizeof(CentralFileHeader)) { qWarning() << "QZip: Failed to read complete header, index may be incomplete"; break; } if (readUInt(header.h.signature) != 0x02014b50) { qWarning() << "QZip: invalid header signature, index may be incomplete"; break; } int l = readUShort(header.h.file_name_length); header.file_name = device->read(l); if (header.file_name.length() != l) { qWarning() << "QZip: Failed to read filename from zip index, index may be incomplete"; break; } l = readUShort(header.h.extra_field_length); header.extra_field = device->read(l); if (header.extra_field.length() != l) { qWarning() << "QZip: Failed to read extra field in zip file, skipping file, index may be incomplete"; break; } l = readUShort(header.h.file_comment_length); header.file_comment = device->read(l); if (header.file_comment.length() != l) { - qWarning() << "QZip: Failed to read read file comment, index may be incomplete"; + qWarning() << "QZip: Failed to read file comment, index may be incomplete"; break; } ZDEBUG("found file '%s'", header.file_name.data()); fileHeaders.append(header); } } void MarbleZipWriterPrivate::addEntry(EntryType type, const QString &fileName, const QByteArray &contents/*, QFile::Permissions permissions, QZip::Method m*/) { #ifndef NDEBUG static const char *entryTypes[] = { "directory", "file ", "symlink " }; ZDEBUG() << "adding" << entryTypes[type] <<":" << fileName.toUtf8().data() << (type == 2 ? QByteArray(" -> " + contents).constData() : ""); #endif if (! (device->isOpen() || device->open(QIODevice::WriteOnly))) { status = MarbleZipWriter::FileOpenError; return; } device->seek(start_of_directory); // don't compress small files MarbleZipWriter::CompressionPolicy compression = compressionPolicy; if (compressionPolicy == MarbleZipWriter::AutoCompress) { if (contents.length() < 64) compression = MarbleZipWriter::NeverCompress; else compression = MarbleZipWriter::AlwaysCompress; } FileHeader header; memset(&header.h, 0, sizeof(CentralFileHeader)); writeUInt(header.h.signature, 0x02014b50); writeUShort(header.h.version_needed, 0x14); writeUInt(header.h.uncompressed_size, contents.length()); writeMSDosDate(header.h.last_mod_file, QDateTime::currentDateTime()); QByteArray data = contents; if (compression == MarbleZipWriter::AlwaysCompress) { writeUShort(header.h.compression_method, 8); ulong len = contents.length(); // shamelessly copied form zlib len += (len >> 12) + (len >> 14) + 11; int res; do { data.resize(len); res = deflate((uchar*)data.data(), &len, (const uchar*)contents.constData(), contents.length()); switch (res) { case Z_OK: data.resize(len); break; case Z_MEM_ERROR: qWarning("QZip: Z_MEM_ERROR: Not enough memory to compress file, skipping"); data.resize(0); break; case Z_BUF_ERROR: len *= 2; break; } } while (res == Z_BUF_ERROR); } // TODO add a check if data.length() > contents.length(). Then try to store the original and revert the compression method to be uncompressed writeUInt(header.h.compressed_size, data.length()); uint crc_32 = ::crc32(0, 0, 0); crc_32 = ::crc32(crc_32, (const uchar *)contents.constData(), contents.length()); writeUInt(header.h.crc_32, crc_32); header.file_name = fileName.toLocal8Bit(); if (header.file_name.size() > 0xffff) { qWarning("QZip: Filename too long, chopping it to 65535 characters"); header.file_name = header.file_name.left(0xffff); } writeUShort(header.h.file_name_length, header.file_name.length()); //h.extra_field_length[2]; writeUShort(header.h.version_made, 3 << 8); //uchar internal_file_attributes[2]; //uchar external_file_attributes[4]; quint32 mode = permissionsToMode(permissions); switch (type) { case File: mode |= S_IFREG; break; case Directory: mode |= S_IFDIR; break; case Symlink: mode |= S_IFLNK; break; } writeUInt(header.h.external_file_attributes, mode << 16); writeUInt(header.h.offset_local_header, start_of_directory); fileHeaders.append(header); LocalFileHeader h = header.h.toLocalHeader(); device->write((const char *)&h, sizeof(LocalFileHeader)); device->write(header.file_name); device->write(data); start_of_directory = device->pos(); dirtyFileTree = true; } ////////////////////////////// Reader /*! \class QZipReader::FileInfo \internal Represents one entry in the zip table of contents. */ /*! \variable FileInfo::filePath The full filepath inside the archive. */ /*! \variable FileInfo::isDir A boolean type indicating if the entry is a directory. */ /*! \variable FileInfo::isFile A boolean type, if it is one this entry is a file. */ /*! \variable FileInfo::isSymLink A boolean type, if it is one this entry is symbolic link. */ /*! \variable FileInfo::permissions A list of flags for the permissions of this entry. */ /*! \variable FileInfo::crc32 The calculated checksum as a crc32 type. */ /*! \variable FileInfo::size The total size of the unpacked content. */ /*! \variable FileInfo::d \internal private pointer. */ /*! \class QZipReader \internal \since 4.5 \brief the QZipReader class provides a way to inspect the contents of a zip archive and extract individual files from it. QZipReader can be used to read a zip archive either from a file or from any device. An in-memory QBuffer for instance. The reader can be used to read which files are in the archive using fileInfoList() and entryInfoAt() but also to extract individual files using fileData() or even to extract all files in the archive using extractAll() */ /*! Create a new zip archive that operates on the \a fileName. The file will be opened with the \a mode. */ MarbleZipReader::MarbleZipReader(const QString &archive, QIODevice::OpenMode mode) { QScopedPointer f(new QFile(archive)); f->open(mode); MarbleZipReader::Status status; if (f->error() == QFile::NoError) status = NoError; else { if (f->error() == QFile::ReadError) status = FileReadError; else if (f->error() == QFile::OpenError) status = FileOpenError; else if (f->error() == QFile::PermissionsError) status = FilePermissionsError; else status = FileError; } d = new MarbleZipReaderPrivate(f.data(), /*ownDevice=*/true); f.take(); d->status = status; } /*! Create a new zip archive that operates on the archive found in \a device. You have to open the device previous to calling the constructor and only a device that is readable will be scanned for zip filecontent. */ MarbleZipReader::MarbleZipReader(QIODevice *device) : d(new MarbleZipReaderPrivate(device, /*ownDevice=*/false)) { Q_ASSERT(device); } /*! Desctructor */ MarbleZipReader::~MarbleZipReader() { close(); delete d; } /*! Returns device used for reading zip archive. */ QIODevice* MarbleZipReader::device() const { return d->device; } /*! Returns true if the user can read the file; otherwise returns false. */ bool MarbleZipReader::isReadable() const { return d->device->isReadable(); } /*! Returns true if the file exists; otherwise returns false. */ bool MarbleZipReader::exists() const { QFile *f = qobject_cast (d->device); if (f == 0) return true; return f->exists(); } /*! Returns the list of files the archive contains. */ QList MarbleZipReader::fileInfoList() const { d->scanFiles(); QList files; for (int i = 0; i < d->fileHeaders.size(); ++i) { MarbleZipReader::FileInfo fi; d->fillFileInfo(i, fi); files.append(fi); } return files; } /*! Return the number of items in the zip archive. */ int MarbleZipReader::count() const { d->scanFiles(); return d->fileHeaders.count(); } /*! Returns a FileInfo of an entry in the zipfile. The \a index is the index into the directory listing of the zipfile. Returns an invalid FileInfo if \a index is out of boundaries. \sa fileInfoList() */ MarbleZipReader::FileInfo MarbleZipReader::entryInfoAt(int index) const { d->scanFiles(); MarbleZipReader::FileInfo fi; if (index >= 0 && index < d->fileHeaders.count()) d->fillFileInfo(index, fi); return fi; } /*! Fetch the file contents from the zip archive and return the uncompressed bytes. */ QByteArray MarbleZipReader::fileData(const QString &fileName) const { d->scanFiles(); int i; for (i = 0; i < d->fileHeaders.size(); ++i) { if (QString::fromLocal8Bit(d->fileHeaders.at(i).file_name) == fileName) break; } if (i == d->fileHeaders.size()) return QByteArray(); FileHeader header = d->fileHeaders.at(i); int compressed_size = readUInt(header.h.compressed_size); int uncompressed_size = readUInt(header.h.uncompressed_size); int start = readUInt(header.h.offset_local_header); //qDebug("uncompressing file %d: local header at %d", i, start); d->device->seek(start); LocalFileHeader lh; d->device->read((char *)&lh, sizeof(LocalFileHeader)); uint skip = readUShort(lh.file_name_length) + readUShort(lh.extra_field_length); d->device->seek(d->device->pos() + skip); int compression_method = readUShort(lh.compression_method); //qDebug("file=%s: compressed_size=%d, uncompressed_size=%d", fileName.toLocal8Bit().data(), compressed_size, uncompressed_size); //qDebug("file at %lld", d->device->pos()); QByteArray compressed = d->device->read(compressed_size); if (compression_method == 0) { // no compression compressed.truncate(uncompressed_size); return compressed; } else if (compression_method == 8) { // Deflate //qDebug("compressed=%d", compressed.size()); compressed.truncate(compressed_size); QByteArray baunzip; ulong len = qMax(uncompressed_size, 1); int res; do { baunzip.resize(len); res = inflate((uchar*)baunzip.data(), &len, (uchar*)compressed.constData(), compressed_size); switch (res) { case Z_OK: if ((int)len != baunzip.size()) baunzip.resize(len); break; case Z_MEM_ERROR: qWarning("QZip: Z_MEM_ERROR: Not enough memory"); break; case Z_BUF_ERROR: len *= 2; break; case Z_DATA_ERROR: qWarning("QZip: Z_DATA_ERROR: Input data is corrupted"); break; } } while (res == Z_BUF_ERROR); return baunzip; } qWarning() << "QZip: Unknown compression method"; return QByteArray(); } /*! Extracts the full contents of the zip file into \a destinationDir on the local filesystem. In case writing or linking a file fails, the extraction will be aborted. */ bool MarbleZipReader::extractAll(const QString &destinationDir) const { QDir baseDir(destinationDir); // create directories first QList allFiles = fileInfoList(); for (const FileInfo& fi: allFiles) { const QString absPath = destinationDir + QDir::separator() + fi.filePath; if (fi.isDir) { if (!baseDir.mkpath(fi.filePath)) return false; if (!QFile::setPermissions(absPath, fi.permissions)) return false; } } // set up symlinks for (const FileInfo& fi: allFiles) { const QString absPath = destinationDir + QDir::separator() + fi.filePath; if (fi.isSymLink) { QString destination = QFile::decodeName(fileData(fi.filePath)); if (destination.isEmpty()) return false; QFileInfo linkFi(absPath); if (!QFile::exists(linkFi.absolutePath())) QDir::root().mkpath(linkFi.absolutePath()); if (!QFile::link(destination, absPath)) return false; /* cannot change permission of links if (!QFile::setPermissions(absPath, fi.permissions)) return false; */ } } for (const FileInfo& fi: allFiles) { const QString absPath = destinationDir + QDir::separator() + fi.filePath; if (fi.isFile) { QDir::root().mkpath(QFileInfo(absPath).dir().absolutePath()); QFile f(absPath); if (!f.open(QIODevice::WriteOnly)) return false; f.write(fileData(fi.filePath)); f.setPermissions(fi.permissions); f.close(); } } return true; } /*! \enum QZipReader::Status The following status values are possible: \value NoError No error occurred. \value FileReadError An error occurred when reading from the file. \value FileOpenError The file could not be opened. \value FilePermissionsError The file could not be accessed. \value FileError Another file error occurred. */ /*! Returns a status code indicating the first error that was met by QZipReader, or QZipReader::NoError if no error occurred. */ MarbleZipReader::Status MarbleZipReader::status() const { return d->status; } /*! Close the zip file. */ void MarbleZipReader::close() { d->device->close(); } ////////////////////////////// Writer /*! \class QZipWriter \internal \since 4.5 \brief the QZipWriter class provides a way to create a new zip archive. QZipWriter can be used to create a zip archive containing any number of files and directories. The files in the archive will be compressed in a way that is compatible with common zip reader applications. */ /*! Create a new zip archive that operates on the \a archive filename. The file will be opened with the \a mode. \sa isValid() */ MarbleZipWriter::MarbleZipWriter(const QString &fileName, QIODevice::OpenMode mode) { QScopedPointer f(new QFile(fileName)); f->open(mode); MarbleZipWriter::Status status; if (f->error() == QFile::NoError) status = MarbleZipWriter::NoError; else { if (f->error() == QFile::WriteError) status = MarbleZipWriter::FileWriteError; else if (f->error() == QFile::OpenError) status = MarbleZipWriter::FileOpenError; else if (f->error() == QFile::PermissionsError) status = MarbleZipWriter::FilePermissionsError; else status = MarbleZipWriter::FileError; } d = new MarbleZipWriterPrivate(f.data(), /*ownDevice=*/true); f.take(); d->status = status; } /*! Create a new zip archive that operates on the archive found in \a device. You have to open the device previous to calling the constructor and only a device that is readable will be scanned for zip filecontent. */ MarbleZipWriter::MarbleZipWriter(QIODevice *device) : d(new MarbleZipWriterPrivate(device, /*ownDevice=*/false)) { Q_ASSERT(device); } MarbleZipWriter::~MarbleZipWriter() { close(); delete d; } /*! Returns device used for writing zip archive. */ QIODevice* MarbleZipWriter::device() const { return d->device; } /*! Returns true if the user can write to the archive; otherwise returns false. */ bool MarbleZipWriter::isWritable() const { return d->device->isWritable(); } /*! Returns true if the file exists; otherwise returns false. */ bool MarbleZipWriter::exists() const { QFile *f = qobject_cast (d->device); if (f == 0) return true; return f->exists(); } /*! \enum QZipWriter::Status The following status values are possible: \value NoError No error occurred. \value FileWriteError An error occurred when writing to the device. \value FileOpenError The file could not be opened. \value FilePermissionsError The file could not be accessed. \value FileError Another file error occurred. */ /*! Returns a status code indicating the first error that was met by QZipWriter, or QZipWriter::NoError if no error occurred. */ MarbleZipWriter::Status MarbleZipWriter::status() const { return d->status; } /*! \enum QZipWriter::CompressionPolicy \value AlwaysCompress A file that is added is compressed. \value NeverCompress A file that is added will be stored without changes. \value AutoCompress A file that is added will be compressed only if that will give a smaller file. */ /*! Sets the policy for compressing newly added files to the new \a policy. \note the default policy is AlwaysCompress \sa compressionPolicy() \sa addFile() */ void MarbleZipWriter::setCompressionPolicy(CompressionPolicy policy) { d->compressionPolicy = policy; } /*! Returns the currently set compression policy. \sa setCompressionPolicy() \sa addFile() */ MarbleZipWriter::CompressionPolicy MarbleZipWriter::compressionPolicy() const { return d->compressionPolicy; } /*! Sets the permissions that will be used for newly added files. \note the default permissions are QFile::ReadOwner | QFile::WriteOwner. \sa creationPermissions() \sa addFile() */ void MarbleZipWriter::setCreationPermissions(QFile::Permissions permissions) { d->permissions = permissions; } /*! Returns the currently set creation permissions. \sa setCreationPermissions() \sa addFile() */ QFile::Permissions MarbleZipWriter::creationPermissions() const { return d->permissions; } /*! Add a file to the archive with \a data as the file contents. The file will be stored in the archive using the \a fileName which includes the full path in the archive. The new file will get the file permissions based on the current creationPermissions and it will be compressed using the zip compression based on the current compression policy. \sa setCreationPermissions() \sa setCompressionPolicy() */ void MarbleZipWriter::addFile(const QString &fileName, const QByteArray &data) { d->addEntry(MarbleZipWriterPrivate::File, QDir::fromNativeSeparators(fileName), data); } /*! Add a file to the archive with \a device as the source of the contents. The contents returned from QIODevice::readAll() will be used as the filedata. The file will be stored in the archive using the \a fileName which includes the full path in the archive. */ void MarbleZipWriter::addFile(const QString &fileName, QIODevice *device) { Q_ASSERT(device); QIODevice::OpenMode mode = device->openMode(); bool opened = false; if ((mode & QIODevice::ReadOnly) == 0) { opened = true; if (! device->open(QIODevice::ReadOnly)) { d->status = FileOpenError; return; } } d->addEntry(MarbleZipWriterPrivate::File, QDir::fromNativeSeparators(fileName), device->readAll()); if (opened) device->close(); } /*! Create a new directory in the archive with the specified \a dirName and the \a permissions; */ void MarbleZipWriter::addDirectory(const QString &dirName) { QString name(QDir::fromNativeSeparators(dirName)); // separator is mandatory if (!name.endsWith(QLatin1Char('/'))) name.append(QLatin1Char('/')); d->addEntry(MarbleZipWriterPrivate::Directory, name, QByteArray()); } /*! Create a new symbolic link in the archive with the specified \a dirName and the \a permissions; A symbolic link contains the destination (relative) path and name. */ void MarbleZipWriter::addSymLink(const QString &fileName, const QString &destination) { d->addEntry(MarbleZipWriterPrivate::Symlink, QDir::fromNativeSeparators(fileName), QFile::encodeName(destination)); } /*! Closes the zip file. */ void MarbleZipWriter::close() { if (!(d->device->openMode() & QIODevice::WriteOnly)) { d->device->close(); return; } //qDebug("QZip::close writing directory, %d entries", d->fileHeaders.size()); d->device->seek(d->start_of_directory); // write new directory for (int i = 0; i < d->fileHeaders.size(); ++i) { const FileHeader &header = d->fileHeaders.at(i); d->device->write((const char *)&header.h, sizeof(CentralFileHeader)); d->device->write(header.file_name); d->device->write(header.extra_field); d->device->write(header.file_comment); } int dir_size = d->device->pos() - d->start_of_directory; // write end of directory EndOfDirectory eod; memset(&eod, 0, sizeof(EndOfDirectory)); writeUInt(eod.signature, 0x06054b50); //uchar this_disk[2]; //uchar start_of_directory_disk[2]; writeUShort(eod.num_dir_entries_this_disk, d->fileHeaders.size()); writeUShort(eod.num_dir_entries, d->fileHeaders.size()); writeUInt(eod.directory_size, dir_size); writeUInt(eod.dir_start_offset, d->start_of_directory); writeUShort(eod.comment_length, d->comment.length()); d->device->write((const char *)&eod, sizeof(EndOfDirectory)); d->device->write(d->comment); d->device->close(); } } #endif // QT_NO_TEXTODFWRITER diff --git a/tools/osm-addresses/pbf/osmformat.proto b/tools/osm-addresses/pbf/osmformat.proto index f919bacc0..18084e54e 100644 --- a/tools/osm-addresses/pbf/osmformat.proto +++ b/tools/osm-addresses/pbf/osmformat.proto @@ -1,260 +1,260 @@ /** Copyright (c) 2010 Scott A. Crosby. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ option optimize_for = LITE_RUNTIME; option java_package = "crosby.binary"; package OSMPBF; /* OSM Binary file format This is the master schema file of the OSM binary file format. This file is designed to support limited random-access and future extendability. A binary OSM file consists of a sequence of FileBlocks (please see fileformat.proto). The first fileblock contains a serialized instance of HeaderBlock, followed by a sequence of PrimitiveBlock blocks that contain the primitives. Each primitiveblock is designed to be independently parsable. It contains a string table storing all strings in that block (keys and values in tags, roles in relations, usernames, etc.) as well as metadata containing the precision of coordinates or timestamps in that block. A primitiveblock contains a sequence of primitive groups, each containing primitives of the same type (nodes, densenodes, ways, relations). Coordinates are stored in signed 64-bit integers. Lat&lon are measured in units nanodegrees. The default of granularity of 100 nanodegrees corresponds to about 1cm on the ground, and a full lat or lon fits into 32 bits. Converting an integer to a lattitude or longitude uses the formula: $OUT = IN * granularity / 10**9$. Many encoding schemes use delta coding when representing nodes and relations. */ ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /* Contains the file header. */ message HeaderBlock { optional HeaderBBox bbox = 1; /* Additional tags to aid in parsing this dataset */ repeated string required_features = 4; repeated string optional_features = 5; optional string writingprogram = 16; optional string source = 17; // From the bbox field. /* Tags that allow continuing an Osmosis replication */ // replication timestamp, expressed in seconds since the epoch, // otherwise the same value as in the "timestamp=..." field // in the state.txt file used by Osmosis optional int64 osmosis_replication_timestamp = 32; // replication sequence number (sequenceNumber in state.txt) optional int64 osmosis_replication_sequence_number = 33; // replication base URL (from Osmosis' configuration.txt file) optional string osmosis_replication_base_url = 34; } /** The bounding box field in the OSM header. BBOX, as used in the OSM header. Units are always in nanodegrees -- they do not obey granularity rules. */ message HeaderBBox { required sint64 left = 1; required sint64 right = 2; required sint64 top = 3; required sint64 bottom = 4; } /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// message PrimitiveBlock { required StringTable stringtable = 1; repeated PrimitiveGroup primitivegroup = 2; // Granularity, units of nanodegrees, used to store coordinates in this block optional int32 granularity = 17 [default=100]; - // Offset value between the output coordinates coordinates and the granularity grid in unites of nanodegrees. + // Offset value between the output coordinates and the granularity grid in unites of nanodegrees. optional int64 lat_offset = 19 [default=0]; optional int64 lon_offset = 20 [default=0]; // Granularity of dates, normally represented in units of milliseconds since the 1970 epoch. optional int32 date_granularity = 18 [default=1000]; // Proposed extension: //optional BBox bbox = XX; } // Group of OSMPrimitives. All primitives in a group must be the same type. message PrimitiveGroup { repeated Node nodes = 1; optional DenseNodes dense = 2; repeated Way ways = 3; repeated Relation relations = 4; repeated ChangeSet changesets = 5; } /** String table, contains the common strings in each block. Note that we reserve index '0' as a delimiter, so the entry at that index in the table is ALWAYS blank and unused. */ message StringTable { repeated bytes s = 1; } /* Optional metadata that may be included into each primitive. */ message Info { optional int32 version = 1 [default = -1]; optional int64 timestamp = 2; optional int64 changeset = 3; optional int32 uid = 4; optional uint32 user_sid = 5; // String IDs // The visible flag is used to store history information. It indicates that // the current object version has been created by a delete operation on the // OSM API. // When a writer sets this flag, it MUST add a required_features tag with // value "HistoricalInformation" to the HeaderBlock. // If this flag is not available for some object it MUST be assumed to be // true if the file has the required_features tag "HistoricalInformation" // set. optional bool visible = 6; } /** Optional metadata that may be included into each primitive. Special dense format used in DenseNodes. */ message DenseInfo { repeated int32 version = 1 [packed = true]; repeated sint64 timestamp = 2 [packed = true]; // DELTA coded repeated sint64 changeset = 3 [packed = true]; // DELTA coded repeated sint32 uid = 4 [packed = true]; // DELTA coded repeated sint32 user_sid = 5 [packed = true]; // String IDs for usernames. DELTA coded // The visible flag is used to store history information. It indicates that // the current object version has been created by a delete operation on the // OSM API. // When a writer sets this flag, it MUST add a required_features tag with // value "HistoricalInformation" to the HeaderBlock. // If this flag is not available for some object it MUST be assumed to be // true if the file has the required_features tag "HistoricalInformation" // set. repeated bool visible = 6 [packed = true]; } // THIS IS STUB DESIGN FOR CHANGESETS. NOT USED RIGHT NOW. // TODO: REMOVE THIS? message ChangeSet { required int64 id = 1; // // // Parallel arrays. // repeated uint32 keys = 2 [packed = true]; // String IDs. // repeated uint32 vals = 3 [packed = true]; // String IDs. // // optional Info info = 4; // optional int64 created_at = 8; // optional int64 closetime_delta = 9; // optional bool open = 10; // optional HeaderBBox bbox = 11; } message Node { required sint64 id = 1; // Parallel arrays. repeated uint32 keys = 2 [packed = true]; // String IDs. repeated uint32 vals = 3 [packed = true]; // String IDs. optional Info info = 4; // May be omitted in omitmeta required sint64 lat = 8; required sint64 lon = 9; } /* Used to densly represent a sequence of nodes that do not have any tags. We represent these nodes columnwise as five columns: ID's, lats, and lons, all delta coded. When metadata is not omitted, We encode keys & vals for all nodes as a single array of integers containing key-stringid and val-stringid, using a stringid of 0 as a delimiter between nodes. ( ( )* '0' )* */ message DenseNodes { repeated sint64 id = 1 [packed = true]; // DELTA coded //repeated Info info = 4; optional DenseInfo denseinfo = 5; repeated sint64 lat = 8 [packed = true]; // DELTA coded repeated sint64 lon = 9 [packed = true]; // DELTA coded // Special packing of keys and vals into one array. May be empty if all nodes in this block are tagless. repeated int32 keys_vals = 10 [packed = true]; } message Way { required int64 id = 1; // Parallel arrays. repeated uint32 keys = 2 [packed = true]; repeated uint32 vals = 3 [packed = true]; optional Info info = 4; repeated sint64 refs = 8 [packed = true]; // DELTA coded } message Relation { enum MemberType { NODE = 0; WAY = 1; RELATION = 2; } required int64 id = 1; // Parallel arrays. repeated uint32 keys = 2 [packed = true]; repeated uint32 vals = 3 [packed = true]; optional Info info = 4; // Parallel arrays repeated int32 roles_sid = 8 [packed = true]; repeated sint64 memids = 9 [packed = true]; // DELTA encoded repeated MemberType types = 10 [packed = true]; }