How does one manually tell NSTextContainer to recalculate the lineFragmentRects? - macos

In my application, I have been adding support for NSTextView allowing subviews to work naturally with the text editor. (For example, pressing "enter" drops every subview lower than the insertion point, and text wraps around subviews.)
I have successfully been able to get word wrap around subviews by overridinglineFragmentRectForProposedRect(proposedRect: NSRect,
sweepDirection: NSLineSweepDirection,
movementDirection: NSLineMovementDirection,
remainingRect: NSRectPointer) -> NSRect.
However, when a subview is dragged, or resized, the breaks in the text need to be recalculated to get the desired effect. The text needs to update itself to wrap around the subview as it is dragged or resized. However, I noticed that typing on a line updates the lineFragmentRect for that line. Is there a way to immediately mark the text as "dirty" after the subview is dragged? Here is the code for the text container subclass:
import Cocoa
class CASTextContainer: NSTextContainer {
var mainView: CASTextView = CASTextView()
var textSubviews: Array<AnyObject> {
get {
return mainView.subviews
}
}
override var simpleRectangularTextContainer: Bool {
get {
return false
}
}
func rectForActiveRange() -> NSRect {
let range = layoutManager.glyphRangeForCharacterRange(textView.selectedRange, actualCharacterRange:nil)
var rect = layoutManager.boundingRectForGlyphRange(range, inTextContainer: self)
rect = NSOffsetRect(rect, textView.textContainerOrigin.x, textView.textContainerOrigin.y)
return rect;
}
override func lineFragmentRectForProposedRect(proposedRect: NSRect,
sweepDirection: NSLineSweepDirection,
movementDirection: NSLineMovementDirection,
remainingRect: NSRectPointer) -> NSRect
{
remainingRect.initialize(NSZeroRect)
var frames: Array<NSRect> = []
if textSubviews.isEmpty {
let fullRect = NSMakeRect(0, 0, containerSize.width, containerSize.height)
return NSIntersectionRect(fullRect, proposedRect)
}
for view in textSubviews {
frames.append(view.frame)
}
// Sort the array so that the frames are ordered by increasing origin x coordinate.
let fullRect = NSMakeRect(0, 0, containerSize.width, containerSize.height)
let region = NSIntersectionRect(fullRect, proposedRect)
let sortedFrames: Array<NSRect> = sorted(frames, { (first: NSRect, second: NSRect) -> Bool in
return first.origin.x < second.origin.x
})
// Get the first rectangle height that overlaps with the text region's height.
var textDrawingRegion = NSZeroRect
var subviewFrame = NSZeroRect // Will be needed later to set remainingRect pointer.
var precedingRegion: NSRect = NSZeroRect // Hold the view frame preceding our insertion point.
for frame in sortedFrames {
if region.origin.y + NSHeight(region) >= frame.origin.y &&
region.origin.y <= frame.origin.y + NSHeight(frame)
{
if region.origin.x <= frame.origin.x {
// Calculate the distance between the preceding subview and the approaching one.
var width: CGFloat = frame.origin.x - precedingRegion.origin.x - NSWidth(precedingRegion)
textDrawingRegion.origin = region.origin
textDrawingRegion.size = NSMakeSize(width, NSHeight(region))
subviewFrame = frame
break
}
else {
precedingRegion = frame
}
}
}
if textDrawingRegion == NSZeroRect {
return region
}
else {
// Set the "break" in the text to the subview's location:
let nextRect = NSMakeRect(subviewFrame.origin.x + NSWidth(subviewFrame),
region.origin.y,
NSWidth(proposedRect),
NSHeight(proposedRect))
remainingRect.initialize(nextRect)
return textDrawingRegion
}
}
}

Related

Cropping NSImage with onscreen coordinates incorrect on different screen sizes

I'm trying to replicate macOS's screenshot functionality, dragging a selection onscreen to provide coordinates for cropping an image. I have it working fine on my desktop Mac (2560x1600), but testing on my laptop (2016 rMBP 15", 2880x1800), the cropped image is completely wrong. I don't understand why I'd get the right results on my desktop, but not on my laptop. I think it has something to do with the Quarts coordinates being different from Cocoa coordinates, seeing as how on the laptop, the resulting image seems like the coordinates are flipped on the Y-axis.
Here is the code I am using to generate the cropping CGRect:
# Segment used to draw the CAShapeLayer:
private func handleDragging(_ event: NSEvent) {
let mouseLoc = event.locationInWindow
if let point = self.startPoint,
let layer = self.shapeLayer {
let path = CGMutablePath()
path.move(to: point)
path.addLine(to: NSPoint(x: self.startPoint.x, y: mouseLoc.y))
path.addLine(to: mouseLoc)
path.addLine(to: NSPoint(x: mouseLoc.x, y: self.startPoint.y))
path.closeSubpath()
layer.path = path
self.selectionRect = path.boundingBox
}
}
private func startDragging(_ event: NSEvent) {
if let window = self.window,
let contentView = window.contentView,
let layer = contentView.layer,
!self.isDragging {
self.isDragging = true
self.startPoint = window.mouseLocationOutsideOfEventStream
shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = 1.0
shapeLayer.fillColor = NSColor.white.withAlphaComponent(0.5).cgColor
shapeLayer.strokeColor = NSColor.systemGray.cgColor
layer.addSublayer(shapeLayer)
}
}
Then this is the code where I actually generate the screenshot and crop using the CGRect:
public func processResults(_ rect: CGRect) {
if let windowID = self.globalWindow?.windowNumber,
let screen = self.getScreenWithMouse(), rect.width > 5 && rect.height > 5 {
self.delegate?.processingResults()
let cgScreenshot = CGWindowListCreateImage(screen.frame, .optionOnScreenBelowWindow, CGWindowID(windowID), .bestResolution)
var rect2 = rect
rect2.origin.y = NSMaxY(self.getScreenWithMouse()!.frame) - NSMaxY(rect);
if let croppedCGScreenshot = cgScreenshot?.cropping(to: rect2) {
let rep = NSBitmapImageRep(cgImage: croppedCGScreenshot)
let image = NSImage()
image.addRepresentation(rep)
self.showPreviewWindow(image: image)
let requests = [self.getTextRecognitionRequest()]
let imageRequestHandler = VNImageRequestHandler(cgImage: croppedCGScreenshot, orientation: .up, options: [:])
DispatchQueue.global(qos: .userInitiated).async {
do {
try imageRequestHandler.perform(requests)
} catch let error {
print("Error: \(error)")
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
self.hidePreviewWindow()
}
}
}
self.globalWindow = nil
}
Not 15 minutes after I asked this question, I tried one more thing and it works!
Relevant snippet:
var correctedRect = rect
// Set the Y origin properly (counteracting the flipped Y-axis)
correctedRect.origin.y = screen.frame.height - rect.origin.y - rect.height;
// Checks if we're on another screen
if (screen.frame.origin.y < 0) {
correctedRect.origin.y = correctedRect.origin.y - screen.frame.origin.y
}
// Finally, correct the x origin (if we're on another screen, the origin will be larger than zero)
correctedRect.origin.x = correctedRect.origin.x + screen.frame.origin.x
// Generate the screenshot inside the requested rect
let cgScreenshot = CGWindowListCreateImage(correctedRect, .optionOnScreenBelowWindow, CGWindowID(windowID), .bestResolution)

NSDocument printOperationWithSettings not showing all pages

In NSDocument subclass, have this function:
override func printOperationWithSettings(printSettings: [String : AnyObject]) throws -> NSPrintOperation {
let printInfo: NSPrintInfo = self.printInfo
var pageSize = printInfo.paperSize
pageSize.width -= printInfo.leftMargin + printInfo.rightMargin
pageSize.height -= printInfo.topMargin + printInfo.bottomMargin
pageSize.width = pageSize.width * 2
pageSize.height = pageSize.height * 2
let myPage = MyPage(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: pageSize))
let printOperation = NSPrintOperation(view: myPage, printInfo: printInfo)
return printOperation
}
MyPage is, for this test, an NSView subclass that just draws an oval.
class MyPage: NSView {
override var flipped: Bool {
return true
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
NSColor.greenColor().set() // choose color
let figure = NSBezierPath() // container for line(s)
figure.appendBezierPathWithOvalInRect(self.frame)
figure.stroke() // draw line(s)
}
}
I'd expect this to show four pages in the print panel, but it only shows two, equating to the top left and bottom left of the oval. No matter how wide I make myPage's frame, only the leftmost pages are shown. Any ideas why? Thank you!

Changing OSX app window size based on user input that changes views

I'm trying my hand at developing an OSX app. Xcode and Swift are all new to me.
The defaults are all very good at modifying objects when the user changes the window size, but not so good at changing the window size when objects in the view change.
I've seen a couple of examples of recalculating the origin and frame size - I think the math part of it will be straight forward. However, I cannot get a working reference to the NSWindow object. click-drag will not deposit an IBOutlet for the window in any of the .swift files (AppDelegate, ViewController, custom). And typing it in doesn't bind it.
A simplified example of what I am trying to accomplish:
Based on user input, change the content of the display, and adjust the window size to encompass the newly modified display.
On my main storyboard
- Window Controller, segued to
- View Controller, containing a Horizontal Slider and a Container view. The container view is segued to
- Horizontal Split View Controller, segued to
- three repetitive instances of a View Controller.
When the user changes the slider bar, one or more of the three bottom most view controllers will be hidden/unhidden.
The attached pictures show the behavior I am looking for.
Imagine where the text "small group" is, there is a collection of drop down boxes, text boxes, radio buttons, etc.
I am answering my own question here - still unable to bind IBOutlet with NSWindow. Anyone with better solutions, please let me know.
Below is a capture of my Main.storyboard. All of the coding is done in the class junkViewController2 that is associated with the 1st view controller.
Here is the code for junkViewController2. I know, it could be more concise ...
//
// JunkViewController2.swift
// Scratch1
//
import Cocoa
class JunkViewController2: NSViewController {
var junkSplitViewController: JunkSplitViewController!
var myWindow: NSWindow!
var dy: CGFloat!
#IBOutlet weak var mySlider: NSSlider!
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
dy = 0.0
}
#IBAction func mySlider(sender: NSSlider) {
let junkSplitViewController = self.childViewControllers[0]
dy = 0.0
for controller in junkSplitViewController.childViewControllers {
if controller.title == "smallGroup1" {
if mySlider.intValue > 0 {
if controller.view.hidden {
dy = dy + 30.0
}
controller.view.hidden = false
} else {
if !controller.view.hidden {
dy = dy - 30.0
}
controller.view.hidden = true
}
}
if controller.title == "smallGroup2" {
if mySlider.intValue > 1 {
if controller.view.hidden {
dy = dy + 30.0
}
controller.view.hidden = false
} else {
if !controller.view.hidden {
dy = dy - 30.0
}
controller.view.hidden = true
}
}
if controller.title == "smallGroup3" {
if mySlider.intValue > 2 {
if controller.view.hidden {
dy = dy + 30.0
}
controller.view.hidden = false
} else {
if !controller.view.hidden {
dy = dy - 30.0
}
controller.view.hidden = true
}
}
}
resize()
}
func resize() {
var windowFrame = NSApp.mainWindow!.frame
let oldWidth = windowFrame.size.width
let oldHeight = windowFrame.size.height
let old_x = windowFrame.origin.x
let old_y = windowFrame.origin.y
let toAdd = CGFloat(dy)
let newHeight = oldHeight + toAdd
let new_y = old_y - toAdd
windowFrame.size = NSMakeSize(oldWidth, newHeight)
windowFrame.origin = NSMakePoint(old_x, new_y)
NSApp.mainWindow!.setFrame(windowFrame, display: true)
}
}

Set color of NSButton programmatically swift

I generate some NSButtons programmatically with this code:
for i in 1...height {
for j in 1...width {
var but = NSButton(frame: NSRect(x: x, y: y + 78, width: 30, height: 30))
but.tag = k
but.title = ""
but.action = Selector("buttonPressed:")
but.target = self
but.bezelStyle = NSBezelStyle(rawValue: 6)!
but.layer?.backgroundColor = NSColor.blackColor().CGColor
var ges = NSClickGestureRecognizer(target: self, action: Selector("addFlag:"))
ges.buttonMask = 0x2
ges.numberOfClicksRequired = 1
but.addGestureRecognizer(ges)
ar.append(but)
self.view.addSubview(but)
x += 30
k++
}
y += 30
x = 0
}
And I need to set the background color of all buttons to gray or black (randomly). I have no idea how to get or set the NSButton background color. I'm quite new to swift programming and I don't really know obj-c, so if you'll write it on swift, I'll really appreciate it!
I'm doing it with this code
final class MyButton: NSButton {
override func awakeFromNib() {
let layer = CALayer()
layer.backgroundColor = CGColorCreateGenericRGB(59.0/255, 52.0/255.0, 152.0/255.0, 1.0)
self.wantsLayer = true
self.layer = layer
}
}
I read throgh the NSButton reference guide, And it seems that the only way to change it it changing the image. But I have gotten a way to create an image using a colour. Add this extionsion at the top of your class file
extension NSImage {
class func swatchWithColor(color: NSColor, size: NSSize) -> NSImage {
let image = NSImage(size: size)
image.lockFocus()
color.drawSwatchInRect(NSMakeRect(0, 0, size.width, size.height))
image.unlockFocus()
return image
}
}
This will allow us to later create NSImage's using a UIColour. Lastly, When you want to create your button, Set the image using the extension we made.
myButton.image = NSImage.swatchWithColor( NSColor.blackColor(), size: NSMakeSize(100, 100) )
For the size parameter set it to your button's size.
UPDATE* If you want to randomly choose the colour you can do this..
var randomIndex = arc4random_uniform(2) + 1 //Creates a random number between 1 and 2
var colour = NSColor() //Empty colour
if randomIndex == 1 {
//If the random number is one then the colour is black
colour = NSColor.blackColor()
}
else {
//Else if it's not one it's grey
colour = NSColor.grayColor()
}
//set the button's image to the new colour
myButton.image = NSImage.swatchWithColor(colour, size: //My button size)
To get the size go to your storyboard, click on your button and go to the ruler tab. There it shows your button's size.
The bad news is that there is, IMHO, no good way of colouring buttons; they all have advantages and drawbacks.
For everyone who, like me, felt curious about colouring buttons under Yosemite I have written what may not be the ultimate guide to colouring buttons, but definitely a strong contender:
http://www.extelligentcocoa.org/colouring-buttons/
This covers all styles of buttons, and has screenshots for almost any combination, using
backgroundColor
drawRect
cell backgroundColor
monochrome layerEffect
whiteBalance Adjust layerEffect
images set in IB
subclassing NSButton and adding images depending on the button state
If anyone can think of another way of colouring buttons, I'm interested to hear of it!
Okay, here is what I did when I needed to change the look of a button: subclass it.
//
// LSButtonColor.swift
//
// Created by Lloyd Sargent on 8/26/16.
// Copyright © 2016 Canna Software. All rights reserved.
// License: Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the “Software”), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
import Cocoa
class LSButtonColor: NSButton {
fileprivate struct AssociatedKeys {
static var variableDictionary = "ls_variableDictionary"
}
fileprivate var variableDictionary: [String:AnyObject]! {
get {
var localVariableDictionary = objc_getAssociatedObject(self, &AssociatedKeys.variableDictionary) as! [String:AnyObject]!
if localVariableDictionary == nil {
localVariableDictionary = [String:AnyObject]()
objc_setAssociatedObject(self, &AssociatedKeys.variableDictionary, localVariableDictionary, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return localVariableDictionary
}
set(updatedDictionary) {
objc_setAssociatedObject(self, &AssociatedKeys.variableDictionary, updatedDictionary, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var backgroundColor: NSColor! {
get {
return variableDictionary["backgroundColor"] as? NSColor
}
set(newBackgroundColor) {
var localVariableDictionary = variableDictionary
localVariableDictionary?["backgroundColor"] = newBackgroundColor
variableDictionary = localVariableDictionary
}
}
var altBackgroundColor: NSColor! {
get {
return variableDictionary["altBackgroundColor"] as? NSColor
}
set(newAltBackgroundColor) {
var localVariableDictionary = variableDictionary
localVariableDictionary?["altBackgroundColor"] = newAltBackgroundColor
variableDictionary = localVariableDictionary
}
}
var borderColor: NSColor! {
get {
return variableDictionary["borderColor"] as? NSColor
}
set(newBorderColor) {
var localVariableDictionary = variableDictionary
localVariableDictionary?["borderColor"] = newBorderColor
variableDictionary = localVariableDictionary
self.layer?.borderColor = newBorderColor.cgColor
}
}
var cornerRadius: CGFloat {
get {
return variableDictionary["cornerRadius"] as! CGFloat
}
set(newCornerRadius) {
var localVariableDictionary = variableDictionary
localVariableDictionary?["cornerRadius"] = newCornerRadius as AnyObject?
variableDictionary = localVariableDictionary
self.layer?.cornerRadius = newCornerRadius
}
}
var borderWidth: CGFloat {
get {
return variableDictionary["borderWidth"] as! CGFloat
}
set(newBorderWidth) {
var localVariableDictionary = variableDictionary
localVariableDictionary?["borderWidth"] = newBorderWidth as AnyObject?
variableDictionary = localVariableDictionary
self.layer?.borderWidth = newBorderWidth
}
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
if self.isHighlighted {
if self.layer != nil {
self.layer?.backgroundColor = self.altBackgroundColor.cgColor
}
}
else {
if self.layer != nil {
self.layer?.backgroundColor = self.backgroundColor.cgColor
}
}
}
}
Okay, the first thing you might be puzzling over is the objc_getAssociatedObject - originally I did this as a category and it is an easy-peasy way of adding variables to categorys (everyone says you can’t do it, but everyone doesn’t realize that, yes, you can - it’s just not obvious).
Unfortunately, I ran into some issues, so I just made it a class - and didn’t bother to take out the associated object (why mess with success?)
Anyway, you should be able to pull out the relevant code to change the background of any button.

Swift - UIPanRecognizer in a UIStackView

I want to make a UIPanRecognizer in a UIStackView. The UI looks like this.
There's a big square which is a StackView which contains 9 labels.
My goal is when I start to drag my finger within the StackView and if a label contains that touchpoint then its color should be blue and on and on. If I lift my finger all of the labels background color turn back to white.
The labels are in a OutletCollection.
Here's my code:
#IBOutlet var testLabels: [UILabel]!
#IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
var touchedPoint: CGPoint!
if let view = recognizer.view{
if recognizer.state == .began || recognizer.state == .changed {
touchedPoint = recognizer.location(in: view)
for index in testLabels.indices {
if testLabels[index].frame.contains(touchedPoint) {
testLabels[index].backgroundColor = UIColor.blue
}
}
}
if recognizer.state == .ended {
for index in testLabels.indices {
testLabels[index].backgroundColor = UIColor.white
}
}
}
Right now when I touch for example the top-left square and start to drag my finger to the right the whole first column turns blue then the second then the third. That happens when I touch any labels of the first row, but nothing happens when I touch the other squares.
First time, I tried to solve my problem by handle the squares just as an OutletCollection (without the StackView) and the recognizer just worked fine! The reason why I experiment with the StackView that it's so easier to make the layout(just a few constraints needed, without the StackView it is a nightmare).
I'd appreciate any help. Thank you.
Edit: probably this one helps?
Access nested stack views
Each label is a subview of its containing stack view (which is also probably a subview of a stack view), and each label has its own coordinate space.
Assuming your UIPanGestureRecognizer is assigned to the view controller's view, you need to translate the coordinates / frames.
This should work for you:
#IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
var touchedPoint: CGPoint!
if let view = recognizer.view{
if recognizer.state == .began || recognizer.state == .changed {
touchedPoint = recognizer.location(in: view)
for index in testLabels.indices {
// translate / convert the label's bounds from its frame to the view's coordinate space
let testFrame = view.convert(testLabels[index].bounds, from:testLabels[index] )
// check the resulting testFrame for the point
if testFrame.contains(touchedPoint) {
testLabels[index].backgroundColor = UIColor.blue
}
}
}
else if recognizer.state == .ended {
for index in testLabels.indices {
testLabels[index].backgroundColor = UIColor.white
}
}
}
}
You can also simplify your code a bit by using for object in collection instead of indices. This is functionally the same as above, but maybe a little simpler:
#IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
var touchedPoint: CGPoint!
if let view = recognizer.view{
if recognizer.state == .began || recognizer.state == .changed {
touchedPoint = recognizer.location(in: view)
for lbl in testLabels {
// translate / convert the label's bounds from its frame to the view's coordinate space
let testFrame = view.convert(lbl.bounds, from:lbl )
// check the resulting testFrame for the point
if testFrame.contains(touchedPoint) {
lbl.backgroundColor = .blue
}
}
}
else if recognizer.state == .ended {
for lbl in testLabels {
lbl.backgroundColor = .white
}
}
}
}

Resources