<commit_before>/*
 *  Copyright 2016 <NAME>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may
 *  not use these files except in compliance with the License. You may obtain
 *  a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *  License for the specific language governing permissions and limitations
 *  under the License.
 */

import ScreenSaver
import Metal

class MetalScreenSaverView : ScreenSaverView
{
    var device: MTLDevice!
    var displayLink: CVDisplayLink!


    // init and deinit

    override init?(frame: NSRect, isPreview: Bool)
    {
        super.init(frame: frame, isPreview: isPreview)
        device = selectMetalDevice(preferLowPower: true) // TODO: make low power preference a user default?
        wantsLayer = true;
    }

    required init?(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }

    deinit
    {
        CVDisplayLinkStop(displayLink!)
    }

    private func selectMetalDevice(preferLowPower: Bool) -> MTLDevice
    {
        var device: MTLDevice?
        if !preferLowPower {
            device = MTLCreateSystemDefaultDevice()!
        } else {
            for d in MTLCopyAllDevices() {
                device = d
                if d.isLowPower && !d.isHeadless {
                    break
                }
            }
        }
#if DEBUG
        if let name = device?.name {
            NSLog("Using device '\(name)'")
        } else {
            NSLog("No or unknown device")
        }
#endif
        return device! // TODO: can we assume there will always be a device?
    }


    // deferred initialisations that require access to the window

    override func viewDidMoveToSuperview()
    {
        super.viewDidMoveToSuperview()
        if let window = superview?.window {
            layer = makeMetalLayer(window: window, device:device)
            displayLink = makeDisplayLink(window: window)
        }
    }

    private func makeMetalLayer(window: NSWindow, device: MTLDevice) -> CAMetalLayer
    {
        let metalLayer = CAMetalLayer()
        metalLayer.device = device
        metalLayer.pixelFormat = .bgra8Unorm
        metalLayer.framebufferOnly = true
        metalLayer.contentsScale = window.backingScaleFactor
        metalLayer.isOpaque = true
        return metalLayer
    }

    private func makeDisplayLink(window: NSWindow) -> CVDisplayLink
    {
        func displayLinkOutputCallback(_ displayLink: CVDisplayLink, _ inNow: UnsafePointer<CVTimeStamp>, _ inOutputTime: UnsafePointer<CVTimeStamp>, _ flagsIn: CVOptionFlags, _ flagsOut: UnsafeMutablePointer<CVOptionFlags>, _ displayLinkContext: UnsafeMutableRawPointer?) -> CVReturn {
            unsafeBitCast(displayLinkContext, to: MetalScreenSaverView.self).animateOneFrame()
            return kCVReturnSuccess
        }

        var link: CVDisplayLink?
        let screensID = UInt32(window.screen!.deviceDescription["NSScreenNumber"] as! Int)
        CVDisplayLinkCreateWithCGDisplay(screensID, &link)
        CVDisplayLinkSetOutputCallback(link!, displayLinkOutputCallback, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()))
        return link!
    }

    
    // screen saver api

    override class func backingStoreType() -> NSBackingStoreType
    {
        return NSBackingStoreType.retained
    }

    override class func performGammaFade() -> Bool
    {
        return false
    }


    override func startAnimation()
    {
        // we're not calling super because we need to set up our own timer for the animation
        CVDisplayLinkStart(displayLink!)
    }

    override func stopAnimation()
    {
        // we're not calling super because we didn't do it in startAnimation()
        CVDisplayLinkStop(displayLink!)
    }


}
<commit_msg>Tweaking of screen saver configuration.<commit_after>/*
 *  Copyright 2016 <NAME>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may
 *  not use these files except in compliance with the License. You may obtain
 *  a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *  License for the specific language governing permissions and limitations
 *  under the License.
 */

import ScreenSaver
import Metal

class MetalScreenSaverView : ScreenSaverView
{
    var device: MTLDevice!
    var displayLink: CVDisplayLink!


    // init and deinit

    override init?(frame: NSRect, isPreview: Bool)
    {
        super.init(frame: frame, isPreview: isPreview)
        device = selectMetalDevice(preferLowPower: true) // TODO: make low power preference a user default?
        wantsLayer = true;
    }

    required init?(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }

    deinit
    {
        CVDisplayLinkStop(displayLink!)
    }

    private func selectMetalDevice(preferLowPower: Bool) -> MTLDevice
    {
        var device: MTLDevice?
        if !preferLowPower {
            device = MTLCreateSystemDefaultDevice()!
        } else {
            for d in MTLCopyAllDevices() {
                device = d
                if d.isLowPower && !d.isHeadless {
                    break
                }
            }
        }
#if DEBUG
        if let name = device?.name {
            NSLog("Using device '\(name)'")
        } else {
            NSLog("No or unknown device")
        }
#endif
        return device! // TODO: can we assume there will always be a device?
    }


    // deferred initialisations that require access to the window

    override func viewDidMoveToSuperview()
    {
        super.viewDidMoveToSuperview()
        if let window = superview?.window {
            layer = makeMetalLayer(window: window, device:device)
            displayLink = makeDisplayLink(window: window)
        }
    }

    private func makeMetalLayer(window: NSWindow, device: MTLDevice) -> CAMetalLayer
    {
        let metalLayer = CAMetalLayer()
        metalLayer.device = device
        metalLayer.pixelFormat = .bgra8Unorm
        metalLayer.framebufferOnly = true
        metalLayer.contentsScale = window.backingScaleFactor
        metalLayer.isOpaque = true
        return metalLayer
    }

    private func makeDisplayLink(window: NSWindow) -> CVDisplayLink
    {
        func displayLinkOutputCallback(_ displayLink: CVDisplayLink, _ inNow: UnsafePointer<CVTimeStamp>, _ inOutputTime: UnsafePointer<CVTimeStamp>, _ flagsIn: CVOptionFlags, _ flagsOut: UnsafeMutablePointer<CVOptionFlags>, _ displayLinkContext: UnsafeMutableRawPointer?) -> CVReturn {
            unsafeBitCast(displayLinkContext, to: MetalScreenSaverView.self).animateOneFrame()
            return kCVReturnSuccess
        }

        var link: CVDisplayLink?
        let screensID = UInt32(window.screen!.deviceDescription["NSScreenNumber"] as! Int)
        CVDisplayLinkCreateWithCGDisplay(screensID, &link)
        CVDisplayLinkSetOutputCallback(link!, displayLinkOutputCallback, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()))
        return link!
    }

    
    // screen saver api

    override class func backingStoreType() -> NSBackingStoreType
    {
        return NSBackingStoreType.nonretained
    }

    override func startAnimation()
    {
        // we're not calling super because we need to set up our own timer for the animation
        CVDisplayLinkStart(displayLink!)
    }

    override func stopAnimation()
    {
        // we're not calling super because we didn't do it in startAnimation()
        CVDisplayLinkStop(displayLink!)
    }


}

{'fraction_non_alphanumeric': 0.07624890446976336, 'fraction_numerical': 0.0027544760235382495, 'mean_word_length': 2.574049217002237, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6599865', 'n_tokens_mistral': 2216, 'n_tokens_neox': 2144, 'n_words': 627}