Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
simplify zoom lookup
use min() instead of the index/loop approach
  • Loading branch information
flimsyhat committed Jun 4, 2025
commit 2610099f2cbe7a3641c3e022b45cc49c695bf3c8
39 changes: 13 additions & 26 deletions plotdevice/gui/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,38 +149,25 @@ def _set_zoom(self, zoom):
zoom = property(_get_zoom, _set_zoom)

@objc.python_method
def findNearestZoomIndex(self, zoom):
"""Returns the nearest zoom level, and whether we found a direct, exact
match or a fuzzy match."""
try: # Search for a direct hit first.
idx = self.zoomLevels.index(zoom)
return idx, True
except ValueError: # Can't find the zoom level, try looking at the indexes.
idx = 0
try:
while self.zoomLevels[idx] < zoom:
idx += 1
except KeyError: # End of the list
idx = len(self.zoomLevels) - 1 # Just return the last index.
return idx, False
def _findNearestZoomLevel(self, zoom):
"""Find the nearest zoom level to the given zoom value"""
return min(self.zoomLevels, key=lambda x: abs(x - zoom))

@IBAction
def zoomIn_(self, sender):
idx, direct = self.findNearestZoomIndex(self.zoom)
# Direct hits are perfect, but indirect hits require a bit of help.
# Because of the way indirect hits are calculated, they are already
# rounded up to the upper zoom level; this means we don't need to add 1.
if direct:
idx += 1
idx = max(min(idx, len(self.zoomLevels)-1), 0)
self.zoom = self.zoomLevels[idx]
"""Zoom in one level"""
current = self._findNearestZoomLevel(self.zoom)
idx = self.zoomLevels.index(current)
new_idx = min(idx + 1, len(self.zoomLevels) - 1)
self.zoom = self.zoomLevels[new_idx]

@IBAction
def zoomOut_(self, sender):
idx, direct = self.findNearestZoomIndex(self.zoom)
idx -= 1
idx = max(min(idx, len(self.zoomLevels)-1), 0)
self.zoom = self.zoomLevels[idx]
"""Zoom out one level"""
current = self._findNearestZoomLevel(self.zoom)
idx = self.zoomLevels.index(current)
new_idx = max(idx - 1, 0)
self.zoom = self.zoomLevels[new_idx]

@IBAction
def resetZoom_(self, sender):
Expand Down