source: trunk/makeMacApp.py @ 1109

Last change on this file since 1109 was 1109, checked in by toby, 8 years ago

minor doc updates, no rebuild

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 6.2 KB
Line 
1#!/usr/bin/env python
2'''
3*makeMacApp: Create Mac Applet*
4===============================
5
6This script creates an AppleScript app to launch GSAS-II. The app is
7created in the directory where the GSAS-II script is located.
8A softlink to Python is created, but is named GSAS-II, so that
9GSAS-II shows up as the name of the app rather than Python in the
10menu bar, etc. Note that this requires finding an app version of Python
11(expected name .../Resources/Python.app/Contents/MacOS/Python in
12directory tree of the calling python interpreter).
13
14Run this script with one optional argument, the path to the GSASII.py
15The script path may be specified relative to the current path or given
16an absolute path, but will be accessed via an absolute path.
17If no arguments are supplied, the GSASII.py script is assumed to be in the
18same directory as this file.
19
20'''
21import sys, os, os.path, stat, shutil, subprocess, plistlib
22def Usage():
23    print("\n\tUsage: python "+sys.argv[0]+" [<GSAS-II script>]\n")
24    sys.exit()
25
26project="GSAS-II"
27
28if __name__ == '__main__':
29    # find the main GSAS-II script if not on command line
30    if len(sys.argv) == 1:
31        script = os.path.abspath(os.path.join(
32            os.path.split(__file__)[0],
33            "GSASII.py"
34            ))
35    elif len(sys.argv) == 2:
36        script = os.path.abspath(sys.argv[1])
37    else:
38        Usage()
39
40    # make sure we found it
41    if not os.path.exists(script):
42        print("\nFile "+script+" not found")
43        Usage()
44    if os.path.splitext(script)[1].lower() != '.py':
45        print("\nScript "+script+" does not have extension .py")
46        Usage()
47    # where the app will be created
48    scriptdir = os.path.split(script)[0]
49    # name of app
50    apppath = os.path.abspath(os.path.join(scriptdir,project+".app"))
51    iconfile = os.path.join(scriptdir,'gsas2.icns') # optional icon file
52
53    # find the python application; must be an OS X app
54    pythonpath,top = os.path.split(os.path.realpath(sys.executable))
55    while top:
56        if 'Resources' in pythonpath:
57            pass
58        elif os.path.exists(os.path.join(pythonpath,'Resources')):
59            break
60        pythonpath,top = os.path.split(pythonpath)
61    else:
62        print("\nSorry, failed to find a Resources directory associated with "+str(sys.executable))
63        sys.exit()
64    pythonapp = os.path.join(pythonpath,'Resources','Python.app','Contents','MacOS','Python')
65    if not os.path.exists(pythonapp): 
66        print("\nSorry, failed to find a Python app in "+str(pythonapp))
67        sys.exit()
68
69    # new name to call python
70    newpython =  os.path.join(apppath,"Contents","MacOS",project)
71
72    if os.path.exists(apppath): # cleanup
73        print("\nRemoving old "+project+" app ("+str(apppath)+")")
74        shutil.rmtree(apppath)
75
76    # create an AppleScript that launches python with the requested app
77    AppleScript = '''(*   GSAS-II AppleScript by B. Toby (brian.toby@anl.gov)
78     It can launch GSAS-II by double clicking or by dropping a data file
79     or folder over the app.
80     It runs GSAS-II in a terminal window.
81*)
82
83(* test if a file is present and exit with an error message if it is not  *)
84on TestFilePresent(appwithpath)
85        tell application "System Events"
86                if (file appwithpath exists) then
87                else
88                        display dialog "Error: file " & appwithpath & " not found. If you have moved this file recreate the AppleScript with bootstrap.py." with icon caution buttons {{"Quit"}}
89                        return
90                end if
91        end tell
92end TestFilePresent
93
94(*
95------------------------------------------------------------------------
96this section responds to a double-click. No file is supplied to GSAS-II
97------------------------------------------------------------------------
98*)
99on run
100        set python to "{:s}"
101        set appwithpath to "{:s}"
102        TestFilePresent(appwithpath)
103        TestFilePresent(python)
104        tell application "Terminal"
105                activate
106                do script python & " " & appwithpath & "; exit"
107        end tell
108end run
109
110(*
111-----------------------------------------------------------------------------------------------
112this section handles starting with files dragged into the AppleScript
113 o it goes through the list of file(s) dragged in
114 o then it converts the colon-delimited macintosh file location to a POSIX filename
115 o for every non-directory file dragged into the icon, it starts GSAS-II, passing the file name
116------------------------------------------------------------------------------------------------
117*)
118
119on open names
120        set python to "{:s}"
121        set appwithpath to "{:s}"
122        TestFilePresent(appwithpath)
123        repeat with filename in names
124                set filestr to (filename as string)
125                if filestr ends with ":" then
126                        (* should not happen, skip directories *)
127                else
128                        (* if this is an input file, open it *)
129                        set filename to the quoted form of the POSIX path of filename
130                        tell application "Terminal"
131                                activate
132                                do script python & " " & appwithpath & " " & filename & "; exit"
133                        end tell
134                end if
135        end repeat
136end open
137'''
138    shell = os.path.join("/tmp/","appscrpt.script")
139    f = open(shell, "w")
140    f.write(AppleScript.format(newpython,script,newpython,script))
141    f.close()
142
143    try: 
144        subprocess.check_output(["osacompile","-o",apppath,shell],stderr=subprocess.STDOUT)
145    except subprocess.CalledProcessError, msg:
146        print '''Error compiling AppleScript.
147        Report the next message along with details about your Mac to toby@anl.gov'''
148        print msg.output
149        sys.exit()
150
151    # create a link to the python app, but named to match the project
152    os.symlink(pythonapp,newpython)
153
154    # change the icon
155    oldicon = os.path.join(apppath,"Contents","Resources","droplet.icns")
156    if os.path.exists(iconfile) and os.path.exists(oldicon):
157        shutil.copyfile(iconfile,oldicon)
158
159    # Edit the app plist file to restrict the type of files that can be dropped
160    d = plistlib.readPlist(os.path.join(apppath,"Contents",'Info.plist'))
161    d['CFBundleDocumentTypes'] = [{
162        'CFBundleTypeExtensions': ['gpx'],
163        'CFBundleTypeName': 'GSAS-II project',
164        'CFBundleTypeRole': 'Editor'}]
165    plistlib.writePlist(d,os.path.join(apppath,"Contents",'Info.plist'))
166
167    print("\nCreated "+project+" app ("+str(apppath)+
168          ").\nViewing app in Finder so you can drag it to the dock if, you wish.")
169    subprocess.call(["open","-R",apppath])
Note: See TracBrowser for help on using the repository browser.