source: branches/sandbox/makeMacApp.py @ 1245

Last change on this file since 1245 was 1245, checked in by toby, 10 years ago

dup updates in trunk

  • Property svn:eol-style set to native
File size: 8.2 KB
Line 
1#!/usr/bin/env python
2'''
3*makeMacApp: Create Mac Applet*
4===============================
5
6This script creates an AppleScript app to launch EXPGUI. The app is
7created in the main directory where the GSAS files are located.
8
9Run this script with one optional argument, the path to the expgui file.
10The script path may be specified relative to the current path or given
11an absolute path, but will be converted to an absolute path.
12If no arguments are supplied, this script will look for file
13expgui in the same directory as this file.
14
15'''
16import sys, os, os.path, stat, shutil, subprocess, plistlib
17def Usage():
18    print("\n\tUsage: python "+sys.argv[0]+" [<path/>expgui]\n")
19    sys.exit()
20
21project="EXPGUI"
22
23if __name__ == '__main__':
24    # find the expgui tcl script if not on command line
25    if len(sys.argv) == 1:
26        script = os.path.abspath(os.path.join(
27            os.path.split(__file__)[0],
28            "expgui"
29            ))
30    elif len(sys.argv) == 2:
31        script = os.path.abspath(sys.argv[1])
32    else:
33        Usage()
34
35    while os.path.isdir(script):
36        print("found expgui directory: "+str(script))
37        script = os.path.join(script,'expgui')
38
39    # make sure we found it
40    if not os.path.exists(script):
41        print("\nFile "+script+" not found")
42        Usage()
43    # where the app will be created
44    scriptdir = os.path.split(os.path.split(script)[0])[0]
45    # name of app
46    apppath = os.path.abspath(os.path.join(scriptdir,project+".app"))
47    iconfile = os.path.join(scriptdir,'expgui','expgui.icns') # optional icon file
48
49    if os.path.exists(apppath): # cleanup
50        print("\nRemoving old "+project+" app ("+str(apppath)+")")
51        shutil.rmtree(apppath)
52
53    # create an AppleScript that launches python with the requested app
54    AppleScript = '''(*   Launch EXPGUI: launches EXPGUI by double clicking on app or by dropping a data file or folder on the app
55
56version for 10.6 and later
57
58original script by F. Farges; farges@univ-mlv.fr ; many changes by B. Toby brian.toby@anl.gov
59
60To debug this script, create file /tmp/EXPGUIdebug.txt (from command line: touch /tmp/EXPGUIdebug.txt)
61The output from launching EXPGUI will be appended to the end of that file.
62*)
63
64
65(*--------------------------------------------------------
66Define subroutines  used in later sections of code
67-----------------------------------------------------------
68*)
69
70(*  get  directory  from a file name *)
71on GetParentPath(theFile)
72        tell application "Finder" to return container of theFile as text
73end GetParentPath
74
75(* find a wish executable or return an error *)
76on GetWishExe(myPath)
77        set WishExe to myPath & "exe:ncnrpack"
78        set WishExe to the POSIX path of WishExe
79        tell application "System Events"
80                if (file WishExe exists) then
81                        return WishExe
82                end if
83                (*set WishExe to "/sw/bin/wish"
84                if (file WishExe exists) then
85                        return WishExe
86                end if*)
87                error ("Error: Tcl/Tk executable, " & WishExe & " was not found. See installation instructions.")
88        end tell
89end GetWishExe
90
91(* test if a file is present and exit with an error message if it is not  *)
92on TestFilePresent(appwithpath)
93        tell application "System Events"
94                if (file appwithpath exists) then
95                else
96                        error ("Error: file " & appwithpath & " not found. This EXPGUI AppleScript must be run from the gsas directory. Did you move it?")
97                end if
98        end tell
99end TestFilePresent
100
101(*
102--------------------------------------------------------------
103this section responds to a double-click. It starts X11 and then expgui, provided
104the expgui script is in the expgui folder of the location of this applescript
105 o it finds the location of the current script and finds the expgui
106     tcl script relative to the applescript
107 o it finds a version of Tcl/Tk to run either relative to the script location
108     or if not present there, in the place where Fink would install it
109 o it opens X11 (if needed)
110--------------------------------------------------------------
111*)
112on run
113        set Prefix to "cd ~;PATH=$PATH:/usr/local/bin:/usr/X11R6/bin "
114        tell application "Finder"
115                if POSIX file "/tmp/EXPGUIdebug.txt" exists then
116                        set Output to "/tmp/EXPGUIdebug.txt"
117                else
118                        set Output to "/dev/null"
119                end if
120        end tell
121        set myPath to (path to me)
122        set ParentPath to GetParentPath(myPath)
123        set appwithpath to ParentPath & "expgui:expgui"
124        TestFilePresent(appwithpath)
125        set posixapp to quoted form of the POSIX path of appwithpath
126        set WishExe to the quoted form of GetWishExe(ParentPath)
127       
128        tell application "Finder"
129                launch application "X11"
130        end tell
131       
132        set results to do shell script Prefix & WishExe & " " & posixapp & "  >> " & Output & " 2>&1 &"
133end run
134
135(*
136----------------------------------------------------------------------
137this section handles opening files dragged into the AppleScript
138 o it finds the location of the current script and finds the expgui
139     tcl script relative to the applescript
140 o it finds a version of Tcl/Tk to run either relative to the script location
141     or if not present there, in the place where Fink would install it
142 o it opens X11 (if needed)
143 o it goes through the list of files dragged in
144 o then it converts the colon-delimited macintosh file location to a POSIX filename
145 o for every non-directory file dragged into the icon, it tries to open that file in the script
146-----------------------------------------------------------------------
147*)
148
149on open names
150       
151        set Prefix to "PATH=$PATH:/usr/local/bin:/usr/X11R6/bin "
152        tell application "Finder"
153                if POSIX file "/tmp/EXPGUIdebug.txt" exists then
154                        set Output to "/tmp/EXPGUIdebug.txt"
155                else
156                        set Output to "/dev/null"
157                end if
158        end tell
159        set myPath to (path to me)
160        set ParentPath to GetParentPath(myPath)
161        set appwithpath to GetParentPath(myPath) & "expgui:expgui"
162        TestFilePresent(appwithpath)
163        set posixapp to the quoted form of the POSIX path of appwithpath
164        set WishExe to the quoted form of GetWishExe(ParentPath)
165       
166        tell application "Finder"
167                launch application "X11"
168        end tell
169       
170        set filePath to ""
171        repeat with i in names
172                set macpath to (i as string)
173                if macpath ends with ":" then
174                        (* if this is a directory; start EXPGUI in that folder *)
175                        set filename to the quoted form of the POSIX path of macpath
176                        set results to do shell script "cd " & filename & ";" & Prefix & WishExe & "  " & posixapp & "  >> " & Output & " 2>&1 &"
177                else if macpath ends with ".EXP" then
178                        (* if this is an experiment file, open it *)
179                        set filename to the quoted form of the POSIX path of macpath
180                        set results to do shell script "cd ~;" & Prefix & WishExe & " " & posixapp & " " & filename & "  >> " & Output & " 2>&1 &"
181                else
182                        display dialog "This is not a valid GSAS Experiment file: " & macpath with icon caution buttons {"OK"}
183                end if
184        end repeat
185end open
186'''
187    shell = os.path.join("/tmp/","appscrpt.script")
188    f = open(shell, "w")
189    f.write(AppleScript)
190    f.close()
191
192    if sys.version_info[0]+sys.version_info[1]/10. >= 2.7:
193        try: 
194            subprocess.check_output(["osacompile","-o",apppath,shell],stderr=subprocess.STDOUT)
195        except subprocess.CalledProcessError, msg:
196            print('Error compiling AppleScript.\n'+
197                  'Report the next message along with details about your Mac to toby@anl.gov')
198            print(msg.output)
199            sys.exit()
200    else:
201        try: 
202            subprocess.call(["osacompile","-o",apppath,shell])
203        except Exception, msg:
204            print('Error compiling AppleScript in python <=2.6\n'+
205                  'Report the next message along with details about your Mac to toby@anl.gov')
206            print(msg)
207            sys.exit()
208    # change the icon
209    oldicon = os.path.join(apppath,"Contents","Resources","droplet.icns")
210    if os.path.exists(iconfile) and os.path.exists(oldicon):
211        shutil.copyfile(iconfile,oldicon)
212
213    # Edit the app plist file to restrict the type of files that can be dropped
214    d = plistlib.readPlist(os.path.join(apppath,"Contents",'Info.plist'))
215    d['CFBundleDocumentTypes'] = [{
216        'CFBundleTypeExtensions': ['EXP'],
217        'CFBundleTypeName': 'GSAS project',
218        'CFBundleTypeRole': 'Editor'}]
219    plistlib.writePlist(d,os.path.join(apppath,"Contents",'Info.plist'))
220
221    print("\nCreated "+project+" app ("+str(apppath)+
222          ").\nViewing app in Finder so you can drag it to the dock if, you wish.")
223    subprocess.call(["open","-R",apppath])
Note: See TracBrowser for help on using the repository browser.