Example #1
0
def _update_mac_app_info():
    if sys.platform.startswith('darwin'):
        try:
            from Foundation import NSBundle  # noqa
            bundle = NSBundle.mainBundle()
            if bundle:
                app_info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
                if app_info:
                    app_info['CFBundleName'] = extrap.__title__
            from AppKit import NSWindow
            NSWindow.setAllowsAutomaticWindowTabbing_(False)
        except ImportError:
            pass
Example #2
0
    def dp_it(cls):
        # Create a new application instance ...
        pu_app = NSApplication.sharedApplication()

        # ... and create its delgate.  Note the use of the
        # Objective C constructors below, because Delegate
        # is a subcalss of an Objective C class, NSObject
        pu_delegate = WDelegate.alloc().init()
        # Tell the application which delegate object to use.
        pu_app.setDelegate_(pu_delegate)

        # Now we can can start to create the window ...
        pu_frame = ((0, 0), (350.0, 100.0))
        # (Don't worry about these parameters for the moment. They just specify
        # the type of window, its size and position etc)
        pu_window = NSWindow.alloc(
        ).initWithContentRect_styleMask_backing_defer_(pu_frame, 15, 2, 0)
        # ... tell it which delegate object to use (here it happens
        # to be the same delegate as the application is using)...
        pu_window.setDelegate_(pu_delegate)
        # ... and set some properties. Unicode strings are preferred.
        pu_window.setTitle_(GC_TONO_NM)
        # All set. Now we can show the window ...
        pu_window.center()
        pu_window.orderFrontRegardless()

        # ... and start the application
        AppHelper.runEventLoop()
Example #3
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()
Example #4
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()
Example #5
0
def openAbout():
    global about
    global linkpolicy
    if not about:
        about = NSWindow.alloc()
        rect = Foundation.NSMakeRect(0,0,300,370)
        styleMask = NSTitledWindowMask | NSClosableWindowMask | \
            NSResizableWindowMask | NSMiniaturizableWindowMask
        about.initWithContentRect_styleMask_backing_defer_(rect, styleMask, NSBackingStoreBuffered, False)
        about.setTitle_('About Otto')
        #about.setBackgroundColor_(NSColor.blueColor()) # not working (try it on the webview instead)

        webview = WebKit.WebView.alloc()
        webview.initWithFrame_(rect)
        webview.setFrameLoadDelegate_(NSApp.delegate())

        respath = os.environ['RESOURCEPATH']
        pageurl = Foundation.NSURL.URLWithString_('file://'+respath+'/static/html/about.html')
        aboutreq = Foundation.NSURLRequest.requestWithURL_(pageurl)
        webview.mainFrame().loadRequest_(aboutreq)

        if not linkpolicy:
            linkpolicy = LinkPolicyDelegate.alloc().init()
        webview.setPolicyDelegate_(linkpolicy)

        about.setReleasedWhenClosed_(False)
        about.setContentView_(webview)

    if not about.isVisible():
      about.center()
      #about.display()
    about.orderFrontRegardless()
    about.makeKeyAndOrderFront_(None)
Example #6
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()
Example #7
0
def openAbout():
    global about
    global aboutpolicy
    if not about:
        about = NSWindow.alloc()
        rect = Foundation.NSMakeRect(0,0,300,370)
        styleMask = NSTitledWindowMask | NSClosableWindowMask | \
            NSResizableWindowMask | NSMiniaturizableWindowMask
        about.initWithContentRect_styleMask_backing_defer_(rect, styleMask, NSBackingStoreBuffered, False)
        about.setTitle_('About Otto')
        #about.setBackgroundColor_(NSColor.blueColor()) # not working (try it on the webview instead)

        webview = WebKit.WebView.alloc()
        webview.initWithFrame_(rect)
        webview.setFrameLoadDelegate_(NSApp.delegate())

        respath = os.environ['RESOURCEPATH']
        print 'respath =', respath
        pageurl = Foundation.NSURL.URLWithString_('file://'+respath+'/static/html/about.html')
        aboutreq = Foundation.NSURLRequest.requestWithURL_(pageurl)
        webview.mainFrame().loadRequest_(aboutreq)

        aboutpolicy = AboutPolicyDelegate.alloc().init()
        webview.setPolicyDelegate_(aboutpolicy)

        about.setReleasedWhenClosed_(False)
        about.setContentView_(webview)

    if not about.isVisible():
      about.center()
      #about.display()
    about.orderFrontRegardless()
    about.makeKeyAndOrderFront_(None)
Example #8
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()
Example #9
0
def openMainWindow():
    global win
    global linkpolicy
    global selectfolderdelegate

    if win:
        #win.orderFrontRegardless()
        win.makeKeyAndOrderFront_(None)
        return

    #if win:
    #    del win

    # http://stackoverflow.com/questions/7221699/how-to-load-user-css-in-a-webkit-webview-using-pyobjc

    rect = Foundation.NSMakeRect(0,0,1020,800)
    win = NSWindow.alloc()
    styleMask = NSTitledWindowMask | NSClosableWindowMask | \
        NSResizableWindowMask | NSMiniaturizableWindowMask
    win.initWithContentRect_styleMask_backing_defer_(rect, styleMask, NSBackingStoreBuffered, False)
    win.setTitle_('Otto Audio Jukebox')
    win.center()
    win.setFrameAutosaveName_('mainWindow')
    win.setCollectionBehavior_(NSWindowCollectionBehaviorFullScreenPrimary)
    #win.setBackgroundColor_(NSColor.blackColor().set())  # doesn't seem to do anything

    webview = WebKit.WebView.alloc()
    webview.initWithFrame_(rect)

    #webview.preferences().setUserStyleSheetEnabled_(objc.YES)
    #print webview.preferences().userStyleSheetEnabled()
    #cssurl = Foundation.NSURL.URLWithString_('static/css/webview.css')
    #webview.preferences().setUserStyleSheetLocation_(cssurl)
    #print webview.preferences().userStyleSheetLocation()

    #webview.setCustomUserAgent_('Otto')
    webview.setApplicationNameForUserAgent_('Otto_OSX')  # client uses this to tell if they are running in our webview
    #anfua = webview.applicationNameForUserAgent()
    #print '%%%%%%%%%%%%%%%% appnameforUA', anfua
    #cua = webview.customUserAgent()
    #print '%%%%%%%%%%%%%%%% customUA', cua

    selectfolderdelegate = SelectFolderDelegate.alloc().init()
    webview.setUIDelegate_(selectfolderdelegate)

    pageurl = Foundation.NSURL.URLWithString_('http://localhost:8778/')
    req = Foundation.NSURLRequest.requestWithURL_(pageurl)
    webview.mainFrame().loadRequest_(req)
    #print '$$$$$$$$$$$$$$$$$$$$', webview.stringByEvaluatingJavaScriptFromString_('window.otto = window.otto || {}; otto.app = true;')

    if not linkpolicy:
        linkpolicy = LinkPolicyDelegate.alloc().init()
    webview.setPolicyDelegate_(linkpolicy)

    win.setReleasedWhenClosed_(False)
    win.setContentView_(webview)
    #win.display()
    win.orderFrontRegardless()
    win.makeKeyAndOrderFront_(None)
Example #10
0
 def __init__(self, position, size):
     frame = ((position.x, position.y), (size.width, size.height))
     self.window = NSWindow.alloc()
     self.window.initWithContentRect_styleMask_backing_defer_(frame, NSTitledWindowMask | NSClosableWindowMask, 2,
                                                              False)
     self.window.setLevel_(3)
     self.window.setDelegate_(Delegate.instance())
     self.window.setContentSize_((size.width, size.height))
Example #11
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)
Example #12
0
def openNotices():
    global notices
    if not notices:
        notices = NSWindow.alloc()
        rect = Foundation.NSMakeRect(100,100,570,800)
        styleMask = NSTitledWindowMask | NSClosableWindowMask | \
            NSResizableWindowMask | NSMiniaturizableWindowMask
        notices.initWithContentRect_styleMask_backing_defer_(rect, styleMask, NSBackingStoreBuffered, False)
        notices.setFrameTopLeftPoint_( NSPoint(300, NSHeight(notices.screen().frame()) - 200) )
        notices.setTitle_('Otto Notices')
        #notices.setFrameAutosaveName_('noticesWindow')

        scrollview = NSScrollView.alloc().initWithFrame_(notices.contentView().frame())
        contentSize = scrollview.contentSize()
 
        scrollview.setBorderType_(NSNoBorder)
        scrollview.setHasVerticalScroller_(True)
        scrollview.setHasHorizontalScroller_(False)
        scrollview.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable)

        textview = NSTextView.alloc()
        textview.initWithFrame_( NSMakeRect(0, 0, contentSize.width, contentSize.height) )
        textview.setMaxSize_(NSMakeSize(FLT_MAX, FLT_MAX))
        textview.setVerticallyResizable_(True)
        textview.setHorizontallyResizable_(False)
        textview.setAutoresizingMask_(NSViewWidthSizable)
        textview.textContainer().setContainerSize_(NSMakeSize(contentSize.width, FLT_MAX))
        textview.textContainer().setWidthTracksTextView_(True)
        textview.setEditable_(False)
        textview.setSelectable_(True)
        #textview.setBackgroundColor_(NSColor.blueColor())

        scrollview.setDocumentView_(textview)

        respath = os.environ['RESOURCEPATH']
        try:
            with codecs.open( os.path.join(respath, 'THIRD-PARTY-NOTICES'), 'r', 'utf-8') as f:
                noticestext = f.read()
        except IOError:
            noticestext = 'Could not read THIRD-PARTY-NOTICES file.'
        storage = textview.textStorage()
        nsstring = NSAttributedString.alloc().initWithString_(noticestext)
        storage.insertAttributedString_atIndex_(nsstring, 0)

        notices.setReleasedWhenClosed_(False)
        notices.setContentView_(scrollview)

    #if not notices.isVisible():
    #  notices.center()
    #  #notices.display()
    notices.orderFrontRegardless()
    notices.makeKeyAndOrderFront_(None)
    def init_sdl_window(self):
        if self.sdl_window:
            return
        if self.window is not None:
            return
        if self.streamController.stream is None:
            return
        if self.streamController.stream.video_windows is None:
            return
        if self.streamController.stream.video_windows.remote is None:
            return

        self.sdl_window = self.streamController.stream.video_windows.remote

        self.initial_size = self.streamController.stream.video_windows.remote.size
        self.aspect_ratio = float(self.initial_size[0]) / self.initial_size[1]
        self.sessionController.log_debug('Remote aspect ratio is %.2f' % self.aspect_ratio)

        self.initial_aspect_ratio = self.aspect_ratio

        found = False
        for ratio in self.valid_aspect_ratios:
            if ratio is None:
                continue
            diff = ratio - self.aspect_ratio
            if diff < 0:
                diff = diff * -1
            if self.aspect_ratio > 0.95 * ratio and self.aspect_ratio < 1.05 * ratio:
                found = True
                break

        if not found:
            self.valid_aspect_ratios.append(self.aspect_ratio)

        self.window = NSWindow(cobject=self.sdl_window.native_handle)
        self.window.setTitle_(self.title)
        self.window.setDelegate_(self)
        self.sessionController.log_debug('Init %s in %s' % (self.window, self))
        self.dif_y = self.window.frame().size.height - self.streamController.stream.video_windows.remote.size[1]
        #self.toogleAlwaysOnTop()
        self.updateTrackingAreas()

        frame = self.window.frame()
        self.sessionController.log_info('Remote video stream at %0.fx%0.f resolution' % (frame.size.width, frame.size.height-self.dif_y))
        frame.size.width = 640
        frame.size.height = frame.size.width / self.aspect_ratio
        frame.size.height += self.dif_y
        self.window.setFrame_display_(frame, True)
        self.window.center()
        self.window.registerForDraggedTypes_(NSArray.arrayWithObject_(NSFilenamesPboardType))
    def createWindow(self) -> NSWindow:
        style = (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable
                 | NSWindowStyleMaskMiniaturizable
                 | NSWindowStyleMaskResizable)

        window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
            NSMakeRect(10, 10, 800, 600),  # Initial
            style,
            NSBackingStoreBuffered,
            False)
        window.setTitle_("My App")
        window.setLevel_(NSStatusWindowLevel)
        window.setFrameAutosaveName_("main-window")

        return window
Example #15
0
    def test_020_do_parse_args(self):

        s = u'/Users/donb/Ashley+Roberts/'
        map ( lambda x: x == 2 , ('1', 'b', '4') )
    
        app = NSApplication.sharedApplication()
        obj = app
        
        # print "type(app) is", type(NSApplication), type(NSObject)
        
        printB("test_020", obj)

        printB("test_020 (second run)", obj)

        printB("test_020 (third run)", obj)
        
        win = NSWindow.alloc()

        win_frame = ((100.0, 350.0), (1000.0, 639.0))        
    
        # deferCreation
    
        # Specifies whether the window server creates a window device for the window immediately. 
        # When YES, the window server defers creating the window device until the window is moved onscreen. All display messages sent to the window or its views are postponed until the window is created, just before it’s moved onscreen.

        deferCreation = objc.YES
        # deferCreation = objc.NO

        win.initWithContentRect_styleMask_backing_defer_ (
                            win_frame, 
                                NSTitledWindowMask  |  NSClosableWindowMask | 
                                NSMiniaturizableWindowMask |    NSResizableWindowMask, # |  NSTexturedBackgroundWindowMask,
                            NSBackingStoreBuffered, 
                            deferCreation 
                        )   

        win.setTitle_ ('OpenWorld')
        win.setLevel_ (NSNormalWindowLevel) # 3)                   # floating window
        win.setCollectionBehavior_(1 << 7) # NSWindowCollectionBehaviorFullScreenPrimary

        # wf = win.frame()
        # x, y = wf.origin
        # width, height = wf.size
        # s = "origin=(x=%r y=%r) size=(width=%r height=%r)" % (x,y,width,height)

        win.setViewsNeedDisplay_(objc.NO)

        printB("Win", win, add=['frame'])
Example #16
0
 def initWithImageDir_(self, imageDir):
     self = super(SickWindow, self).initWithContentRect_styleMask_backing_defer_(NSRect((0, 0), (self.WIDTH, self.HEIGHT)), NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask, NSBackingStoreBuffered, YES)
     if not self:
         return
     self.ani = None
     self.setContentView_(SickView.alloc().initWithFrame_imageDir_(NSRect((0, 0), (self.WIDTH, self.HEIGHT)), imageDir))
     self.setTitle_(u'X marks the spot')
     self.started = False
     self.fade_window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(NSRect(self.frame().origin, (self.WIDTH, self.HEIGHT)), NSBorderlessWindowMask, NSBackingStoreBuffered, YES)
     self.fade_window.setOpaque_(NO)
     self.fade_window.setLevel_(NSFloatingWindowLevel)
     self.fade_window.setIgnoresMouseEvents_(YES)
     self.fade_window.setAlphaValue_(0.0)
     self.fade_window.setContentView_(ColorView.alloc().initWithFrame_(NSRect((0, 0), (self.WIDTH, self.HEIGHT))))
     self.fade_window.orderFront_(self)
     self.fade_window.setReleasedWhenClosed_(NO)
     self.addChildWindow_ordered_(self.fade_window, NSWindowAbove)
     self.setReleasedWhenClosed_(NO)
     return self
Example #17
0
    def preferences(self, _):
        if 'prefController' not in self.__dict__:
            # Initialize preference window
            rect = NSMakeRect(0, 0, 500, 500)
            window = NSWindow.alloc(
            ).initWithContentRect_styleMask_backing_defer_(
                rect, NSTitledWindowMask | NSClosableWindowMask,
                NSBackingStoreBuffered, False)
            window.setTitle_('Preference')
            window.center()
            self.prefController = PreferenceController.alloc().initWithWindow_(
                window)
            self.prefController.window().makeKeyWindow()
            # self.prefController.window().setLevel_(NSFloatingWindowLevel)
            self.prefController.window().orderFront_(self)
            self.prefController.setSettingChangedCallback_withArgs_(
                self.reloadSettings, [])

        if not self.prefController.window().isVisible():
            self.prefController.window().makeKeyAndOrderFront_(self)
Example #18
0
def openLicense():
    global license
    if not license:
        license = NSWindow.alloc()
        rect = Foundation.NSMakeRect(100,100,570,440)
        #styleMask = NSTitledWindowMask | NSClosableWindowMask | \
        #    NSResizableWindowMask | NSMiniaturizableWindowMask
        styleMask = NSTitledWindowMask | NSClosableWindowMask | \
            NSMiniaturizableWindowMask
        license.initWithContentRect_styleMask_backing_defer_(rect, styleMask, NSBackingStoreBuffered, False)
        license.setTitle_('Otto License')
        #license.setBackgroundColor_(NSColor.blueColor()) # not working
        #license.setFrameAutosaveName_('licenseWindow')
        license.setFrameTopLeftPoint_( NSPoint(200, NSHeight(license.screen().frame()) - 100) )

        textview = NSTextView.alloc()
        textview.initWithFrame_(rect)
        textview.setEditable_(False)
        textview.setSelectable_(True)

        respath = os.environ['RESOURCEPATH']
        try:
            with codecs.open( os.path.join(respath, 'LICENSE'), 'r', 'utf-8') as f:
                licensetext = f.read()
        except IOError:
            licensetext = 'Could not read LICENSE file.'
        storage = textview.textStorage()
        nsstring = NSAttributedString.alloc().initWithString_(licensetext)
        storage.insertAttributedString_atIndex_(nsstring, 0)

        license.setReleasedWhenClosed_(False)
        license.setContentView_(textview)

    #if not license.isVisible():
    #  license.center()
    #  #license.display()
    license.orderFrontRegardless()
    license.makeKeyAndOrderFront_(None)
Example #19
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)
Example #20
0
    def __init__(self, *args, **kwds):
        if sys.platform.startswith("win"):
            kwds["style"] = wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP
        wx.Frame.__init__(self, *args, **kwds)
        self.Show()
        if wx.Platform == '__WXMAC__' and hasattr(self, 'MacGetTopLevelWindowRef'):
            try:
                from AppKit import NSWindow, NSApp, NSFloatingWindowLevel
                window_ref = self.MacGetTopLevelWindowRef()
                nsw = NSWindow.alloc().initWithWindowRef_(window_ref)
                nsw.setLevel_(NSFloatingWindowLevel)
            except ImportError:
                print "No AppKit module => can't make progress window stay on top."

        self.start_time = time.time()
        self.end_times = None
        self.current_module = None
        self.pause_start_time = None
        self.previous_pauses_duration = 0.

        # GUI stuff
        self.BackgroundColour = cellprofiler.preferences.get_background_color()
        self.tbicon = wx.TaskBarIcon()
        self.tbicon.SetIcon(get_cp_icon(), "CellProfiler2.0")
        self.SetTitle("CellProfiler %s"%(version.title_string))
        self.SetSize((640, 480))
        self.panel = wx.Panel(self, wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)
        times_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.elapsed_control = wx.StaticText(self.panel, -1, 
                                             label=self.elapsed_label(), 
                                             style=wx.ALIGN_LEFT)
        self.remaining_control = wx.StaticText(self.panel, -1, 
                                               label=self.remaining_label(), 
                                               style=wx.ALIGN_RIGHT)
        times_sizer.Add(self.elapsed_control, 1, wx.ALIGN_LEFT | wx.ALL, 5)
        times_sizer.Add(self.remaining_control, 1, wx.ALIGN_RIGHT | wx.ALL, 5)
        sizer.Add(times_sizer, 0, wx.EXPAND)
        self.gauge = wx.Gauge(self.panel, -1, style=wx.GA_HORIZONTAL)
        self.gauge.SetValue(0)
        self.gauge.SetRange(100)
        sizer.Add(self.gauge, 0, wx.ALL | wx.EXPAND, 5)
        self.image_set_control = wx.StaticText(self.panel, -1, label=image_set_label(None, None))
        sizer.Add(self.image_set_control, 0, wx.LEFT | wx.RIGHT, 5)
        self.current_module_control = wx.StaticText(self.panel, -1, label=module_label(None))
        sizer.Add(self.current_module_control, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM, 5)
        buttons_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.play_pause_button = wx.BitmapButton(self.panel, -1, 
                                                 bitmap=wx.BitmapFromImage(get_builtin_image('pause')))
        self.play_pause_button.SetToolTipString("Pause")
        buttons_sizer.Add(self.play_pause_button, 0, wx.ALL, 5)
        self.stop_button = wx.BitmapButton(self.panel, -1, bitmap=wx.BitmapFromImage(get_builtin_image('stop')))
        self.stop_button.SetToolTipString("Stop")
        buttons_sizer.Add(self.stop_button, 0, wx.ALL, 5)
        save_bitmap = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE,
                                               wx.ART_CMN_DIALOG, 
                                               (16,16))
        self.save_button = wx.BitmapButton(self.panel, -1, bitmap = save_bitmap)
        self.save_button.SetToolTipString("Save measurements")
        buttons_sizer.Add(self.save_button, 0, wx.ALL, 5)
        sizer.Add(buttons_sizer, 0, wx.CENTER)
        self.panel.SetSizer(sizer)
        sizer.Fit(self)

        # Timer that updates elapsed
        timer_id = wx.NewId()
        self.timer = wx.Timer(self.panel, timer_id)
        self.timer.Start(500)
        wx.EVT_TIMER(self.panel, timer_id, self.on_timer)
Example #21
0
def main():

    app = NSApplication.sharedApplication()
    
    printB("App (init)", app, only=['acceptsFirstResponder', 'nextResponder']+
                ['activationPolicy','isActive', 'mainWindow', 'canEnterFullScreenMode','windows',
                                'currentSystemPresentationOptions', 'delegate', 'presentationOptions'])


    # oh give me a place in the dock, and allow activation…    
    app.setActivationPolicy_( NSApplicationActivationPolicyRegular    ) 
    
    # app.activateIgnoringOtherApps_(objc.YES)


    printB("App", app, only=['acceptsFirstResponder', 'nextResponder']+
                ['activationPolicy','isActive', 'mainWindow', 'canEnterFullScreenMode','windows',
                                'currentSystemPresentationOptions', 'delegate', 'presentationOptions'])


    delegate = AppDelegate.alloc().init()
    NSApp().setDelegate_(delegate)

    #
    #       Win
    #

    win = NSWindow.alloc()

    win_frame = ((100.0, 350.0), (1000.0, 639.0))        
    
    # deferCreation
    
    # Specifies whether the window server creates a window device for the window immediately. 
    # When YES, the window server defers creating the window device until the window is moved onscreen. All display messages sent to the window or its views are postponed until the window is created, just before it’s moved onscreen.

    deferCreation = objc.YES
    # deferCreation = objc.NO

    win.initWithContentRect_styleMask_backing_defer_ (
                        win_frame, 
                            NSTitledWindowMask  |  NSClosableWindowMask | 
                            NSMiniaturizableWindowMask |    NSResizableWindowMask, # |  NSTexturedBackgroundWindowMask,
                        NSBackingStoreBuffered, 
                        deferCreation 
                    )   

    win.setTitle_ ('OpenWorld')
    win.setLevel_ (NSNormalWindowLevel) # 3)                   # floating window
    win.setCollectionBehavior_(1 << 7) # NSWindowCollectionBehaviorFullScreenPrimary

    wf = win.frame()
    x, y = wf.origin
    width, height = wf.size
    s = "origin=(x=%r y=%r) size=(width=%r height=%r)" % (x,y,width,height)

    printB("Win", win, add=['frame'])
    win.setViewsNeedDisplay_(objc.NO)
    # print_setters(win)

    win_delegate = WinDelegate.alloc().init()
    win.setDelegate_(win_delegate)

    printB("WinDelegate", win_delegate)  # like AppDelegate


    AppHelper.runEventLoop()
Example #22
0
        def _run_progress(comm_queue, message_txt, title_txt, use_bar):
            from AppKit import NSBundle, NSApplication, NSWindow, NSApp, NSScreen, NSMakeRect, NSMakePoint, NSProgressIndicator, NSWindow, \
                               NSTitledWindowMask, NSBackingStoreBuffered, NSProgressIndicatorPreferredAquaThickness, NSTextField, \
                               NSStatusWindowLevel, NSProgressIndicatorBarStyle, NSProgressIndicatorSpinningStyle, NSObject, \
                               NSApplicationDefined, NSEvent, NSTimer, NSSmallControlSize

            class MainController(NSObject):
                timer = None

                def kickRunLoop(self):
                    event = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(NSApplicationDefined, \
                                    NSMakePoint(0,0), 0, 0.0, 0, None, 0, 0, 0)
                    NSApp.postEvent_atStart_(event, True)

                def checkProcess_(self, timer):
                    if not comm_queue.empty():
                        # We Get Signal, Take Off Every Zig - er, time to shut down this forked process
                        # Clear the queue
                        while not comm_queue.empty():
                            ignore = comm_queue.get_nowait()
                        NSApp.stop_(None)
                        # After you stop the runloop, the app has to receive another event to determine the runloop stopped ...
                        self.kickRunLoop()

                def run(self):
                    # You could adjust the 1.0 here to how ever many seconds you wanted to wait between checks to terminate
                    self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
                        1.0, self, self.checkProcess_, None, True)
                    NSApp.activateIgnoringOtherApps_(True)
                    NSApp.run()

            # Evil hack to make this process not show in the Dock
            bundle = NSBundle.mainBundle()
            info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
            info['LSUIElement'] = '1'
            # Create our NSApplication instance
            app = NSApplication.sharedApplication()
            # Create a window, size doesn't matter now, we're going to resize it in the end
            window = NSWindow.alloc(
            ).initWithContentRect_styleMask_backing_defer_(
                NSMakeRect(0, 0, 500, 500), NSTitledWindowMask,
                NSBackingStoreBuffered, True)
            # Build the window from the bottom up
            # Create the progress indicator, placement doesn't matter, will be set later
            progress = NSProgressIndicator.alloc().init()
            if use_bar:
                progress.setStyle_(NSProgressIndicatorBarStyle)
            else:
                progress.setStyle_(NSProgressIndicatorSpinningStyle)
            progress.setUsesThreadedAnimation_(True)
            progress.setIndeterminate_(True)
            progress.startAnimation_(None)
            # Create the text, which will define the width of everything else - size doesn't matter at first...
            message = NSTextField.alloc().initWithFrame_(
                NSMakeRect(20, 50, 20, 20))
            message.setStringValue_(message_txt)
            message.setBezeled_(False)
            message.setDrawsBackground_(False)
            message.setEditable_(False)
            message.setSelectable_(False)
            # Resize the field to fit the text
            message.sizeToFit()
            window.contentView().addSubview_(message)
            # Now we can calculate the width
            # Fix the window geometry
            # A default NSAlert is 420x150, let's aim for something with similar geometry!
            frame = NSMakeRect(0, 0, max(420,
                                         message.frame().size.width + 40), 110)
            screen = NSScreen.mainScreen()
            screenFrame = screen.frame()
            # Fix the progressbar geometry
            if use_bar:
                # Set the bar to stretch the width of the dialog
                progress.setFrame_(
                    NSMakeRect(20, 20, frame.size.width - 40,
                               NSProgressIndicatorPreferredAquaThickness))
            else:
                # Center the spinning wheel at the bottom
                progress.setControlSize_(NSSmallControlSize)
                progress.setFrame_(
                    NSMakeRect((frame.size.width / 2) - 8, 20, 16, 16))
            window.contentView().addSubview_(progress)
            # Pleasant centering, 2/3rds of the way up, in the middle
            highCenterPoint = NSMakePoint(
                (screenFrame.size.width / 2) - (frame.size.width / 2),
                1.3 * (screenFrame.size.height / 2) - (frame.size.height / 2))
            window.setFrame_display_animate_(frame, True, False)
            window.setFrameOrigin_(highCenterPoint)
            window.makeKeyAndOrderFront_(None)
            window.setLevel_(NSStatusWindowLevel)
            window.setTitle_(title_txt)
            window.display()
            controller = MainController.alloc().init()
            controller.run()
class VideoWindowController(NSWindowController):

    valid_aspect_ratios = [None, 1.33, 1.77]
    aspect_ratio_descriptions = {1.33: '4/3', 1.77: '16/9'}
    finished = False
    videoControlPanel = None
    full_screen = False
    initialLocation = None
    always_on_top = False
    localVideoWindow = None
    full_screen_in_progress = False
    mouse_in_window = True
    mouse_timer = None
    window = None
    title = None
    initial_size = None
    dif_y = 0
    disconnectedPanel = None
    show_window_after_full_screen_ends = None
    sdl_window = None
    tracking_area = None
    fliped = False
    aspect_ratio = None
    initial_aspect_ratio = None

    def __new__(cls, *args, **kwargs):
        return cls.alloc().init()

    def __init__(self, streamController):
        self.streamController = streamController
        self.sessionController.log_debug('Init %s' % self)
        self.title = NSLocalizedString("Video with %s", "Window title") % self.sessionController.getTitleShort()
        self.videoControlPanel = VideoControlPanel(self)
        self.flipWnd = mbFlipWindow.alloc().init()
        self.flipWnd.setFlipRight_(True)

    def initLocalVideoWindow(self):
        sessionControllers = self.sessionController.sessionControllersManager.sessionControllers
        other_video_sessions = any(sess for sess in sessionControllers if sess.hasStreamOfType("video") and sess.streamHandlerOfType("video") != self.streamController)
        if not other_video_sessions and not NSApp.delegate().contactsWindowController.localVideoVisible():
            self.localVideoWindow = VideoStreamInitialLocalWindowController(self)

    @property
    def sessionController(self):
        return self.streamController.sessionController

    @run_in_gui_thread
    def init_sdl_window(self):
        if self.sdl_window:
            return
        if self.window is not None:
            return
        if self.streamController.stream is None:
            return
        if self.streamController.stream.video_windows is None:
            return
        if self.streamController.stream.video_windows.remote is None:
            return

        self.sdl_window = self.streamController.stream.video_windows.remote

        self.initial_size = self.streamController.stream.video_windows.remote.size
        self.aspect_ratio = float(self.initial_size[0]) / self.initial_size[1]
        self.sessionController.log_debug('Remote aspect ratio is %.2f' % self.aspect_ratio)

        self.initial_aspect_ratio = self.aspect_ratio

        found = False
        for ratio in self.valid_aspect_ratios:
            if ratio is None:
                continue
            diff = ratio - self.aspect_ratio
            if diff < 0:
                diff = diff * -1
            if self.aspect_ratio > 0.95 * ratio and self.aspect_ratio < 1.05 * ratio:
                found = True
                break

        if not found:
            self.valid_aspect_ratios.append(self.aspect_ratio)

        self.window = NSWindow(cobject=self.sdl_window.native_handle)
        self.window.setTitle_(self.title)
        self.window.setDelegate_(self)
        self.sessionController.log_debug('Init %s in %s' % (self.window, self))
        self.dif_y = self.window.frame().size.height - self.streamController.stream.video_windows.remote.size[1]
        #self.toogleAlwaysOnTop()
        self.updateTrackingAreas()

        frame = self.window.frame()
        self.sessionController.log_info('Remote video stream at %0.fx%0.f resolution' % (frame.size.width, frame.size.height-self.dif_y))
        frame.size.width = 640
        frame.size.height = frame.size.width / self.aspect_ratio
        frame.size.height += self.dif_y
        self.window.setFrame_display_(frame, True)
        self.window.center()
        self.window.registerForDraggedTypes_(NSArray.arrayWithObject_(NSFilenamesPboardType))

    def draggingEntered_(self, sender):
        if self.finished:
            return

        pboard = sender.draggingPasteboard()
        if pboard.types().containsObject_(NSFilenamesPboardType):
            pboard = sender.draggingPasteboard()
            fnames = pboard.propertyListForType_(NSFilenamesPboardType)
            for f in fnames:
                if not os.path.isfile(f) and not os.path.isdir(f):
                    return NSDragOperationNone
            return NSDragOperationCopy
        return NSDragOperationNone

    def prepareForDragOperation_(self, sender):
        if self.finished:
            return

        pboard = sender.draggingPasteboard()
        if pboard.types().containsObject_(NSFilenamesPboardType):
            fnames = pboard.propertyListForType_(NSFilenamesPboardType)
            for f in fnames:
                if not os.path.isfile(f) and not os.path.isdir(f):
                    return False
            return True
        return False

    def performDragOperation_(self, sender):
        if self.finished:
            return

        pboard = sender.draggingPasteboard()
        if pboard.types().containsObject_(NSFilenamesPboardType):
            filenames = pboard.propertyListForType_(NSFilenamesPboardType)
            return self.sendFiles(filenames)
        return False

    def sendFiles(self, fnames):
        filenames = [unicodedata.normalize('NFC', file) for file in fnames if os.path.isfile(file) or os.path.isdir(file)]
        if filenames:
            self.sessionController.sessionControllersManager.send_files_to_contact(self.sessionController.account, self.sessionController.target_uri, filenames)
            return True
        return False

    def updateTrackingAreas(self):
        if self.tracking_area is not None:
            self.window.contentView().removeTrackingArea_(self.tracking_area)
            self.tracking_area = None

        rect = NSZeroRect
        rect.size = self.window.contentView().frame().size
        self.tracking_area = NSTrackingArea.alloc().initWithRect_options_owner_userInfo_(rect,
                                                                                         NSTrackingMouseEnteredAndExited|NSTrackingActiveAlways, self, None)
        self.window.contentView().addTrackingArea_(self.tracking_area)

    @property
    def sessionController(self):
        return self.streamController.sessionController

    def keyDown_(self, event):
        s = event.characters()
        key = s[0].upper()
        if key == chr(27):
            pass
                # TODO video: "Handle Escape"
        else:
            NSView.keyDown_(self, event)

    def mouseEntered_(self, event):
        self.mouse_in_window = True
        self.stopMouseOutTimer()
        if self.videoControlPanel is not None:
            self.videoControlPanel.show()

    def mouseExited_(self, event):
        if self.full_screen or self.full_screen_in_progress:
            return
        self.mouse_in_window = False
        self.startMouseOutTimer()

    def showDisconnectedPanel(self):
        self.disconnectedPanel = VideoDisconnectWindow()
        self.disconnectedPanel.window.setTitle_(self.title)

    def changeAspectRatio(self):
        try:
            idx = self.valid_aspect_ratios.index(self.aspect_ratio)
        except ValueError:
            self.aspect_ratio = None
        else:
            try:
                self.aspect_ratio = self.valid_aspect_ratios[idx+1]
            except IndexError:
                self.aspect_ratio = self.valid_aspect_ratios[1]

        if self.aspect_ratio:
            try:
                desc = self.aspect_ratio_descriptions[self.aspect_ratio]
            except KeyError:
                desc = "%.2f" % self.aspect_ratio

            self.sessionController.log_info("Aspect ratio set to %s" % desc)

        self.updateAspectRatio()

    def updateAspectRatio(self):
        if not self.window:
            return

        if not self.sdl_window:
            return

        if self.aspect_ratio is not None:
            frame = self.window.frame()
            currentSize = frame.size
            scaledSize = currentSize
            scaledSize.height = scaledSize.width / self.aspect_ratio
            frame.size = scaledSize
            self.window.setFrame_display_animate_(frame, True, False)
            self.sdl_window.size = (frame.size.width, frame.size.height)
        elif self.initial_aspect_ratio is not None:
            frame = self.window.frame()
            currentSize = frame.size
            scaledSize = currentSize
            scaledSize.height = scaledSize.width / self.initial_aspect_ratio
            frame.size = scaledSize
            self.window.setFrame_display_animate_(frame, True, False)
            self.sdl_window.size = (frame.size.width, frame.size.height)

    @run_in_gui_thread
    def show(self):
        self.sessionController.log_debug("Show %s" % self)
        if self.finished:
            return

        self.init_sdl_window()
        self.updateAspectRatio()

        if self.videoControlPanel is not None:
            self.videoControlPanel.show()

        self.flip1()

    def flip2(self):
        if self.localVideoWindow and not self.fliped:
            self.flipWnd.flip_to_(self.localVideoWindow.window, self.window)
            self.fliped = True
        else:
            self.window.orderFront_(self)

    def flip1(self):
        # simpler alternative to flip
        if self.localVideoWindow:
            self.localVideoWindow.hide()
        self.window.orderFront_(self)

    def windowWillResize_toSize_(self, window, frameSize):
        if self.aspect_ratio is not None:
            currentSize = self.window.frame().size
            scaledSize = frameSize
            scaledSize.width = frameSize.width
            scaledSize.height = scaledSize.width / self.aspect_ratio
            scaledSize.height += self.dif_y
            return scaledSize
        else:
            return frameSize

    def windowDidResize_(self, notification):
        if not self.streamController.stream:
            return

        if not self.streamController.stream.video_windows:
            return

        if not self.streamController.stream.video_windows.remote:
            return

        # update underlying SDL window
        frame = self.window.frame()
        if frame.size.width != self.streamController.stream.video_windows.remote.size[0]:
            self.streamController.stream.video_windows.remote.size = (frame.size.width, frame.size.height - self.dif_y)

        self.updateTrackingAreas()

    @run_in_gui_thread
    def hide(self):
        if self.localVideoWindow:
            self.localVideoWindow.hide()

        if self.window:
            self.window.orderOut_(self)

        if self.videoControlPanel is not None:
            self.videoControlPanel.hide()

    @run_in_gui_thread
    def goToFullScreen(self):
        self.sessionController.log_debug('goToFullScreen %s' % self)

        if self.finished:
            return

        if self.localVideoWindow:
            self.localVideoWindow.hide()

        if not self.full_screen:
            if self.window:
                self.window.toggleFullScreen_(None)
                self.show()

    @run_in_gui_thread
    def goToWindowMode(self, window=None):
        if self.full_screen:
            self.show_window_after_full_screen_ends = window
            if self.window:
                self.window.toggleFullScreen_(None)
                self.show()

    @run_in_gui_thread
    def toggleFullScreen(self):
        self.sessionController.log_debug('toggleFullScreen %s' % self)

        if self.full_screen_in_progress:
            return

        self.full_screen_in_progress = True
        if self.full_screen:
            self.goToWindowMode()
        else:
            self.goToFullScreen()

    def windowWillResize_toSize_(self, window, frameSize):
        if self.aspect_ratio is None:
            return frameSize

        currentSize = self.window.frame().size
        scaledSize = frameSize
        scaledSize.width = frameSize.width
        scaledSize.height = scaledSize.width / self.aspect_ratio
        return scaledSize

    def windowDidEnterFullScreen_(self, notification):
        if self.window:
            if self.streamController.ended:
                self.window.orderOut_(self)
                return

        self.sessionController.log_debug('windowDidEnterFullScreen %s' % self)

        self.full_screen_in_progress = False
        self.full_screen = True
        self.stopMouseOutTimer()
        NSApp.delegate().contactsWindowController.showLocalVideoWindow()
        NotificationCenter().post_notification("BlinkVideoWindowFullScreenChanged", sender=self)

        if self.videoControlPanel:
            self.videoControlPanel.show()
            self.videoControlPanel.window().makeKeyAndOrderFront_(None)

        if self.window:
            self.window.setLevel_(NSNormalWindowLevel)

    def windowDidExitFullScreen_(self, notification):
        self.sessionController.log_debug('windowDidExitFullScreen %s' % self)

        self.full_screen_in_progress = False
        self.full_screen = False
        NSApp.delegate().contactsWindowController.hideLocalVideoWindow()
        NotificationCenter().post_notification("BlinkVideoWindowFullScreenChanged", sender=self)

        if self.show_window_after_full_screen_ends is not None:
            self.show_window_after_full_screen_ends.makeKeyAndOrderFront_(None)
            self.show_window_after_full_screen_ends = None
        else:
            if self.window:
                self.window.orderFront_(self)
                self.window.setLevel_(NSFloatingWindowLevel if self.always_on_top else NSNormalWindowLevel)

    def keyDown_(self, event):
        super(VideoWindowController, self).keyDown_(event)

    def windowWillClose_(self, sender):
        self.sessionController.log_debug('windowWillClose %s' % self)
        NSApp.delegate().contactsWindowController.hideLocalVideoWindow()
        self.sessionController.removeVideoFromSession()
        if not self.sessionController.hasStreamOfType("chat"):
            NotificationCenter().post_notification("BlinkVideoWindowClosed", sender=self)

    def windowShouldClose_(self, sender):
        return True

    @run_in_gui_thread
    def close(self):
        self.sessionController.log_debug('Close %s' % self)

        if self.finished:
            return

        self.finished = True

        self.goToWindowMode()

        self.flipWnd = None

        self.stopMouseOutTimer()

        self.videoControlPanel.close()

        if self.window:
            self.window.performClose_(None)

        if self.localVideoWindow:
            self.localVideoWindow.close()

    def dealloc(self):
        self.sessionController.log_debug('Dealloc %s' % self)
        self.tracking_area = None
        self.videoControlPanel = None
        self.localVideoWindow = None
        self.streamController = None
        super(VideoWindowController, self).dealloc()

    def toogleAlwaysOnTop(self):
        self.always_on_top  = not self.always_on_top
        self.window.setLevel_(NSFloatingWindowLevel if self.always_on_top else NSNormalWindowLevel)

    def stopMouseOutTimer(self):
        if self.mouse_timer is not None:
            if self.mouse_timer.isValid():
                self.mouse_timer.invalidate()
            self.mouse_timer = None

    def startMouseOutTimer(self):
        if self.mouse_timer is None:
            self.mouse_timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(3, self, "mouseOutTimer:", None, False)
            NSRunLoop.currentRunLoop().addTimer_forMode_(self.mouse_timer, NSRunLoopCommonModes)
            NSRunLoop.currentRunLoop().addTimer_forMode_(self.mouse_timer, NSEventTrackingRunLoopMode)

    def mouseOutTimer_(self, timer):
        self.videoControlPanel.hide()
        self.mouse_timer = None

    def getSecondaryScreen(self):
        try:
            secondaryScreen = (screen for screen in NSScreen.screens() if screen != NSScreen.mainScreen() and screen.deviceDescription()[NSDeviceIsScreen] == 'YES').next()
        except (StopIteration, KeyError):
            secondaryScreen = None
        return secondaryScreen
Example #24
0
    def __init__(self, parent):
        super(QMainWindow, self).__init__(parent)
        uic.loadUi('ui/mainWindow.ui', self)

        self.play_btn.clicked.connect(self.play_btn_clicked)
        self.stop_btn.clicked.connect(self.stop_btn_clicked)
        self.fullscreen_btn.clicked.connect(self.switch_fullscreen_mode)
        self.volume_slider.sliderMoved.connect(self.volume_changed)
        self.tv_channel_list.channelActivated.connect(self.activated_channel)
        self.radio_channel_list.channelActivated.connect(
            self.activated_channel)

        self.video_player.playback_started.connect(self.video_playback_started)
        self.video_player.playback_paused.connect(self.video_playback_paused)
        self.video_player.playback_stopped.connect(self.video_playback_stopped)
        self.video_player.playback_error.connect(self.video_playback_error)
        self.video_player.volume_changed.connect(self.video_volume_changed)
        self.video_player.chromecast_available.connect(
            self.chromecast_available)
        self.video_player.chromecast_connected.connect(
            self.chromecast_connected)

        self.chlist_manager = ChannelListManager()
        self.chlist_manager.channel_added.connect(self.channel_added)
        self.chlist_manager.channellist_available.connect(
            self.channel_list_available)

        self.statusbar.addPermanentWidget(self.bottom_bar, 1)
        self.splitter.setStretchFactor(1, 1)
        self.progress_bar.hide()
        self.progress_label.setText(self.tr("Idle"))
        self.video_player.set_volume(self.volume_slider.value())

        self.channellist_show_actiongroup = QActionGroup(self)
        self.channellist_show_actiongroup.triggered.connect(
            self.show_channel_list)
        chlist_showall_action = QAction(self.tr("All"), self.menu_show_chlist)
        chlist_showall_action.setCheckable(True)
        chlist_showall_action.setChecked(True)
        chlist_showall_action.setActionGroup(self.channellist_show_actiongroup)
        self.menu_show_chlist.addAction(chlist_showall_action)

        os_type = platform.system()
        log.info('Detected OS type: {0}'.format(os_type))
        if os_type == 'Darwin':
            from AppKit import NSWindow, NSUserDefaults
            NSWindow.setAllowsAutomaticWindowTabbing_(False)
            NSUserDefaults.standardUserDefaults().setBool_forKey_(
                False, "NSFullScreenMenuItemEverywhere")
            self.playlist_tab_widget.setDocumentMode(True)

            channel_list_action = self.menubar.actions()[0].menu().actions()[0]
            preferences_list_action = self.menubar.actions()[0].menu().actions(
            )[1]
            self.menubar.removeAction(self.menubar.actions()[0])
            channel_list_action.menu().addAction(preferences_list_action)
            self.menubar.insertAction(self.menubar.actions()[0],
                                      channel_list_action)

        self.load_settings()

        # Set custom icons
        self.play_btn.setIcon(TXIcon('icons/play-button.svg'))
        self.stop_btn.setIcon(TXIcon('icons/stop-button.svg'))
        self.fullscreen_btn.setIcon(TXIcon('icons/fullscreen.svg'))
        self.cast_btn.setIcon(TXIcon('icons/cast.svg'))

        self.cast_label_pixmap.setHidden(True)
        self.cast_label.setHidden(True)
        self.cast_btn.hide()
Example #25
0
    def __init__(self, *args, **kwds):
        if sys.platform.startswith("win"):
            kwds["style"] = wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP
        wx.Frame.__init__(self, *args, **kwds)
        self.Show()
        if wx.Platform == '__WXMAC__' and hasattr(self,
                                                  'MacGetTopLevelWindowRef'):
            try:
                from AppKit import NSWindow, NSApp, NSFloatingWindowLevel
                window_ref = self.MacGetTopLevelWindowRef()
                nsw = NSWindow.alloc().initWithWindowRef_(window_ref)
                nsw.setLevel_(NSFloatingWindowLevel)
            except ImportError:
                print "No AppKit module => can't make progress window stay on top."

        self.start_time = time.time()
        self.end_times = None
        self.current_module = None
        self.pause_start_time = None
        self.previous_pauses_duration = 0.

        # GUI stuff
        self.BackgroundColour = cellprofiler.preferences.get_background_color()
        self.tbicon = wx.TaskBarIcon()
        self.tbicon.SetIcon(get_cp_icon(), "CellProfiler2.0")
        self.SetTitle("CellProfiler %s" % (version.title_string))
        self.SetSize((640, 480))
        self.panel = wx.Panel(self, wx.ID_ANY)
        sizer = wx.BoxSizer(wx.VERTICAL)
        times_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.elapsed_control = wx.StaticText(self.panel,
                                             -1,
                                             label=self.elapsed_label(),
                                             style=wx.ALIGN_LEFT)
        self.remaining_control = wx.StaticText(self.panel,
                                               -1,
                                               label=self.remaining_label(),
                                               style=wx.ALIGN_RIGHT)
        times_sizer.Add(self.elapsed_control, 1, wx.ALIGN_LEFT | wx.ALL, 5)
        times_sizer.Add(self.remaining_control, 1, wx.ALIGN_RIGHT | wx.ALL, 5)
        sizer.Add(times_sizer, 0, wx.EXPAND)
        self.gauge = wx.Gauge(self.panel, -1, style=wx.GA_HORIZONTAL)
        self.gauge.SetValue(0)
        self.gauge.SetRange(100)
        sizer.Add(self.gauge, 0, wx.ALL | wx.EXPAND, 5)
        self.image_set_control = wx.StaticText(self.panel,
                                               -1,
                                               label=image_set_label(
                                                   None, None))
        sizer.Add(self.image_set_control, 0, wx.LEFT | wx.RIGHT, 5)
        self.current_module_control = wx.StaticText(self.panel,
                                                    -1,
                                                    label=module_label(None))
        sizer.Add(self.current_module_control, 0,
                  wx.LEFT | wx.RIGHT | wx.BOTTOM, 5)
        buttons_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.play_pause_button = wx.BitmapButton(
            self.panel,
            -1,
            bitmap=wx.BitmapFromImage(get_builtin_image('pause')))
        self.play_pause_button.SetToolTipString("Pause")
        buttons_sizer.Add(self.play_pause_button, 0, wx.ALL, 5)
        self.stop_button = wx.BitmapButton(self.panel,
                                           -1,
                                           bitmap=wx.BitmapFromImage(
                                               get_builtin_image('stop')))
        self.stop_button.SetToolTipString("Stop")
        buttons_sizer.Add(self.stop_button, 0, wx.ALL, 5)
        save_bitmap = wx.ArtProvider.GetBitmap(wx.ART_FILE_SAVE,
                                               wx.ART_CMN_DIALOG, (16, 16))
        self.save_button = wx.BitmapButton(self.panel, -1, bitmap=save_bitmap)
        self.save_button.SetToolTipString("Save measurements")
        buttons_sizer.Add(self.save_button, 0, wx.ALL, 5)
        sizer.Add(buttons_sizer, 0, wx.CENTER)
        self.panel.SetSizer(sizer)
        sizer.Fit(self)

        # Timer that updates elapsed
        timer_id = wx.NewId()
        self.timer = wx.Timer(self.panel, timer_id)
        self.timer.Start(500)
        wx.EVT_TIMER(self.panel, timer_id, self.on_timer)