ASObjC: NSURLConnection – http get and post

--
--  pgURLAppDelegate.applescript
--  pgURL
--
--  Created by goodtime on 4/10/11.
--  Copyright 2011 NiceMac. All rights reserved.

-- demonstrates doing a GET or POST Request using NSURLConnection.  Runs in the Background (not in main thread)
-- contains no UI... might add one later, for now it just logs or displays alerts
-- see console log and feel free to change the URL
-- reference material: http://cocoawithlove.com/2008/09/cocoa-application-driven-by-http-data.html

script pgURLAppDelegate
    property parent : class "NSObject"
    property self : current application's pgURLAppDelegate -- should match the script delegate name above

    property myURL : "http://www.heise.de"  -- URL of your request
    property postMethod : "POST"  -- use POST for POST
    property myBody : ""  -- PUT YOUR POST MESSAGE HERE if trying to do a POST

    -- URL Request Encoding
    property myEncoding : NSUTF8StringEncoding of current application --code for UTF8

    property getMethod : "GET"  -- use GET for any other Requests
    property intermediateMsg : "" --  Text String returned from the request (may not be complete for long downloads)
    property entireMsg : "" --  All the Text String returned from the request

    on pgURL_(myURL, myBody, myMethod)
        -- String to NSURL
        tell class "NSURL" of current application
            set myURL to URLWithString_(myURL)
        end tell

        -- String 
        tell class "NSString" of current application
            set myBody to stringWithString_(myBody)
        end

        set myBody to myBody's dataUsingEncoding_(myEncoding)

        tell class "NSString" of current application
            set myMethod to myMethod
        end

        tell NSMutableURLRequest of current application
            set myRequest to requestWithURL_(myURL)
        end

        tell myRequest
            setHTTPMethod_(myMethod)
        end

        -- add the Message Body when sending a POST Method
        if myMethod = "POST" then
            tell myRequest
                setHTTPBody_(myBody)
            end
        end

        -- form the connection
        set myConnection to (((current application's class "NSURLConnection")'s alloc)'s initWithRequest_delegate_(myRequest, self))
    end

    -- handle the connection in the background (not in main thread)
    -- this is controlled by the next four threads
    on connection_didReceiveResponse_(myConnection, response)

        tell class "NSHTTPURLResponse" of current application
            set statusText to (localizedStringForStatusCode_(statusCode of response)) as text
            set statusCode to (statusCode of response) as string
        end

        -- if it fails to do anything, show what it didn't do here (the error)
        if statustext = "no error" then
            -- I am not really sure if this does anything or if it is reseting the returnData properly
            tell current application's returnData
                setLength_(0)
            end
            else
            display alert "HTTP Error: " & statusCode & return & "Error Message: " & statusText & "." 
        end
    end

    on connection_didReceiveData_(myConnection, returnData)

        -- convert Data returned to String (Don't ever forget how to do this, it is a pain when do forget)
        set my intermediateMsg to (((current application's class "NSString")'s alloc)'s initWithData_encoding_(returnData, current application's NSUTF8StringEncoding)) as string
        log "didReceivedData:"

        log intermediateMsg & return & return

        set my entireMsg to my entireMsg & intermediateMsg

    end

    on connection_didFailWithError_(myConnection,trpErr)
        -- display alert trpErr as string
        log trpErr

        set EM to ""
        try
            set newError to (NSLocalizedDescription of userInfo of (trpErr)) as string
                on error EM
            -- if AppleScript can't do this, so what else is wrong
            set errorMore to EM
        end

        display alert newError & return & return & errorMore
    end

    on connectionDidFinishLoading_(myConnection)
        log "connection Finished."

        -- here you can do what you want to do with the intermediateMsg
        log "here is your entire message returned:"
        log entireMsg

        log "end of line."
    end

    on applicationWillFinishLaunching_(aNotification)
        -- Insert code here to initialize your application before any files are opened 

        -- run the request here for demonstration purposes
        pgURL_(myURL, myBody, getMethod)

    end applicationWillFinishLaunching_

    on applicationShouldTerminate_(sender)
        -- Insert code here to do any housekeeping before your application quits 
        return current application's NSTerminateNow
    end applicationShouldTerminate_

end script

ASObjC: NSImage – open, crop and save image

--Cocoa crop
set srcImage to NSImage's alloc()'s initWithContentsOfFile_(picPath)
srcView's setImage_(srcImage)

set w to _width's stringValue() as string as number
set h to _height's stringValue() as string as number
set t to _top's stringValue() as string as number
set l to _left's stringValue() as string as number

set destImage to NSImage's alloc()'s initWithSize_({|width|:w, height:h})

set destRect to {|size|:{w, h}, origin:{0, 0}}
set srcRect to {|size|:{w, h}, origin:{l, t}}

destImage's lockFocus()
srcImage's drawInRect_fromRect_operation_fraction_(destRect, srcRect, current application's NSCompositeSourceOver, 1.0)
destImage's unlockFocus()

destView's setImage_(destImage)

--save as png
set theData to destImage's TIFFRepresentation()
set myNsBitmapImageRepObj to NSBitmapImageRep's imageRepWithData_(theData)
set myNewImageData to (myNsBitmapImageRepObj's representationUsingType_properties_(current application's NSPNGFileType, missing value))
if not (myNewImageData's writeToFile_atomically_(picPath, true)) as boolean then
    set messageText to "There was an error writing to file"
    display dialog messageText buttons {"Ok"}
end if

AppleScript: System Events – versteckte Fenster anzeigen/anpassen

(*
A little script to gather any application windows that are partially offscreen in some way and shift them back to the desktop.
This is particularly useful if you use a MacBook with an external display.
*)
tell application "Finder"
	-- get desktop dimensions (dw = desktop width; dh = desktop height)
	set db to bounds of window of desktop
	set {dw, dh} to {item 3 of db, item 4 of db}
end tell

tell application "System Events"
	repeat with proc in application processes
		tell proc
			repeat with win in windows
				-- get window dimensions (w = width; h = height)
				set {w, h} to size of win

				-- get window postion (l = left of window; t = top of window)
				set {l, t} to position of win

				-- nh = new window height; nw = new window width
				set {nh, nw} to {h, w}

				-- window width is bigger than desktop size,
				-- so set new window width to match the desktop
				if (w > dw) then set nw to dw

				-- window height is bigger than the desktop size (minus menu bar),
				-- so set new window height to be desktop height - 22 pixels
				if (h > dh - 22) then set nh to dh - 22

				-- r = right coordinate of window; b = bottom coordinate of window
				set {r, b} to {l + nw, t + nh}

				-- nl = new left coordinate; nt = new top coordinate
				set {nl, nt} to {l, t}

				-- left coordinate is off screen, so set new left coordinate
				-- to be 0 (at the left edge of the desktop)
				if (l < 0) then set nl to 0

				-- top coordinate is above bottom of menu bar (22 pixels tall),
				-- so set new top coordinate to be 22
				if (t < 22) then set nt to 22

				-- right coordinate extends beyond desktop width,
				-- so set new left coordinate to be desktop width - window width
				if (r > dw) then set nl to dw - nw

				-- bottom coordinate extends beyond desktop height,
				-- so set new top coordinate to be desktop height - window height
				if (b > dh) then set nt to dh - nh

				-- if we have calculated a new top or left coordinate, reposition window
				if (l > nl or t > nt) then set position of win to {nl, nt}

				-- if we have calculated a new height or width, resize window
				if (h > nh or w > nw) then set size of win to {nw, nh}
			end repeat
		end tell
	end repeat
end tell

 

Applescript: TextEdit example

tell application "TextEdit"
	activate
	close every document saving no
	make new document at the beginning of documents
	set the name of window 1 to "Font Samples"
	set zoomed of the front window to true
	set the text of the front document to "The quick brown fox jumped over the lazy dog."
	tell the text of the front document
		set the font to "Lucinda Grande"
		set the size to 24
	end tell
end tell