def changeTextFont_(self, sender): "The user changed the current font selection, so update the default font" # Get font name and size from user defaults defaults = NSUserDefaultsController.sharedUserDefaultsController().values() fontName = getKey(defaults, 'FontName') fontSize = getKey(defaults, 'FontSize') # Create font from name and size; initialize font panel font = NSFont.fontWithName_size_(fontName, fontSize) if font is None: font = NSFont.systemFontOfSize_(NSFont.systemFontSize()) NSFontManager.sharedFontManager().setSelectedFont_isMultiple_(font, False) NSFontManager.sharedFontManager().orderFrontFontPanel_(self) # Set window as firstResponder so we get changeFont: messages self.window().makeFirstResponder_(self.window())
def show_context(self, options, x, y): y = self.frame().size.height - y menu = DropboxNSMenu.menuWithDropboxMenuDescriptor_(options) if MAC_VERSION >= SNOW_LEOPARD: menu.popUpMenuPositioningItem_atLocation_inView_(None, NSMakePoint(x, y), self) return fake_event = NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_(NSLeftMouseDown, NSMakePoint(x, y), 0, 0, self.window().windowNumber(), None, 0, 0, 0) NSMenu.popUpContextMenu_withEvent_forView_withFont_(menu, fake_event, self, NSFont.systemFontOfSize_(12.75))
def changeFont_(self, sender): "This is the message the font panel sends when a new font is selected" # Get selected font fontManager = NSFontManager.sharedFontManager() selectedFont = fontManager.selectedFont() if selectedFont is None: selectedFont = NSFont.systemFontOfSize_(NSFont.systemFontSize()) panelFont = fontManager.convertFont_(selectedFont) # Get and store details of selected font # Note: use fontName, not displayName. The font name identifies the font to # the system, we use a value transformer to show the user the display name fontSize = panelFont.pointSize() defaults = NSUserDefaultsController.sharedUserDefaultsController().values() defaults.setValue_forKey_(panelFont.fontName(), "FontName") defaults.setValue_forKey_(fontSize, "FontSize")
def changeFont_(self, sender): "This is the message the font panel sends when a new font is selected" # Get selected font fontManager = NSFontManager.sharedFontManager() selectedFont = fontManager.selectedFont() if selectedFont is None: selectedFont = NSFont.systemFontOfSize_(NSFont.systemFontSize()) panelFont = fontManager.convertFont_(selectedFont) # Get and store details of selected font # Note: use fontName, not displayName. The font name identifies the font to # the system, we use a value transformer to show the user the display name fontSize = panelFont.pointSize() defaults = NSUserDefaultsController.sharedUserDefaultsController( ).values() defaults.setValue_forKey_(panelFont.fontName(), "FontName") defaults.setValue_forKey_(fontSize, "FontSize")
def changeTextFont_(self, sender): "The user changed the current font selection, so update the default font" # Get font name and size from user defaults defaults = NSUserDefaultsController.sharedUserDefaultsController( ).values() fontName = getKey(defaults, "FontName") fontSize = getKey(defaults, "FontSize") # Create font from name and size; initialize font panel font = NSFont.fontWithName_size_(fontName, fontSize) if font is None: font = NSFont.systemFontOfSize_(NSFont.systemFontSize()) NSFontManager.sharedFontManager().setSelectedFont_isMultiple_( font, False) NSFontManager.sharedFontManager().orderFrontFontPanel_(self) # Set window as firstResponder so we get changeFont: messages self.window().makeFirstResponder_(self.window())
def awakeFromNib(self): self.setFont_(NSFont.userFixedPitchFontOfSize_(10)) self.p_colors = { "stderr": NSColor.redColor(), "stdout": NSColor.blueColor(), "code": NSColor.blackColor(), } self.setHistoryLength_(50) self.setHistoryView_(0) self.setInteracting_(False) self.setAutoScroll_(True) self.setSingleLineInteraction_(False) self.p_history = [""] self.p_input_callbacks = [] self.p_input_lines = [] self.setupTextView() self.interpreter.connect()
def awakeFromNib(self): self = super(PyInterpreter, self).init() self._font = NSFont.userFixedPitchFontOfSize_(10) self._stderrColor = NSColor.redColor() self._stdoutColor = NSColor.blueColor() self._codeColor = NSColor.blackColor() self._historyLength = 50 self._history = [""] self._historyView = 0 self._characterIndexForInput = 0 self._stdin = PseudoUTF8Input(self._nestedRunLoopReaderUntilEOLchars_) # self._stdin = PseudoUTF8Input(self.readStdin) self._stderr = PseudoUTF8Output(self.writeStderr_) self._stdout = PseudoUTF8Output(self.writeStdout_) self._isInteracting = False self._console = AsyncInteractiveConsole() self._interp = self._console.asyncinteract(write=self.writeCode_).next self._autoscroll = True self.applicationDidFinishLaunching_(None)
def awakeFromNib(self): self = super(PyInterpreter, self).init() self._font = NSFont.userFixedPitchFontOfSize_(10) self._stderrColor = NSColor.redColor() self._stdoutColor = NSColor.blueColor() self._codeColor = NSColor.blackColor() self._historyLength = 50 self._history = [''] self._historyView = 0 self._characterIndexForInput = 0 self._stdin = PseudoUTF8Input(self._nestedRunLoopReaderUntilEOLchars_) #self._stdin = PseudoUTF8Input(self.readStdin) self._stderr = PseudoUTF8Output(self.writeStderr_) self._stdout = PseudoUTF8Output(self.writeStdout_) self._isInteracting = False self._console = AsyncInteractiveConsole() self._interp = partial(next, self._console.asyncinteract( write=self.writeCode_, )) self._autoscroll = True
def set_title(self, title): self.title = title if title is not None: # This is hacky, but works # https://github.com/jaredks/rumps/issues/30 fg_color = NSColor.systemOrangeColor() bg_color = NSColor.darkGrayColor() font = NSFont.menuBarFontOfSize_(0) attributes = propertyListFromPythonCollection( { NSForegroundColorAttributeName: fg_color, NSBackgroundColorAttributeName: bg_color, NSFontAttributeName: font, }, conversionHelper=lambda x: x, ) string = NSAttributedString.alloc().initWithString_attributes_( " " + title, attributes) self._nsapp.nsstatusitem.setAttributedTitle_(string)
def build_lastfm_menu(self) -> List[Any]: def login_lastfm(_): self.title = f"{Icons.music} Logging into Last.fm, check your browser..." self.lastfm.make_session() self.set_scrobbling(True) self.refresh_menu() def logout_lastfm(_): self.lastfm.reset() self.refresh_menu() def toggle_scrobbling(_): self.set_scrobbling(not self.scrobble) self.refresh() self.refresh_menu() if not self.lastfm.username: self.set_scrobbling(False) return [ 'Not logged in.', None, rumps.MenuItem('Log in with Last.fm...', callback=login_lastfm) ] history = ['No tracks scrobbled yet...'] if self.history: history = ['Last 5 Scrobbles'] for itm in reversed(self.history[-5:]): history.append( make_font(f'• {itm}', NSFont.menuFontOfSize_(12.0))) scrobble_enabled = rumps.MenuItem('Enable scrobbling', callback=toggle_scrobbling) scrobble_enabled.state = self.scrobble return [ f'Logged in as {self.lastfm.username}', scrobble_enabled, None, *history, None, rumps.MenuItem('Log out...', callback=logout_lastfm) ]
def drawRect_(self, rect): defaults = NSUserDefaultsController.sharedUserDefaultsController().values() favoriteColor = NSUnarchiver.unarchiveObjectWithData_(getKey(defaults, 'FavoriteColor')) fontName = getKey(defaults, 'FontName') fontSize = getKey(defaults, 'FontSize') favoriteFont = NSFont.fontWithName_size_(fontName, fontSize) wordOfTheDay = getKey(defaults, 'WordOfTheDay') # Do the actual drawing myBounds = self.bounds() # = (x, y), (bw, bh) NSDrawLightBezel(myBounds, myBounds) favoriteColor.set() NSRectFill(NSInsetRect(myBounds, 2, 2)) attrsDictionary = {NSFontAttributeName: favoriteFont} attrString = NSAttributedString.alloc().initWithString_attributes_(wordOfTheDay, attrsDictionary) attrSize = attrString.size() # = (bw, bh) attrString.drawAtPoint_( NSMakePoint( (attrSize.width / -2) + (myBounds.size.width / 2), (attrSize.height / -2) + (myBounds.size.height / 2), ), )
def set_title(self, title, color_list=None): self.title = title if color_list is None: color_list = self.default_color_list if title is not None: if self.truncate and len(title) > 40: title = title[:37] + '...' # This is hacky, but works # https://github.com/jaredks/rumps/issues/30 color = NSColor.colorWithCalibratedRed_green_blue_alpha_( color_list[0] / 255, color_list[1] / 255, color_list[2] / 255, color_list[3]) font = NSFont.menuBarFontOfSize_(0) attributes = propertyListFromPythonCollection( { NSForegroundColorAttributeName: color, NSFontAttributeName: font }, conversionHelper=lambda x: x) string = NSAttributedString.alloc().initWithString_attributes_( ' ' + title, attributes) self._nsapp.nsstatusitem.setAttributedTitle_(string)
def transformedValue_(self, aValue): font = NSFont.fontWithName_size_(aValue, 12) return font.displayName()
def make_attributed_string(text, font=NSFont.menuFontOfSize_(0.0)): attributes = propertyListFromPythonCollection({NSFontAttributeName: font}, conversionHelper=lambda x: x) return NSAttributedString.alloc().initWithString_attributes_( text, attributes)
# Get and store details of selected font # Note: use fontName, not displayName. The font name identifies the font to # the system, we use a value transformer to show the user the display name fontSize = panelFont.pointSize() defaults = NSUserDefaultsController.sharedUserDefaultsController().values() defaults.setValue_forKey_(panelFont.fontName(), "FontName") defaults.setValue_forKey_(fontSize, "FontSize") # Set up initial values for defaults: # Create dictionary with keys and values for WordOfTheDay, FontName, # FontSize, and FavoriteColor. Mostly straightforward, but: # # Store the fontName of the font as the default; the textfield displays # the font's displayName using a value transformer. # # The color must be archived -- you can't store NSColors directly in NSUserDefaults. dictionary = {} dictionary['WordOfTheDay'] = 'Today' systemFont = NSFont.systemFontOfSize_(NSFont.systemFontSize()) dictionary["FontName"] = systemFont.fontName() dictionary["FontSize"] = systemFont.pointSize() archivedColor = NSArchiver.archivedDataWithRootObject_(NSColor.greenColor()) dictionary['FavoriteColor'] = archivedColor NSUserDefaultsController.sharedUserDefaultsController().setInitialValues_(dictionary) # Create and register font name value transformer transformer = FontNameToDisplayNameTransformer.alloc().init() NSValueTransformer.setValueTransformer_forName_(transformer, 'FontNameToDisplayNameTransformer')
import rumps import speedtest as st from AppKit import NSAttributedString from PyObjCTools.Conversion import propertyListFromPythonCollection from Cocoa import (NSFont, NSFontAttributeName, NSColor, NSForegroundColorAttributeName) font = NSFont.fontWithName_size_("Monaco", 11.0) red = NSColor.redColor() yellow = NSColor.yellowColor() green = NSColor.greenColor() class SpeedTestApp(object): def __init__(self): self.config = { "app_name": "SpeedTest", "start": "Check Speed", "interval": 1500 } self.app = rumps.App(self.config["app_name"]) self.timer = rumps.Timer(self.on_tick, 60) self.interval = self.config["interval"] self.set_up_menu() self.update_button = rumps.MenuItem(title=self.config["start"], callback=self.check_speed) self.app.menu = [self.update_button] def set_up_menu(self): self.timer.stop() self.timer.count = 0
def build_menu(self) -> List[Any]: def make_open(p): return lambda _: run(p.value, 'activate') always_visible = [('Open Player', [ rumps.MenuItem(f'{p.name}', callback=make_open(p)) for p in self.mb.players ]), None, ('Last.fm Scrobbling', self.build_lastfm_menu()), None, rumps.MenuItem('Force Refresh', callback=self.force_refresh, key='r'), rumps.MenuItem('Quit', callback=rumps.quit_application, key='q')] player = self.mb.get_active_player() if not player: return ['No player open currently.', None, *always_visible] track = player.get_track() if not track: return ['Nothing playing currently.', None, *always_visible] def make_menu_button(method): def cb(func) -> Callable[[Any], None]: def inner(_: Any) -> None: func() self.refresh() return inner attr = method.lower() return rumps.MenuItem(f'{getattr(Icons, attr)} {method}', callback=cb(getattr(player, attr))) buttons_paused = [make_menu_button('Play')] buttons_playing = [ make_menu_button('Pause'), make_menu_button('Next'), make_menu_button('Previous') ] buttons = buttons_paused if player.status == PlayerStatus.PAUSED else buttons_playing art_menu = [] art_path = player.get_album_cover() if art_path and os.path.isfile(art_path): art_menu = [ rumps.MenuItem("", callback=dummy_callback, icon=art_path, dimensions=[192, 192]), None ] if not player.scrobbling: scrobble_message = f'{Icons.error} No scrobbler running' else: scrobblers = map(lambda scrob: scrob.name, self.mb.get_player_scrobblers(player.app)) scrobble_message = f'Scrobbling using {", ".join(scrobblers)}' song_metadata = [rumps.MenuItem(track.title, callback=dummy_callback)] if track.artist: song_metadata.append(track.artist) if track.album: song_metadata.append( make_font(track.album, NSFont.menuFontOfSize_(12.0))) return [ *buttons, None, *art_menu, *song_metadata, None, f'Now playing on {player.app.name}', make_font(scrobble_message, NSFont.menuFontOfSize_(10.0)), None, *always_visible ]
def make_font(text, font=NSFont.menuFontOfSize_(0.0)): attr_string = make_attributed_string(text, font) menuitem = rumps.MenuItem("") menuitem._menuitem.setAttributedTitle_(attr_string) return menuitem
fontSize = panelFont.pointSize() defaults = NSUserDefaultsController.sharedUserDefaultsController( ).values() defaults.setValue_forKey_(panelFont.fontName(), "FontName") defaults.setValue_forKey_(fontSize, "FontSize") # Set up initial values for defaults: # Create dictionary with keys and values for WordOfTheDay, FontName, # FontSize, and FavoriteColor. Mostly straightforward, but: # # Store the fontName of the font as the default; the textfield displays # the font's displayName using a value transformer. # # The color must be archived -- you can't store NSColors directly in NSUserDefaults. dictionary = {} dictionary["WordOfTheDay"] = "Today" systemFont = NSFont.systemFontOfSize_(NSFont.systemFontSize()) dictionary["FontName"] = systemFont.fontName() dictionary["FontSize"] = systemFont.pointSize() archivedColor = NSArchiver.archivedDataWithRootObject_(NSColor.greenColor()) dictionary["FavoriteColor"] = archivedColor NSUserDefaultsController.sharedUserDefaultsController().setInitialValues_( dictionary) # Create and register font name value transformer transformer = FontNameToDisplayNameTransformer.alloc().init() NSValueTransformer.setValueTransformer_forName_( transformer, "FontNameToDisplayNameTransformer")
import plistlib import launchd import rumps import subprocess from AppKit import NSAttributedString from PyObjCTools.Conversion import propertyListFromPythonCollection from Cocoa import (NSFont, NSFontAttributeName, NSColor, NSForegroundColorAttributeName) from launchd.cmd import launchctl ICON_PATH = "../assets/[email protected]" USER_AGENTS = os.path.expanduser('~/Library/LaunchAgents') FONT = NSFont.fontWithName_size_("Hack Nerd Font", 14.0) color = { "red": NSColor.redColor(), "blue": NSColor.blueColor(), "green": NSColor.greenColor() } r_attr = propertyListFromPythonCollection( { # NSFontAttributeName: FONT, NSForegroundColorAttributeName: color['red'] }, conversionHelper=lambda x: x) g_attr = propertyListFromPythonCollection( { # NSFontAttributeName: FONT, NSForegroundColorAttributeName: color['green']