Using an applescript in a cocoa-applescript application

Hello,
I have an applescript I am trying to use in a project. I have everything set up so when you click a button it runs this:
repeat
set statusOld to checkStatus()
set statusNew to checkStatus()
repeat while statusOld is equal to statusNew
delay 1
set statusNew to checkStatus()
end repeat
if statusNew is true then
display dialog "Device Added - put some real code here"
else
display dialog "Device Removed - put some real code here"
end if
end repeat
on checkStatus()
set myString to do shell script "system_profiler SPBluetoothDataType"
if myString does not contain "DR-BT101" then
return false
else
set AppleScript's text item delimiters to "name:"
set myList to the text items of myString
set numberOfDevices to count of myList
set counter to 1
repeat numberOfDevices times
if item counter of myList contains "DR-BT101" then
if item counter of myList contains "Connected: Yes" then
return true
else if item counter of myList contains "Connected: No" then
return false
else
display dialog "Error Parsing"
end if
end if
set counter to counter + 1
end repeat
end if
end checkStatus
However, It will not run because of the "on checkStatus()" part. How would I fix this and also make it so the user can stop running the script?

It's pretty easy to block the user interface when converting AppleScripts that use repeat loops. For an example of the other approach that uses a repeating timer, create a new example project (named "Timer Example") with the following script. Then from *Interface Builder*, create a couple of buttons (named "Start" and "Stop") and connect the buttons to the doButtonStuff action. You can see the progress of things in the run console.
The main difference is that instead of a tight repeat loop that hogs the entire run loop, a timer is set up to check things every once in a while. Since the application is now free to do other things in between firings of the timer, your user interface stays responsive.
<pre style="
font-family: Monaco, 'Courier New', Courier, monospace;
font-size: 10px;
font-weight: normal;
margin: 0px;
padding: 5px;
border: 1px solid #000000;
width: 720px; height: 340px;
color: #000000;
background-color: #DAFFB6;
overflow: auto;"
title="this text can be pasted into Xcode 3.2.x (Snow Leopard)">
# MARK: -
# MARK: Application Properties
property thisApp : current application
property NSTimer : class "NSTimer"
property NSRunLoop : class "NSRunLoop"
script Timer_ExampleAppDelegate -- change the name to match your example project if needed
# MARK: -
# MARK: Script Properties
property parent : class "NSObject"
property myTimer : missing value -- this will be a repeating timer
property statusOld : missing value -- this will be the original status
# MARK: -
# MARK: Interface Builder Actions
on doButtonStuff_(sender)
log "doButton..."
set theButton to (sender's |title| as text)
if theButton is "Start" then
log "timer started..."
if myTimer is missing value or not myTimer's isValid() then -- check if the timer is already running
set myTimer to NSTimer's timerWithTimeInterval_target_selector_userInfo_repeats_(2, me, "doCheck", missing value, true) -- create
NSRunLoop's mainRunLoop()'s addTimer_forMode_(myTimer, thisApp's NSDefaultRunLoopMode) -- start the timer
end if
else if theButton is "Stop" then
log "timer stopped..."
myTimer's invalidate() -- stop the timer
end if
end doButtonStuff_
# MARK: -
# MARK: Script Handlers
on doCheck()
script check
on checkStatus()
log "checkStatus..."
set myString to (do shell script "system_profiler SPBluetoothDataType")
if myString does not contain "DR-BT101" then return false
set tempTID to AppleScript's text item delimiters -- save existing delimiters
set AppleScript's text item delimiters to "name:"
set myList to the text items of myString
set AppleScript's text item delimiters to tempTID -- restore delimiters
repeat with anItem in myList
set anItem to contents of anItem -- dereference list item
if anItem contains "DR-BT101" then
if anItem contains "Connected: Yes" then
return true
else if anItem contains "Connected: No" then
return false
end if
end if
end repeat
display dialog "Error Parsing" -- oops
end checkStatus
end script
repeat
if statusOld is missing value then set statusOld to check's checkStatus()
set statusNew to check's checkStatus()
if statusNew is equal to statusOld then return -- no change
if statusNew is true then
-- myTimer's invalidate() -- stop the timer
display dialog "Device Added - put some real code here"
else
-- myTimer's invalidate() -- stop the timer
display dialog "Device Removed - put some real code here"
end if
end repeat
end doCheck
end script</pre>

Similar Messages

  • Web View not loading in Cocoa Applescript application?

    Hey guys...me again, and I need help, AGAIN, haha.
    I found a tutorial for web views in Cocoa Applescript because I couldnt find it anywhere, but it wont load.
    The web view does not display anything when the app is launching.
    I am using Cocoa Applescript.
    This is my AppDelegate.applescript I am using for the web view:
    script AppDelegate
      property parent : class "NSObject"
        property ourWebView : missing value (* This links the webview *)
              on applicationWillFinishLaunching_(aNotification)
      -- tell ourWebView to setMainFrameURL_("http://tinyurl.com/RMHTML")
              end applicationWillFinishLaunching_
              on applicationShouldTerminate_(sender)
      -- Insert code here to do any housekeeping before your application quits
                        return current application's NSTerminateNow
              end applicationShouldTerminate_
        on myButtonHandler_(sender)
            activate application "Terminal"
            tell application "System Events" to keystroke "Desktop/RecoverDevice"
            tell application "System Events" to keystroke return
            delay 1
            tell application "System Events" to keystroke "setenv auto-boot true"
            delay 1
            tell application "System Events" to keystroke return
            delay 1
            tell application "System Events" to keystroke "saveenv"
            delay 1
            tell application "System Events" to keystroke return
            delay 1
            tell application "System Events" to keystroke "reboot"
            delay 1
            tell application "System Events" to keystroke return
            delay 1
            tell application "Terminal"
                quit
            end tell
        end doMyButton_
        on myButtontwoHandler_(sender)
            open location "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=YF2DKZYRH6B GA"
        end doMyButton2_
    end script
    Whoever helps me will be thanked in my apps about page...
    Thanks, Adam B

    When I launch it...it says this:
    2012-01-22 17:21:01.658 RecoverMe[96706:407] Error loading /Library/Application Support/SIMBL/Plugins/GreaseKit.bundle/Contents/MacOS/GreaseKit:  dlopen(/Library/Application Support/SIMBL/Plugins/GreaseKit.bundle/Contents/MacOS/GreaseKit, 265): no suitable image found.  Did find:
              /Library/Application Support/SIMBL/Plugins/GreaseKit.bundle/Contents/MacOS/GreaseKit: GC capability mismatch
    Does that have anything to do with it not loading the webview?

  • How can I use removeAllCachedResponses in Cocoa-Applescript?

    How can I clear the cache of a Webview in Cocoa-Applescript using this method?

    Well, webviews can get very complicated depending on what you are doing.  Your application will cache its own stuff in your user's ~/Library/Caches folder, so you don't need to set up anything extra for that, anyway.
    The removeAllCachedResponses method doesn't seem to work all that well (emptying caches in Safari doesn't either), but setting the cache size to zero won't save anything and will just result in the default cache files, for example:
    set sharedCache to current application's NSURLCache's alloc's initWithMemoryCapacity:0 diskCapacity:0 diskPath:(missing value)
    current application's NSURLCache's setSharedURLCache:sharedCache
    I suppose you could also do what the Safari Cookies plugin does and just manually delete the caches when the program exits.

  • Using applescript to react to a application error

    Hey, my friends
    I want to using applescript to handle with some application error. For example, I send a iMessage to my friend for the first time, after a while the Message application may return a messagebox said that he is not using iMessage service. And I want my computer say it out loud using "say" script. How can I do that? Or is that impossible?
    There might be a way by using some error log file belongs to the application from which I want to be notified if an error happend. But I don't know where I can find those log files.
    Any ideas?
    Thanks!
    Qiu.

    I'd figure out how to do the shutdown from the command line.  You then should be able to do this from an applescript.
    There is some way of initiating an apple script on a remote machine but I do not know how.
    What OS is the remote server using?
    Robert

  • Cocoa Applescript can't use AppleScript's text item delimiters

    Here is my code
    if (track_name_html as text) contains (publisher_name as text) then
                try
                    set s to track_name_html as text
                    set AppleScript's text item delimiters to "- "
                    set track_name1 to text item 2 of s
                    on error
                    set track_name1 to track_name_html as text
                end try
                else
                set track_name1 to track_name_html as text
            end if
            track_name_ui's setStringValue_(track_name as text)
    When I try to log track_name it returns blank. It's very important for my Cocoa-Applescript App.
    Thnaks in advance

    After looking documention I found insertText()
    Then I make a handler for quick insertion to text view
    on statusin(statustx)
            set my statuseditable to true
            set timetx to do shell script "date +'%H:%M'"
            status's insertText_(timetx & " - " & statustx & return)
            set my statuseditable to false
            end statusin

  • How can I make a window transparent but keep its objects opaque in Cocoa-Applescript?

    How can I do this in Cocoa-Applescript, Xcode? As well, is it possible to blur the area behind where the transparent window is?

    You can set the window transparency with something like:
    theWindow's setBackgroundColor:(current application's NSColor's clearColor)
    theWindow's setOpaque:false
    I haven't seen a way using public APIs to blur behind the window, but I'm not sure about using ASObjC with stuff like Core Image, anyway.
    You might also try something like setting the background to a gray color and play with the grayscale and alpha values (colorWithCalibratedWhite:0.0 alpha:0.2, for example).

  • How can I create Tracking-Areas in Cocoa-Applescript?

    How can I create multiple tracking areas that activate handlers that are specific to a certain area, when the mouse enters that area, in Cocoa-Applescript, Xcode 5?

    You can use NSTrackingArea to set up the area(s) you want to track.  For example, if you have a view named "myView" that you wanted to use, you can set up a tracking area by specifying the rectangle (I am going to use the entire view) and tracking options with something like:
       set options to (current application's NSTrackingMouseEnteredAndExited as integer) + (current application's NSTrackingActiveInKeyWindow as integer) + (current application's NSTrackingInVisibleRect as integer)
       set trackingArea to current application's class "NSTrackingArea"'s alloc's initWithRect:(myView's frame()) options:options owner:me userInfo:"tracking myView"
       myView's addTrackingArea:trackingArea
    The options are a bit wordy, but they determine how things are tracked - you could also just look up what they are in the class headers and use that.  You then need to add NSResponder handlers in the owner class for what you are interested in - for this example, they would be:
      on mouseEntered:theEvent -- cursor has entered a tracking rectangle
        log "mouseEntered"
        log theEvent's userData() -- data specific to a trackingArea
      end mouseEntered:
      on mouseExited:theEvent -- cursor has exited a tracking rectangle
        log "mouseExited"
        log theEvent's userData() -- data specific to a trackingArea
      end mouseExited:
    When using multiple tracking areas, you can add some user info that can be retrieved from the event.  In the above example, I used the string "tracking myView", but it can be whatever you want.

  • Cannot Understand Event Earsffdr Cocoa-Applescript

    Hello Guys,
    I'm trying to just write a little X-code 4 app to display it's own directory, using Cocoa-Applescript. I've created a window under MainMenu.xib, and linked it to my code in AppDelegate.applescript. My code looks something like this:
    on myButtonHandler_(sender)
            set theFolder to POSIX path of (the path to current application)
            set theFile to theFolder & "/Contents/Resources/Dir.app"
            display dialog (the path to me)
            return void
        end myButtonHandler
    The app builds perfectly, but when I click the button, it says:
    [AppDelegate myButtonHandler:]: «script» doesn’t understand the «event earsffdr» message. (error -1708)
    I have no idea what is happening there, so any help is appreciated!
    P.S This code also works perfectly in Applescript Editor, but I want it to look better with a window, so this is really weird.

    I've tried the applecation bundle thing, and my code looks like this:
        on myButtonHandler_(sender)
            set theFolder to POSIX path of (the path to current application's NSBundle's mainBundle()'s bundlePath())
            set theFile to theFolder & "/Contents/Resources/Dir.app"
            display dialog theFile
        end myButtonHandler
    But now the error is:
    «class ocid» id «data optr00000000E0B3660401000000» doesn’t understand the «event earsffdr» message. (error -1708)
    In Applescript Editor, the code makes the error : NSBundle doesn’t understand the mainBundle message.
    In addition, 'path to current application' doesen't work either, and it displays the original error.

  • Setting text item delimiters in Cocoa-Applescript App

    Does anyone know of a problem with text item delimiters in a Cocoa-Applescript App.  This is in Xcode 4.5.2 and  Mountain Lion
    the following code seems to fail  to set the text item delimeter  to + when I run it in Coca-AppleScript
    --  TSTAppDelegate.applescript
    --  Test Text item Delimiters
    --  Created by Frank Caggiano on 12/22/12.
    --  Copyright (c) 2012 Frank Caggiano. All rights reserved.
    script TSTAppDelegate
      property parent : class "NSObject"
              on applicationWillFinishLaunching_(aNotification)
      -- Insert code here to initialize your application before any files are opened
            tstTxtDel()
              end applicationWillFinishLaunching_
              on applicationShouldTerminate_(sender)
      -- Insert code here to do any housekeeping before your application quits
                        return current application's NSTerminateNow
              end applicationShouldTerminate_
        on tstTxtDel()
            set text item delimiters to "+"
            set d to "-s http://www.nietzschefamilycircus.com"
            set r to do shell script "curl  " & d & " | ~/Desktop/try.pl"
            display dialog "r is " & r
            set rr to every text item of r
            display dialog "rr " & rr
            display dialog "curl " & first text item of rr & " -o "
    end
    end script
    However if you put the tstTstDel() function in the Applescript editor it works as expected.
    The try.pl script is
    #!/usr/bin/perl
    $s ="";
    while (<>) {
        $s .= $_;
    $s =~ m{class="comic"(.*)<div class="footer">}si;
    ($link, $caption,$jj) = ($1 =~ m{<img src="(.*)" alt=.*class="quote">(.*)(</div>.*</div>)}si);
    print $link, "+", $caption, "\n";
    I know this worked in the past. The Coca-Applescript app was written at least as far back as Snow Leopard. The site I am parsing changed their format and I was updating the app as a means to learn the new Coca-Applescript environment.
    Any help appreciated

    OK found it, I needed to use
    set Applescript's text item delimiters to "+"
    instead of just
    set text item delimiters to "+"
    I suppose it is a scoping thing.

  • How can I create a Table View in Cocoa Applescript?

    This is my last resort. I've searched for days and only found tutorials for iPhone and Cocoa, and I have no idea where to start. I'm looking for a way to create a Table View, and fill it with a few cells that call a handler when clicked. I've looked through the Xcode help, the Apple documentation, and countless tutorials, and I don't know what to do. I'm sure what I'm asking is possible, because usually what is possible in Cocoa is possible in Cocoa-Applescript.
    Perhaps something like:
    myTableView's addCell_OfType_WithHandler("This is a text cell", text, "myHandler:")
    I would appretiate any responses and brief descriptions on the matter.

    You did not answer my first question, which was not an idle question. I'll answer here, but if cross-chatter appears in a different thread I'll ignore it. You'll have to keep track of the mess yourself.
    Apple_For_The_Win wrote:
    At this point, I've dragged a Table View onto my window, in Xcode. I've connected it to the value "myTableView", and that's where I need help. I'm specifically trying to add cells into the table view.
    I'll assume that 'connected it to the value "myTableView"' means that you've control-dragged in XCode from the table view in Main Menu.xib to a property in your applescript app delegate called myTableView. If that's not the case, please correct me.
    I prefer to use an array controller for this, so please drag an array controller object into main menu.nib. once you've done that, do the following:
    open the applescript app delegate and add a new property called "tableController"
    select the table view in the object list (you may need to open some disclosure triangles to reach it). and add appropriate (an) column name(s). you can hide column titles later if you like, but having named columns makes life easier.
    select the array controller in the object list
    rename the array controller "table data"
    open the attributes inspector, and then add the column name(s) as key(s) in the object controller area
    open the bindings inspector, and where it says "controller content", open the disclosure arrow and bind the content to the App Delegate object on the model key path self.tableController
    select the table view in the object list again, then go down a level and select each column in turn
    for each column, open the bindings inspector, and where it says "value", open the disclosure arrow and bind the content to the Table Data object with the controller key arrangedObjects model key path being the name of the column (which is the name of the key in the controller as well)
    back in the applescript app delegate, add code like the following:
      -- create a list of records, where each record represents a row and the column name is the record key
      set myData to {{column_1_name:"hello"}}
      -- convert it to an NSArray and add it to the controller content. don't forget the *my* keyword, or it won't work
      set my tableController to NSArray's arrayWithArray:myData
      -- may or may not be needed
      myTableView's reloadData()
    That should populate the table with simple text. if you want something more complicated (like buttons or links) then create the more complicated elements separately and add them to the data.

  • What handler is called when a Status-Bar-Icon is clicked in Cocoa-Applescript?

    In Cocoa-Applescript Xcode, what handler is called when the Status-Bar-Icon for my app is clicked? Are there any variables or connections that I have to make?

    Thanks Red_menace! I don't know what the Apple community would do without you.
    For others viewing this question, the following is the proper format, for Cocoa-Applescript:
    property NSStatusBar : class "NSStatusBar"
    property StatusItem : ""
    on applicationWillFinishLaunching_()
    set StatusItem to NSStatusBar's systemStatusBar's statusItemWithLength_(current application's NSSquareStatusItemLength)
    StatusItem's setAction_("myAction:")
    end applicationWillFinishLaunching_
    on myAction_()
    say "Hello!"
    end myAction_
    Where "myAction:" is the action that you want to call when the Status-Bar-Item is clicked. It should also be noted that this handler will not be called if a menu or view is already linked to it's click action.

  • Simple introduction/tutorial on how to make Cocoa-Applescript Applets?

    I'm looking for a simple tutorial on how to make Cocoa-Applescript Applets.  I'm pretty new to Applescript, but fairly good at it, and I was wondering how Cocoa-Applescript Applets worked.  I was curious as I've been wondering if it was possible to somehow display images in Applescript, and it apparently is the only/easiest way.  My problem is that I haven't been able to find any tutorials on using it, so I was wondering if you guys could point me in the right direction, that'd be great!
    thanks in advance

    The main difference is with how the Cocoa APIs are used - in addition to the AppleScript and AppleScriptObjC release notes, there are some examples and resources at Mac OS X Automation.  Note that in Yosemite, AppleScriptObjC is available to all scripts, not just applets and libraries.

  • How to display an image in Cocoa-Applescript?

    I made my script, but for a welcome message there is no image. How do I display one embeded in a dialog box with text underneath? I'm making this with ApplescriptEditor, not Xcode. Let's say this image was called "MCL.PNG". Thanks in advance.

    A Cocoa-AppleScript uses the Cocoa frameworks, so that is what I thought you were talking about.  A regular AppleScript display dialog can only use an icon, and it is positioned on the left without any text (unless the text is a part of the icon).  If you have an icon file, you can use an alias or file reference using the with icon parameter for the command (see the Standard Additions scripting dictionary), for example:
    display dialog "testing" with icon file "path:to:your:icon"

  • How can I prevent my fullscreen app from closing when escape is pressed in Cocoa-Applescript?

    How can I prevent my fullscreen Cocoa-Applescript app from being closed when a user presses escape?

    Actually, in testing something else with Thunderbird as the receiving email client, I found that blanks in the Full Name entry box works when the recipient does not have a history with you. My earlier tests were from one account to another of my accounts, but viewing the received message in Mail. Mail knew the address so added the Full Name from history. The Thunderbird I was testing another issue with, was a virgin installation, and had the same recipient account, but not the sending one, setup. In Thunderbird only the actual email address came in, and no name.
    Ernie

  • Capture an image using the web camera from a web application

    Hi All,
    Could anyone please share the steps what have to be followed for capture an image using the web camera from a web application.
    I have a similar requirement like this,
    1) Detect the Webcam on the users machine from the web application.(To be more clear when the user clicks on 'Add Photo' tool from the web application)
    2) When the user confirms to save, save the Image in users machine at some temporary location with some unique file name.
    3) Upload the Image to the server from the temporary location.
    Please share the details like, what can be used and how it can be used etc...
    Thanks,
    Suman

    1) Detect the Webcam on the users machine from the web application.(To be more clear when the user clicks on 'Add Photo' tool from the web application)There's not really any good way to do this with JMF. You'd have to somehow create a JMF web-start application that will install the native JMF binaries, and then kick off the capture device scanning code from the application, and then scan through the list of devices found to get the MediaLocator of the web cam.
    2) When the user confirms to save, save the Image in users machine at some temporary location with some unique file name.You'd probably be displaying a "preview" window and then you'd just want to capture the image. There are a handful of ways you could capture the image, but it really depends on your situation.
    3) Upload the Image to the server from the temporary location.You can find out how to do this on google.
    All things told, this application is probably more suited to be a FMJ (Freedom for Media in Java) application than a JMF application. JMF relies on native code to capture from the web cams, whereas FMJ does not.
    Alternately, you might want to look into Adobe Flex for this particular application.

Maybe you are looking for

  • BATCH SPLIT in Order Delivery and PGI (SD)

    Hi Could anybody tell me the following: 1) What is the concept of Batch Split? 2) How it is shown when a Delivery Order is created? 3) How it afftects when Goods Issue is done? 4) How can we calculate the total delivery quantity when there is a Batch

  • Criticisms? First package for r5u870-svn

    NOTE: see below for finished product So I'm building a Pkgbuild for the fun of learning how to do so. In particular this one is for the r5u870 webcam driver which downloads from the svn and not a static source. Thus far I have this: # contributor: or

  • CRM Technical Presentation

    Hi all     I have been asked to present a CRM Technical presentation to all the Non-CRM Developers here in my company.  This presentation should be more of Technical One than speaking Business/Functional Points.    But i am really donot know, what ar

  • Error "-7500" occurred in the current database connection "LCA"

    LC & apo box rebooted due hardware failure now once LC is up then all cif quuese are failing with "An SQL error occurred when executing Native SQL" error. Looking further it indicates lc issue. Getting multiple dumps in apo box with :- Short text    

  • Notes won't update

    Hi guys. I installed Mountain Lion today and everything but one feature is working AWESOME! Notes won't update. I have a tonne of notes on my iphone 4S that aren't showing up in my notes on my 2012 macbook pro. I can't seem to figure out why though.