Revert "Added wizardless commands (pack and unpack)" and re-implement original soluti...
[appimagekit/gsi.git] / AppImageAssistant.AppDir / AppImageAssistant
blobbb5812e0bd1f93298dc3255e13e70c39bc40880c
1 #!/usr/bin/env python2
3 # /**************************************************************************
4
5 # Copyright (c) 2005-15 Simon Peter
6
7 # All Rights Reserved.
8
9 # Permission is hereby granted, free of charge, to any person obtaining a copy
10 # of this software and associated documentation files (the "Software"), to deal
11 # in the Software without restriction, including without limitation the rights
12 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 # copies of the Software, and to permit persons to whom the Software is
14 # furnished to do so, subject to the following conditions:
15
16 # The above copyright notice and this permission notice shall be included in
17 # all copies or substantial portions of the Software.
18
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 # THE SOFTWARE.
26
27 # ******************************************************
29 __version__="0.9.3"
32 # TODO:
33 # Find out why it freezes on Fedora 12
36 import os, sys
37 from locale import gettext as _
39 import shutil
40 import os
41 from subprocess import *
42 import tempfile
43 import sys
44 import bz2
45 import xdgappdir 
46 import commands
47 import threading
48 import glob
51 def usage():
52     print "Usage:"
53     print " ", "<input AppDir>", "<output AppImage>"
54     print "     ", "Create an AppImage from an AppDir"
55     print " ", "-f, --force"
56     print "     ", "Overwrite target if already existing"
57     print " ", "-h, --help"
58     print "     ", "Show this help message"
59     print " ", "<no arguments>"
60     print "     ", "Start AppImage creation wizard"
61     exit(0)
64 if len(sys.argv) == 2:
65     usage()
67 for arg in sys.argv:
68     if arg in ["-h", "--help"]:
69         usage()
71 if len(sys.argv) == (3):
72     os.system(os.path.dirname(__file__) + "/package %s %s" % (sys.argv[1], sys.argv[2]))
73     exit(0)
75 import  gtk, vte
76 import xdgappdir # bundled with this app
77 import dialogs # part of kiwi; bundled with this app
79 application_icon = os.path.join(os.path.dirname(sys.argv[0]), "AppImageAssistant.png")
81 def error(string, fatal=True):
82     print(string)
83     if fatal == True:
84         buttontype = gtk.BUTTONS_CANCEL
85     else:
86         buttontype = gtk.BUTTONS_OK
87     message = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, buttontype, string)
88     resp = message.run()
89     message.destroy()
90     if fatal == True:
91         exit(1)
93     '''
94     returns 1 if yes was pressed,
95             0 if no  was pressed,
96        -1 if dialog was cancled
97                '''
99     d=gtk.GtkWindow()
100     hbox = gtk.GtkHButtonBox()
101     def delete_event(widget, event, d):
102         d.callback_return=-1
103         return gtk.FALSE
104     d.connect("delete_event", delete_event, d)
105     d.add(hbox)
106     def callback(widget, data):
107         d=data[0]
108         data=data[1]
109         d.hide()
110         d.callback_return=data
112     yes = gtk.GtkButton(yes_text)
113     yes.connect("clicked", callback, (d, 1))
114     hbox.pack_start(yes)
116     no = gtk.GtkButton(no_text)
117     no.connect("clicked", callback, (d, 0))
118     hbox.pack_start(no)
120     d.set_modal(gtk.TRUE)
121     d.show_all()
122     d.callback_return=None
123     while d.callback_return==None:
124         gtk.mainiteration(gtk.TRUE) # block until event occurs
125     return d.callback_return
127 def threaded(f):
128     def wrapper(*args):
129         t = threading.Thread(target=f, args=args)
130         t.setDaemon(True)
131         t.start()
132     wrapper.__name__ = f.__name__
133     wrapper.__dict__ = f.__dict__
134     wrapper.__doc__  = f.__doc__
135     return wrapper
137 class Assistant(gtk.Assistant):
138     def __init__(self):
139         gtk.Assistant.__init__(self)
140         self.connect('close', gtk.main_quit)
141         self.connect('cancel',gtk.main_quit)
142         #self.connect('prepare', self.callback_prepare) 
143         self.set_icon_from_file(application_icon)
144         self.set_size_request(640, 480)
145         self.init_intro_page()
147     def text_page(self, header, text):
148         label = gtk.Label(text)
149         label.show()
150         label.set_line_wrap(True)
151         self.append_page(label)
152         self.set_page_title(label, header)
153         self.set_page_complete(label, True)    
154         self.set_page_header_image(label, gtk.gdk.pixbuf_new_from_file(application_icon))
156     def chooser_page(self, header):
157         chooser = gtk.FileChooserWidget(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
158         chooser.connect("selection-changed", self.check_if_appdir_callback)
159         chooser.connect("key-release-event", self.check_if_appdir_callback)
160         if len(sys.argv) > 1:
161             chooser.set_current_folder(sys.argv[1])
162         else:
163             chooser.set_current_folder(os.environ.get('HOME'))
164         chooser.show()
165         self.append_page(chooser)
166         self.set_page_title(chooser, header)
167         self.set_page_complete(chooser, False)
168         self.set_page_header_image(chooser, gtk.gdk.pixbuf_new_from_file(application_icon))
170     def runner_page(self, callable):    
171         vbox = gtk.VBox()
172         vbox.set_name("MAIN_RUNNER_PAGE")
173         label = gtk.Label(_("Running..."))
174         label.set_line_wrap(True)
175         vbox.pack_start(label, False, False, 0)
176         runbox = RunBox(self)
177         runbox.connect('realize', callable)
178         vbox.pack_start(runbox, True, True, 0)
179         self.append_page(vbox)
180         self.set_page_title(vbox, "Running...")
181         self.set_page_header_image(vbox, gtk.gdk.pixbuf_new_from_file(application_icon))
182         vbox.show_all()
183         self.set_page_complete(vbox, True) ##############################
184         self.set_page_type(vbox, gtk.ASSISTANT_PAGE_PROGRESS) 
186         # UNTIL HERE IT IS GENERIC ====================================================
188     def result_page(self):
189         vbox = gtk.VBox()
190         icon = gtk.Image()
191         vbox.pack_start(icon, False, False, 0)
192         vbox.show_all()
193         scrolled = gtk.ScrolledWindow()
194         scrolled.add_with_viewport(vbox)
195         scrolled.show()
196         self.append_page(scrolled)
197         self.set_page_header_image(vbox, gtk.gdk.pixbuf_new_from_file(application_icon))
198         icon.show()
199         filetype = Popen(["file", "-k", "-r", self.targetname], stdout=PIPE).communicate()[0]
200         # print filetype
201         if "ISO 9660" in filetype and "LSB executable" in filetype:
202             icon.set_from_file(os.path.join(os.path.dirname(sys.argv[0]), "Gnome-emblem-default.png"))
203             self.set_page_title(vbox, "Done")
204             self.set_page_type(vbox, gtk.ASSISTANT_PAGE_SUMMARY)
205             basesystems = glob.glob('/System/iso/*.iso')
206             basesystems.append("/cdrom/casper/filesystem.squashfs")
207             for basesystem in basesystems:
208                 print basesystem
209                 button = gtk.Button(_("Run in %s") % (basesystem))
210                 button.connect('clicked', self.testrun, basesystem, self.targetname)
211                 vbox.pack_start(button)
212                 button.show()
213         else:
214             icon.set_from_file(os.path.join(os.path.dirname(sys.argv[0]), "Gnome-dialog-warning.png"))
215             self.set_page_title(icon, "An error has occured")         
217     def testrun(self, sender, basesystem, appimage):
218         # Need an involved workaround because running as root means that we cannot access files inside the AppImage due to permissions
219         shutil.copyfile(os.path.join(os.path.dirname(sys.argv[0]), "testappimage"), "/tmp/testappimage")
220         shutil.copyfile(os.path.join(os.path.dirname(sys.argv[0]), "unionfs-fuse"), "/tmp/unionfs-fuse")
221         os.system("sudo chmod 755 /tmp/testappimage /tmp/unionfs-fuse")
222         os.system("sudo xterm -hold -e /tmp/testappimage  '" + basesystem + "' '" + appimage + "'")
224     def check_if_appdir_callback(self, widget, dummy=False):
225         print _("Checking whether %s is an AppDir" % (widget.get_filename()))
226         self.set_page_complete(widget, True)
227         candidate = widget.get_filename()
228         if not os.path.isfile(os.path.join(candidate, "AppRun")):
229             self.set_page_complete(widget, False)
230             return
232         self.H = xdgappdir.AppDirXdgHandler(candidate) 
233         print self.H
234         if self.H.desktopfile == None:
235             self.set_page_complete(widget, False)
236             error(_("Can't find this AppDir's desktop file"), False)
237             return
238         if self.H.executable == None:
239             self.set_page_complete(widget, False)
240             error(_("Can't find the executable in this AppDir's desktop file"), False)
241             return
242         if self.H.icon == None:
243             self.set_page_complete(widget, False)
244             error(_("Can't find the icon in this AppDir's desktop file"), False)
245             return
247         self.appdir = candidate
248         try:
249             self.targetname = os.path.join(os.path.dirname(self.appdir), self.H.name)
250         except:
251             self.targetname = os.path.join(os.path.dirname(self.appdir), os.path.basename(self.H.executable))
253         if os.path.exists(self.targetname):
254             self.set_page_complete(widget, False)
255             resp = dialogs.yesno(_("%s already exists, do you want to delete it?") % (self.targetname))
256             if resp == gtk.RESPONSE_YES:
257                 try:
258                     os.unlink(self.targetname)
259                     self.set_page_complete(widget, True)
260                     self.set_current_page(self.get_current_page() + 1) # go to the next page        
261                 except:
262                     error(_("%s already exists, delete it first if you want to create a new one") % (self.targetname), False)
263             return
265     def init_intro_page(self):
266         self.text_page("AppImageAssistant " + __version__, "This assistant helps you to package an AppDir for distribution as an AppImage. It is part of AppImageKit. \n\nPlease see http://portablelinuxapps.org/forum for more information.")
267         self.chooser_page("Please select the AppDir")
268         self.runner_page(self.run1_func)
270     @threaded # For this to work, the gtk.gdk.threads_init() function must be called before the gtk.main() function
271     def run1_func(self, widget):
272         command = ["python", os.path.join(os.path.dirname(sys.argv[0]), "package"), self.appdir, self.targetname]
273         print "Running command:"
274         print command
275         gtk.gdk.threads_enter() # this must be called in a function that is decorated with @threaded
276         widget.run_command(command) # this is the long-running command
277         gtk.gdk.threads_leave() # this must be called in a function that is decorated with @threaded
279 class RunBox(vte.Terminal):
280     def __init__(self, assistant):
281         vte.Terminal.__init__(self)
282         self.connect('child-exited', self.run_command_done_callback)
283         self.assistant = assistant # the assistant is passed in here so that we can e.g., disable forward buttons
285     def run_command(self, command_list):
286         self.assistant.set_page_complete(self.assistant.get_nth_page(self.assistant.get_current_page()), False)
287         self.thread_running = True
288         command = command_list
289         pid =  self.fork_command(command=command[0], argv=command, directory=os.getcwd())
290         while self.thread_running:
291             gtk.main_iteration()
293     def run_command_done_callback(self, terminal):
294         print('child done')
295         self.assistant.set_page_complete(self.assistant.get_nth_page(self.assistant.get_current_page()), True) # enable the next page button
296         self.assistant.result_page() # only now initialize the results page because it needs to check whether we succeeded
297         self.assistant.set_current_page(self.assistant.get_current_page() + 1) # go to the next page
298         self.thread_running = False        
301 if __name__=="__main__":
302     A = Assistant()
303     A.show()
304     gtk.gdk.threads_init() # The gtk.gdk.threads_init() function must be called before the gtk.main() function
305     gtk.main()