def _setup_windows(self): self._description_window = rumps.Window(title="Description", cancel=True, dimensions=(320, 40)) self._project_window = rumps.Window(title="Which project?", dimensions=(320, 40))
def add_one_time_event(self, sender): window = rumps.Window( title=sender.title, message='Select Day/Time (HH:MM, 24 hour) for one time class', ok='Cancel', dimensions=(200, 24)) window.add_buttons('Sun', 'Sat', 'Fri', 'Thu', 'Wen', 'Tue', 'Mon') response = window.run() day = 8 - response.clicked if day < 7: try: datetime.datetime.strptime(response.text, '%H:%M').time() except Exception as e: rumps.Window(title='Error Parsing Date', message='Please try again', dimensions=(0, 0)).run() return data = self.read_json() for classData in data: if classData['name'] == sender.title: classData['times'].append({ 'type': 'temp', 'dotw': weekDays[day], 'time': response.text }) self.write_json(data)
def execute_as_root(description, command): if not root_allowed: return False global password, dialog_open if dialog_open: return if not password: if not AppKit.NSThread.isMainThread() or utils.is_menu_open(): # Cannot show a dialogue on a background thread or when the menu is open return window = rumps.Window( "Please enter your admin or root password:"******"HappyMac: To %s, an admin or root password is needed." % description, cancel = "Cancel" ) window._textfield = AppKit.NSSecureTextField.alloc().initWithFrame_(Foundation.NSMakeRect(0, 0, 200, 25)) window._alert.setAccessoryView_(window._textfield) window._alert.window().setInitialFirstResponder_(window._textfield) try: dialog_open = True response = window.run() finally: dialog_open = False if response.clicked: password = response.text if password: os.popen('echo "%s" | sudo -S %s' % (password, command)).read() return True return False
def myCallback(self): myWindow = rumps.Window("", "Add an application", "application name", cancel=True, dimensions=(320, 25)) response = myWindow.run() os.system('open -a python') invalidApplicationName = True while invalidApplicationName: if response.clicked: #do stuff for clicked invalidApplicationName = not verifyApplication( response.text.strip().lower()) if not invalidApplicationName: os.system('python3 workspaceManager.py ' + 'add' + ' ' + workspaceName + ' ' + response.text.strip().lower()) myApplication.update() break else: myWindow.message = "Invalid application name -- try again" response = myWindow.run() else: break
def add_folder_button(self, sender): res = rumps.Window( cancel=True, message= 'Please enter an absolute path, or one that starts from `~`.', title='Add Folder').run() if res.clicked: resp = rumps.Window( cancel=True, title='Add Name', message= 'Please enter a name for the path, this will be displayed in the menu.' ).run() if resp.clicked: self.add_path(res.text, resp.text)
def change_something(self, message, key): model = None try: with open("/usr/local/etc/shadowsocks-libev.json", "r") as f: model = json.loads(f.read()) except: pass if not model: print "Warning: using base model" model = base_model w = rumps.Window(message=message, title='Easy ShadowSocks', default_text=model.get(key, ""), cancel=True) r = w.run() if not r.clicked: return model[key] = r.text with open("/usr/local/etc/shadowsocks-libev.json", "w") as f: f.write(json.dumps(model)) subprocess.call([ "launchctl", "unload", os.path.expanduser( "~/Library/LaunchAgents/homebrew.mxcl.shadowsocks-libev.plist") ]) time.sleep(1) subprocess.call([ "launchctl", "load", os.path.expanduser( "~/Library/LaunchAgents/homebrew.mxcl.shadowsocks-libev.plist") ])
def start_timer(self, sender, interval): for btn in [*self.buttons.values()]: btn.set_callback(None) # sender.title could be "Start Timer"/"Continue Timer"/"Pause Timer" if sender.title == 'Start Timer': start_quote = self.get_quote() # add a window for user input t = rumps.Window(message='{}\nWhat will this raindrop for?'.format(start_quote), title='Raindrop', default_text='Unspecific', dimensions=(160,40)) self.current_user_input = t.run().text print('raindrop.start: {}, {}, {}'.format(timez(), self.current_user_input, interval)) with open(self.log, 'a') as log_writer: # append mode log_writer.write('raindrop.start: {}, {}, {}\n'.format(timez(), self.current_user_input, interval)) # reset timer & set stop time self.timer.count = 0 self.timer.end = interval # change title of MenuItem from 'Start timer' to 'Pause timer' sender.title = 'Pause Timer' # lift off! start the timer self.timer.start() elif sender.title == 'Continue Timer': sender.title = 'Pause Timer' # lift off! start the timer self.timer.start() else: # 'Pause Timer' sender.title = 'Continue Timer' self.timer.stop()
def about(self, _): about_window = rumps.Window(message = "Additional Info", title = "About", default_text = "Contact me: [email protected] \nProject can be found @: https://github.com/JanuszPXYZ/unPlug", ok = None, dimensions = (300,300)) about_window.run()
def set_apikey(self): ''' Open window to set api key ''' self.logger.info('Opening \'set_apikey\' window') api_key_window = rumps.Window( title='Enter your API key:', message='Right click to paste', default_text=self.config['apikey'], ok='Confirm', cancel='I don\'t have one', dimensions=(250, 20), ) response = api_key_window.run() if response.clicked == 0: # Cancel self.logger.info('Cancelled \'set_apikey\' window') return False apikey = response.text.strip() if not apikey: self.logger.info('API Key was not entered') rumps.alert(title='You did not enter an API Key', message='Try again') return self.set_apikey() self.logger.info('Setting API Key') self.config['apikey'] = apikey self.climacell.set_apikey(apikey) CONFIG.save(self.config) return True
def cb(sender): minutes = sender.value if not minutes: dlg = rumps.Window("Enter interval length in minutes:", "Custom interval", str(self.config.interval), dimensions=(320, 120), cancel=True) while True: res = dlg.run() if res.clicked == 0: return try: minutes = int(res.text) break except ValueError: rumps.alert("Error", "Invalid input!") dlg.default_text = res.text continue sender.title = "Custom: %s minutes" % minutes else: menu["Custom..."].title = "Custom..." # Closure magic... for item in menu.values(): item.state = False sender.state = True self.set_interval(minutes)
def myCallback(self): myWindow = rumps.Window("", "Add a workspace", "workspace name", cancel=True, dimensions=(320, 25)) response = myWindow.run() os.system('open -a python') invalidWorkspaceName = True while invalidWorkspaceName: myWindow.message = "Add a workspace" if response.clicked: #do stuff for clicked invalidWorkspaceName = response.text.strip().lower( ) in workspaceNames or ' ' in response.text.strip() if not invalidWorkspaceName: os.system('python3 workspaceManager.py ' + 'create' + ' ' + response.text.strip().lower()) myApplication.update() break elif ' ' in response.text.strip(): myWindow.message = "Workspace names may only be one word long" response = myWindow.run() else: myWindow.message = "Invalid workspace name -- try again" response = myWindow.run() else: break
def callback(self, sender): res = rumps.Window( cancel=True, message='Please enter a file extension, without `.`', title='Add Extension For {}'.format(parent_folder)).run() if res.clicked: self.add_extension(res.text, parent_folder, parent_menu)
def progress(self, _): prog = os.popen("~/dunnit/dunnit-progress frommenu").read() win = rumps.Window("foo", 'bar', dimensions=(500, 600)) win.title = 'Dunnit Progress Today' win.message = "This is an in-flight view of your day so far. It's just a ledger of raw entries; you'll have a chance to edit it in a better format when you close the day." win.default_text = prog resp = win.run() print(resp)
def inner(_): previous_value = str(self.opts[opt.name]) response = rumps.Window("Set value for '%s'..." % (opt.name), opt.help, dimensions=(200, 20), default_text=previous_value).run() if response.text: self.opts[opt.name] = opt.type(response.text)
def changeit(self, _): response = rumps.Window('Enter new interval (In seconds)').run() if response.clicked: try: rumps.timer.__dict__["*timers"][0].interval = int(response.text) rumps.alert("Interval set as %s seconds." % response.text) except ValueError: rumps.alert("Invalid value")
def winbtn(self, sender): wins = rumps.Window(dimensions=(220, 18), cancel="NO", ok="YES") wins.title = 'titles' wins.default_text = "some thing Response hwo get it" wins.messages = "msg" wins.add_button("txt") wins.run() print(sender.state)
def help(self, _): with open('help.txt', 'r') as file: txt = file.read() win = rumps.Window("foo", 'bar', dimensions=(500, 600)) win.title = 'Dunnit Help' win.message = "All about Dunnit and its usage'" win.default_text = txt resp = win.run()
def push_key(self, userid): path = os.chdir("/Users/" + self.login + "/.ssh") Files = glob.glob1(path, '*.pub') public_id = Files[0] print(public_id) child = pexpect.spawn("scp -o StrictHostKeyChecking=no " + "/Users/" + self.login + "/.ssh/" + public_id + " " + userid + "@hpcc.msu.edu:.ssh/authorized_keys") #print '/bin/cat ~/.ssh/id_rsa.pub | ssh ' + userid + '@hpcc.msu.edu -o StrictHostKeyChecking=no "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"' #child = pexpect.spawn("cat ~/.ssh/id_rsa.pub | ssh " + userid + "@hpcc.msu.edu -o StrictHostKeyChecking=no 'cat >> ~/.ssh/authorized_keys'") child.expect('Password:'******'Password:', pexpect.EOF, pexpect.TIMEOUT]) print(result, "result") if result == 0 and Max_attempts >= 1: self.HPCC_PASS = rumps.Window( title="Incorrect HPCC password. Attempt: (" "/3)", message="Please re-enter your HPCC password:"******"Incorrect HPCC password and userID", message= "Please check your that you entered your HPCC username or Password Correctly." ) sys.exit(0) else: break Max_attempts -= 1
def pop_duration_time(sender): response = rumps.Window("Please enter a new duration (minutes)").run() if response.clicked: duration_interval = config["interval"] // 60 try: duration_interval = int(response.text) finally: config["interval"] = duration_interval * 60 sender.title = duration_time_label()
def preferences_update_email(self, sender): text = self.preferences.email() logging.info("Prompting for new email") prompt = rumps.Window("", "Enter your email address", text, dimensions=(275, 25)) result = prompt.run() self.preferences.email(result.text)
def notify_general(self, msg="msg", title="Title", buttons={}, timeout=3600): window = rumps.Window(title, msg) window.title = title window.message = msg window.default_text = 'eh' for button in buttons: window.add_buttons(button) res = window.run() return res
def showtodos(self, _): with open('help.txt', 'r') as file: txt = file.read() prog = os.popen("~/dunnit/dunnit-showtodos frommenu").read() win = rumps.Window("foo", 'bar', dimensions=(500, 600)) win.title = 'Dunnit Todos' win.message = "These are all the things you planned to do." win.default_text = prog resp = win.run()
def mount(self, _): print(self.login) self.UID = rumps.Window(title="HPCC username", message="Please enter your MSU NETID:", dimensions=(250, 50)).run() UserID = str( self.UID.text ) # since rumps.Window returns its type from window class we need to convert it to string if (self.key_present(UserID)): # SSH does not connect through print("The SSH keys are present {}".format( self.key_present(UserID))) else: print("Need to generate ssh keys") self.alert = rumps.alert( title="SSH Keys", message= "To mount your HPCC drive using SSHFS, you need to generate SSH Key-Based " "authentication. Would you like to continue to create your SSH Keys. NOTE: " "By clicking continue, the program will generate two files onto your computer " "system, a public and a private key. Additionally, the public key will be copied " "to your HPCC system account to a file within the your home directory at ~/.ssh/authorized_keys." " This procedure will enable Password-less login when connecting to the HPCC. This way, you'll " "be able to automatically login each time immediately without needing to enter your password. ", ok="Continue", cancel="Cancel") if self.alert == 0: sys.exit(0) self.gen_key() self.push_key(UserID) sshfs_cmd = "/usr/local/bin/sshfs -o allow_other,defer_permissions,IdentityFile=~/.ssh/id_rsa" remote_host = "@hpcc.msu.edu:/mnt/home/" options = "-o cache=no -o nolocalcaches -o volname=hpcc -o StrictHostKeyChecking=no" # StrictHostKeyChecking ignores authentication for first time use os.mkdir(self.local_mount_point + self.path) var = sshfs_cmd + " " + UserID + remote_host + UserID + " " + self.local_mount_point + self.path + " " + options print(var) os.system(var) if ( self.drive_mounted() ): # os.system() returns the encoded process exit value. 0 means succecss no error self.menu["Mount HPCC"].set_callback(None) rumps.notification( title="HPCC drive Mounted", subtitle="Sucessfull", # !!!!Fix This message="Your drive is located at " + self.local_mount_point + self.path, sound=True)
def preferences(self, _): response = rumps.Window('输入你的 Session', cancel="取消", ok="确认").run() if response.clicked: if response.text.strip(): session = response.text self.setting_config['session'] = session self.save_settings() self.init_app() else: rumps.alert("session 值存在问题!", icon_path=self.get_icon('alert'))
def __onKeyClicked(self, item): key_name = item.title.split(": ")[0] key = next(k for k in KEY_NAMES if KEY_NAMES[k] == key_name) self.window = rumps.Window(f"Select key for {KEY_NAMES[key]}", title="Enter the key", default_text=self.config[key]) res = self.window.run() self.editConfigKey(key, res.text) self.setMenu() self.setHotkeys()
def Config(self, _): window = rumps.Window( dimensions=(320, 120), ok=u"确定", cancel="Cancel", ) window.title = 'Dietary Restrictions' window.message = 'Information regarding dietary restrictions.' window.default_text = 'mlh.get_dietary_users()' window.run()
def add_expansion(self, _): window = rumps.Window( "Specify trigger shortcut (do not include prefix):", "Specify New Trigger") first_prompt = window.run() trigger = first_prompt.text if not self.wsdaemon.validate_unique_trigger(trigger): rumps.alert(f"Expansion with trigger {trigger} already exists!") return False elif len(trigger) > self.wsdaemon.buffer_limit: rumps.alert( f"Trigger \"{trigger}\" too long, max length is {self.wsdaemon.buffer_limit} characters" ) return False window = rumps.Window(f"Specify expansion for {trigger}:", "Specify New Expansion") second_prompt = window.run() expansion = second_prompt.text self.wsdaemon.save_expansion(trigger, expansion)
def showInfo(self, _): '''shows info windows''' w = rumps.Window( message="WorkMode v0.0.1", default_text= "Copyright © 2020 Felix Heilingbrunner & Domenico Di Ruocco, All Rights Reserved.\n\nThis is an alpha version of the product distributed under the Apache-2.0 License.\n\nYou may obtain a copy of the License at:\nhttps://www.apache.org/licenses/LICENSE-2.0", title="About WorkMode", dimensions=(380, 150)) w._textfield.setSelectable_(False) w.run()
def changeFromFile(self, sender): input = rumps.Window(message='', title='Enter the file path of an image here:', default_text=getpass.getuser() + '/image', ok='Change', cancel='Exit', dimensions=(320, 160)) response = input.run() if response.clicked: wallpaper_file(response.text)
def pop_break_time(sender): response = rumps.Window("Please enter a new break period (minutes)").run() break_interval = config["break_interval"] // 60 if response.clicked: try: break_interval = int(response.text) finally: config["break_interval"] = break_interval * 60 sender.title = break_time_label()