Skip to content

Instantly share code, notes, and snippets.

@connordavenport
Created September 16, 2023 16:18
Show Gist options
  • Save connordavenport/6e401c4b2912c7ec1f9e90199c901e1a to your computer and use it in GitHub Desktop.
Save connordavenport/6e401c4b2912c7ec1f9e90199c901e1a to your computer and use it in GitHub Desktop.
Fit the current space center text to the view width, it measures the longest line (broken up by newlines) and scales it based on that.
from mojo.UI import CurrentSpaceCenter
def measureLine(pointSize, records):
scale = pointSize / window.font.info.unitsPerEm
sublists = []
currentSublist = []
lineBreakChar = "NewLineGlyph"
for item in records:
if item.glyph.objectName == lineBreakChar:
if currentSublist:
sublists.append(currentSublist)
currentSublist = [item]
else:
currentSublist.append(item)
if currentSublist:
sublists.append(currentSublist)
allLines = []
for line in sublists:
lineWidth = 0
for record in line:
gsWidth = 0
gsWidth += record.glyph.width
gsWidth += record.xPlacement
gsWidth += record.xAdvance
lineWidth += gsWidth*scale
allLines.append(lineWidth)
return allLines
debug = False
window = CurrentSpaceCenter()
view = window.glyphLineView.getNSScrollView()
frame = view.frame().size
width = frame.width
nps = ps = window.getPointSize()
m = max(measureLine(ps, window.glyphRecords))
if m > width:
if debug: print("make smaller")
while m > width - 50:
nps -= 1
m = max(measureLine(nps, window.glyphRecords))
else:
if debug: print("make bigger")
while m < width - 50:
nps += 1
m = max(measureLine(nps, window.glyphRecords))
window.setPointSize(nps)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment