~jonobacon/acire/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
#!/usr/bin/python
# -*- coding: utf-8 -*-
### BEGIN LICENSE
# Copyright (C) 2009 Jono Bacon <jono@ubuntu.com>
#This program is free software: you can redistribute it and/or modify it 
#under the terms of the GNU General Public License version 3, as published 
#by the Free Software Foundation.
#
#This program is distributed in the hope that it will be useful, but 
#WITHOUT ANY WARRANTY; without even the implied warranties of 
#MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR 
#PURPOSE.  See the GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License along 
#with this program.  If not, see <http://www.gnu.org/licenses/>.
### END LICENSE

import sys
import os
import gtk
import fnmatch
import re
import vte
import gtksourceview2
import pango
import webbrowser
import gconf
from mechanize import Browser
import tempfile     #Used in run_snippet to run user-modded snippet
###Needed to check for GTK version, gtk.FileChooserDialog available, see save_snippet()
import pygtk
pygtk.require('2.0')
if gtk.pygtk_version < (2,3,90):
    print "PyGtk ver. 2.3.90 or later required for FileChooserDialog, to save snippets."
###/Needed to check for GTK version


# Check if we are working in the source tree or from the installed 
# package and mangle the python path accordingly
if os.path.dirname(sys.argv[0]) != ".":
    if sys.argv[0][0] == "/":
        fullPath = os.path.dirname(sys.argv[0])
    else:
        fullPath = os.getcwd() + "/" + os.path.dirname(sys.argv[0])
else:
    fullPath = os.getcwd()
sys.path.insert(0, os.path.dirname(fullPath))

from acire import AboutAcireDialog, PreferencesAcireDialog
from acire.acireconfig import getdatapath

# Set up translations
import gettext
import locale
locale.setlocale(locale.LC_ALL, '')
gettext.install('acire', unicode=True)

class AcireWindow(gtk.Window):
    __gtype_name__ = "AcireWindow"

    def __init__(self):
        """__init__ - This function is typically not called directly.
        Creation a AcireWindow requires redeading the associated ui
            file and parsing the ui definition extrenally,
        and then calling AcireWindow.finish_initializing().

        Use the convenience function NewAcireWindow to create
        AcireWindow object.

        """
        pass

    def finish_initializing(self, builder):
        """finish_initalizing should be called after parsing the ui definition
        and creating a AcireWindow object with it in order to finish
        initializing the start of the new AcireWindow instance.

        """
        #get a reference to the builder and set up the signals
        self.builder = builder
        self.builder.connect_signals(self)

        #uncomment the following code to read in preferences at start up
        #dlg = PreferencesAcireDialog.NewPreferencesAcireDialog()
        #self.preferences = dlg.get_preferences()

        #code for other initialization actions should be added here

        # browser for grabbing docs titles
        self.browser = Browser()

        # references to glade widgets

        self.editor_viewport = self.builder.get_object("editor_viewport")
        self.editor_scroll = self.builder.get_object("editor_scroll")
        self.execute_button = self.builder.get_object("execute_buton")
        self.copy_button = self.builder.get_object("copy_buton")
        self.categories_combo = self.builder.get_object("categories_combo")
        self.snippets_tv = self.builder.get_object("snippets_tv")
        self.description_label = self.builder.get_object("description_label")
        self.location_label = self.builder.get_object("location_label")
        self.terminal_scroll = self.builder.get_object("terminal_scroll")
        self.terminal_expander = self.builder.get_object("terminal_expander")
        self.status_label = self.builder.get_object("status_label")
        self.docs_box = self.builder.get_object("docs_box")
        
        # set up source view
        
        self.editor_buffer = gtksourceview2.Buffer()
        self.editor_view = gtksourceview2.View(self.editor_buffer)
        self.editor_view.set_show_line_numbers(True)
    

        # read system's monospace font, fallback to 'monospace 10'
        self.gconf = gconf.client_get_default()
        gconf_mono_font = self.gconf.get_string("/desktop/gnome/interface/monospace_font_name")

        if gconf_mono_font:
            font_desc = pango.FontDescription(gconf_mono_font)
        else:
            font_desc = pango.FontDescription('monospace 10')

        if font_desc:
            self.editor_view.modify_font(font_desc)

        self.editor_scroll.add(self.editor_view)
        
        # apply gtksourceview2 colors used by gedit
        style_scheme_name = self.gconf.get_string('/apps/gedit-2/preferences/editor/colors/scheme')
        if style_scheme_name is not None:
            style_scheme = gtksourceview2.StyleSchemeManager().get_scheme(style_scheme_name)
            if style_scheme:
                self.editor_buffer.set_style_scheme(style_scheme)

        # set up terminal
        self.terminal = vte.Terminal()
        self.terminal_scroll.add(self.terminal)
        #self.terminal.fork_command()
        self.terminal.show()
        
        self.snippetsdir = os.environ.get("SNIPPETS_DIR", "/usr/share/python-snippets")
        self.snippetsfiles = []
        self.snippetsdata = {}

        # set up the tree view

        self.snippets_model = gtk.ListStore(str, str, str)
        self.snippets_tv.set_model(self.snippets_model)
        self.tvcolumn = gtk.TreeViewColumn(_("Available Snippets"))
        self.cellpb = gtk.CellRendererPixbuf()
        self.cell_name = gtk.CellRendererText()        
        self.tvcolumn.pack_start(self.cellpb, False)
        self.tvcolumn.pack_start(self.cell_name, True)
        self.tvcolumn.set_attributes(self.cellpb, stock_id=0)
        self.tvcolumn.set_attributes(self.cell_name, text=1)
        self.snippets_tv.append_column(self.tvcolumn)

        # set up categories combo box
        self.categories_liststore = gtk.ListStore(str)
        self.categories_combo.set_model(self.categories_liststore)
        title_cell = gtk.CellRendererText()
        self.categories_combo.pack_start(title_cell, True)
        self.categories_combo.add_attribute(title_cell, 'text', 0)

        # set up some variables for the current snippet
        self.current_name = None
        self.current_filename = None
        self.current_description = None

        self.get_snippets_file_list()

        self.update_categories_combo()

    def update_categories_combo(self):
        """Update the categories combo box with categories from across the snippets."""                

        finalcats = []

        for snippet in self.snippetsdata:
            splitlist = self.snippetsdata[snippet]["cats"].split(',')
            for s in splitlist:
                finalcats.append(s.lstrip().rstrip())

        finalcats = list(set(finalcats))
        finalcats = sorted(finalcats,cmp=lambda x,y: cmp(x.lower(), y.lower()))
        
        templist = []
        templist.append(_("All"))
        self.categories_liststore.append(templist)
            
        for i in finalcats:
            templist = []
            templist.append(i)
            self.categories_liststore.append(templist)

        self.categories_combo.set_active(0)

    def select_combo_category(self, widget, data=None):
        """Select an item from the category combo box."""

        cat = self.categories_combo.get_active_text()
        self.update_snippets_treeview(cat)

                            
    def snippet_selected(self, widget, data=None):
        """Snippet is selected from the treeview"""
        
        selection = widget.get_selection()
        (model, it) = selection.get_selected()

        self.current_filename = self.snippets_model.get_value(it, 2)

        # read in the snippet
        file_object = open(self.current_filename)

        try:
            all_the_text = file_object.read()
        finally:
            file_object.close()

        lines  = all_the_text.splitlines()

        # set language

        manager = gtksourceview2.language_manager_get_default()

        if os.path.isabs(self.current_filename):
            path = self.current_filename
        else:
            path = os.path.abspath(self.current_filename)

        language = manager.guess_language(path)

        if language:
            self.editor_buffer.set_highlight_syntax(True)
            self.editor_buffer.set_language(language)
        else:
            print 'No language found for file "%s"' % self.current_filename
            self.editor_buffer.set_highlight_syntax(False)
        # load file

        self.editor_buffer.set_text(all_the_text)
        self.editor_buffer.set_data('filename', self.current_filename)
        self.editor_view.show()
        self.editor_buffer.set_modified(False)  #Reqd for check in run_snippet()

        self.editor_viewport.show_all()

        # update snippet information
                    
        self.location_label.set_text(self.current_filename)
        self.description_label.set_text(self.snippetsdata[self.current_filename]["description"])

        # update docs

        ## first delete any existing docs buttons:

        kids = self.docs_box.get_children()

        for k in kids:
            k.destroy()

        if "docs" in self.snippetsdata[self.current_filename]:
            docslist = self.snippetsdata[self.current_filename]["docs"].split(',')

            for d in docslist:
                url = d.lstrip().rstrip()
                self.browser.open(url)
                title = self.browser.title()

                docsbutton = gtk.LinkButton(url, title)
                docsbutton.set_alignment(0, 0)
                docsbutton.show()

                self.docs_box.add(docsbutton)
                self.docs_box.set_child_packing(docsbutton, False, False, 0, gtk.PACK_START)
        else:
            docsbutton = gtk.LinkButton("http://wiki.ubuntu.com/PythonSnippets", _("Click to here to add documentaton for this snippet."))
            docsbutton.set_alignment(0, 0)
            docsbutton.show()

            self.docs_box.add(docsbutton)
            self.docs_box.set_child_packing(docsbutton, False, False, 0, gtk.PACK_START)

        self.docs_box.show()

    def run_snippet(self, widget, data=None):
        """Run the currently selected snippet"""

        self.clear_terminal()
        cmd = "/usr/bin/python"
        #If user has changed code in the editor, save as a temp file and exec that instead.
        tmp_sn_filename = self.current_filename
        #Check for mods needs set_modified(False) in snippet_selected()
        if self.editor_buffer.get_modified() == True:
            (tmp_sn_fd, tmp_sn_filename) = tempfile.mkstemp(
                prefix = os.path.basename(self.current_filename).split(".")[0] + '-', 
                suffix = ".py")     #get_snippets_file_list() also mandates '.py' extn
            e = self.editor_buffer
            #mkstemp returns fd NUMBER, not Py file object - so used os.* below
            os.write(tmp_sn_fd, e.get_text(e.get_start_iter(), e.get_end_iter()))
            os.fdatasync(tmp_sn_fd)            
            os.close(tmp_sn_fd)
            
        argv = [cmd, tmp_sn_filename]
        directory = os.path.dirname(self.current_filename)
        self.terminal.fork_command(command=cmd, argv=argv, envv=None, directory=directory)
        self.terminal_expander.set_expanded(True)
        ###if self.editor_buffer.get_modified() == True:
            #TO-DO: rm'ing the temp file here deletes it before it is exec'd in vte terminal :-(
            #For now, leaving the file(s) there; need ideas for cleanup - on app shutdown?
            ###os.unlink(tmp_sn_filename)
                                
    def save_snippet(self, widget, data=None):
        if not self.current_filename:
            md = gtk.MessageDialog(self, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, 
                gtk.BUTTONS_CLOSE, _("Please choose a snippet first."))
            md.run()
            md.destroy()            
            return
        if gtk.pygtk_version < (2,3,90):
            md = gtk.MessageDialog(self, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, 
                gtk.BUTTONS_CLOSE, _("Sorry, PyGTK must be at least version 2.4 to display the Save As dialog!"))
            md.run()
            md.destroy()            
            return
        
        dialog = gtk.FileChooserDialog(_("Save Snippet As..."),
                                       None,
                                       gtk.FILE_CHOOSER_ACTION_SAVE,
                                       (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                        gtk.STOCK_SAVE_AS, gtk.RESPONSE_OK))
        dialog.set_default_response(gtk.RESPONSE_OK)
        
        filter = gtk.FileFilter()
        filter.set_name(_("All files"))
        filter.add_pattern("*")
        dialog.add_filter(filter)
        
        filter = gtk.FileFilter()
        filter.set_name(_("Python scripts"))
        filter.add_mime_type("application/x-python")
        filter.add_mime_type("text/plain")
        filter.add_mime_type("application/octet-stream")
        filter.add_pattern("*.py")
        dialog.add_filter(filter)
        
        if os.getenv("HOME"):
            dialog.set_current_folder(os.getenv("HOME"))
        dialog.set_current_name(os.path.basename(self.current_filename))
        dialog.set_do_overwrite_confirmation(True)
        
        response = dialog.run()
        if response == gtk.RESPONSE_OK:
            saveas_filename = dialog.get_filename()
            saveas_file = open(saveas_filename, 'w', False)
            e = self.editor_buffer
            saveas_file.write(e.get_text(e.get_start_iter(), e.get_end_iter()))
            saveas_file.close()
        dialog.destroy()
        
    def copy_snippet(self, widget, data=None):
        clpb = gtk.Clipboard()
        #self.editor_buffer.copy_clipboard(clpb)
        e = self.editor_buffer
        textdata = e.get_text(e.get_start_iter(), e.get_end_iter())
        clpb.set_text(textdata, len=-1)

    def clear_terminal(self):
        self.terminal.reset(True, True)
        

    def get_snippets_file_list(self):
        """Read in the snippets directory and put all Python files into a list."""

        dirlist = os.walk(self.snippetsdir)

        for path, subdirs, files in dirlist:
            for f in files:
                if fnmatch.fnmatch(f, "*.py"):
                    self.snippetsfiles.append(os.path.join(path,f))

        self.scan_for_metadata()
        
    def scan_for_metadata(self):
        """Scan snippets files for meta data."""
        
        for f in self.snippetsfiles:
            file_object = open(f)

            try:
                all_the_text = file_object.read()
            finally:
                file_object.close()

            lines  = all_the_text.splitlines()

            itemdict = {}
            maindict = {}
            templist = []
            
            for l in lines:
                name = re.search(r'\[SNIPPET_NAME: (.*?)]', l)
                cats = re.search(r'\[SNIPPET_CATEGORIES: (.*?)]', l)    
                description = re.search(r'\[SNIPPET_DESCRIPTION: (.*?)]', l)
                docs = re.search(r'\[SNIPPET_DOCS: (.*?)]', l)

                if name is not None:
                    itemdict['name'] = name.groups()[0]

                if cats is not None:
                    itemdict['cats'] = cats.groups()[0]

                if description is not None:
                    itemdict['description'] = description.groups()[0]

                if docs is not None:
                    itemdict['docs'] = docs.groups()[0]

                self.snippetsdata[f] = itemdict

        self.status_label.set_text(str(len(self.snippetsdata)) + _(" snippets available"))

    def contribute_snippet_info(self, widget, data=None):
        """Show how to contribute a snippet in the web browser"""

        webbrowser.open_new_tab("http://wiki.ubuntu.com/PythonSnippets")
                
    def update_snippets_treeview(self, category):
        """Update snippets treeview with available snippets."""

        templist = []        

        # clear the tree view for when we change the current category
        self.snippets_model.clear()

        if len(self.snippetsdata) == 0:
            md = gtk.MessageDialog(self, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, _("No snippets data has been found. Please install the python-snippets package to get them."))
            md.run()
            md.destroy()

        if category == _("All"):
            for i in self.snippetsdata:
                templist.append(gtk.STOCK_FILE)
                templist.append(self.snippetsdata[i]['name'])
                templist.append(i)

                self.snippets_model.append(templist)

                templist = []
        else:
            for i in self.snippetsdata:
                if category in self.snippetsdata[i]['cats']:
                    templist.append(gtk.STOCK_FILE)
                    templist.append(self.snippetsdata[i]['name'])
                    templist.append(i)

                    self.snippets_model.append(templist)

                    templist = []

	#Sort the items in the treeview based on column 1, the text of each item
	rows = [tuple(r) + (i,) for i, r in enumerate(self.snippets_model)]
	rows.sort(key=lambda tup:(str.lower(tup[1])))
	self.snippets_model.reorder([r[-1] for r in rows])

                        
    def about(self, widget, data=None):
        """about - display the about box for acire """
        about = AboutAcireDialog.NewAboutAcireDialog()
        response = about.run()
        about.destroy()

    def preferences(self, widget, data=None):
        """preferences - display the preferences window for acire """
        prefs = PreferencesAcireDialog.NewPreferencesAcireDialog()
        response = prefs.run()
        if response == gtk.RESPONSE_OK:
            #make any updates based on changed preferences here
            pass
        prefs.destroy()

    def quit(self, widget, data=None):
        """quit - signal handler for closing the AcireWindow"""
        self.destroy()

    def on_destroy(self, widget, data=None):
        """on_destroy - called when the AcireWindow is close. """
        #clean up code for saving application state should be added here

        gtk.main_quit()

    def all_files(root, patterns='*', single_level=False, yield_folders=False):
        # Expand patterns from semicolon-separated string to list
        patterns = patterns.split(';')
        for path, subdirs, files in os.walk(root):
            if yield_folders:
                files.extend(subdirs)
            files.sort( )
            for name in files:
                for pattern in patterns:
                    if fnmatch.fnmatch(name, pattern):
                        yield os.path.join(path, name)
                        break
            if single_level:
                break


def NewAcireWindow():
    """NewAcireWindow - returns a fully instantiated
    AcireWindow object. Use this function rather than
    creating a AcireWindow directly.
    """

    #look for the ui file that describes the ui
    ui_filename = os.path.join(getdatapath(), 'ui', 'AcireWindow.ui')
    if not os.path.exists(ui_filename):
        ui_filename = None

    builder = gtk.Builder()
    builder.set_translation_domain('acire')
    builder.add_from_file(ui_filename)
    window = builder.get_object("acire_window")
    window.finish_initializing(builder)
    return window

if __name__ == "__main__":
    #support for command line options
    import logging, optparse
    parser = optparse.OptionParser(version="%prog %ver")
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help=_("Show debug messages"))
    (options, args) = parser.parse_args()

    #set the logging level to show debug messages
    if options.verbose:
        logging.basicConfig(level=logging.DEBUG)
        logging.debug('logging enabled')

    #run the application
    window = NewAcireWindow()
    window.show()
    gtk.main()