def init(self): if self: NSBundle.loadNibNamed_owner_("EnrollmentWindow", self) icloud_sync_enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled") self.syncWithiCloudCheckbox.setHidden_(not icloud_sync_enabled) self.selectRadio_(self.radioMatrix) if not SIPManager().validateAddAccountAction(): self.nextButton.setEnabled_(False) self.purchaseProLabel.setHidden_(False) if NSApp.delegate().contactsWindowController.first_run: NotificationCenter().add_observer(self, name='SIPAccountManagerDidAddAccount') if NSApp.delegate().applicationName == 'SIP2SIP': self.allowed_domains = ['sip2sip.info'] self.syncWithiCloudCheckbox.setHidden_(True) self.syncWithiCloudCheckbox.setState_(NSOffState) self.domainButton.setHidden_(True) self.addressText.cell().setPlaceholderString_('*****@*****.**') if NSApp.delegate().applicationName == 'Blink': self.syncWithiCloudCheckbox.setHidden_(True) return self
def initWithAccount_target_name_(self, account, target, display_name): self = super(SMSViewController, self).init() if self: self.notification_center = NotificationCenter() self.account = account self.target_uri = target self.display_name = display_name self.queue = [] self.messages = {} self.history=ChatHistory() self.local_uri = '%s@%s' % (account.id.username, account.id.domain) self.remote_uri = '%s@%s' % (self.target_uri.user, self.target_uri.host) NSBundle.loadNibNamed_owner_("SMSView", self) self.chatViewController.setContentFile_(NSBundle.mainBundle().pathForResource_ofType_("ChatView", "html")) self.chatViewController.setAccount_(self.account) self.chatViewController.resetRenderedMessages() self.chatViewController.inputText.unregisterDraggedTypes() self.chatViewController.inputText.setMaxLength_(MAX_MESSAGE_LENGTH) self.splitView.setText_("%i chars left" % MAX_MESSAGE_LENGTH) return self
def initWithFrame_oldTransfer_(self, frame, transferInfo): self = NSView.initWithFrame_(self, frame) if self: self.oldTransferInfo = transferInfo NSBundle.loadNibNamed_owner_("FileTransferItemView", self) filename = transferInfo.file_path if filename.endswith(".download"): filename = filename[:-len(".download")] self.updateIcon(NSWorkspace.sharedWorkspace().iconForFile_(filename)) self.nameText.setStringValue_(os.path.basename(filename)) self.fromText.setStringValue_('To %s' % transferInfo.remote_uri if transferInfo.direction=='outgoing' else 'From %s' % transferInfo.remote_uri) if transferInfo.status == "completed": status = "%s %s Completed"%(format_size(transferInfo.file_size, 1024), unichr(0x2014)) else: error = transferInfo.status if transferInfo.direction == "outgoing": status = error else: status = "%s of %s"%(format_size(transferInfo.bytes_transfered, 1024), format_size(transferInfo.file_size, 1024)) status = "%s %s %s"%(status, unichr(0x2014), error) self.sizeText.setStringValue_(status) frame.size = self.view.frame().size self.setFrame_(frame) self.addSubview_(self.view) self.relayoutForDone() self.done = True return self
def __init__(self, image): NSBundle.loadNibNamed_owner_("ScreensharingPreviewPanel", self) self.view.setImage_(image) self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(5.0, self, "closeTimer:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSModalPanelRunLoopMode) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) self.window.orderFront_(None)
def __init__(self): self.app_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname) if not isdir(self.app_dir): mkdir(self.app_dir) self.plugin_dir = join(self.app_dir, 'plugins') if not isdir(self.plugin_dir): mkdir(self.plugin_dir) self.home = expanduser('~') self.respath = getattr(sys, 'frozen', False) and normpath(join(dirname(sys.executable), pardir, 'Resources')) or dirname(__file__) if not getattr(sys, 'frozen', False): # Don't use Python's settings if interactive self.bundle = 'uk.org.marginal.%s' % appname.lower() NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = self.bundle self.bundle = NSBundle.mainBundle().bundleIdentifier() self.defaults = NSUserDefaults.standardUserDefaults() settings = self.defaults.persistentDomainForName_(self.bundle) or {} self.settings = dict(settings) # Check out_dir exists if not self.get('outdir') or not isdir(self.get('outdir')): self.set('outdir', NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0])
def initWithFrame_oldTransfer_(self, frame, transferInfo): self = NSView.initWithFrame_(self, frame) if self: self.oldTransferInfo = transferInfo NSBundle.loadNibNamed_owner_("FileTransferItemView", self) filename = transferInfo.file_path if filename.endswith(".download"): filename = filename[:-len(".download")] self.updateIcon(NSWorkspace.sharedWorkspace().iconForFile_(filename)) self.nameText.setStringValue_(os.path.basename(filename)) self.fromText.setStringValue_('To %s from account %s' % (transferInfo.remote_uri, transferInfo.local_uri) if transferInfo.direction=='outgoing' else 'From %s to account %s' % (transferInfo.remote_uri, transferInfo.local_uri)) time_print = format_date(transferInfo.time) if transferInfo.status == "completed": t = NSLocalizedString("Completed transfer of ", "Label") status = t + "%s %s" % (format_size(transferInfo.file_size, 1024), time_print) else: if transferInfo.direction == "outgoing": status = '%s %s' % (transferInfo.status.title(), time_print) self.retryButton.setHidden_(False) else: #status = "%s of %s"%(format_size(transferInfo.bytes_transfered, 1024), format_size(transferInfo.file_size, 1024)) status = "%s %s" % (transferInfo.status.title(), time_print) self.sizeText.setStringValue_(status) frame.size = self.view.frame().size self.setFrame_(frame) self.addSubview_(self.view) self.relayoutForDone() self.done = True return self
def __init__(self): if self: BlinkLogger().log_debug('Starting History Viewer') NSBundle.loadNibNamed_owner_("HistoryViewer", self) self.all_contacts = BlinkHistoryViewerContact('Any Address', name=u'All Contacts') self.bonjour_contact = BlinkHistoryViewerContact('bonjour', name=u'Bonjour Neighbours', icon=NSImage.imageNamed_("NSBonjour")) self.notification_center = NotificationCenter() self.notification_center.add_observer(self, name='ChatViewControllerDidDisplayMessage') self.notification_center.add_observer(self, name='AudioCallLoggedToHistory') self.notification_center.add_observer(self, name='BlinkContactsHaveChanged') self.notification_center.add_observer(self, name='BlinkTableViewSelectionChaged') self.notification_center.add_observer(self, name='BlinkConferenceContactPresenceHasChanged') self.notification_center.add_observer(self, name='BlinkShouldTerminate') self.searchText.cell().setSendsSearchStringImmediately_(True) self.searchText.cell().setPlaceholderString_(NSLocalizedString("Type text and press Enter", "Placeholder text")) self.chatViewController.setContentFile_(NSBundle.mainBundle().pathForResource_ofType_("ChatView", "html")) self.chatViewController.setHandleScrolling_(False) self.entriesView.setShouldCloseWithWindow_(False) for c in ('remote_uri', 'local_uri', 'date', 'type'): col = self.indexTable.tableColumnWithIdentifier_(c) descriptor = NSSortDescriptor.alloc().initWithKey_ascending_(c, True) col.setSortDescriptorPrototype_(descriptor) self.chat_history = ChatHistory() self.session_history = SessionHistory() self.setPeriod(1) self.selectedTableView = self.contactTable
def __init__(self, target=None, default_domain=None): self._participants = [] self.default_domain = default_domain NSBundle.loadNibNamed_owner_("AddParticipantsWindow", self) if target is not None: self.target.setStringValue_(target) self.target.setHidden_(False)
def __init__(self, videoWindowController): self.videoWindowController = videoWindowController self.log_debug('Init %s' % self) NSBundle.loadNibNamed_owner_("VideoControlPanel", self) self.window().setTitle_(self.videoWindowController.title) self.notification_center = NotificationCenter() self.notification_center.add_observer(self,sender=self.videoWindowController) self.notification_center.add_observer(self, name='BlinkMuteChangedState') self.updateButtons()
def initWithOwner_(self, owner): self= super(SMSWindowController, self).init() if self: self._owner = owner NSBundle.loadNibNamed_owner_("SMSSession", self) self.notification_center = NotificationCenter() self.notification_center.add_observer(self, name="BlinkShouldTerminate") self.unreadMessageCounts = {} return self
def init(self): self = super(PhotoPicker, self).init() if self: NSBundle.loadNibNamed_owner_("PhotoPicker", self) self.lock = NSLock.alloc().init() self.captureButton.setHidden_(True) self.previewButton.setHidden_(False) self.cancelButton.setHidden_(True) return self
def __init__(self): # It's only possible to send notifications if we have a bundle # identifier set. This happens by default if using Python # installed as a Framework (e.g. the system Python), but isn't # set in a virtualenv. NSBundle.mainBundle().infoDictionary().setdefault( "CFBundleIdentifier", "org.4pisky.tools") self.NSUserNotification = lookUpClass("NSUserNotification") NCenter = lookUpClass("NSUserNotificationCenter") self.center = NCenter.defaultUserNotificationCenter()
def init(self): NotificationCenter().add_observer(self, name="BlinkFileTransferInitializing") NotificationCenter().add_observer(self, name="BlinkFileTransferRestarting") NotificationCenter().add_observer(self, name="BlinkFileTransferDidFail") NotificationCenter().add_observer(self, name="BlinkFileTransferDidEnd") NotificationCenter().add_observer(self, name="BlinkFileTransferSpeedDidUpdate") NotificationCenter().add_observer(self, name="BlinkShouldTerminate") NSBundle.loadNibNamed_owner_("FileTransferWindow", self) self.transferSpeed.setStringValue_("") return self
def initWithOwner_(self, owner): self = super(ConferenceScreenSharing, self).init() if self: self.owner = owner NSBundle.loadNibNamed_owner_("ConferenceScreenSharing", self) self.screensharing_fit_window = True self.screensharing_uri = None self.screensharing_url = None self.display_name = None self.webView.setShouldCloseWithWindow_(True) NotificationCenter().add_observer(self, name='SIPSessionGotConferenceInfo') return self
def startOutgoing(self, is_update): if self.direction == "active": # viewer # open viewer self.sessionController.log_info("Requesting access to remote screen") else: self.sessionController.log_info("Sharing local screen...") NSBundle.loadNibNamed_owner_("ScreenServerWindow", self) self.statusProgress.startAnimation_(None) self.statusWindow.setTitle_("Screen Sharing with %s" % self.sessionController.getTitleShort()) #self.statusItem.show(self) NotificationCenter().add_observer(self, sender=self.stream.handler) NotificationCenter().add_observer(self, sender=self.stream) self.changeStatus(STREAM_PROPOSING if is_update else STREAM_CONNECTING)
def getItemView(self): array = NSMutableArray.array() context = NSMutableDictionary.dictionary() context.setObject_forKey_(self, NSNibOwner) context.setObject_forKey_(array, NSNibTopLevelObjects) path = NSBundle.mainBundle().pathForResource_ofType_("AlertPanelView", "nib") if not NSBundle.loadNibFile_externalNameTable_withZone_(path, context, self.zone()): raise RuntimeError("Internal Error. Could not find AlertPanelView.nib") for obj in array: if isinstance(obj, NSBox): return obj else: raise RuntimeError("Internal Error. Could not find NSBox in AlertPanelView.nib")
def __init__(self): if self: NotificationCenter().add_observer(self, name="BlinkFileTransferInitializing") NotificationCenter().add_observer(self, name="BlinkFileTransferRestarting") NotificationCenter().add_observer(self, name="BlinkFileTransferDidFail") NotificationCenter().add_observer(self, name="BlinkFileTransferDidEnd") NotificationCenter().add_observer(self, name="BlinkFileTransferSpeedDidUpdate") NotificationCenter().add_observer(self, name="BlinkShouldTerminate") NSBundle.loadNibNamed_owner_("FileTransferWindow", self) self.transferSpeed.setStringValue_('') self.load_transfers_from_history()
def __init__(self, name, title=None, icon=None, menu=None, quit_button='Quit'): _require_string(name) self._name = name self._icon = self._icon_nsimage = self._title = None self.icon = icon self.title = title self.quit_button = quit_button self._menu = Menu() if menu is not None: self.menu = menu self._application_support = application_support(self._name) if not 'CFBundleIdentifier' in NSBundle.mainBundle().infoDictionary(): NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = name
def init(self): self = super(AlertPanel, self).init() if self: NSBundle.loadNibNamed_owner_("AlertPanel", self) self.panel.setLevel_(3000) self.panel.setWorksWhenModal_(True) self.extraHeight = self.panel.contentRectForFrameRect_(self.panel.frame()).size.height - self.sessionsListView.frame().size.height self.sessionsListView.setSpacing_(2) NotificationCenter().add_observer(self, name="CFGSettingsObjectDidChange") self.init_speech_recognition() self.init_speech_synthesis() return self
def startIncoming(self, is_update): if self.direction == "active": # viewer # open viewer self.sessionController.log_info("Preparing to view remote screen") self.stream.handler = ExternalVNCViewerHandler() else: self.sessionController.log_info("Sharing local screen...") self.stream.handler = ExternalVNCServerHandler(("localhost", self.vncServerPort)) NSBundle.loadNibNamed_owner_("ScreenServerWindow", self) self.statusProgress.startAnimation_(None) self.statusWindow.setTitle_("Screen Sharing with %s" % self.sessionController.getTitleShort()) #self.statusItem.show(self) NotificationCenter().add_observer(self, sender=self.stream.handler) NotificationCenter().add_observer(self, sender=self.stream) self.changeStatus(STREAM_INCOMING)
def get_serial(): """Get system serial number.""" # Credit to Mike Lynn IOKit_bundle = NSBundle.bundleWithIdentifier_("com.apple.framework.IOKit") functions = [ ("IOServiceGetMatchingService", b"II@"), ("IOServiceMatching", b"@*"), ("IORegistryEntryCreateCFProperty", b"@I@@I") ] objc.loadBundleFunctions(IOKit_bundle, globals(), functions) kIOMasterPortDefault = 0 kIOPlatformSerialNumberKey = 'IOPlatformSerialNumber' kCFAllocatorDefault = None platformExpert = IOServiceGetMatchingService( kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice") ) serial = IORegistryEntryCreateCFProperty( platformExpert, kIOPlatformSerialNumberKey, kCFAllocatorDefault, 0 ) return serial
def init(self): self = super(VideoMirrorWindowController, self).init() if self: NSBundle.loadNibNamed_owner_("VideoMirrowWindow", self) userdef = NSUserDefaults.standardUserDefaults() savedFrame = userdef.stringForKey_("NSWindow Frame MirrorWindow") if savedFrame: x, y, w, h = str(savedFrame).split()[:4] frame = NSMakeRect(int(x), int(y), int(w), int(h)) self.window.setFrame_display_(frame, True) self.window.setAlphaValue_(0.9) return self
def classBundle(cls): framework = NSBundle.bundleForClass_(cls).bundlePath() if framework.startswith(SYSFRAMEWORKS_DIR): framework = framework[len(SYSFRAMEWORKS_DIR):] if framework.endswith('.framework'): framework = framework[:-len('.framework')] return framework
def pathForResource(resourceName, extension, path=None): if path and len(path) > 10: bundlePath = path[:path.find("/Contents/Resources/")] bundle = NSBundle.bundleWithPath_(bundlePath) return bundle.pathForResource_ofType_(resourceName, extension) else: raise("Please supply path")
def asyncinteract(self, write=None, banner=None): if self.lock: raise ValueError("Can't nest") self.lock = True if write is None: write = self.write cprt = u'Type "help", "copyright", "credits" or "license" for more information.' if banner is None: write( u"Python %s in %s\n%s\n" % (sys.version, NSBundle.mainBundle().objectForInfoDictionaryKey_("CFBundleName"), cprt) ) else: write(banner + "\n") more = 0 _buff = [] try: while True: if more: prompt = sys.ps2 else: prompt = sys.ps1 write(prompt) # yield the kind of prompt we have yield more # next input function yield _buff.append more = self.push(_buff.pop()) except: self.lock = False raise self.lock = False
def __init__(self): self.smiley_directory = None self.icon = None self.smileys = {} self.smileys_html = {} self.smiley_keys = [] self.load_theme(str(NSBundle.mainBundle().resourcePath())+"/smileys" , "default")
def init(self): self = super(BlinkAppDelegate, self).init() if self: self.applicationName = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleExecutable")) self.applicationNamePrint = 'Blink' if self.applicationName == 'Blink Pro' else self.applicationName build = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleVersion")) date = str(NSBundle.mainBundle().infoDictionary().objectForKey_("BlinkVersionDate")) BlinkLogger().log_info(u"Starting %s build %s from %s" % (self.applicationNamePrint, build, date)) self.registerURLHandler() NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerDidWake:", NSWorkspaceDidWakeNotification, None) NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerWillSleep:", NSWorkspaceWillSleepNotification, None) NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallTelephoneNumberWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately) NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallSipAddressWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately) NotificationCenter().add_observer(self, name="SIPApplicationDidStart") NotificationCenter().add_observer(self, name="SIPApplicationWillEnd") NotificationCenter().add_observer(self, name="SIPApplicationDidEnd") NotificationCenter().add_observer(self, name="CFGSettingsObjectDidChange") # remove obsolete settings userdef = NSUserDefaults.standardUserDefaults() userdef.removeObjectForKey_('SIPTrace') userdef.removeObjectForKey_('MSRPTrace') userdef.removeObjectForKey_('XCAPTrace') userdef.removeObjectForKey_('EnablePJSIPTrace') userdef.removeObjectForKey_('EnableNotificationsTrace') def purge_screenshots(): screenshots_folder = ApplicationData.get('.tmp_screenshots') if os.path.exists(screenshots_folder): try: shutil.rmtree(screenshots_folder) except EnvironmentError: pass try: from Updater import Updater except ImportError: pass else: self.updater = Updater() call_in_thread('file-io', purge_screenshots) return self
def __init__(self, storage_folder=ApplicationData.get('photos'), high_res=False, history=True): self.history = history NSBundle.loadNibNamed_owner_("PhotoPicker", self) self.lock = NSLock.alloc().init() self.captureButton.setHidden_(True) self.previewButton.setHidden_(False) self.countdownCheckbox.setHidden_(True) self.storage_folder = storage_folder self.high_res = high_res if self.high_res: self.photoView.setCropSize_() if not self.history: self.tabView.selectTabViewItem_(self.cameraTabView) self.previewButton.setHidden_(True) self.countdownCheckbox.setHidden_(False) self.captureButton.setHidden_(False)
def registerURLHandler(self): event_class = event_id = fourcharToInt("GURL") event_manager = NSAppleEventManager.sharedAppleEventManager() event_manager.setEventHandler_andSelector_forEventClass_andEventID_(self, "getURL:withReplyEvent:", event_class, event_id) bundleID = NSBundle.mainBundle().bundleIdentifier() LaunchServices.LSSetDefaultHandlerForURLScheme("sip", bundleID) LaunchServices.LSSetDefaultHandlerForURLScheme("tel", bundleID)
def iconForName(name): """Return the NSImage instance representing a `name` item.""" bundle = NSBundle.bundleWithIdentifier_(haskellBundleIdentifier) imgpath = bundle.pathForResource_ofType_(name, 'png') img = NSImage.alloc().initWithContentsOfFile_(imgpath) # Autoreleasing the image seems to randomly crash Espresso. # img.autorelease() return img
#MenuTitle: Move ogonek anchors to baseline intersection # -*- coding: utf-8 -*- __doc__=""" Moves all ogonek and _ogonek anchors to the rightmost intersection of the outline with the baseline. """ import math from Foundation import NSPoint, NSBundle thisFont = Glyphs.font # frontmost font thisFontMaster = thisFont.selectedFontMaster # active master listOfSelectedLayers = thisFont.selectedLayers # active layers of selected glyphs GLYPHSAPPVERSION = NSBundle.bundleForClass_(NSClassFromString("GSMenu")).infoDictionary().objectForKey_("CFBundleShortVersionString") GLYPHS_IS_OLD = GLYPHSAPPVERSION.startswith("1.") measurementTool = None if GLYPHS_IS_OLD: measurementTool = NSClassFromString("GlyphsToolMeasurement").alloc().init() def angle( firstPoint, secondPoint ): xDiff = firstPoint.x - secondPoint.x yDiff = firstPoint.y - secondPoint.y tangens = yDiff / xDiff angle = math.atan( tangens ) * 180.0 / math.pi return angle def sliceIntersections( thisLayer, startPoint, endPoint ): if measurementTool: return measurementTool.calculateIntersectionsForLayer_startPoint_endPoint_( thisLayer, startPoint, endPoint ) else: return thisLayer.calculateIntersectionsStartPoint_endPoint_( startPoint, endPoint )
def main(sysArgs=None): """Parses command line, sets up logging, and launches main GUI. """ if sysArgs is None: sysArgs = sys.argv[1:] # Valid Input Options shortOpt = "hv" longOpt = [ "help", "version", "info", "debug", "verbose", "style=", "config=", "data=", "testmode", ] helpMsg = ( "novelWriter {version} ({date})\n" "{copyright}\n" "\n" "This program is distributed in the hope that it will be useful,\n" "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" "GNU General Public License for more details.\n" "\n" "Usage:\n" " -h, --help Print this message.\n" " -v, --version Print program version and exit.\n" " --info Print additional runtime information.\n" " --debug Print debug output. Includes --info.\n" " --verbose Increase verbosity of debug output. Includes --debug.\n" " --style= Sets Qt5 style flag. Defaults to 'Fusion'.\n" " --config= Alternative config file.\n" " --data= Alternative user data path.\n").format( version=__version__, copyright=__copyright__, date=__date__, ) # Defaults logLevel = logging.WARN logFormat = "{levelname:8} {message:}" confPath = None dataPath = None testMode = False qtStyle = "Fusion" cmdOpen = None # Parse Options try: inOpts, inRemain = getopt.getopt(sysArgs, shortOpt, longOpt) except getopt.GetoptError as E: print(helpMsg) print("ERROR: %s" % str(E)) sys.exit(2) if len(inRemain) > 0: cmdOpen = inRemain[0] for inOpt, inArg in inOpts: if inOpt in ("-h", "--help"): print(helpMsg) sys.exit(0) elif inOpt in ("-v", "--version"): print("novelWriter Version %s [%s]" % (__version__, __date__)) sys.exit(0) elif inOpt == "--info": logLevel = logging.INFO elif inOpt == "--debug": logLevel = logging.DEBUG logFormat = "[{asctime:}] {name:>22}:{lineno:<4d} {levelname:8} {message:}" elif inOpt == "--verbose": logLevel = VERBOSE logFormat = "[{asctime:}] {name:>22}:{lineno:<4d} {levelname:8} {message:}" elif inOpt == "--style": qtStyle = inArg elif inOpt == "--config": confPath = inArg elif inOpt == "--data": dataPath = inArg elif inOpt == "--testmode": testMode = True # Set Config Options CONFIG.cmdOpen = cmdOpen # Set Logging cHandle = logging.StreamHandler() cHandle.setFormatter(logging.Formatter(fmt=logFormat, style="{")) pkgLogger = logging.getLogger(__package__) pkgLogger.addHandler(cHandle) pkgLogger.setLevel(logLevel) logger.info("Starting novelWriter %s (%s) %s" % (__version__, __hexversion__, __date__)) # Check Packages and Versions errorData = [] errorCode = 0 if sys.hexversion < 0x030600f0: errorData.append("At least Python 3.6.0 is required, found %s." % CONFIG.verPyString) errorCode |= 4 if CONFIG.verQtValue < 50200: errorData.append("At least Qt5 version 5.2 is required, found %s." % CONFIG.verQtString) errorCode |= 8 if CONFIG.verPyQtValue < 50200: errorData.append("At least PyQt5 version 5.2 is required, found %s." % CONFIG.verPyQtString) errorCode |= 16 try: import lxml # noqa: F401 except ImportError: errorData.append("Python module 'lxml' is missing.") errorCode |= 32 if errorData: errApp = QApplication([]) errMsg = QErrorMessage() errMsg.resize(500, 300) errMsg.showMessage( ("<h3>A critical error has been encountered</h3>" "<p>novelWriter cannot start due to the following issues:<p>" "<p> - %s</p>" "<p>Shutting down ...</p>") % ("<br> - ".join(errorData))) for errMsg in errorData: logger.critical(errMsg) errApp.exec_() sys.exit(errorCode) # Finish initialising config CONFIG.initConfig(confPath, dataPath) if CONFIG.osDarwin: try: from Foundation import NSBundle bundle = NSBundle.mainBundle() info = bundle.localizedInfoDictionary() or bundle.infoDictionary() info["CFBundleName"] = "novelWriter" except ImportError as e: logger.error("Failed to set application name") logger.error(str(e)) # Import GUI (after dependency checks), and launch from nw.guimain import GuiMain if testMode: nwGUI = GuiMain() return nwGUI else: nwApp = QApplication([CONFIG.appName, ("-style=%s" % qtStyle)]) nwApp.setApplicationName(CONFIG.appName) nwApp.setApplicationVersion(__version__) nwApp.setWindowIcon(QIcon(CONFIG.appIcon)) nwApp.setOrganizationDomain(__domain__) # Connect the exception handler before making the main GUI sys.excepthook = exceptionHandler # Launch main GUI nwGUI = GuiMain() if not nwGUI.hasProject: nwGUI.showProjectLoadDialog() nwGUI.releaseNotes() sys.exit(nwApp.exec_())
# Code liberally cribbed from here: # http://programtalk.com/vs2/?source=python/10467/pyLoginItems/pyLoginItems.py # # Author: [email protected] ############################################################# from Foundation import NSURL from LaunchServices import kLSSharedFileListFavoriteItems, kLSSharedFileListNoUserInteraction from Foundation import NSBundle import subprocess import objc # The ObjC bridge for LSSharedFileList is broken/missing on 10.11 and above, # this black magic loads the necessary bits manually SFL_bundle = NSBundle.bundleWithIdentifier_( 'com.apple.coreservices.SharedFileList') functions = [ ('LSSharedFileListCreate', '^{OpaqueLSSharedFileListRef=}^{__CFAllocator=}^{__CFString=}@'), ('LSSharedFileListCopySnapshot', '^{__CFArray=}^{OpaqueLSSharedFileListRef=}o^I'), ('LSSharedFileListItemCopyDisplayName', '^{__CFString=}^{OpaqueLSSharedFileListItemRef=}'), ('LSSharedFileListItemResolve', 'i^{OpaqueLSSharedFileListItemRef=}Io^^{__CFURL=}o^{FSRef=[80C]}'), ('LSSharedFileListItemMove', 'i^{OpaqueLSSharedFileListRef=}^{OpaqueLSSharedFileListItemRef=}^{OpaqueLSSharedFileListItemRef=}' ), ('LSSharedFileListItemRemove', 'i^{OpaqueLSSharedFileListRef=}^{OpaqueLSSharedFileListItemRef=}'), ('LSSharedFileListInsertItemURL',
# Tested on 10.11 # Assumes your network is in a state to actually do the discovery and that you have # automatic timezone discovery enabled in Date & Time and Location services enabled # (Generally this means wifi enabled on your device and network stack is up) # For enabling location services and auto, check Allister's work here: # https://gist.github.com/arubdesu/b72585771a9f606ad800 from Foundation import NSBundle TZPP = NSBundle.bundleWithPath_("/System/Library/PreferencePanes/DateAndTime.prefPane/Contents/Resources/TimeZone.prefPane") TimeZonePref = TZPP.classNamed_('TimeZonePref') ATZAdminPrefererences = TZPP.classNamed_('ATZAdminPrefererences') atzap = ATZAdminPrefererences.defaultPreferences() pref = TimeZonePref.alloc().init() atzap.addObserver_forKeyPath_options_context_(pref, "enabled", 0, 0) result = pref._startAutoTimeZoneDaemon_(0x1)
def _init_mne_qtapp(enable_icon=True, pg_app=False, splash=False): """Get QApplication-instance for MNE-Python. Parameter --------- enable_icon: bool If to set an MNE-icon for the app. pg_app: bool If to create the QApplication with pyqtgraph. For an until know undiscovered reason the pyqtgraph-browser won't show without mkQApp from pyqtgraph. splash : bool | str If not False, display a splash screen. If str, set the message to the given string. Returns ------- app : ``qtpy.QtWidgets.QApplication`` Instance of QApplication. splash : ``qtpy.QtWidgets.QSplashScreen`` Instance of QSplashScreen. Only returned if splash is True or a string. """ from qtpy.QtCore import Qt from qtpy.QtGui import QIcon, QPixmap, QGuiApplication from qtpy.QtWidgets import QApplication, QSplashScreen app_name = 'MNE-Python' organization_name = 'MNE' # Fix from cbrnr/mnelab for app name in menu bar # This has to come *before* the creation of the QApplication to work. # It also only affects the title bar, not the application dock. # There seems to be no way to change the application dock from "python" # at runtime. if sys.platform.startswith("darwin"): try: # set bundle name on macOS (app name shown in the menu bar) from Foundation import NSBundle bundle = NSBundle.mainBundle() info = bundle.localizedInfoDictionary() or bundle.infoDictionary() info["CFBundleName"] = app_name except ModuleNotFoundError: pass if pg_app: from pyqtgraph import mkQApp app = mkQApp(app_name) else: app = QApplication.instance() or QApplication(sys.argv or [app_name]) app.setApplicationName(app_name) app.setOrganizationName(organization_name) if enable_icon or splash: icons_path = _qt_init_icons() if enable_icon: # Set icon kind = 'bigsur_' if platform.mac_ver()[0] >= '10.16' else 'default_' app.setWindowIcon(QIcon(f"{icons_path}/mne_{kind}icon.png")) out = app if splash: pixmap = QPixmap(f"{icons_path}/mne_splash.png") pixmap.setDevicePixelRatio( QGuiApplication.primaryScreen().devicePixelRatio()) qsplash = QSplashScreen(pixmap, Qt.WindowStaysOnTopHint) qsplash.setAttribute(Qt.WA_ShowWithoutActivating, True) if isinstance(splash, str): alignment = int(Qt.AlignBottom | Qt.AlignHCenter) qsplash.showMessage( splash, alignment=alignment, color=Qt.white) qsplash.show() app.processEvents() out = (out, qsplash) return out
def init(self): NSBundle.loadNibNamed_owner_("Nickname", self) return self
def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) #Variables. self.page = 1 self.file_saved = True # Changes to false when a file has been changed but not saved. self.max_page = 0 self.dir_path = "" self.edit_page_path = "" self.tiff_im = None self.menubar = tk.Menu(self) self.__build_menubar() self.parent = parent self.__create_content_grid() self.__create_frames() self.__build_page_list() self.__create_notebook() #PDF Input Tab self.pdf_label = tk.Label(self.pdf_tab, image=None) self.pdf_label.pack(fill="both", expand="yes") #TIFF Input Tab self.tiff_label = tk.Label(self.tiff_tab, image=None) self.tiff_label.pack(fill="both", expand="yes") #OCR Input Tab self.ocr_text = tk.Text(self.ocr_tab) self.ocr_text.config(state=tk.DISABLED) self.ocr_text.pack(fill="both", expand="yes") #TXT Input Tab self.text_text = tk.Text(self.text_tab) self.text_text.focus() self.text_text.pack(fill="both", expand="yes") self.text_text.bind('<Key>', self.change_callback) self.text_text.bind('<<Modified>>', self.change_callback) # attach popup to frame self.text_text.bind('<Button-2>', self.edit_menu_popup_event) #Rendered View self.rendered_text = tk.Text(self.render_frame) self.rendered_text.config(state=tk.DISABLED) self.rendered_text.pack(fill="both", expand="yes") self.text_parse_engine = script_parse_engine.ScriptParseEngine( self.text_text) self.text_render_engine = script_render_engine.ScriptRenderEngine( self.rendered_text, self.text_parse_engine) self.__build_buttons() sticky_all = ("N", "S", "E", "W") self.page_list_frame.grid(sticky=sticky_all, row=0, column=0) self.input_notebook.grid(sticky=sticky_all, row=0, column=1) self.render_frame.grid(sticky=sticky_all, row=0, column=2) self.page_control_frame.grid(sticky=sticky_all, row=1, column=0) self.input_control_frame.grid(sticky=sticky_all, row=1, column=1) self.render_control_frame.grid(sticky=sticky_all, row=1, column=2) self.content.pack(fill="both", expand="yes") # Check if we're on OS X, first. if platform == 'darwin': from Foundation import NSBundle bundle = NSBundle.mainBundle() if bundle: info = bundle.localizedInfoDictionary( ) or bundle.infoDictionary() if info and info['CFBundleName'] == 'Python': info['CFBundleName'] = "ScriptEditor" self.parent.config(menu=self.menubar)
def frozen(): global DATADIR, LOCALEDIR, DATADIR_IS_UNINSTALLED bundle = NSBundle.mainBundle() resource_path = bundle.resourcePath().fileSystemRepresentation().decode( "utf-8") bundle_path = bundle.bundlePath().fileSystemRepresentation().decode( "utf-8") frameworks_path = bundle.privateFrameworksPath().fileSystemRepresentation( ).decode("utf-8") executable_path = bundle.executablePath().fileSystemRepresentation( ).decode("utf-8") etc_path = os.path.join(resource_path, "etc") lib_path = os.path.join(resource_path, "lib") share_path = os.path.join(resource_path, "share") # Main libraries environment variables #dyld_library_path = os.environ.get('DYLD_LIBRARY_PATH', '').split(':') #dyld_library_path.insert(0, lib_path) #dyld_library_path.insert(1, frameworks_path) #os.environ['DYLD_LIBRARY_PATH'] = ':'.join(dyld_library_path) #print "DYLD_LIBRARY_PATH %s" % os.environ.get('DYLD_LIBRARY_PATH', '') # Glib and GI environment variables os.environ['GSETTINGS_SCHEMA_DIR'] = os.path.join(share_path, "glib-2.0") os.environ['GI_TYPELIB_PATH'] = os.path.join(lib_path, "girepository-1.0") # Avoid GTK warnings unless user specifies otherwise debug_gtk = os.environ.get('G_ENABLE_DIAGNOSTIC', "0") os.environ['G_ENABLE_DIAGNOSTIC'] = debug_gtk # GTK environment variables os.environ['GTK_DATA_PREFIX'] = resource_path os.environ['GTK_EXE_PREFIX'] = resource_path os.environ['GTK_PATH'] = resource_path # XDG environment variables os.environ['XDG_CONFIG_DIRS'] = os.path.join(etc_path, "xdg") os.environ['XDG_DATA_DIRS'] = ":".join( (share_path, os.path.join(share_path, "meld"))) os.environ['XDG_CONFIG_HOME'] = etc_path # Pango environment variables os.environ['PANGO_RC_FILE'] = os.path.join(etc_path, "pango", "pangorc") os.environ['PANGO_SYSCONFDIR'] = etc_path os.environ['PANGO_LIBDIR'] = lib_path # Gdk environment variables os.environ['GDK_PIXBUF_MODULEDIR'] = os.path.join(lib_path, "gdk-pixbuf-2.0", "2.10.0", "loaders") #os.environ['GDK_RENDERING'] = "image" # Python environment variables os.environ['PYTHONHOME'] = resource_path original_python_path = os.environ.get('PYTHONPATH', "") python_path = ":".join( (lib_path, os.path.join(lib_path, "python", "lib-dynload"), os.path.join(lib_path, "python"), original_python_path)) os.environ['PYTHONPATH'] = python_path # meld specific DATADIR = os.path.join(share_path, "meld") LOCALEDIR = os.path.join(share_path, "mo") DATADIR_IS_UNINSTALLED = True
def initWithOwner_(self, owner): self = objc.super(AccountSettings, self).init() if self: self.owner = owner NSBundle.loadNibNamed_owner_("AccountSettings", self) return self
def init(self): NSBundle.loadNibNamed_owner_("Updater", self) return self
def NSLocalizedString(key, comment): return NSBundle.mainBundle().localizedStringForKey_value_table_(key, '', None)
import objc from Foundation import NSBundle # Predefine some opaque types DASessionRef = objc.createOpaquePointerType('DASessionRef', '^{__DASession=}', None) DADiskRef = objc.createOpaquePointerType('DADiskRef', '^{__DADisk=}', None) # Load DiskManagement framework classes DiskManagment = objc.loadBundle('DiskManagment', globals(), bundle_path='/System/Library/PrivateFrameworks/DiskManagement.framework') # Load DiskArbitration framework functions DiskArbitration_bundle = NSBundle.bundleWithIdentifier_('com.apple.DiskArbitration') functions = [ ('DASessionCreate', '@o@'), ('DADiskGetBSDName', '*^{__DADisk=}'), ] objc.loadBundleFunctions(DiskArbitration_bundle, globals(), functions) class diskRef(object): def __init__(self, dObj, controller, rawRef=False): if rawRef: self.cf_type = objc.objc_object(c_void_p=dObj.__pointer__) self.ref_type = dObj else: self.cf_type = dObj self.ref_type = DADiskRef(c_void_p=(dObj.__c_void_p__().value)) self.controller = controller def __repr__(self): return self.cf_type.__repr__() @property def devname(self):
def __init__(self, model): self.model = model self.parent = Tk() try: import Pmw self.balloon = Pmw.Balloon(self.parent) textCheck.pmw = self.balloon except: self.balloon = None print('Use pip to install Pmw in order to use tooltips') bgcolors = ('#FFFFFF', '#EEEEEE') fnum = 1 # # CALLBACK FUNCTION GENERATORS FOR TKINTER ELEMENTS # def setVar(param, item=None): def sv(val=None): #Different widgets send different things to the callback… if param.type == 'slider': val = float(val) elif param.type == 'menu': val = {y: x for x, y in param.opts.items()}[val] elif param.type == 'check': val = (param.element if item is None else param.element[item]).BooleanVar.get() #Parameters that don't update automatically if param.type in ['slider', 'menu', 'check']: param.set(val, item, updateGUI=False) if callable(param.callback): if param.obj is None: param.callback(self.model, param.name, val) else: param.callback(self.model, param.name, item, val) return sv Param.setVar = setVar #For shock buttons. #Can't do an inline lambda here because lambdas apparently don't preserve variable context def shockCallback(name): return lambda: self.model.shocks[name].do(self.model) class progressBar(Progressbar): def __init__(self, determinate=True, root=None): super().__init__(root, length=250, style="whitebg.Horizontal.TProgressbar") self.determinate(determinate, False) self.running = False @property def mode(self): #Windows returns a string here, and MacOS returns an object mode = self.cget('mode') return mode if isinstance(mode, str) else self.cget('mode').string def determinate(self2, det, refresh=True): self2.config(mode='determinate' if det else 'indeterminate') if det: super().stop() elif self2.running: super().start() if refresh: self.parent.update() def update(self, n): self['value'] = n * 100 def start(self): if self.mode == 'indeterminate': super().start() def stop(self): if self.mode == 'indeterminate': super().stop() self.update(1) def done(self): self.stop() self.update(0) class runButton(Button): def __init__(self2, root, bg='#EEEEEE'): super().__init__(root, text='Run', command=self.model.launchVisual, padx=10, pady=10, highlightbackground=bg) def run(self2): self2['text'] = 'Pause' self2['command'] = self.model.stop def pause(self2): self2['text'] = 'Run' self2['command'] = self.model.start def terminate(self2): self2['text'] = 'New Model' self2['command'] = self.model.launchVisual # # CONSTRUCT CONTROL PANEL INTERFACE # def drawCircle(frame, color, bg): circle = Canvas(frame, width=17, height=12, bg=bg, highlightthickness=0) circle.create_oval(0, 0, 12, 12, fill=color, outline='') return circle def renderParam(frame, param, item=None, bg='#EEEEEE'): if param.type in ['hidden', 'checkgrid']: return #Parent frame for per-item parameters if param.obj is not None and item is None: expFrame = expandableFrame(frame, bg=bg, padx=5, pady=10, text=param.title, fg="#333", font=font) efSub = expFrame.subframe i = 0 param.element = {} for name, b in param.keys.items(): if hasattr(b, 'money') and b.money: continue #Do this separately because they should all be stacked f = renderParam(efSub, param, item=name, bg=bg) if param.type == 'checkentry': f.grid(row=i, column=0) efSub.columnconfigure(0, weight=1) #Everything else goes in the two-column format else: f.grid(row=ceil((i + 1) / 2) * 2, column=i % 2) for c in range(2): efSub.columnconfigure(c, weight=1) i += 1 return expFrame #Single parameters, including the individual per-item parameters else: title = param.title if item is None else item.title() wrap = Frame(frame, bg=bg, padx=10 if item is None and not getattr(param, 'config', False) else 0, pady=8 if item is None and not getattr(param, 'config', False) else 0) #Get .value directly rather than .get because we need the Var() items #Except for checkentry since it doesn't store its values in .value if param.value is not None: val = param.value if item is None else param.value[item] #These put the circle beside the widget if param.type in ['check', 'checkentry']: if param.type == 'check': v = BooleanVar(value=val) el = Checkbutton(wrap, text=title, var=v, onvalue=True, offvalue=False, command=param.setVar(item), bg=bg) el.BooleanVar = v elif param.type == 'checkentry': dflt = param.get(item) el = checkEntry( wrap, title, bg=bg, width=15, padx=0 if getattr(param, 'config', False) else 10, pady=0 if getattr(param, 'config', False) else 5, type='int' if param.entryType is int else 'string', command=param.setVar(item)) if param.name == 'stopafter' and param.event: el.disable() el.entryValue.set('Event: ' + param.get()) el.checkVar.set(True) el.textbox.config(font=( 'Helvetica Neue', 12, 'italic')) #Lucida doesn't have an italic? else: el.set(dflt) if item is not None: el.grid(row=0, column=1) drawCircle(wrap, param.keys[item].color.hex, bg).grid(row=0, column=0) else: el.pack( anchor='center' if param.type == 'check' else 'w') #These need a separate label else: if param.type == 'menu': v = StringVar(value=param.opts[val]) el = OptionMenu(wrap, v, *param.opts.values(), command=param.setVar(item)) el.StringVar = v #Save to set later el.config(bg=bg) elif param.type == 'slider': if isinstance(param.opts, dict): el = Scale(wrap, from_=param.opts['low'], to=param.opts['high'], resolution=param.opts['step'], orient=HORIZONTAL, length=150, highlightthickness=0, command=param.setVar(item), bg=bg) else: el = logSlider( wrap, title=title if getattr(param, 'config', False) else None, orient=HORIZONTAL, values=param.opts, length=150, command=param.setVar(item), bg=bg) el.set(param.get(item)) if item is None and not getattr(param, 'config', False): label = Label(wrap, text=title, fg="#333", bg=bg).pack(side=LEFT, padx=8, pady=3) el.pack(side=RIGHT) elif getattr(param, 'config', False): el.pack() else: lframe = Frame(wrap, bg=bg, padx=0, pady=0) label = Label(lframe, text=title, fg="#333", bg=bg).grid(row=0, column=1, pady=(0, 8)) drawCircle(lframe, param.keys[item].color.hex, bg).grid(row=0, column=0, pady=(0, 8)) lframe.grid(row=1, column=0) el.grid(row=0, column=0) if self.balloon and param.desc is not None: self.balloon.bind(el, param.desc) if item is None: param.element = el else: param.element[item] = el return wrap ctop = self.model.doHooks('CpanelTop', [self, bgcolors[fnum % 2]]) if ctop: ctop.pack(fill="x", side=TOP) fnum += 1 frame1 = Frame(self.parent, padx=10, pady=10, bg=bgcolors[fnum % 2]) renderParam(frame1, self.model.params['stopafter'], bg=bgcolors[fnum % 2]).grid(row=0, column=0, columnspan=3) renderParam(frame1, self.model.params['csv'], bg=bgcolors[fnum % 2]).grid(row=1, column=0, columnspan=3) if not self.model.params['stopafter'].event: self.model.params['stopafter'].element.entryValue.set(10000) self.model.params['csv'].set('filename') self.model.params['csv'].set(False) font = ('Lucida Grande', 16) if sys.platform == 'darwin' else ('Calibri', 14) renderParam(frame1, self.model.params['refresh'], bg=bgcolors[fnum % 2]).grid(row=2, column=0, columnspan=2, pady=(10, 0)) self.runButton = runButton(frame1, bgcolors[fnum % 2]) self.runButton.grid(row=2, column=2, pady=(15, 0)) for c in range(2): frame1.columnconfigure(c, weight=1) frame1.pack(fill="x", side=TOP) fnum += 1 #Can't change the background color of a progress bar on Mac, so we have to put a gray stripe on top :-/ frame0 = Frame(self.parent, padx=10, pady=0, bg=bgcolors[1]) self.progress = progressBar(root=frame0) self.progress.grid(row=0, column=0) frame0.columnconfigure(0, weight=1) frame0.pack(fill="x", side=TOP) caip = self.model.doHooks('CpanelAboveItemParams', [self, bgcolors[fnum % 2]]) if caip: caip.pack(fill="x", side=TOP) fnum += 1 for k, param in model.goodParams.items(): e = renderParam(None, param, bg=bgcolors[fnum % 2]) if e is not None: e.pack(fill="x") if model.goodParams != {}: fnum += 1 #Only increment the stripe counter if we had any good params to draw for p, v in model.primitives.items(): if v.breedParams != {}: for k, param in v.breedParams.items(): e = renderParam(None, param, bg=bgcolors[fnum % 2]) if e is not None: e.pack(fill="x") fnum += 1 cap = self.model.doHooks('CpanelAboveParams', [self, bgcolors[fnum % 2]]) if cap: cap.pack(fill="x", side=TOP) fnum += 1 #Parameter sliders for k, param in self.model.params.items(): if not getattr(param, 'config', False): e = renderParam(self.parent, param, bg=bgcolors[fnum % 2]) if e is not None: e.pack(fill=X) fnum += 1 #Checkgrid parameters for p in self.model.params.values(): if p.type != 'checkgrid' or p.name == 'shocks': continue cg = checkGrid(parent=self.parent, text=p.title, columns=getattr(p, 'columns', 3), bg=bgcolors[fnum % 2], callback=p.setVar()) for k, v in p.opts.items(): if not isinstance(v, (tuple, list)): v = (v, None) elif len(v) < 2: v = (v[0], None) cg.addCheck(k, v[0], p.vars[k], v[1]) p.element = cg p.element.pack(fill=BOTH) fnum += 1 cas = self.model.doHooks('CpanelAboveShocks', [self, bgcolors[fnum % 2]]) if cas: cas.pack(fill="x", side=TOP) fnum += 1 #Shock checkboxes and buttons if self.model.shocks.number > 0: frame8 = expandableFrame(self.parent, text='Shocks', padx=5, pady=8, font=font, bg=bgcolors[fnum % 2]) frame8.checks = {} active = self.model.param('shocks') self.model.params['shocks'].element = frame8 for shock in self.model.shocks.shocksExceptButtons.values(): bv = BooleanVar(value=shock.name in active) shock.element = Checkbutton(frame8.subframe, text=shock.name, var=bv, onvalue=True, offvalue=False, bg=bgcolors[fnum % 2], anchor=W, command=shock.setCallback) shock.element.BooleanVar = bv #To set via the shock object frame8.checks[shock.name] = bv #To set via the shock parameter if self.balloon and shock.desc is not None: self.balloon.bind(shock.element, shock.desc) shock.element.pack(fill=BOTH) b = 0 if len(self.model.shocks.buttons): bframe = Frame(frame8.subframe, bg=bgcolors[fnum % 2]) for c in range(2): bframe.columnconfigure(c, weight=1) for shock in self.model.shocks.buttons.values(): shock.element = Button(bframe, text=shock.name, command=shockCallback(shock.name), padx=10, pady=10, highlightbackground=bgcolors[fnum % 2]) shock.element.grid(row=3 + int(ceil((b + 1) / 2)), column=b % 2, sticky='W') if self.balloon and shock.desc is not None: self.balloon.bind(shock.element, shock.desc) b += 1 bframe.pack(fill=BOTH) frame8.pack(fill="x", side=TOP) cbot = self.model.doHooks('CpanelBottom', [self, bgcolors[fnum % 2]]) if cbot: cbot.pack(fill="x", side=TOP) fnum += 1 #Set application name self.parent.title(self.model.name + (' ' if self.model.name != '' else '') + 'Control Panel') self.parent.resizable(0, 0) if sys.platform == 'darwin': try: from Foundation import NSBundle bundle = NSBundle.mainBundle() if bundle: info = bundle.localizedInfoDictionary( ) or bundle.infoDictionary() if info and info['CFBundleName'] == 'Python': info['CFBundleName'] = 'Helipad' except: print('Use pip to install pyobjc for nice Mac features')
#!/usr/bin/env python # Nicolas Seriot # 2015-04-11 import argparse import os import time from Foundation import NSBundle, NSClassFromString, NSDictionary, NSURL success = NSBundle.bundleWithPath_("/System/Library/PrivateFrameworks/PhotoLibraryPrivate.framework/Versions/A/Frameworks/PAImaging.framework").load() assert success == True CIImage = NSClassFromString("CIImage") assert CIImage CIFilter = NSClassFromString("CIFilter") assert CIFilter NSBitmapImageRep = NSClassFromString("NSBitmapImageRep") assert NSBitmapImageRep IPAPhotoAdjustmentStackSerializer_v10 = NSClassFromString("IPAPhotoAdjustmentStackSerializer_v10") assert IPAPhotoAdjustmentStackSerializer_v10 ipaPASS = IPAPhotoAdjustmentStackSerializer_v10.alloc().init() def apply_cifilter_with_name(filter_name, orientation, in_path, out_path, dry_run=False): print "-- in: ", in_path
#!/usr/bin/python approved_UUIDs = ['your-beacon-UUID-here'] # see line 64 path_to_lock_sound = '/Users/frogor/Desktop/car_lock.m4a' path_to_warn_sound = '/Users/frogor/Desktop/viper_warning.m4a' import time import objc from objc import NO from Foundation import NSBundle, NSClassFromString, NSObject, NSRunLoop, NSDate, NSUUID, NSMakeRange, NSURL from AVFoundation import AVAudioPlayer import Quartz global lock_player global warn_player CoreBluetooth = NSBundle.bundleWithIdentifier_('com.apple.CoreBluetooth') _ = CoreBluetooth.load() CBCentralManager = NSClassFromString('CBCentralManager') constants = [ ('CBCentralManagerScanOptionAllowDuplicatesKey', '@'), ('CBAdvertisementDataManufacturerDataKey', '@'), ] objc.loadBundleVariables(CoreBluetooth, globals(), constants) Login = NSBundle.bundleWithPath_( '/System/Library/PrivateFrameworks/login.framework') functions = [ ('SACLockScreenImmediate', '@'), ]
#!/usr/bin/env python import time from Foundation import NSObject, NSAppleScript, NSBundle, NSDistributedNotificationCenter from AppKit import NSWorkspace, NSWorkspaceDidWakeNotification, NSWorkspaceDidLaunchApplicationNotification, NSWorkspaceDidTerminateApplicationNotification from PyObjCTools import AppHelper import os from subprocess import call info = NSBundle.mainBundle().infoDictionary() info["LSBackgroundOnly"] = "1" class EventNotifier(): def __init__(self, distributed_path, notification_path): self.distributed_path = distributed_path self.notification_path = notification_path self.notification_manager = NotificationManager() def run(self): self.load_events(self.notification_path, self.notification_manager.register_handler) self.load_events( self.distributed_path, self.notification_manager.register_distributed_handler) self.notification_manager.run()
def getBundlePath(): return NSBundle.mainBundle().bundlePath()
def init(self): self = objc.super(LocalTitleBarView, self).init() if self: NSBundle.loadNibNamed_owner_("VideoLocalTitleBarView", self) return self
import objc from Foundation import NSBundle IOKit = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit') functions = [ ("IOServiceGetMatchingService", b"II@"), ("IOServiceMatching", b"@*"), ("IORegistryEntryCreateCFProperties", b"IIo^@@I"), ("IOPSCopyPowerSourcesByType", b"@I"), ("IOPSCopyPowerSourcesInfo", b"@"), ] objc.loadBundleFunctions(IOKit, globals(), functions) # matches information pulled by: pmset -g rawbatt def raw_battery_dict(): battery = IOServiceGetMatchingService( 0, IOServiceMatching("AppleSmartBattery")) if (battery != 0): # we have a battery err, props = IORegistryEntryCreateCFProperties(battery, None, None, 0) return props # matches information pulled by: pmset -g batt def adjusted_battery_dict(): try: battery = list(IOPSCopyPowerSourcesByType(0))[0] except:
def applicationDidFinishLaunching_(self, sender): BlinkLogger().log_debug("Application launched") branding_file = NSBundle.mainBundle().infoDictionary().objectForKey_("BrandingFile") try: branding = __import__(branding_file) except ImportError: try: import branding except ImportError: branding = Null branding.setup(self) if self.updater and self.sp_update_url is not None: self.updater.sp.setFeedURL_(NSURL.URLWithString_(self.sp_update_url)) self.blinkMenu.setTitle_(self.applicationNamePrint) config_file = ApplicationData.get('config') self.icloud_manager = iCloudManager() self.backend = SIPManager() self.contactsWindowController.setup(self.backend) while True: try: first_run = not os.path.exists(config_file) self.contactsWindowController.first_run = first_run self.backend.init() self.backend.fetch_account() accounts = AccountManager().get_accounts() if not accounts or (first_run and accounts == [BonjourAccount()]): self.wait_for_enrollment = True self.enroll() break except FileParserError as exc: BlinkLogger().log_warning("Error parsing configuration file: %s" % exc) if NSRunAlertPanel(NSLocalizedString("Error", "Window title"), NSLocalizedString("The configuration file is corrupted. You will need to replace it and re-enter your account information. \n\nYour current configuration file will be backed up to %s.corrupted. ", "Label") % config_file, NSLocalizedString("Replace", "Button title"), NSLocalizedString("Quit", "Button title"), None) != NSAlertDefaultReturn: NSApp.terminate_(None) return os.rename(config_file, config_file+".corrupted") BlinkLogger().log_info("Renamed configuration file to %s" % config_file+".corrupted") except BaseException as exc: import traceback print(traceback.print_exc()) NSRunAlertPanel(NSLocalizedString("Error", "Window title"), NSLocalizedString("There was an error during startup of core functionality:\n%s", "Label") % exc, NSLocalizedString("Quit", "Button title"), None, None) NSApp.terminate_(None) return # window should be shown only after enrollment check if self.wait_for_enrollment: BlinkLogger().log_info('Starting User Interface') self.contactsWindowController.model.moveBonjourGroupFirst() self.contactsWindowController.showWindow_(None) self.wait_for_enrollment = False self.contactsWindowController.setupFinished() SMSWindowManager.SMSWindowManager().setOwner_(self.contactsWindowController) self.debugWindow = DebugWindow.alloc().init() self.chatWindowController = ChatWindowController.ChatWindowController.alloc().init()
from Foundation import NSMutableURLRequest from Foundation import NSURLRequestReloadIgnoringLocalCacheData from Foundation import NSURLResponseUnknownLength from Foundation import NSLog from Foundation import NSURLCredential, NSURLCredentialPersistenceNone from Foundation import NSPropertyListSerialization from Foundation import NSPropertyListMutableContainersAndLeaves from Foundation import NSPropertyListXMLFormat_v1_0 # pylint: enable=E0611 # Disable PyLint complaining about 'invalid' names # pylint: disable=C0103 # disturbing hack warning! # this works around an issue with App Transport Security on 10.11 bundle = NSBundle.mainBundle() info = bundle.localizedInfoDictionary() or bundle.infoDictionary() info['NSAppTransportSecurity'] = {'NSAllowsArbitraryLoads': True} ssl_error_codes = { -9800: u'SSL protocol error', -9801: u'Cipher Suite negotiation failure', -9802: u'Fatal alert', -9803: u'I/O would block (not fatal)', -9804: u'Attempt to restore an unknown session', -9805: u'Connection closed gracefully', -9806: u'Connection closed via error', -9807: u'Invalid certificate chain', -9808: u'Bad certificate format', -9809: u'Underlying cryptographic error', -9810: u'Internal error',
def set_fake_bundleid(bundleid): # disturbing hack warning! Thank you, @frogor bundle = NSBundle.mainBundle() info = bundle.localizedInfoDictionary() or bundle.infoDictionary() # override the bundleid with the one we want info['CFBundleIdentifier'] = bundleid
try: import objc except ImportError: subprocess.run(["pip3", "install", "pyobjc"], stdout=subprocess.PIPE) try: import objc except ImportError: raise Exception( "Missing PyObjc library!\nPlease run the following before starting OCLP:\npip3 install pyobjc" ) from CoreFoundation import CFRelease, kCFAllocatorDefault # type: ignore # pylint: disable=no-name-in-module from Foundation import NSBundle # type: ignore # pylint: disable=no-name-in-module from PyObjCTools import Conversion IOKit_bundle = NSBundle.bundleWithIdentifier_("com.apple.framework.IOKit") # pylint: disable=invalid-name io_name_t_ref_out = b"[128c]" # io_name_t is char[128] const_io_name_t_ref_in = b"r*" CFStringRef = b"^{__CFString=}" CFDictionaryRef = b"^{__CFDictionary=}" CFAllocatorRef = b"^{__CFAllocator=}" # pylint: enable=invalid-name # https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html functions = [ ("IORegistryEntryCreateCFProperties", b"IIo^@" + CFAllocatorRef + b"I"), ("IOServiceMatching", CFDictionaryRef + b"r*"), ("IOServiceGetMatchingServices", b"II" + CFDictionaryRef + b"o^I"), ("IOIteratorNext", b"II"),
def get_fake_bundleid(): # get the current bundleid (which might have been overridden) bundle = NSBundle.mainBundle() info = bundle.localizedInfoDictionary() or bundle.infoDictionary() return info['CFBundleIdentifier']
# This was all run from user space # I haven't tested it with root # ... but it didn't prompt for any permissions under userspace ^_^ # Tested on 10.11.5 import objc from Foundation import NSBundle EAP8021X_bundle = NSBundle.bundleWithPath_('/System/Library/PrivateFrameworks/EAP8021X.framework') Security_bundle = NSBundle.bundleWithIdentifier_('com.apple.security') kEAPOLClientDomainUser = 1 kEAPOLClientDomainSystem = 3 E_functions = [ ('EAPOLClientConfigurationCopyProfiles', '@@'), ('EAPOLClientConfigurationCopyAllLoginWindowProfiles', '@@'), ('EAPOLClientConfigurationCopyAllSystemProfiles', '@@'), ('EAPOLClientConfigurationCreate', '@^@'), ('EAPOLClientConfigurationGetProfileWithID', '@@@'), ('EAPOLClientItemIDCopyIdentity', '@@i'), ('EAPOLClientItemIDCreateWithProfile', '@@'), ('EAPOLClientProfileGetAuthenticationProperties', '@@'), ('EAPOLClientProfileGetUserDefinedName', '@@'), ('EAPOLClientProfileGetWLANSSIDAndSecurityType', '@@o^@'), ('EAPOLClientProfileGetID', '@@'), ('EAPOLControlCopyStateAndStatus', 'i*o^io^@'), ('EAPSecCertificateCopyAttributesDictionary', '@@'), ('EAPSecCertificateCopyUserNameString', '@@'), ] S_functions = [
AVMediaTypeVideo, AVMediaTypeMuxed, AVVideoCodecJPEG, AVVideoCodecKey ) import objc from Quartz.QuartzCore import kCALayerHeightSizable, kCALayerWidthSizable from Quartz.CoreGraphics import kCGColorBlack, CGColorGetConstantColor from Quartz import CVBufferRetain, NSCIImageRep, CIImage, CVBufferRelease from Quartz.CoreVideo import kCVPixelBufferPixelFormatTypeKey from Quartz.CoreVideo import kCVPixelFormatType_32BGRA bundle = NSBundle.bundleWithPath_(objc.pathForFramework('CoreMedia.framework')) objc.loadBundleFunctions(bundle, globals(), [('CMSampleBufferGetImageBuffer', b'@@')]) import objc import re from BlinkLogger import BlinkLogger from util import run_in_gui_thread from sipsimple.core import Engine from sipsimple.application import SIPApplication from sipsimple.configuration.settings import SIPSimpleSettings from sipsimple.threading.green import run_in_green_thread from application.notification import NotificationCenter, IObserver, NotificationData from application.python import Null
def __init__(self) -> None: info_dict = NSBundle.mainBundle().infoDictionary() if "CFBundleIdentifier" not in info_dict: info_dict["CFBundleIdentifier"] = BUNDLE_IDENTIFIER
# coding=utf-8 import SegmentsPen reload(SegmentsPen) from fontTools.misc.arrayTools import pointInRect from fontTools.misc.arrayTools import offsetRect, sectRect from Foundation import NSBundle import objc _path = NSBundle.mainBundle().bundlePath() _path = _path + "/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/BridgeSupport/GlyphsCore.bridgesupport" f = open(_path) objc.parseBridgeSupport(f.read(), globals(), _path) f.close() def segmentInBound(segment, bounds): minX, minY, maxX, maxY = bounds for point in segment: if pointInRect(point, bounds): return True found = minX <= point[0] <= maxX if found: return True return False class OCCTouche(object): """Checks a font for touching glyphs. font = CurrentFont()
progress_method=progress_method, additional_headers=item.get('additional_headers')) except PkgCachingError, err: return False, unicode(err) NSLog("additional packages complete") # we need to wrap our call to startosinstall with a utility # that makes startosinstall think it is connected to a tty-like # device so its output is unbuffered so we can get progress info # otherwise we get nothing until the process exits. # # Get path to python interpreter python_interpreter = "/usr/bin/python" if not os.path.exists(python_interpreter): python_interpreter = os.path.join( NSBundle.mainBundle().privateFrameworksPath(), "Python.framework/Versions/2.7/bin/python") # Try to find our ptyexec tool # first look in the this file's enclosing directory # (../) this_dir = os.path.dirname(os.path.abspath(__file__)) ptyexec_path = os.path.join(this_dir, 'ptyexec') if os.path.exists(python_interpreter) and os.path.exists(ptyexec_path): cmd = [python_interpreter, ptyexec_path] elif os.path.exists('/usr/bin/script'): # fall back to /usr/bin/script # this is not preferred because it uses way too much CPU # checking stdin for input that will never come... cmd = ['/usr/bin/script', '-q', '-t', '1', '/dev/null'] else: # don't wrap it in a tty-like environment at all. Progress info will
def NSLocalizedStringFromTable(key, tbl, comment): return NSBundle.mainBundle().localizedStringForKey_value_table_(key, '', tbl)