/* ascript: A wrapper for Apple's osascript utility Copyright (C) 2005 Nafees Bin Zafar This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*! \file ascript.cc \author Nafees Bin Zafar \date 10/10/03 $Id: ascript.cc,v 1.1.1.1 2004/10/26 19:27:16 nafees Exp $ \brief This program is a wrapper around osascript to allow for unix styled AppleScript shell scripts. This will allow you to write a shell script beginning with #!/path/to/ascript followed by the AppleScript source. Here is a dinky example: #!/usr/bin/ascript -- Created by Nafees Bin Zafar on Mon Nov 10 2003. tell application "iTunes" if player state is not playing then play else pause end if end tell */ #include #include #include #include using namespace std; #include int main(int argc, char** argv) { /* 1. build the argument list to pass to execv() 2. fork 3. child execs osascript 4. parent writes script to child */ // build an argument list like: // osascript - argv[1] argv[2] argv[3] ... NULL char** l_args; l_args = new char*[ argc + 1 ]; for ( int c = 2; c < argc; c++ ) { l_args[c] = argv[c]; } l_args[0] = "/usr/bin/osascript"; l_args[1] = "-"; l_args[argc] = NULL; pid_t pid; int pipefd[2]; // 0: child reads 1: parent writes ifstream script; // script file if ( pipe( pipefd ) == -1 ) { cerr << "Error creating pipe. Exiting." << endl; exit( 1 ); } string input; switch ( pid = fork() ) { case -1: // error cerr << "Error fork()-ing. Exiting." << endl; exit( -1 ); case 0: // child proc close( pipefd[1] ); dup2( pipefd[0], STDIN_FILENO ); execv( l_args[0], l_args ); // we shouldn't be here exit( -1 ); default: // parent proc close( pipefd[0] ); script.open( argv[1] ); getline( script, input ); // eat the #!/.../ascript line while( script.good() ) { getline( script, input ); input += "\n"; write( pipefd[1], input.c_str(), input.length() ); } close( pipefd[1] ); wait( NULL ); } delete [] l_args; return 0; }