Skip to content

Instantly share code, notes, and snippets.

@ryanbugden
Created July 24, 2023 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanbugden/6ac0a581fca711057b956513267b3d17 to your computer and use it in GitHub Desktop.
Save ryanbugden/6ac0a581fca711057b956513267b3d17 to your computer and use it in GitHub Desktop.
Adds a Close All Fonts menu item
from AppKit import NSApp, NSMenuItem, NSAlternateKeyMask, NSCommandKeyMask
from mojo.tools import CallbackWrapper
from mojo.subscriber import Subscriber, registerRoboFontSubscriber
from mojo.UI import PutFile, AskYesNoCancel
class close_all_fonts_menu_item(Subscriber):
'''
A startup script that places a menu item in the File dropdown menu.
Clicking this item will Close All Fonts and disregard any other
types of unsaved documents like scripts.
Ryan Bugden
'''
def build(self):
# Inject the menu item
title = 'Close All Fonts'
self.main_menu = NSApp().mainMenu()
font_menu = self.main_menu.itemWithTitle_('File')
if not font_menu:
print('Close All Fonts Menu Item - Error')
return
font_menu = font_menu.submenu()
if font_menu.itemWithTitle_(title):
return
index = font_menu.indexOfItemWithTitle_('Close')
self.target = CallbackWrapper(self.close_all_fonts)
self.new_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(title, 'action:', '')
self.new_item.setTarget_(self.target)
font_menu.insertItem_atIndex_(self.new_item, index+1)
def close_all_fonts(self, sender):
for f in AllFonts():
# If the font hasn’t been saved (including if it’s a brand new one and therefore doesn't have a path.)
if f.path == None or f.hasChanged():
message_name = f.fontWindow().w.getNSWindow().title()
save_choice = AskYesNoCancel(
f'Do you want to save {message_name} before closing it?',
title='Save before closing?',
default=1,
informativeText='Your changes will be lost if you don’t save them.'
)
# Yes
if save_choice == 1:
self.save_and_close(f, f.path)
# No
elif save_choice == 0:
f.close()
# Cancel does nothing.
# If the font is already saved, close it.
else:
f.close()
def save_and_close(self, f, path):
# If there is not yet a path for the font, let’s choose one.
if not path:
if f.info.familyName and f.info.styleName:
message_name = f'{f.info.familyName} {f.info.styleName}'
file_name = f'{f.info.familyName.replace(" ", "_")}-{f.info.styleName.replace(" ", "_")}.ufo'
else:
message_name = f.fontWindow().w.getNSWindow().title()
file_name = message_name.replace(" ", "_") + '.ufo'
path = PutFile(f'Save {message_name} as...', file_name)
f.save(path)
f.close()
if __name__ == '__main__':
registerRoboFontSubscriber(close_all_fonts_menu_item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment