<commit_before>//
//  DocumentWindow.swift
//
//  CotEditor
//  https://coteditor.com
//
//  Created by 1024jp on 2014-10-31.
//
//  ---------------------------------------------------------------------------
//
//  © 2014-2021 1024jp
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  https://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 Combine
import Cocoa

final class DocumentWindow: NSWindow {
    
    // MARK: Public Properties
    
    var contentBackgroundColor: NSColor = .controlBackgroundColor {
        
        didSet {
            guard !self.isOpaque, contentBackgroundColor != oldValue else { return }
            
            self.backgroundColor = contentBackgroundColor.withAlphaComponent(self.backgroundAlpha)
            self.invalidateShadow()
            self.contentView?.needsDisplay = true
        }
    }
    
    @objc var backgroundAlpha: CGFloat = 1.0 {
        
        didSet {
            backgroundAlpha = backgroundAlpha.clamped(to: 0.2...1.0)
            
            guard !self.styleMask.contains(.fullScreen) else { return }
            
            self.isOpaque = (backgroundAlpha == 1.0)
            
            self.invalidateShadow()
            self.contentView?.needsDisplay = true
            self.invalidateRestorableState()
        }
    }
    
    
    // MARK: Private Properties
    
    private var appearanceObserver: AnyCancellable?
    
    
    
    // MARK: -
    // MARK: Window Methods
    
    /// keys to be restored from the last session
    override class var restorableStateKeyPaths: [String] {
        
        return super.restorableStateKeyPaths + [
            #keyPath(backgroundAlpha),
        ]
    }
    
    
    /// notify about opacity change
    override var isOpaque: Bool {
        
        willSet {
            self.willChangeValue(for: \.isOpaque)
        }
        
        didSet {
            self.didChangeValue(for: \.isOpaque)
            
            guard isOpaque != oldValue else { return }
            
            self.backgroundColor = isOpaque ? nil : self.contentBackgroundColor.withAlphaComponent(self.backgroundAlpha)
            
            self.invalidateTitlebarOpacity()
            
            if isOpaque {
                self.appearanceObserver = nil
            } else if self.appearanceObserver == nil {
                self.appearanceObserver = self.publisher(for: \.effectiveAppearance)
                    .sink { [weak self] _ in self?.invalidateTitlebarOpacity() }
            }
        }
    }
    
    
    /// resore UI state
    override func restoreState(with coder: NSCoder) {
        
        super.restoreState(with: coder)
        
        if coder.containsValue(forKey: #keyPath(backgroundAlpha)) {
            self.backgroundAlpha = CGFloat(coder.decodeDouble(forKey: #keyPath(backgroundAlpha)))
        }
    }
    
    
    /// store UI state
    override func encodeRestorableState(with coder: NSCoder) {
        
        super.encodeRestorableState(with: coder)
        
        coder.encode(self.backgroundAlpha, forKey: #keyPath(backgroundAlpha))
    }
    
    
    
    // MARK: Private Methods
    
    /// make sure window title bar (incl. toolbar) is opaque
    private func invalidateTitlebarOpacity() {
        
        guard let titlebarView = self.standardWindowButton(.closeButton)?.superview else { return }
        
        // dirty manupulation to avoid the title bar being dyed in the window background color (2016-01).
        titlebarView.wantsLayer = !self.isOpaque
        titlebarView.layer?.backgroundColor = self.isOpaque ? nil : NSColor.windowBackgroundColor.cgColor(for: self.effectiveAppearance)
    }
    
}



// MARK: Window Tabbing

extension DocumentWindow {
    
    /// settable window user tabbing preference (Don't forget to set to `nil` after use.)
    static var tabbingPreference: NSWindow.UserTabbingPreference?
    
    <commit_msg>Fix backgroundAlpha restoration<commit_after>//
//  DocumentWindow.swift
//
//  CotEditor
//  https://coteditor.com
//
//  Created by 1024jp on 2014-10-31.
//
//  ---------------------------------------------------------------------------
//
//  © 2014-2021 1024jp
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  https://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 Combine
import Cocoa

final class DocumentWindow: NSWindow {
    
    // MARK: Public Properties
    
    var contentBackgroundColor: NSColor = .controlBackgroundColor {
        
        didSet {
            guard !self.isOpaque, contentBackgroundColor != oldValue else { return }
            
            self.backgroundColor = contentBackgroundColor.withAlphaComponent(self.backgroundAlpha)
            self.invalidateShadow()
            self.contentView?.needsDisplay = true
        }
    }
    
    @objc var backgroundAlpha: CGFloat = 1.0 {
        
        didSet {
            backgroundAlpha = backgroundAlpha.clamped(to: 0.2...1.0)
            
            guard !self.styleMask.contains(.fullScreen) else { return }
            
            self.isOpaque = (backgroundAlpha == 1.0)
            
            self.invalidateShadow()
            self.contentView?.needsDisplay = true
            self.invalidateRestorableState()
        }
    }
    
    
    // MARK: Private Properties
    
    private var appearanceObserver: AnyCancellable?
    
    
    
    // MARK: -
    // MARK: Window Methods
    
    /// keys to be restored from the last session
    override class var restorableStateKeyPaths: [String] {
        
        return super.restorableStateKeyPaths + [
            #keyPath(backgroundAlpha),
        ]
    }
    
    
    /// notify about opacity change
    override var isOpaque: Bool {
        
        willSet {
            self.willChangeValue(for: \.isOpaque)
        }
        
        didSet {
            self.didChangeValue(for: \.isOpaque)
            
            guard isOpaque != oldValue else { return }
            
            self.backgroundColor = isOpaque ? nil : self.contentBackgroundColor.withAlphaComponent(self.backgroundAlpha)
            
            self.invalidateTitlebarOpacity()
            
            if isOpaque {
                self.appearanceObserver = nil
            } else if self.appearanceObserver == nil {
                self.appearanceObserver = self.publisher(for: \.effectiveAppearance)
                    .sink { [weak self] _ in self?.invalidateTitlebarOpacity() }
            }
        }
    }
    
    
    /// resore UI state
    override func restoreState(with coder: NSCoder) {
        
        super.restoreState(with: coder)
        
        if coder.containsValue(forKey: #keyPath(backgroundAlpha)) {
            self.backgroundAlpha = CGFloat(coder.decodeDouble(forKey: #keyPath(backgroundAlpha)))
        }
    }
    
    
    /// store UI state
    override func encodeRestorableState(with coder: NSCoder) {
        
        super.encodeRestorableState(with: coder)
        
        coder.encode(Double(self.backgroundAlpha), forKey: #keyPath(backgroundAlpha))
    }
    
    
    
    // MARK: Private Methods
    
    /// make sure window title bar (incl. toolbar) is opaque
    private func invalidateTitlebarOpacity() {
        
        guard let titlebarView = self.standardWindowButton(.closeButton)?.superview else { return }
        
        // dirty manupulation to avoid the title bar being dyed in the window background color (2016-01).
        titlebarView.wantsLayer = !self.isOpaque
        titlebarView.layer?.backgroundColor = self.isOpaque ? nil : NSColor.windowBackgroundColor.cgColor(for: self.effectiveAppearance)
    }
    
}



// MARK: Window Tabbing

extension DocumentWindow {
    
    /// settable window user tabbing preference (Don't forget to set to `nil` after use.)
    static var tabbingPreference: NSWindow.UserTabbingPreference?
    
    
{'fraction_non_alphanumeric': 0.10091116173120729, 'fraction_numerical': 0.009567198177676537, 'mean_word_length': 1.846353322528363, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 4, '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': '3937699', 'n_tokens_mistral': 2416, 'n_tokens_neox': 2321, 'n_words': 598}