~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
#!/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 subprocess

# 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

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

        # references to glade widgets

        self.editor = self.builder.get_object("editor")
        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.snippetsdir = "/home/jono/source/snippets"
        self.snippetsfiles = []
        self.snippetsdata = []

        # set up the tree view

        self.snippets_model = gtk.ListStore(str, 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:
            for item in snippet:
                splitlist = item['cats'].split(',')
                for s in splitlist:
                    if len(finalcats) == 0:
                        finalcats.append(s)
                    else:
                        for c in finalcats:
                            if c != s:
                                finalcats.append(s)
                                break
                            else:
                                break

        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()

        # set the current snippet variables
        self.current_name = self.snippets_model.get_value(it, 1)
        self.current_filename = self.snippets_model.get_value(it, 2)
        self.current_description = self.snippets_model.get_value(it, 3)

        # read in the snippet
        file_object = open(os.path.join(self.snippetsdir, self.current_filename))

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

        lines  = all_the_text.splitlines()

        # clear the textview
        buf = self.editor.get_buffer()
        (start, end) = buf.get_bounds()

        buf.delete(start, end)
        self.editor.show()

        # show the code                
        for l in lines:
            self.editor.get_buffer().insert(self.editor.get_buffer().get_end_iter(), l)
            self.editor.get_buffer().insert(self.editor.get_buffer().get_end_iter(), "\n")
            
        self.location_label.set_text(self.snippetsdir + "/" + self.current_filename)
        self.description_label.set_text(self.current_description)

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

        fn = os.path.join(self.snippetsdir, self.current_filename)
        subprocess.Popen(['python', fn])
                                
    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(f)

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

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

            lines  = all_the_text.splitlines()

            tempdict = {}
            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)

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

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

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

            if tempdict:
                tempdict['filename'] = f            
                templist.append(tempdict)
                self.snippetsdata.append(templist)

        self.update_snippets_treeview("All")

                
    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 category == "All":
            for i in self.snippetsdata:
                for item in i:
                    templist.append(gtk.STOCK_FILE)
                    templist.append(item['name'])
                    templist.append(item['filename'])
                    templist.append(item['description'])                

                    self.snippets_model.append(templist)

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

                        self.snippets_model.append(templist)

                        templist = []            

                        
    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.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()