Ejemplo n.º 1
0
    def applicationDidFinishLaunching_(self, notification):
        #activate logging with ToggleProxy -logging 1 
        self.shouldLog = NSUserDefaults.standardUserDefaults().boolForKey_("logging")
        
        # load icon files
        self.active_image = NSImage.imageNamed_("StatusBarImage")
        self.inactive_image = NSImage.imageNamed_("StatusBarImage-inactive")
        self.no_network_image = NSImage.imageNamed_("StatusBarImage-noNetwork")
        self.active_image.setTemplate_(True)
        self.inactive_image.setTemplate_(True)
        self.no_network_image.setTemplate_(True)

        # make status bar item
        self.statusitem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
        self.statusitem.retain()
        self.statusitem.setHighlightMode_(False)
        self.statusitem.setEnabled_(True)

        # insert a menu into the status bar item
        self.menu = NSMenu.alloc().init()
        self.statusitem.setMenu_(self.menu)

        # open connection to the dynamic (configuration) store
        self.store = SCDynamicStoreCreate(None, "name.klep.toggleproxy", self.dynamicStoreCallback, None)
        self.prefDict = SCNetworkProtocolGetConfiguration(SCNetworkServiceCopyProtocol(self.service, kSCNetworkProtocolTypeProxies))
        self.constructMenu()

        self.watchForProxyOrIpChanges()
        self.updateUI()
        self.setEnvVariables()
Ejemplo n.º 2
0
def notify(title,
           subtitle,
           info_text,
           delay=0,
           sound=False,
           userInfo={},
           is_error=False):
    icon = NSImage.alloc().initByReferencingFile_(
        os.path.join(ICON_PATH, 'douban.png'))

    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(info_text)
    notification.setUserInfo_(userInfo)
    notification.set_identityImage_(icon)
    if is_error:
        error_image = NSImage.alloc().initByReferencingFile_(
            os.path.join(ICON_PATH, 'error.png'))
        notification.setContentImage_(error_image)
    if sound:
        notification.setSoundName_('NSUserNotificationDefaultSoundName')

    notification.setDeliveryDate_(
        Foundation.NSDate.dateWithTimeInterval_sinceDate_(
            delay, Foundation.NSDate.date()))
    NSUserNotificationCenter.defaultUserNotificationCenter(
    ).scheduleNotification_(notification)
Ejemplo n.º 3
0
 def __init__(self,
              posSize,
              imagePath=None,
              imageNamed=None,
              imageObject=None,
              title=None,
              bordered=True,
              imagePosition="top",
              callback=None,
              sizeStyle="regular"):
     super(ImageButton, self).__init__(posSize,
                                       title=title,
                                       callback=callback,
                                       sizeStyle=sizeStyle)
     image = None
     if imagePath is not None:
         image = NSImage.alloc().initWithContentsOfFile_(imagePath)
     elif imageNamed is not None:
         image = NSImage.imageNamed_(imageNamed)
     elif imageObject is not None:
         image = imageObject
     if image is not None:
         self._nsObject.setImage_(image)
     self._nsObject.setBordered_(bordered)
     if title is None:
         position = NSImageOnly
     else:
         position = _imagePositionMap[imagePosition]
         if imagePosition == "left":
             self._nsObject.setAlignment_(NSRightTextAlignment)
         elif imagePosition == "right":
             self._nsObject.setAlignment_(NSLeftTextAlignment)
     if not bordered:
         self._nsObject.cell().setHighlightsBy_(NSNoCellMask)
     self._nsObject.setImagePosition_(position)
Ejemplo n.º 4
0
  def applicationDidFinishLaunching_(self, notification):
    self.noDevice = None

    #Create menu
    self.menu = NSMenu.alloc().init()

    self.barItem = dict()

    # Load images
    self.noDeviceImage = NSImage.alloc().initByReferencingFile_('icons/no_device.png')
    self.barImage = dict(kb = NSImage.alloc().initByReferencingFile_('icons/kb.png'),
			 magicMouse = NSImage.alloc().initByReferencingFile_('icons/magic_mouse.png'),
			 mightyMouse = NSImage.alloc().initByReferencingFile_('icons/mighty_mouse.png'),
			 magicTrackpad = NSImage.alloc().initByReferencingFile_('icons/TrackpadIcon.png'))

    #Define menu items
    self.statusbar = NSStatusBar.systemStatusBar()
    self.menuAbout = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('About BtBatStat', 'about:', '')
    self.separator_menu_item = NSMenuItem.separatorItem()
    self.menuQuit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')

    # Get the timer going
    self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 10.0, self, 'tick:', None, True)
    NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
    self.timer.fire()

    #Add menu items
    self.menu.addItem_(self.menuAbout)
    self.menu.addItem_(self.separator_menu_item)
    self.menu.addItem_(self.menuQuit)

    #Check for updates
    checkForUpdates()
Ejemplo n.º 5
0
 def __init__(self, posSize, segmentDescriptions, callback=None, selectionStyle="one", sizeStyle="small"):
     self._setupView(self.nsSegmentedControlClass, posSize)
     if self.nsSegmentedCellClass != NSSegmentedCell:
         self._nsObject.setCell_(self.nsSegmentedCellClass.alloc().init())
     if callback is not None:
         self._setCallback(callback)
     self._setSizeStyle(sizeStyle)
     nsObject = self._nsObject
     nsObject.setSegmentCount_(len(segmentDescriptions))
     nsObject.cell().setTrackingMode_(_trackingModeMap[selectionStyle])
     for segmentIndex, segmentDescription in enumerate(segmentDescriptions):
         width = segmentDescription.get("width", 0)
         title = segmentDescription.get("title", "")
         enabled = segmentDescription.get("enabled", True)
         imagePath = segmentDescription.get("imagePath")
         imageNamed = segmentDescription.get("imageNamed")
         imageObject = segmentDescription.get("imageObject")
         # create the NSImage if needed
         if imagePath is not None:
             image = NSImage.alloc().initWithContentsOfFile_(imagePath)
         elif imageNamed is not None:
             image = NSImage.imageNamed_(imageNamed)
         elif imageObject is not None:
             image = imageObject
         else:
             image = None
         nsObject.setWidth_forSegment_(width, segmentIndex)
         nsObject.setLabel_forSegment_(title, segmentIndex)
         nsObject.setEnabled_forSegment_(enabled, segmentIndex)
         if image is not None:
             nsObject.setImage_forSegment_(image, segmentIndex)
Ejemplo n.º 6
0
    def applicationDidFinishLaunching_(self, _n):
        self.statusbar = NSStatusBar.systemStatusBar()

        self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength)
        self.image = NSImage.alloc().initByReferencingFile_("mydock.icns")
        for i in self.toggles:
            self.toggle_images[i] = NSImage.alloc().initByReferencingFile_(i+".png")

        #self.statusitem.setTitle_(u"Set up %s" % NAME)
        self.statusitem.setImage_(self.image)
        self.statusitem.setHighlightMode_(1)
        self.statusitem.setToolTip_("Docker tray tool")


        self.menu = NSMenu.alloc().init()

        # menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Kill', 'killornot:', '')
        # menuitem.setState_(NSOnState if not self.kill else NSOffState)
        # self.menu.addItem_(menuitem)

        # menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Docker instances', 'instances:', '')
        # self.menu.addItem_(menuitem)
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')
        self.menu.addItem_(menuitem)

        self.statusitem.setMenu_(self.menu)

        # Get config if there is any
        self.restore_config()

        #print("interval: %s" % self.interval)
        self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, self.interval, self, 'loop:', None, True)
        getattr(self, self.loop_func)("Bs?")
Ejemplo n.º 7
0
 def __init__(self, posSize,
             imagePath=None, imageNamed=None, imageObject=None,
             title=None, bordered=True, imagePosition="top", callback=None, sizeStyle="regular"):
     super(ImageButton,  self).__init__(posSize, title=title, callback=callback, sizeStyle=sizeStyle)
     image = None
     if imagePath is not None:
         image = NSImage.alloc().initWithContentsOfFile_(imagePath)
     elif imageNamed is not None:
         image = NSImage.imageNamed_(imageNamed)
     elif imageObject is not None:
         image = imageObject
     if image is not None:
         self._nsObject.setImage_(image)
     self._nsObject.setBordered_(bordered)
     if title is None:
         position = NSImageOnly
     else:
         position= _imagePositionMap[imagePosition]
         if imagePosition == "left":
             self._nsObject.setAlignment_(NSRightTextAlignment)
         elif imagePosition == "right":
             self._nsObject.setAlignment_(NSLeftTextAlignment)
     if not bordered:
         self._nsObject.cell().setHighlightsBy_(NSNoCellMask)
     self._nsObject.setImagePosition_(position)
Ejemplo n.º 8
0
            def _pyobjc_notify(message,
                               title=None,
                               subtitle=None,
                               appIcon=None,
                               contentImage=None,
                               open_URL=None,
                               delay=0,
                               sound=False):

                swizzle(objc.lookUpClass('NSBundle'), b'bundleIdentifier',
                        swizzled_bundleIdentifier)
                notification = NSUserNotification.alloc().init()
                notification.setInformativeText_(message)
                if title:
                    notification.setTitle_(title)
                if subtitle:
                    notification.setSubtitle_(subtitle)
                if appIcon:
                    url = NSURL.alloc().initWithString_(appIcon)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.set_identityImage_(image)
                if contentImage:
                    url = NSURL.alloc().initWithString_(contentImage)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.setContentImage_(image)

                if sound:
                    notification.setSoundName_(
                        "NSUserNotificationDefaultSoundName")
                notification.setDeliveryDate_(
                    NSDate.dateWithTimeInterval_sinceDate_(
                        delay, NSDate.date()))
                NSUserNotificationCenter.defaultUserNotificationCenter(
                ).scheduleNotification_(notification)
Ejemplo n.º 9
0
    def setImage(self, imagePath=None, imageNamed=None, imageObject=None):
        """
        Set the image in the view.

        **imagePath** A file path to an image.

        **imageNamed** The name of an image already load as a `NSImage`_
        by the application.

        **imageObject** A `NSImage`_ object.

        .. note::
           Only one of *imagePath*, *imageNamed*, *imageObject* should be set.

        .. _NSImage: https://developer.apple.com/documentation/appkit/nsimage?language=objc
        """
        if imagePath is not None:
            image = NSImage.alloc().initWithContentsOfFile_(imagePath)
        elif imageNamed is not None:
            image = NSImage.imageNamed_(imageNamed)
        elif imageObject is not None:
            image = imageObject
        else:
            raise ValueError("no image source defined")
        self._nsObject.setImage_(image)
Ejemplo n.º 10
0
 def __init__(self, posSize, segmentDescriptions, callback=None, selectionStyle="one", sizeStyle="small"):
     self._setupView(self.nsSegmentedControlClass, posSize)
     if self.nsSegmentedCellClass != NSSegmentedCell:
         self._nsObject.setCell_(self.nsSegmentedCellClass.alloc().init())
     if callback is not None:
         self._setCallback(callback)
     self._setSizeStyle(sizeStyle)
     nsObject = self._nsObject
     nsObject.setSegmentCount_(len(segmentDescriptions))
     nsObject.cell().setTrackingMode_(_trackingModeMap[selectionStyle])
     for segmentIndex, segmentDescription in enumerate(segmentDescriptions):
         width = segmentDescription.get("width", 0)
         title = segmentDescription.get("title", "")
         enabled = segmentDescription.get("enabled", True)
         imagePath = segmentDescription.get("imagePath")
         imageNamed = segmentDescription.get("imageNamed")
         imageTemplate = segmentDescription.get("imageTemplate")
         imageObject = segmentDescription.get("imageObject")
         # create the NSImage if needed
         if imagePath is not None:
             image = NSImage.alloc().initWithContentsOfFile_(imagePath)
         elif imageNamed is not None:
             image = NSImage.imageNamed_(imageNamed)
         elif imageObject is not None:
             image = imageObject
         else:
             image = None
         nsObject.setWidth_forSegment_(width, segmentIndex)
         nsObject.setLabel_forSegment_(title, segmentIndex)
         nsObject.setEnabled_forSegment_(enabled, segmentIndex)
         if image is not None:
             if imageTemplate is not None:
                 # only change the image template setting if its either True or False
                 image.setTemplate_(imageTemplate)
             nsObject.setImage_forSegment_(image, segmentIndex)
Ejemplo n.º 11
0
            def _pyobjc_notify(message, title=None, subtitle=None, appIcon=None, contentImage=None, open_URL=None, delay=0, sound=False):

                swizzle(objc.lookUpClass('NSBundle'),
                        b'bundleIdentifier',
                        swizzled_bundleIdentifier)
                notification = NSUserNotification.alloc().init()
                notification.setInformativeText_(message)
                if title:
                    notification.setTitle_(title)
                if subtitle:
                    notification.setSubtitle_(subtitle)
                if appIcon:
                    url = NSURL.alloc().initWithString_(appIcon)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.set_identityImage_(image)
                if contentImage:
                    url = NSURL.alloc().initWithString_(contentImage)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.setContentImage_(image)

                if sound:
                    notification.setSoundName_(
                        "NSUserNotificationDefaultSoundName")
                notification.setDeliveryDate_(
                    NSDate.dateWithTimeInterval_sinceDate_(delay, NSDate.date()))
                NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(
                    notification)
Ejemplo n.º 12
0
    def populateList(self, sender):
        self.selected.clear()
        self.w.list._removeSelection()
        item = self.pathList.titleOfSelectedItem()

        for i in range(len(self.w.list)):
            del self.w.list[0]

        thisItem = {}
        image = None
        id = os.getuid()
        systemWarning = "You should not edit or remove existing system's daemons. These jobs are required for a working macOS system."

        if item != 'Active Daemons':
            if item == 'User Agents':
                homedir = os.path.expanduser('~')
                path = homedir + '/Library/LaunchAgents'
                # If the folder doesn't exist in the user folder, create it
                try:
                    os.listdir(path)
                except:
                    os.mkdir(path)
            elif item == 'Global Agents':
                path = '/Library/LaunchAgents'
            elif item == 'Global Daemons':
                path = '/Library/LaunchDaemons'
            elif item == 'System Agents':
                path = '/System/Library/LaunchAgents'
                self._warning(self, systemWarning, "showSystemWarning")
            elif item == 'System Daemons':
                path = '/System/Library/LaunchDaemons'
                self._warning(self, systemWarning, "showSystemWarning")

            items = []
            files = os.listdir(path)
            count = 0

            for file in files:
                if file.endswith('.plist'):
                    file = file.replace('.plist', '')
                    try:
                        pid = launchd.LaunchdJob(file).pid
                    except:
                        pid = False
                    if launchd.LaunchdJob(file).exists() and pid != None:
                        image = NSImage.imageNamed_(NSImageNameStatusAvailable)
                    elif launchd.LaunchdJob(file).exists() and pid == None:
                        image = NSImage.imageNamed_(
                            NSImageNameStatusPartiallyAvailable)
                    else:
                        image = NSImage.imageNamed_(NSImageNameStatusNone)
                    state = True
                    thisItem['image'] = image
                    thisItem['name'] = file
                    self.w.list.append(thisItem)
                    count += 1
            self.w.counter.set(str(count) + ' Jobs')
Ejemplo n.º 13
0
    def applicationDidFinishLaunching_(self, notification):
        # load icon files
        self.active_image = NSImage.imageNamed_("active")
        self.inactive_image = NSImage.imageNamed_("inactive")

        # make status bar item
        self.statusitem = NSStatusBar.systemStatusBar().statusItemWithLength_(
            NSVariableStatusItemLength)
        self.statusitem.retain()
        self.statusitem.setHighlightMode_(False)
        self.statusitem.setEnabled_(True)

        # insert a menu into the status bar item
        self.menu = NSMenu.alloc().init()
        self.statusitem.setMenu_(self.menu)

        # open connection to the dynamic (configuration) store
        self.store = SCDynamicStoreCreate(None, "name.klep.toggleproxy",
                                          self.dynamicStoreCallback, None)

        proxyRef = SCNetworkServiceCopyProtocol(self.service,
                                                kSCNetworkProtocolTypeProxies)
        prefDict = SCNetworkProtocolGetConfiguration(proxyRef)

        hasProxies = False

        # For each of the proxies we are concerned with, check to see if any
        # are configured. If so (even if not enabled), create a menuitem for
        # that proxy type.

        for proxy in self.proxies.values():
            enabled = CFDictionaryGetValue(prefDict, proxy['pref'])
            if enabled is not None:
                proxy[
                    'menuitem'] = self.menu.addItemWithTitle_action_keyEquivalent_(
                        proxy['title'], proxy['action'],
                        proxy['keyEquivalent'])
                hasProxies = True
            else:
                proxy['menuitem'] = None

        if hasProxies:
            self.menu.addItem_(NSMenuItem.separatorItem())
            self.enableallmi = self.menu.addItemWithTitle_action_keyEquivalent_(
                'Enable All', 'enableall', '')
            self.disableallmi = self.menu.addItemWithTitle_action_keyEquivalent_(
                'Disable All', 'disableall', '')
            self.menu.addItem_(NSMenuItem.separatorItem())

        # Need a way to quit
        self.menu.addItemWithTitle_action_keyEquivalent_(
            "Quit", "quitApp:", "")

        # Start working
        # self.loadNetworkServices()
        self.watchForProxyChanges()
        self.updateProxyStatus()
Ejemplo n.º 14
0
    def _createToolbarItem(self, itemData):
        itemIdentifier = itemData.get("itemIdentifier")
        if itemIdentifier is None:
            raise VanillaError(
                "toolbar item data must contain a unique itemIdentifier string"
            )
        if itemIdentifier in self._toolbarItems:
            raise VanillaError("toolbar itemIdentifier is not unique: %r" %
                               itemIdentifier)

        if itemIdentifier not in self._toolbarAllowedItemIdentifiers:
            self._toolbarAllowedItemIdentifiers.append(itemIdentifier)
        if itemData.get("visibleByDefault", True):
            self._toolbarDefaultItemIdentifiers.append(itemIdentifier)

        if itemIdentifier.startswith("NS"):
            # no need to create an actual item for a standard Cocoa toolbar item
            return

        label = itemData.get("label")
        paletteLabel = itemData.get("paletteLabel", label)
        toolTip = itemData.get("toolTip", label)
        imagePath = itemData.get("imagePath")
        imageNamed = itemData.get("imageNamed")
        imageObject = itemData.get("imageObject")
        view = itemData.get("view")
        callback = itemData.get("callback", None)
        # create the NSImage if needed
        if imagePath is not None:
            image = NSImage.alloc().initWithContentsOfFile_(imagePath)
        elif imageNamed is not None:
            image = NSImage.imageNamed_(imageNamed)
        elif imageObject is not None:
            image = imageObject
        else:
            image = None
        toolbarItem = NSToolbarItem.alloc().initWithItemIdentifier_(
            itemIdentifier)
        toolbarItem.setLabel_(label)
        toolbarItem.setPaletteLabel_(paletteLabel)
        toolbarItem.setToolTip_(toolTip)
        if image is not None:
            toolbarItem.setImage_(image)
        elif view is not None:
            toolbarItem.setView_(view)
            toolbarItem.setMinSize_(view.frame().size)
            toolbarItem.setMaxSize_(view.frame().size)
        if callback is not None:
            target = VanillaCallbackWrapper(callback)
            toolbarItem.setTarget_(target)
            toolbarItem.setAction_("action:")
            self._toolbarCallbackWrappers[itemIdentifier] = target
        if itemData.get("selectable", False):
            self._toolbarSelectableItemIdentifiers.append(itemIdentifier)
        self._toolbarItems[itemIdentifier] = toolbarItem
Ejemplo n.º 15
0
    def _createToolbarItem(self, itemData):
        itemIdentifier = itemData.get("itemIdentifier")
        if itemIdentifier is None:
            raise VanillaError("toolbar item data must contain a unique itemIdentifier string")
        if itemIdentifier in self._toolbarItems:
            raise VanillaError("toolbar itemIdentifier is not unique: %r" % itemIdentifier)

        if itemIdentifier not in self._toolbarAllowedItemIdentifiers:
            self._toolbarAllowedItemIdentifiers.append(itemIdentifier)
        if itemData.get("visibleByDefault", True):
            self._toolbarDefaultItemIdentifiers.append(itemIdentifier)

        if itemIdentifier.startswith("NS"):
            # no need to create an actual item for a standard Cocoa toolbar item
            return

        label = itemData.get("label")
        paletteLabel = itemData.get("paletteLabel", label)
        toolTip = itemData.get("toolTip", label)
        imagePath = itemData.get("imagePath")
        imageNamed = itemData.get("imageNamed")
        imageObject = itemData.get("imageObject")
        imageTemplate = itemData.get("imageTemplate")
        view = itemData.get("view")
        callback = itemData.get("callback", None)
        # create the NSImage if needed
        if imagePath is not None:
            image = NSImage.alloc().initWithContentsOfFile_(imagePath)
        elif imageNamed is not None:
            image = NSImage.imageNamed_(imageNamed)
        elif imageObject is not None:
            image = imageObject
        else:
            image = None
        toolbarItem = NSToolbarItem.alloc().initWithItemIdentifier_(itemIdentifier)
        toolbarItem.setLabel_(label)
        toolbarItem.setPaletteLabel_(paletteLabel)
        toolbarItem.setToolTip_(toolTip)
        if image is not None:
            if imageTemplate is not None:
                # only change the image template setting if its either True or False
                image.setTemplate_(imageTemplate)
            toolbarItem.setImage_(image)
        elif view is not None:
            toolbarItem.setView_(view)
            toolbarItem.setMinSize_(view.frame().size)
            toolbarItem.setMaxSize_(view.frame().size)
        if callback is not None:
            target = VanillaCallbackWrapper(callback)
            toolbarItem.setTarget_(target)
            toolbarItem.setAction_("action:")
            self._toolbarCallbackWrappers[itemIdentifier] = target
        if itemData.get("selectable", False):
            self._toolbarSelectableItemIdentifiers.append(itemIdentifier)
        self._toolbarItems[itemIdentifier] = toolbarItem
Ejemplo n.º 16
0
    def initWithFrame_imageDir_(self, frame, imageDir):
        self = super(IntroView, self).initWithFrame_(frame)
        if not self:
            return None
        dropboxImage = NSImage.alloc().initWithContentsOfFile_(os.path.join(imageDir, u'box_stroked_150.png'))
        iW, iH = dropboxImage.size()
        newHeight = iH * 300.0 / iW
        self.dropboxViewFinalPosition = NSRect((25, frame.size[1] - 43 - newHeight), (300, newHeight))
        self.dropboxView = ShadowedImage.alloc().initWithFrame_(self.dropboxViewFinalPosition)
        self.dropboxView.setImageScaling_(NSScaleToFit)
        self.dropboxView.setImage_(dropboxImage)
        self.dropboxView.setShadowColor_(NSColor.colorWithCalibratedRed_green_blue_alpha_(0, 0, 0, 0.5))
        self.dropboxView.setShadowOffset_((0.0, -2.0))
        self.dropboxView.setShadowBlurRadius_(5.0)
        logoImage = NSImage.alloc().initWithContentsOfFile_(os.path.join(imageDir, u'dropboxlogo.png'))
        iW, iH = logoImage.size()
        newHeight = iH * 300.0 / iW
        self.logoViewFinalPosition = NSRect((25, frame.size[1] - 334 - newHeight), (300, newHeight))
        self.logoView = NSImageView.alloc().initWithFrame_(self.logoViewFinalPosition)
        self.logoView.setImage_(logoImage)
        self.versionView = NSTextView.alloc().initWithFrame_(NSRect((0, 0), frame.size))
        self.versionView.setDrawsBackground_(NO)
        self.versionView.setEditable_(NO)
        self.versionView.setSelectable_(NO)
        self.versionView.textStorage().mutableString().setString_(u'Version %s' % build_number.VERSION)
        self.versionView.textStorage().setFont_(NSFont.labelFontOfSize_(14))
        self.versionView.layoutManager().glyphRangeForTextContainer_(self.versionView.textContainer())
        textSize1 = self.versionView.layoutManager().usedRectForTextContainer_(self.versionView.textContainer()).size
        textAnchor1 = 5
        self.versionView2 = NSTextView.alloc().initWithFrame_(NSRect((0, 0), frame.size))
        self.versionView2.setDrawsBackground_(NO)
        self.versionView2.setEditable_(NO)
        self.versionView2.setSelectable_(NO)
        self.versionView2.textStorage().mutableString().setString_(u'Copyright \xa9 2007-2010 Dropbox Inc.')
        self.versionView2.setFont_(NSFont.systemFontOfSize_(NSFont.systemFontSizeForControlSize_(NSSmallControlSize)))
        self.versionView2.layoutManager().glyphRangeForTextContainer_(self.versionView2.textContainer())
        textSize2 = self.versionView2.layoutManager().usedRectForTextContainer_(self.versionView2.textContainer()).size
        textAnchor2 = 4
        bottomToLogoViewBaseline = self.logoView.frame().origin[1] + 17
        textSeparation = 10
        combinedHeight = textSize1[1] + textSize2[1] + textSeparation
        self.versionView2FinalPosition = NSRect(((frame.size[0] - textSize2[0]) / 2.0, (bottomToLogoViewBaseline - combinedHeight) / 2.0), (textSize2[0], textSize2[1] + textAnchor2))
        self.versionView2.setFrame_(self.versionView2FinalPosition)
        self.versionViewFinalPosition = NSRect(((frame.size[0] - textSize1[0]) / 2.0, self.versionView2.frame().origin[1] + textSeparation + self.versionView2.frame().size[1]), (textSize1[0], textSize1[1] + textAnchor1))
        self.versionView.setFrame_(self.versionViewFinalPosition)
        for _view in (self.dropboxView,
         self.logoView,
         self.versionView,
         self.versionView2):
            self.addSubview_(_view)

        return self
Ejemplo n.º 17
0
    def setupStatusBar(self):
        statusbar = NSStatusBar.systemStatusBar()
        statusitem = statusbar.statusItemWithLength_(20).retain()

        icon = NSImage.imageNamed_('status')
        icon.setSize_((20, 20))
        statusitem.setImage_(icon)

        iconHighlight = NSImage.imageNamed_('status-hi')
        iconHighlight.setSize_((20, 20))
        statusitem.setAlternateImage_(iconHighlight)

        statusitem.setHighlightMode_(1)

        # TODO: Put this whole menu creation stuff into interface builder!
        menu = NSMenu.alloc().init()

        linkMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            'Post a Link', 'doLink:', '')
        linkMenu.setTarget_(self)
        # Make it possible to invoke the link menu via a keyboard shortcut.
        linkMenu.setKeyEquivalentModifierMask_(NSShiftKeyMask
                                               | NSCommandKeyMask)
        linkMenu.setKeyEquivalent_('l')
        menu.addItem_(linkMenu)

        menu.addItem_(NSMenuItem.separatorItem())

        previewMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            'Update Preview', 'doPreview:', '')
        previewMenu.setTarget_(self)
        menu.addItem_(previewMenu)

        publishMenuItem = NSMenuItem.alloc(
        ).initWithTitle_action_keyEquivalent_('Publish', None, '')
        publishMenu = NSMenu.alloc().init()
        s3MenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            'S3', 'doPublish:', '')
        s3MenuItem.setTarget_(self)
        publishMenu.addItem_(s3MenuItem)
        publishMenuItem.setSubmenu_(publishMenu)
        menu.addItem_(publishMenuItem)

        menu.addItem_(NSMenuItem.separatorItem())

        quitMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
            'Quit', 'terminate:', '')
        menu.addItem_(quitMenu)

        statusitem.setMenu_(menu)
        menu.release()
Ejemplo n.º 18
0
def movie_maker(movdir,imgdir,timeval,timescale,ih):
	print('making movie %s' % ih)
	imgpaths = glob.glob(os.path.join(imgdir,'ocean_his_*_%s.png'%ih))
	imgpaths.sort()
	
	movpath = os.path.join(movdir,'%s.mov' %ih )
	
	'''I am creating a new image sequence (QuickTime movie).'''
	mov, err = QTMovie.alloc().initToWritableFile_error_(movpath, None)
	
	if mov == None:
		errmsg = 'Could not create movie file: %s' % (movpath)
		raise IOError, errmsg
		
	duration = QTMakeTime(timeval, timescale)
	# you can also use "tiff"
#		attrs = {QTAddImageCodecType: 'avc1'}#, QTAddImageCodecQuality: codecHighQuality}
	attrs = {QTAddImageCodecType: 'avc1'}
	
	for imgpath in imgpaths:
#		img = NSImage.alloc().initWithContentsOfFile_(imgpath)
		img = NSImage.alloc().initByReferencingFile_(imgpath)
		mov.addImage_forDuration_withAttributes_(img, duration, attrs)
		del(img)
	print('Writing movie %s' %ih)
	mov.updateMovieFile()
Ejemplo n.º 19
0
    def _setup_ui_dialogs(self):
        # This needs to be here otherwise we can't install the dialog
        if 'STOQ_TEST_MODE' in os.environ:
            return
        log.debug('providing graphical notification dialogs')
        from stoqlib.gui.base.dialogs import DialogSystemNotifier
        from stoqlib.lib.interfaces import ISystemNotifier
        from kiwi.component import provide_utility
        provide_utility(ISystemNotifier, DialogSystemNotifier(), replace=True)

        from gi.repository import Gtk
        from kiwi.environ import environ
        from stoqlib.gui.stockicons import STOQ_LAUNCHER
        Gtk.Window.set_default_icon_name(STOQ_LAUNCHER)

        if platform.system() == 'Darwin':
            from AppKit import NSApplication, NSData, NSImage
            # FIXME: This should be a 48x48 icon
            data = environ.get_resource_string('stoq', 'pixmaps', 'hicolor',
                                               '24x24', 'actions',
                                               'stoq-launcher.png')
            data = NSData.alloc().initWithBytes_length_(data, len(data))
            icon = NSImage.alloc().initWithData_(data)
            app = NSApplication.sharedApplication()
            app.setApplicationIconImage_(icon)
Ejemplo n.º 20
0
def openSplash():
    global splash
    splash = NSWindow.alloc()
    rect = NSMakeRect(0,0,240,420)
    styleMask = 0
    splash.initWithContentRect_styleMask_backing_defer_(rect, styleMask, NSBackingStoreBuffered, False)

    # http://stackoverflow.com/questions/19437580/splash-screen-in-osx-cocoa-app

    splashImage = NSImageView.alloc().initWithFrame_(rect)
    splashImage.setImageScaling_(NSScaleToFit)
    splashImage.setImage_(NSImage.imageNamed_('ottosplash.png'))
    #[customView addSubview:splashImage];

    #splash.setContentView_(webview)
    splash.setContentView_(splashImage)
    splash.setHasShadow_(True)
    splash.setOpaque_(False)
    splash.setBackgroundColor_(NSColor.clearColor())

    # xPos = NSWidth([[splashWindow screen] frame])/2 - NSWidth([splashWindow frame])/2;
    #CGFloat yPos = NSHeight([[splashWindow screen] frame])/2 - NSHeight([splashWindow frame])/2;
    #[splashWindow setFrame:NSMakeRect(xPos, yPos, NSWidth([splashWindow frame]), NSHeight([splashWindow frame])) display:YES];
    splash.center()
    splash.orderFrontRegardless()
Ejemplo n.º 21
0
    def applicationDidFinishLaunching_(self, notification):
        self.statusbar = NSStatusBar.systemStatusBar()
        # Create the statusbar item
        self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength)
        # Set initial image
        raw_data = base64.b64decode(''.join(GOAGENT_ICON_DATA.strip().splitlines()))
        self.image_data = NSData.dataWithBytes_length_(raw_data, len(raw_data))
        self.image = NSImage.alloc().initWithData_(self.image_data)
        self.statusitem.setImage_(self.image)
        # Let it highlight upon clicking
        self.statusitem.setHighlightMode_(1)
        # Set a tooltip
        self.statusitem.setToolTip_('GoAgent OSX')

        # Build a very simple menu
        self.menu = NSMenu.alloc().init()
        # Show Menu Item
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Show', 'show:', '')
        self.menu.addItem_(menuitem)
        # Hide Menu Item
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Hide', 'hide:', '')
        self.menu.addItem_(menuitem)
        # Rest Menu Item
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Reset', 'reset:', '')
        self.menu.addItem_(menuitem)
        # Default event
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')
        self.menu.addItem_(menuitem)
        # Bind it to the status item
        self.statusitem.setMenu_(self.menu)
Ejemplo n.º 22
0
    def setupUI(self):
        self.statusbar = NSStatusBar.systemStatusBar()
        self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength) #NSSquareStatusItemLength #NSVariableStatusItemLength

        # Set initial image icon
        icon_path = os.path.join(current_path, "../trayicon.ico")
        image = NSImage.alloc().initByReferencingFile_(icon_path)
        image.setScalesWhenResized_(True)
        image.setSize_((20, 20))
        self.statusitem.setImage_(image)

        # Let it highlight upon clicking
        self.statusitem.setHighlightMode_(1)
        self.statusitem.setToolTip_("ZeroNet")

        # Build a very simple menu
        self.menu = NSMenu.alloc().init()
        self.menu.setAutoenablesItems_(False)

        #self.create_menu_item( 'ip_external', 'IP: %s' % INFO['ip_external'],  'info:')
        self.menu.addItem_( NSMenuItem.separatorItem() )

        # Links
        self.create_menu_item( 'open_zeronet', 'Open ZeroNet',  'open:')
        self.create_menu_item( 'open_reddit', 'Zeronet Reddit Community', 'openreddit:')
        self.create_menu_item( 'open_gh', 'Report issues/feature requests', 'opengithub:')

        self.menu.addItem_( NSMenuItem.separatorItem() )

        self.create_menu_item( 'quit_zeronet', 'Quit ZeroNet', 'windowWillClose:' )

        # Bind it to the status item and hide dock icon
        self.statusitem.setMenu_(self.menu)
        NSApp.setActivationPolicy_(NSApplicationActivationPolicyProhibited)
Ejemplo n.º 23
0
    def addOverlapToolbarItem(self, info):

        toolbarItems = info['toolbarItems']

        label = 'Add Overlap w/ UI'
        identifier = 'addOverlapUI'
        filename = 'AddOverlapButtonUI.pdf'
        callback = self.addOverlap
        index = -2

        imagePath = os.path.join(self.base_path, 'resources', filename)
        image = NSImage.alloc().initByReferencingFile_(imagePath)

        view = ToolbarGlyphTools((30, 25), [dict(image=image, toolTip=label)],
                                 trackingMode="one")

        for item in list(toolbarItems):
            if item['itemIdentifier'] == identifier:
                toolbarItems.remove(item)

        newItem = dict(itemIdentifier=identifier,
                       label=label,
                       callback=callback,
                       view=view)

        toolbarItems.insert(index, newItem)
Ejemplo n.º 24
0
 def getToolbarIcon(self):
     """
     Get icon PDF and return to tool
     """
     iconFileDir = os.path.join(currentDir, "..", "resources", "checkParallelIcon.pdf")
     toolbarIcon = NSImage.alloc().initWithContentsOfFile_(iconFileDir)
     return toolbarIcon
Ejemplo n.º 25
0
 def setupLayers(self):
     resources_dir = get_resources_dir() if hasattr(build_number, 'frozen') else u'images/status'
     badgePath = os.path.join(resources_dir, 'notification-badge.tiff')
     self.badgeImage = NSImage.alloc().initWithContentsOfFile_(badgePath)
     self.overlayLayer = None
     self.badgeRect = NSMakeRect(self.ICON_RECT.origin.x + self.ICON_RECT.size.width - self.BADGE_WIDTH, self.ICON_RECT.origin.y, self.BADGE_WIDTH, self.BADGE_HEIGHT)
     if not CocoaSettings.is_accelerated_compositing_supported():
         return
     self.setWantsLayer_(objc.YES)
     layer = self.layer()
     overlayPosition = CGPoint(self.ICON_RECT.origin.x + self.ICON_RECT.size.width - self.BADGE_WIDTH / 2.0, self.ICON_RECT.origin.y + self.BADGE_HEIGHT)
     overlayRect = CGRect(CGPoint(0, 0), CGSize(self.BADGE_WIDTH, self.BADGE_HEIGHT))
     self.overlayLayer = overlayLayer = CALayer.layer()
     overlayLayer.setBounds_(overlayRect)
     overlayLayer.setPosition_(overlayPosition)
     overlayLayer.setContents_(self.badgeImage)
     overlayLayer.setAnchorPoint_(CGPoint(0.5, 1.0))
     overlayLayer.setHidden_(True)
     self.appearAnimation = CAAnimationGroup.animation()
     self.appearAnimation.setDuration_(2)
     self.appearAnimation.setRepeatCount_(1)
     animations = []
     scale = CAKeyframeAnimation.animationWithKeyPath_('transform.rotation.z')
     scale.setDuration_(0.825)
     scale.setKeyTimes_((0, 0.2, 0.4, 0.6, 0.8, 1.0))
     scale.setValues_((0, 0.34906585, -0.34906585, 0.261799388, -0.261799388, 0))
     scale.setRemovedOnCompletion_(True)
     scale.setTimingFunction_(CAMediaTimingFunction.functionWithName_(kCAMediaTimingFunctionEaseOut))
     animations.append(scale)
     self.appearAnimation.setAnimations_(animations)
     layer.addSublayer_(overlayLayer)
Ejemplo n.º 26
0
def send_OS_X_notify(title, content, img_path):
    '''发送Mac桌面通知'''
    def swizzle(cls, SEL, func):
        old_IMP = cls.instanceMethodForSelector_(SEL)

        def wrapper(self, *args, **kwargs):
            return func(self, old_IMP, *args, **kwargs)

        new_IMP = objc.selector(wrapper,
                                selector=old_IMP.selector,
                                signature=old_IMP.signature)
        objc.classAddMethod(cls, SEL, new_IMP)

    def swizzled_bundleIdentifier(self, original):
        # Use iTunes icon for notification
        return 'com.apple.itunes'

    swizzle(objc.lookUpClass('NSBundle'), b'bundleIdentifier',
            swizzled_bundleIdentifier)
    notification = NSUserNotification.alloc().init()
    notification.setInformativeText_('')
    notification.setTitle_(title.decode('utf-8'))
    notification.setSubtitle_(content.decode('utf-8'))

    notification.setInformativeText_('')
    notification.setUserInfo_({})
    if img_path is not None:
        image = NSImage.alloc().initWithContentsOfFile_(img_path)
        # notification.setContentImage_(image)
        notification.set_identityImage_(image)
    notification.setDeliveryDate_(
        NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date()))
    NSUserNotificationCenter.defaultUserNotificationCenter().\
        scheduleNotification_(notification)
Ejemplo n.º 27
0
	def setFromPixels(self, width, height, pixels):
		if usePyObjC:
			from AppKit import NSImage, NSBitmapImageRep, NSCalibratedRGBColorSpace
			self._image = NSImage.alloc().initWithSize_((width, height))
			pixels = [(int(r * a / 255), int(g * a / 255), int(b * a / 255), a) for r, g, b, a in pixels]
			pixels = ''.join([chr(r) + chr(g) + chr(b) + chr(a) for r, g, b, a in pixels])
			rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
				(pixels, None, None, None, None),
				width, height,
				8, 4,
				True,
				False,
				NSCalibratedRGBColorSpace,
				width * 4, 32,
			)
			self._image.addRepresentation_(rep)
			self.__pixels = pixels # it seems that NSImageRep does not copy the pixel data, so we must retain it here
		else:
			import wx
			self._image = wx.EmptyImage(width, height)
			data = []
			for y in xrange(height):
				for x in xrange(width):
					pixel = pixels[x + width * y]
					self._image.SetRGB(x, y, pixel[0], pixel[1], pixel[2])
					if self._image.HasAlpha():
						self._image.SetAlpha(x, y, pixel[3])
Ejemplo n.º 28
0
	def generateThumbnail(self):
		if not self._thumbnail:
			if usePyObjC:
				from AppKit import NSBitmapImageRep, NSCalibratedRGBColorSpace, NSGraphicsContext, NSCompositeCopy, NSImage
				from Foundation import NSRect
				image = self.image
				rep = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
					None,
					int(self.thumbnailSize), int(self.thumbnailSize),
					8, 4,
					True,
					False,
					NSCalibratedRGBColorSpace,
					0, 32,
				)
				context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(rep)
				oldContext = NSGraphicsContext.currentContext()
				NSGraphicsContext.setCurrentContext_(context)
				image.drawInRect_fromRect_operation_fraction_(
					NSRect((0, 0), (self.thumbnailSize, self.thumbnailSize)),
					NSRect((0, 0), image.size()),
					NSCompositeCopy,
					1.0,
				)
				NSGraphicsContext.setCurrentContext_(oldContext)
				self._thumbnail = NSImage.alloc().initWithSize_((self.thumbnailSize, self.thumbnailSize))
				self._thumbnail.addRepresentation_(rep)
			else:
				import wx
				try:
					image = self.image.Scale(self.thumbnailSize, self.thumbnailSize, wx.IMAGE_QUALITY_HIGH)
				except AttributeError: # wx 2.6 can't do IMAGE_QUALITY_HIGH
					image = self.image.Scale(self.thumbnailSize, self.thumbnailSize)
				self._thumbnail = wx.BitmapFromImage(image)
		return self._thumbnail
Ejemplo n.º 29
0
	def __init__(self, width, height):
		GPixmap.__init__(self)
		#ns_size = NSSize(width, height)
		#ns_image = NSImage.alloc().initWithSize_(ns_size)
		ns_image = NSImage.alloc().init()
		ns_image.setCacheMode_(NSImageCacheNever)
		row_bytes = 4 * width
		ns_bitmap = NSBitmapImageRep.alloc().\
			initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
			None, width, height, 8, 4, True, False, NSCalibratedRGBColorSpace, row_bytes, 32)
		ns_image.addRepresentation_(ns_bitmap)
		ns_bitmap_context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(ns_bitmap)
		ns_graphics_context = FlippedNSGraphicsContext.alloc().initWithBase_(ns_bitmap_context)
		ns_tr = NSAffineTransform.transform()
		ns_tr.translateXBy_yBy_(0.0, height)
		ns_tr.scaleXBy_yBy_(1.0, -1.0)
		#  Using __class__ to get +saveGraphicsState instead of -saveGraphicsState
		NSGraphicsContext.__class__.saveGraphicsState()
		try:
			NSGraphicsContext.setCurrentContext_(ns_graphics_context)
			ns_tr.concat()
		finally:
			NSGraphicsContext.__class__.restoreGraphicsState()
		self._init_with_ns_image(ns_image, flipped = True) #False)
		self._ns_bitmap_image_rep = ns_bitmap
		self._ns_graphics_context = ns_graphics_context
Ejemplo n.º 30
0
def drawIcon(foregroundColor, backgroundColor):
    image = NSImage.alloc().initWithSize_((120, 11))
    image.lockFocus()
    foregroundColor.set()
    path = NSBezierPath.bezierPath()
    path.setLineWidth_(1.0)
    # left
    path.moveToPoint_((0, 5.5))
    path.lineToPoint_((15, 5.5))
    path.moveToPoint_((4, 8.5))
    path.lineToPoint_((0, 5.5))
    path.lineToPoint_((4, 2.5))
    # right
    path.moveToPoint_((120, 5.5))
    path.lineToPoint_((105, 5.5))
    path.moveToPoint_((114, 8.5))
    path.lineToPoint_((120, 5.5))
    path.lineToPoint_((114, 2.5))
    # center
    path.moveToPoint_((50, 5.5))
    path.lineToPoint_((70, 5.5))
    path.moveToPoint_((54, 8.5))
    path.lineToPoint_((50, 5.5))
    path.lineToPoint_((54, 2.5))
    path.moveToPoint_((66, 8.5))
    path.lineToPoint_((70, 5.5))
    path.lineToPoint_((66, 2.5))
    path.stroke()
    image.unlockFocus()
    return image
Ejemplo n.º 31
0
def send_OS_X_notify(title, content, img_path):
    '''发送Mac桌面通知'''
    def swizzle(cls, SEL, func):
        old_IMP = cls.instanceMethodForSelector_(SEL)

        def wrapper(self, *args, **kwargs):
            return func(self, old_IMP, *args, **kwargs)
        new_IMP = objc.selector(wrapper, selector=old_IMP.selector,
                                signature=old_IMP.signature)
        objc.classAddMethod(cls, SEL, new_IMP)

    def swizzled_bundleIdentifier(self, original):
        # Use iTunes icon for notification
        return 'com.apple.itunes'

    swizzle(objc.lookUpClass('NSBundle'),
            b'bundleIdentifier',
            swizzled_bundleIdentifier)
    notification = NSUserNotification.alloc().init()
    notification.setInformativeText_('')
    notification.setTitle_(title.decode('utf-8'))
    notification.setSubtitle_(content.decode('utf-8'))

    notification.setInformativeText_('')
    notification.setUserInfo_({})
    if img_path is not None:
        image = NSImage.alloc().initWithContentsOfFile_(img_path)
        # notification.setContentImage_(image)
        notification.set_identityImage_(image)
    notification.setDeliveryDate_(
            NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date())
    )
    NSUserNotificationCenter.defaultUserNotificationCenter().\
        scheduleNotification_(notification)
Ejemplo n.º 32
0
def getImage(name):
    if name not in imageCache:
        imagePath = os.path.join(resourcesDirectory, name + ".pdf")
        image = NSImage.alloc().initWithContentsOfFile_(imagePath)
        image.setTemplate_(True)
        imageCache[name] = image
    return imageCache[name]
Ejemplo n.º 33
0
def load_image(image_name, lazy = False):
    code = get_current_code()
    degrade_options = [code, None]
    if LOCALE_SPLITCHAR in code:
        short = code.split(LOCALE_SPLITCHAR)[0]
        degrade_options.insert(1, short)
    for lang in degrade_options:
        image_dir = get_image_dir(lang)
        image_path = os.path.join(image_dir, image_name)
        if not os.path.exists(image_path):
            continue
        if lazy:
            return NSImage.alloc().initByReferencingFile_(image_path)
        return NSImage.alloc().initWithContentsOfFile_(image_path)

    raise AttributeError('!! Attempt to load missing image %r' % image_name)
Ejemplo n.º 34
0
 def __init__(self, width, height):
     GPixmap.__init__(self)
     # ns_size = NSSize(width, height)
     # ns_image = NSImage.alloc().initWithSize_(ns_size)
     ns_image = NSImage.alloc().init()
     ns_image.setCacheMode_(NSImageCacheNever)
     row_bytes = 4 * width
     ns_bitmap = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
         None, width, height, 8, 4, True, False, NSCalibratedRGBColorSpace, row_bytes, 32
     )
     ns_image.addRepresentation_(ns_bitmap)
     ns_bitmap_context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(ns_bitmap)
     ns_graphics_context = FlippedNSGraphicsContext.alloc().initWithBase_(ns_bitmap_context)
     ns_tr = NSAffineTransform.transform()
     ns_tr.translateXBy_yBy_(0.0, height)
     ns_tr.scaleXBy_yBy_(1.0, -1.0)
     #  Using __class__ to get +saveGraphicsState instead of -saveGraphicsState
     NSGraphicsContext.__class__.saveGraphicsState()
     try:
         NSGraphicsContext.setCurrentContext_(ns_graphics_context)
         ns_tr.concat()
     finally:
         NSGraphicsContext.__class__.restoreGraphicsState()
     self._init_with_ns_image(ns_image, flipped=True)  # False)
     self._ns_bitmap_image_rep = ns_bitmap
     self._ns_graphics_context = ns_graphics_context
Ejemplo n.º 35
0
    def draw_texture(self, texture, location, scale):
        ''' Draws the texture into this build's graphics context
        at the location, to the given scale.

        self.render() needs to a call parent of this method, in order
        to set up the Cocoa graphics context for the draw calls to work

        texture: a Texture object
        location: (tx, ty) tuple
        scale: (sx, sy) tuple
        '''

        tx, ty = location
        sx, sy = scale

        # Cache all assets so we don't frequently reload our PDFs.
        path = texture.path()
        if path in Build._asset_cache:
            tex = Build._asset_cache[path].copy()
        else:
            tex = NSImage.alloc().initWithContentsOfFile_(path)
            Build._asset_cache[path] = tex.copy()

        if isinstance(texture, TextureWithIndex):
            rep = tex.representations()[0]
            rep.setCurrentPage_(texture.index())

        # TODO: support opacity
        if (sx != 1 or sy != 1):
            #tex = tex.resize((sx, sy))
            tex.setSize_(NSSize(sx, sy))

        # Cocoa uses inverted Y-axis...
        ty_ = self.kpf.height - tex.size().height - ty
        tex.drawAtPoint_fromRect_operation_fraction_(NSPoint(tx, ty_), NSZeroRect, NSCompositeSourceOver, 1.0)
Ejemplo n.º 36
0
def MenuImageRepresentationFactory(glyph):
    font = glyph.font
    cellHeight = 60.0
    cellWidth = 60.0
    imageSize = (cellWidth, cellHeight)
    availableHeight = cellHeight * .6
    yBuffer = int((cellHeight - availableHeight) / 2)
    upm = font.info.unitsPerEm
    descender = font.info.descender
    scale = availableHeight / upm
    glyphWidth = glyph.width * scale
    centerOffset = (cellWidth - glyphWidth) * 0.5
    path = glyph.getRepresentation("defconAppKit.NSBezierPath")
    image = NSImage.alloc().initWithSize_(imageSize)
    image.lockFocus()
    bounds = ((0, 0), imageSize)
    MenuImageBackgroundColor.set()
    NSRectFillUsingOperation(bounds, NSCompositeSourceOver)
    transform = NSAffineTransform.transform()
    transform.translateXBy_yBy_(centerOffset, yBuffer)
    transform.scaleXBy_yBy_(scale, scale)
    transform.translateXBy_yBy_(0, abs(descender))
    transform.concat()
    MenuImageGlyphColor.set()
    path.fill()
    image.unlockFocus()
    return image
Ejemplo n.º 37
0
def init():
    print "init ui cocoa"
    global browserwindow
    app = NSApplication.sharedApplication()
    app.setActivationPolicy_(1)
    start_taskbar()
    app.finishLaunching()
    _browserwindow = NSWindow.alloc()
    icon = NSImage.alloc().initByReferencingFile_(settings.mainicon)
    app.setApplicationIconImage_(icon)

    deleg = Delegate.alloc()
    deleg.init()
    app.setDelegate_(deleg)

    signal.signal(signal.SIGINT, mac_sigint)

    from .input import BrowserDelegate
    bd = BrowserDelegate.alloc()
    bd.init()
    browserwindow = draw_browser(_browserwindow, bd)
    from .... import ui
    ui.log.debug('using cocoa')
    atexit.register(exit)
    gevent_timer(deleg)
    ui.module_initialized.set()
    sys.exit = exit
    AppHelper.runEventLoop()
Ejemplo n.º 38
0
	def init(self):
		"""
		Do all initializing here.
		"""
		try:
			# Settings, default values
			self.name = 'My File Format'
			self.icon = 'ExportIcon'
			self.toolbarPosition = 100
			
			if hasattr(self, 'settings'):
				self.settings()
			
			# Dialog stuff
			# Initiate empty self.dialog here in case of Vanilla dialog,
			# where .dialog is not defined at the class’s root.
			if not hasattr(self, 'dialog'):
				self.dialog = None
			
			thisBundle = NSBundle.bundleForClass_(NSClassFromString(self.className()))
			self.toolbarIcon = NSImage.alloc().initWithContentsOfFile_(thisBundle.pathForImageResource_(self.icon))
			self.toolbarIcon.setName_(self.icon)
			
			if hasattr(self, 'start'):
				self.start()
		
		except:
			self.logError(traceback.format_exc())
		
		return self
Ejemplo n.º 39
0
 def add(self, canvas_or_context):
     if self.movie is None:
         # The first frame will be written to a temporary png file,
         # then opened as a movie file, then saved again as a movie.
         handle, self.tmpfname = mkstemp(".tiff")
         canvas_or_context.save(self.tmpfname)
         try:
             movie, err = QTMovie.movieWithFile_error_(self.tmpfname, None)
             movie.setAttribute_forKey_(NSNumber.numberWithBool_(True), QTMovieEditableAttribute)
             range = QTMakeTimeRange(QTMakeTime(0, 600), movie.duration())
             movie.scaleSegment_newDuration_(range, self._time)
             if err is not None:
                 raise str(err)
             movie.writeToFile_withAttributes_(self.fname, {QTMovieFlatten: True})
             self.movie, err = QTMovie.movieWithFile_error_(self.fname, None)
             self.movie.setAttribute_forKey_(NSNumber.numberWithBool_(True), QTMovieEditableAttribute)
             if err is not None:
                 raise str(err)
             self.imageTrack = self.movie.tracks()[0]
         finally:
             os.remove(self.tmpfname)
     else:
         try:
             canvas_or_context.save(self.tmpfname)
             img = NSImage.alloc().initByReferencingFile_(self.tmpfname)
             self.imageTrack.addImage_forDuration_withAttributes_(img, self._time, {QTAddImageCodecType: "tiff"})
         finally:
             try:
                 os.remove(self.tmpfname)
             except OSError:
                 pass
     self.frame += 1
Ejemplo n.º 40
0
def makeStatusBarMenu():
    global statusImages
    global images
    global statusbar
    global state
    global statusItem

    for i in statusImages.keys():  # Load all images
        images[i] = NSImage.alloc().initByReferencingFile_(statusImages[i])

    statusBar = NSStatusBar.systemStatusBar()
    statusItem = statusBar.statusItemWithLength_(NSVariableStatusItemLength)
    statusItem.setImage_(images[state])  # Set initial image
    statusItem.setHighlightMode_(1)  # Let it highlight upon clicking
    statusItem.setToolTip_('Otto')

    statusMenu = NSMenu.alloc().init()
    statusItem.setMenu_(statusMenu)

    # status bar menu
    (F7, F8, F9) = ('', '', '')
    if hotkeys:
        #(F7, F8, F9) = (NSF7FunctionKey, NSF8FunctionKey, NSF9FunctionKey)
        # sadly i can't currently distunguish between multiple hot keys
        (F7, F8, F9) = ('', '', NSF8FunctionKey)  # note that F9 actually equals F8
    togglePlay = statusMenu.addItemWithTitle_action_keyEquivalent_('Play/Pause', 'togglePlay:', F8)
    nextItem = statusMenu.addItemWithTitle_action_keyEquivalent_('Next', 'next:', F9)
    mainWindowItem = statusMenu.addItemWithTitle_action_keyEquivalent_('Main Window', 'mainWindow:', F7)
    togglePlay.setKeyEquivalentModifierMask_(0)
    nextItem.setKeyEquivalentModifierMask_(0)
    mainWindowItem.setKeyEquivalentModifierMask_(0)
    statusMenu.addItem_(NSMenuItem.separatorItem())
    statusMenu.addItemWithTitle_action_keyEquivalent_('Scan Music', 'loadMusic:', '')
    statusMenu.addItem_(NSMenuItem.separatorItem())
    statusMenu.addItemWithTitle_action_keyEquivalent_('Quit Otto', 'terminate:', '')
Ejemplo n.º 41
0
def resize_image(source_img, dimensions, method = ResizeMethod.FIT):
    assert source_img
    NSApplication.sharedApplication()
    initial_width = float(dimensions[0])
    initial_height = float(dimensions[1])
    width = source_img.bestRepresentationForDevice_(None).pixelsWide()
    height = source_img.bestRepresentationForDevice_(None).pixelsHigh()
    pixel_size = NSMakeSize(width, height)
    orig_size = source_img.size()
    width_ratio = initial_width / pixel_size[0]
    height_ratio = initial_height / pixel_size[1]
    if method == ResizeMethod.FIT:
        width_ratio = min(width_ratio, height_ratio)
        height_ratio = min(width_ratio, height_ratio)
    if method == ResizeMethod.CROP:
        width_ratio = max(width_ratio, height_ratio)
        height_ratio = max(width_ratio, height_ratio)
    resized_width = width * width_ratio
    resized_height = height * height_ratio
    crop_width = orig_size.width
    crop_height = orig_size.height
    if method is ResizeMethod.CROP:
        crop_width = initial_width / resized_width * orig_size.width
        crop_height = initial_height / resized_height * orig_size.height
    final_width = min(resized_width, initial_width)
    final_height = min(resized_height, initial_height)
    target_img = NSImage.alloc().initWithSize_(NSMakeSize(final_width, final_height))
    target_img.lockFocus()
    TRACE('Resized image sizes W=%r, H=%r', final_width, final_height)
    source_img.drawInRect_fromRect_operation_fraction_(NSMakeRect(0, 0, final_width, final_height), NSMakeRect((orig_size.width - crop_width) / 2, (orig_size.height - crop_height) / 2, crop_width, crop_height), NSCompositeSourceOver, 1.0)
    target_img.unlockFocus()
    return target_img
Ejemplo n.º 42
0
 def add(self, canvas_or_context):
     if self.movie is None:
         # The first frame will be written to a temporary png file,
         # then opened as a movie file, then saved again as a movie.
         handle, self.tmpfname = mkstemp('.tiff')
         canvas_or_context.save(self.tmpfname)
         try:
             movie, err = QTMovie.movieWithFile_error_(self.tmpfname)
             movie.setAttribute_forKey_(NSNumber.numberWithBool_(True),
                                        QTMovieEditableAttribute)
             range = QTMakeTimeRange(QTMakeTime(0, 600), movie.duration())
             movie.scaleSegment_newDuration_(range, self._time)
             if err is not None:
                 raise str(err)
             movie.writeToFile_withAttributes_(self.fname,
                                               {QTMovieFlatten: True})
             self.movie, err = QTMovie.movieWithFile_error_(self.fname)
             self.movie.setAttribute_forKey_(NSNumber.numberWithBool_(True),
                                             QTMovieEditableAttribute)
             if err is not None: raise str(err)
             self.imageTrack = self.movie.tracks()[0]
         finally:
             os.remove(self.tmpfname)
     else:
         try:
             canvas_or_context.save(self.tmpfname)
             img = NSImage.alloc().initByReferencingFile_(self.tmpfname)
             self.imageTrack.addImage_forDuration_withAttributes_(
                 img, self._time, {QTAddImageCodecType: 'tiff'})
         finally:
             try:
                 os.remove(self.tmpfname)
             except OSError:
                 pass
     self.frame += 1
Ejemplo n.º 43
0
    def initWithBrowser_andForest_reloadInvalidState_(self, browser, forest, reloadInvalidState):
        self = super(SelectiveSyncBrowserDelegate, self).init()
        if self is None:
            return
        from dropbox.mac.internal import get_resources_dir
        self.default_width = None
        icons_path = get_resources_dir() if hasattr(build_number, 'frozen') else u'icons/'
        self.images = {}
        for key, icon in (('dropbox', 'DropboxFolderIcon_leopard.icns'),
         ('shared', 'shared_leopard.icns'),
         ('public', 'public_leopard.icns'),
         ('photos', 'photos_leopard.icns'),
         ('sandbox', 'sandbox_leopard.icns'),
         ('camerauploads', 'camerauploads_leopard.icns')):
            image = NSImage.alloc().initByReferencingFile_(os.path.join(icons_path, icon))
            image.setSize_((16, 16))
            image.setFlipped_(YES)
            image.recache()
            self.images[key] = image

        images_path = get_resources_dir() if hasattr(build_number, 'frozen') else u'images/mac'
        folder_image = NSWorkspace.sharedWorkspace().iconForFileType_(NSFileTypeForHFSTypeCode('fldr'))
        folder_image.setFlipped_(YES)
        folder_image.setSize_(NSMakeSize(16, 16))
        self.images['folder'] = folder_image
        self.forest = forest
        self.browser_reloadAdvancedView_(browser, self.forest.advanced_view)
        self.reloadInvalidState = reloadInvalidState
        TRACE('initialized %r', self.forest)
        self.browser = browser
        return self
Ejemplo n.º 44
0
    def draw_texture(self, texture, location, scale):
        ''' Draws the texture into this build's graphics context
        at the location, to the given scale.

        self.render() needs to a call parent of this method, in order
        to set up the Cocoa graphics context for the draw calls to work

        texture: a Texture object
        location: (tx, ty) tuple
        scale: (sx, sy) tuple
        '''

        tx, ty = location
        sx, sy = scale
        
        tex = NSImage.alloc().initWithContentsOfFile_(texture.path())

        # TODO: support opacity
        if (sx != 1 or sy != 1):
            #tex = tex.resize((sx, sy))
            tex.setSize_(NSSize(sx, sy))

        # Cocoa uses inverted Y-axis...
        ty_ = self.kpf.height - tex.size().height - ty
        tex.drawAtPoint_fromRect_operation_fraction_(NSPoint(tx, ty_), NSZeroRect, NSCompositeSourceOver, 1.0)
Ejemplo n.º 45
0
def openSplash():
    global splash
    splash = NSWindow.alloc()
    rect = NSMakeRect(0,0,240,420)
    styleMask = 0
    splash.initWithContentRect_styleMask_backing_defer_(rect, styleMask, NSBackingStoreBuffered, False)

    # http://stackoverflow.com/questions/19437580/splash-screen-in-osx-cocoa-app

    splashImage = NSImageView.alloc().initWithFrame_(rect)
    splashImage.setImageScaling_(NSScaleToFit)
    splashImage.setImage_(NSImage.imageNamed_('ottosplash.png'))
    #[customView addSubview:splashImage];

    #splash.setContentView_(webview)
    splash.setContentView_(splashImage)
    splash.setHasShadow_(True)
    splash.setOpaque_(False)
    splash.setBackgroundColor_(NSColor.clearColor())

    # xPos = NSWidth([[splashWindow screen] frame])/2 - NSWidth([splashWindow frame])/2;
    #CGFloat yPos = NSHeight([[splashWindow screen] frame])/2 - NSHeight([splashWindow frame])/2;
    #[splashWindow setFrame:NSMakeRect(xPos, yPos, NSWidth([splashWindow frame]), NSHeight([splashWindow frame])) display:YES];
    splash.center()
    splash.orderFrontRegardless()
Ejemplo n.º 46
0
 def buttonToolBar(self, info):
     toolbarItems = info['toolbarItems']
     
     label = 'Show Reference Viewer'
     identifier = 'ReferenceViewer'
     filename = 'ReferenceIcon.pdf'
     callback = self.buttonStartCallback
     index = -2
     
     imagePath = os.path.join(self.base_path, 'resources', filename)
     image = NSImage.alloc().initByReferencingFile_(imagePath)
     
     view = ToolbarGlyphTools(
         (30, 25), 
         [dict(image=image, toolTip=label)], 
         trackingMode="one"
         )
     
     newItem = dict(
         itemIdentifier = identifier,
         label = label,
         callback = callback,
         view = view
         )
     toolbarItems.insert(index, newItem)
Ejemplo n.º 47
0
 def _processExtensionIcon(self, url, data, error):
     if error is None and len(data) > 0:
         image = NSImage.alloc().initWithData_(data)
         self._extensionIcon = image
         postEvent(EXTENSION_ICON_DID_LOAD_EVENT_KEY,
                   item=self,
                   iconURL=self.extensionIconURL())
Ejemplo n.º 48
0
    def _setup_ui_dialogs(self):
        # This needs to be here otherwise we can't install the dialog
        if 'STOQ_TEST_MODE' in os.environ:
            return
        log.debug('providing graphical notification dialogs')
        from stoqlib.gui.base.dialogs import DialogSystemNotifier
        from stoqlib.lib.interfaces import ISystemNotifier
        from kiwi.component import provide_utility
        provide_utility(ISystemNotifier, DialogSystemNotifier(), replace=True)

        from gi.repository import Gtk
        from kiwi.environ import environ
        from kiwi.ui.pixbufutils import pixbuf_from_string
        data = environ.get_resource_string('stoq', 'pixmaps',
                                           'stoq-stock-app-24x24.png')
        Gtk.Window.set_default_icon(pixbuf_from_string(data))

        if platform.system() == 'Darwin':
            from AppKit import NSApplication, NSData, NSImage
            bytes = environ.get_resource_string('stoq', 'pixmaps',
                                                'stoq-stock-app-48x48.png')
            data = NSData.alloc().initWithBytes_length_(bytes, len(bytes))
            icon = NSImage.alloc().initWithData_(data)
            app = NSApplication.sharedApplication()
            app.setApplicationIconImage_(icon)
Ejemplo n.º 49
0
def movie_maker(movdir, imgdir, timeval, timescale, ih):
    print('making movie %s' % ih)
    imgpaths = glob.glob(os.path.join(imgdir, 'ocean_his_*_%s.png' % ih))
    imgpaths.sort()

    movpath = os.path.join(movdir, '%s.mov' % ih)
    '''I am creating a new image sequence (QuickTime movie).'''
    mov, err = QTMovie.alloc().initToWritableFile_error_(movpath, None)

    if mov == None:
        errmsg = 'Could not create movie file: %s' % (movpath)
        raise IOError, errmsg

    duration = QTMakeTime(timeval, timescale)
    # you can also use "tiff"
    #		attrs = {QTAddImageCodecType: 'avc1'}#, QTAddImageCodecQuality: codecHighQuality}
    attrs = {QTAddImageCodecType: 'avc1'}

    for imgpath in imgpaths:
        #		img = NSImage.alloc().initWithContentsOfFile_(imgpath)
        img = NSImage.alloc().initByReferencingFile_(imgpath)
        mov.addImage_forDuration_withAttributes_(img, duration, attrs)
        del (img)
    print('Writing movie %s' % ih)
    mov.updateMovieFile()
Ejemplo n.º 50
0
def init():
    print "init ui cocoa"
    global browserwindow
    app = NSApplication.sharedApplication()
    app.setActivationPolicy_(1)
    start_taskbar()
    app.finishLaunching()
    _browserwindow = NSWindow.alloc()
    icon = NSImage.alloc().initByReferencingFile_(settings.mainicon)
    app.setApplicationIconImage_(icon)
    
    deleg = Delegate.alloc()
    deleg.init()
    app.setDelegate_(deleg)
    
    signal.signal(signal.SIGINT, mac_sigint)
    
    from .input import BrowserDelegate
    bd = BrowserDelegate.alloc()
    bd.init()
    browserwindow = draw_browser(_browserwindow, bd)
    from .... import ui
    ui.log.debug('using cocoa')
    atexit.register(exit)
    gevent_timer(deleg)
    ui.module_initialized.set()
    sys.exit = exit
    AppHelper.runEventLoop()
Ejemplo n.º 51
0
    def _setup_ui_dialogs(self):
        # This needs to be here otherwise we can't install the dialog
        if 'STOQ_TEST_MODE' in os.environ:
            return
        log.debug('providing graphical notification dialogs')
        from stoqlib.gui.base.dialogs import DialogSystemNotifier
        from stoqlib.lib.interfaces import ISystemNotifier
        from kiwi.component import provide_utility
        provide_utility(ISystemNotifier, DialogSystemNotifier(), replace=True)

        import gtk
        from kiwi.environ import environ
        from kiwi.ui.pixbufutils import pixbuf_from_string
        data = environ.get_resource_string(
            'stoq', 'pixmaps', 'stoq-stock-app-24x24.png')
        gtk.window_set_default_icon(pixbuf_from_string(data))

        if platform.system() == 'Darwin':
            from AppKit import NSApplication, NSData, NSImage
            bytes = environ.get_resource_string(
                'stoq', 'pixmaps', 'stoq-stock-app-48x48.png')
            data = NSData.alloc().initWithBytes_length_(bytes, len(bytes))
            icon = NSImage.alloc().initWithData_(data)
            app = NSApplication.sharedApplication()
            app.setApplicationIconImage_(icon)
Ejemplo n.º 52
0
    def setupStatusBar(self):
        statusbar = NSStatusBar.systemStatusBar()
        statusitem = statusbar.statusItemWithLength_(20).retain()
        
        icon = NSImage.imageNamed_('status')
        icon.setSize_((20, 20))
        statusitem.setImage_(icon)
        
        iconHighlight = NSImage.imageNamed_('status-hi')
        iconHighlight.setSize_((20, 20))
        statusitem.setAlternateImage_(iconHighlight)
        
        statusitem.setHighlightMode_(1)
        
        # TODO: Put this whole menu creation stuff into interface builder!
        menu = NSMenu.alloc().init()
        
        linkMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Post a Link', 'doLink:', '')
        linkMenu.setTarget_(self);
        # Make it possible to invoke the link menu via a keyboard shortcut.
        linkMenu.setKeyEquivalentModifierMask_(NSShiftKeyMask | NSCommandKeyMask)
        linkMenu.setKeyEquivalent_('l')
        menu.addItem_(linkMenu)
        
        
        menu.addItem_(NSMenuItem.separatorItem())
        
        previewMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Update Preview', 'doPreview:', '')
        previewMenu.setTarget_(self);
        menu.addItem_(previewMenu)
        
        publishMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Publish', None, '')
        publishMenu = NSMenu.alloc().init();
        s3MenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('S3', 'doPublish:', '')
        s3MenuItem.setTarget_(self);
        publishMenu.addItem_(s3MenuItem)
        publishMenuItem.setSubmenu_(publishMenu)
        menu.addItem_(publishMenuItem)
        
        menu.addItem_(NSMenuItem.separatorItem())

        quitMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')
        menu.addItem_(quitMenu)
        
        statusitem.setMenu_(menu)
        menu.release();
Ejemplo n.º 53
0
    def setIconWithContentsOfFile_(self, path):
        """Convenience method for adding an icon.

        Args:
            path: String path to a valid NSImage filetype (png)
        """
        icon = NSImage.alloc().initWithContentsOfFile_(path)
        self.setIcon_(icon)  # pylint: disable=no-member
Ejemplo n.º 54
0
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
Ejemplo n.º 55
0
 def drawRect_(self, rect):
     image = NSImage.alloc().initWithContentsOfFile_(image_path)
     rep = image.representations()[0]
     bg_width = rep.pixelsWide()
     bg_height = rep.pixelsHigh()
     image.drawInRect_fromRect_operation_fraction_(((self.getLeftOffset(bg_width), self.getTopOffset(bg_height)), (bg_width, bg_height)), NSZeroRect, NSCompositeCopy, 1.0)
     imageView = NSImageView.alloc().init()
     imageView.setImage_(image)
     self.addSubview_(imageView)
Ejemplo n.º 56
0
 def refreshWithSender_(self, sender):
     if self.crawlTask is not None:
         return self.stopRefreshWithSender_(sender)
     logger.debug('%r refreshWithSender:%r', self, sender)
     sender.setImage_(NSImage.imageNamed_(NSImageNameStopProgressTemplate))
     self.crawlTask = NSThread.alloc().initWithTarget_selector_object_(
         self, 'crawlWithSender:', sender
     )
     self.crawlTask.start()
Ejemplo n.º 57
0
 def initStatusBarItem(self):
     iconPath = utils.resource_path("qsx", "png")
     self.statusMenuItemIcon = NSImage.alloc().\
         initWithContentsOfFile_(iconPath)
     self.statusItem = NSStatusBar.\
         systemStatusBar().statusItemWithLength_(20)
     self.statusItem.setMenu_(self.status_menu)
     self.statusItem.setTitle_("QSX")
     self.statusItem.setImage_(self.statusMenuItemIcon)
Ejemplo n.º 58
0
    def setupUI(self):
        self.statusbar = NSStatusBar.systemStatusBar()
        # Create the statusbar item
        self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength)
        # Set initial image
        raw_data = base64.b64decode(''.join(GOAGENT_ICON_DATA.strip().splitlines()))
        self.image_data = NSData.dataWithBytes_length_(raw_data, len(raw_data))
        self.image = NSImage.alloc().initWithData_(self.image_data)
        self.statusitem.setImage_(self.image)
        # Let it highlight upon clicking
        self.statusitem.setHighlightMode_(1)
        # Set a tooltip
        self.statusitem.setToolTip_(GOAGENT_TITLE)

        # Build a very simple menu
        self.menu = NSMenu.alloc().init()
        # Show Menu Item
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Show', 'show:', '')
        self.menu.addItem_(menuitem)
        # Hide Menu Item
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Hide', 'hide2:', '')
        self.menu.addItem_(menuitem)
        # Rest Menu Item
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Reload', 'reset:', '')
        self.menu.addItem_(menuitem)
        # Default event
        menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'exit:', '')
        self.menu.addItem_(menuitem)
        # Bind it to the status item
        self.statusitem.setMenu_(self.menu)

        # Console window
        frame = NSMakeRect(0,0,550,350)
        self.console_window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(frame, NSClosableWindowMask|NSTitledWindowMask, NSBackingStoreBuffered, False)
        self.console_window.setTitle_(GOAGENT_TITLE)
        self.console_window.setDelegate_(self)

        # Console view inside a scrollview
        self.scroll_view = NSScrollView.alloc().initWithFrame_(frame)
        self.scroll_view.setBorderType_(NSNoBorder)
        self.scroll_view.setHasVerticalScroller_(True)
        self.scroll_view.setHasHorizontalScroller_(False)
        self.scroll_view.setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable)

        self.console_view = NSTextView.alloc().initWithFrame_(frame)
        self.console_view.setVerticallyResizable_(True)
        self.console_view.setHorizontallyResizable_(True)
        self.console_view.setAutoresizingMask_(NSViewWidthSizable)

        self.scroll_view.setDocumentView_(self.console_view)

        contentView = self.console_window.contentView()
        contentView.addSubview_(self.scroll_view)

        # Hide dock icon
        NSApp.setActivationPolicy_(NSApplicationActivationPolicyProhibited)