Source

drivcenDRIVENvpackager / src / vpackager / guitools.py

  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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
#!/usr/bin/env python

#    This file is part of vpackager.
#
#    vpackager is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License v3 as published by
#    the Free Software Foundation.
#
#    vpackager is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY 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 vpackager.  If not, see <http://www.gnu.org/licenses/>.

import gtk
import os
import buildutils
import message
import dbutils
import preferences
import glob
import bottools
import threading
import time


__author__ = 'M0E-lnx'
__author_email__ = 'moc.liamg@xnl.E0M'[::-1]
__version__ = '0.1'

class SearchBox(gtk.Entry):
    """ Search box packed into the history viewer to filter the history.
    This is useful to search for a certain application in the job history"""
    def __init__(self):
        gtk.Entry.__init__(self)
        # Add the find button

        self.set_icon_from_stock(gtk.ENTRY_ICON_PRIMARY,
                                 gtk.STOCK_FIND)
        self.set_icon_from_stock(gtk.ENTRY_ICON_SECONDARY,
                                 gtk.STOCK_CLEAR)

class PrefsDialog(gtk.Dialog):
    """vpackager preferences dialog."""
    def __init__(self, parent=None):
        gtk.Dialog.__init__(self, parent=parent)
        datadir = os.path.dirname(os.path.abspath(__file__))
        datadir = os.path.join(datadir, 'data')
        self.body = self.get_content_area()
        self.set_has_separator(True)
        self.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
        self.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CANCEL)
        #self.config = ConfigParser.ConfigParser()
        self.entries = {}
        conf = preferences.VPConf()
        self.PACKAGER_NAME = conf.GetSetting('packager_name')
        self.DEFAULT_SOURCES_PATH = conf.GetSetting('sources_home')
        self.DATABASE_HOME = conf.GetSetting('database_home')

        # banner
        bannerbox = gtk.HBox()
        img = gtk.Image()
        pixbuf = gtk.gdk.pixbuf_new_from_file(
            os.path.join(datadir, 'vpackager_logo.png'))
        scaled_buf = pixbuf.scale_simple(150, 50, gtk.gdk.INTERP_BILINEAR)
        img.set_from_pixbuf(scaled_buf)
        bannerbox.pack_start(img, False, False, 8)
        banner = BoldLabel("Preferences")
        bannerbox.pack_start(banner, False, True, 2)
        self.body.pack_start(bannerbox, False, True, 2)
        self.set_title('vpackager preferences')
        self.set_size_request(550, 250)

        frame = gtk.Frame('Global Configuration')
        self.body.pack_start(frame, True, True, 4)
        confbox = gtk.VBox()
        frame.add(confbox)
        # packager line
        line_packager = gtk.HBox()
        confbox.pack_start(line_packager, False, True, 4)
        lb_packager = gtk.Label('Packager Name:')
        en_packager = gtk.Entry()
        en_packager.connect('changed', self.packager_change_event)
        line_packager.pack_start(lb_packager, False, False, 2)
        line_packager.pack_start(en_packager, True, True, 2)

        # default sources path
        line_srcs = gtk.HBox()
        confbox.pack_start(line_srcs, False, True, 4)
        lb_srcs = gtk.Label('Build Directory:')
        en_srcs = gtk.Entry()
        en_srcs.connect('changed', self.sources_home_change_event)
        bt_srcs = vButton(stock=gtk.STOCK_OPEN, label='Select')
        bt_srcs.connect('clicked', self.select_sources_dir_event)
        line_srcs.pack_start(lb_srcs, False, False, 2)
        line_srcs.pack_start(en_srcs, True, True, 2)
        line_srcs.pack_start(bt_srcs, False, False, 2)

        # Database location
        line_dbase_loc = gtk.HBox()
        confbox.pack_start(line_dbase_loc, False, True, 4)
        lb_dbase = gtk.Label("Database Location:")
        en_dbase = gtk.Entry()
        en_dbase.connect('changed', self.dbase_home_change_event)
        bt_dbase = vButton(stock=gtk.STOCK_OPEN, label='Select')
        bt_dbase.connect('clicked', self.select_dbase_dir_event)
        line_dbase_loc.pack_start(lb_dbase, False, False, 2)
        line_dbase_loc.pack_start(en_dbase, True, True, 2)
        line_dbase_loc.pack_start(bt_dbase, False, False, 2)
        self.entries['packager'] = en_packager
        self.entries['sources_dir'] = en_srcs
        self.entries['dbase_home'] = en_dbase

        self._set_entries_values()

        self.show_all()

    def select_dbase_dir_event(self, widget=None):
        dia = gtk.FileChooserDialog(
            title = 'Select database directory',
            action = gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
            parent = self,
            buttons = (gtk.STOCK_OK, gtk.RESPONSE_OK,
                       gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
        dia.set_current_folder('/')
        res = dia.run()
        dia.hide()
        if res == gtk.RESPONSE_OK:
            self.DATABASE_HOME = dia.get_filename()
            self.entries['dbase_home'].set_text(self.DATABASE_HOME)
        return dia.destroy()

    def select_sources_dir_event(self, widget=None):
        dia = gtk.FileChooserDialog(
            title = 'Select root build directory',
            action = gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
            parent = self,
            buttons = (gtk.STOCK_OK, gtk.RESPONSE_OK,
                       gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
        dia.set_current_folder('/')
        res = dia.run()
        dia.hide()
        if res == gtk.RESPONSE_OK:
            self.DEFAULT_SOURCES_PATH = dia.get_filename()
            self.entries['sources_dir'].set_text(self.DEFAULT_SOURCES_PATH)
        return dia.destroy()

    def _set_entries_values(self):
        """ Sets the initial values in the fields with the window is shown"""
        self.entries['packager'].set_text(self.PACKAGER_NAME)
        self.entries['sources_dir'].set_text(self.DEFAULT_SOURCES_PATH)
        self.entries['dbase_home'].set_text(self.DATABASE_HOME)

    def packager_change_event(self, widget=None):
        """ UPdate the packager name when the text entry changes"""
        self.PACKAGER_NAME = widget.get_text()

    def sources_home_change_event(self, widget=None):
        """ Update the source home dir"""
        self.DEFAULT_SOURCES_PATH = widget.get_text()

    def dbase_home_change_event(self, widget=None):
        """ Update the database home directory"""
        self.DATABASE_HOME = widget.get_text()

class BoldLabel(gtk.Label):
    """ Preset label that displays text in bigger larger fonts """
    def __init__(self, text):
        gtk.Label.__init__(self)
        self.set_use_markup(True)
        self.set_markup('<span size="xx-large">%s</span>'% text)

class TinyLabel(gtk.Label):
    """ Preset label that displays text in a smaller font """
    def __init__(self, text):
        gtk.Label.__init__(self)
        self.set_use_markup(True)
        self.set_markup('<span size="x-small">%s</span>'% text)

class LogDisplay(gtk.Dialog):
    """ Dialog used to display the build log"""
    def __init__(self, logpath, parent, title='Build Log'):
        gtk.Dialog.__init__(self, parent=parent)
        self.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
        self.body = self.get_content_area()
        self.logpath = logpath
        self.set_size_request(600, 400)
        self.set_has_separator(True)
        self.body.pack_start(self._get_logview(), True, True, 2)
        self.set_title(title)
        self.show_all()

    def _get_logview(self):
        scrl = gtk.ScrolledWindow()
        scrl.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        textview = gtk.TextView()
        for edge in (gtk.TEXT_WINDOW_LEFT, gtk.TEXT_WINDOW_RIGHT,
                     gtk.TEXT_WINDOW_TOP, gtk.TEXT_WINDOW_BOTTOM):
            textview.set_border_window_size(edge, 4)
        scrl.add(textview)
        f = open(self.logpath, 'r')
        data = f.read()
        f.close()
        textview.get_buffer().set_text(data)

        return scrl

class TabStrip(gtk.Notebook):
    """Tabstrip used in the main GUI"""
    def __init__(self):
        gtk.Notebook.__init__(self)
        self.set_property('tab-pos', gtk.POS_LEFT)
        self.connect('switch-page', self.switch_page_event)

    def switch_page_event(self, widget=None, page=None, page_num=0):
        """ Actions to be performed with the user changes the visible tab"""
        # Update the toolbars on the treeviews
        try:
            self.get_nth_page(1).Refresh_Toolbar_Status()
            self.get_nth_page(2).Refresh_Toolbar_Status()
        except:
            pass

class TabIcon(gtk.VBox):
    """ Custom widget composed of a gtk.VBox that shows an image and label
    and is used for the tabstrip label widgets"""
    def __init__(self, label='', stock=None, icon=None):
        gtk.VBox.__init__(self)
        lb = gtk.Label()
        lb.set_use_markup(True)
        lb.set_markup(label)
        lb.set_property('xalign', 0.5)
        if stock:
            img = gtk.Image()
            #pb = gtk.gdk.pixbuf_new_from_file_at_size(
            #    icon, 24, 24)
            #img.set_from_pixbuf(pb)
            img.set_from_stock(stock, gtk.ICON_SIZE_BUTTON)
        elif icon:
            img = gtk.Image()
            pb = gtk.gdk.pixbuf_new_from_file_at_size(
                icon, 24, 24)
            img.set_from_pixbuf(pb)
            #img.set_from_file(icon)
        self.pack_start(lb, False, False, 2)
        self.pack_start(img, False, False, 2)
        self.show_all()

class TableTree(gtk.TreeView):
    """Generic treeview widget that will be used to display the contents of the
    database tables. Will be used to display both queue and history"""
    def __init__(self, model, columns = []):
        gtk.TreeView.__init__(self, model=model)
        i = 0
        for col in columns:
            _col = gtk.TreeViewColumn(col)
            _cr = gtk.CellRendererText()
            _col.pack_start(_cr)
            _col.add_attribute(_cr, 'text', i)
            _col.set_resizable(True)
            self.append_column(_col)
            i += 1
        self.set_headers_visible(True)

    def GetRowCount(self):
        return len(self.get_model())

class AboutJob(gtk.Dialog):
    '''Dialog used to display detailed information about a build job. The user
    interface will not display every detail about the job, but this dialog
    will.'''
    def __init__(self, jobid=None, title='Job Details', parent=None, dbase=None):
        gtk.Dialog.__init__(self, parent=parent)
        if dbase:
            self.dbase = dbase
        else:
            self.dbase = dbutils.dbase()
        self.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
        self.body = self.get_content_area()
        lbtop = BoldLabel('Job Details')
        topbox = gtk.HBox()
        img = gtk.Image()
        self.set_has_separator(True)
        img.set_from_stock(gtk.STOCK_INFO, gtk.ICON_SIZE_BUTTON)
        topbox.pack_start(img, False, False, 2)
        #lbtop.set_markup('<b>Job Details</b>')
        lbtop.set_property('xalign', 0.0)
        topbox.pack_start(lbtop, True, True, 2)
        self.body.pack_start(topbox, False, True, 4)
        # Read the job details
        self._jobid = jobid
        self.set_title(title)
        self.set_size_request(500, 300)
        self.body.pack_start(self._pack_tree(), True, True, 2)
        self.show_all()

    def _pack_tree(self):
        sw = gtk.ScrolledWindow()
        sw.set_policy(gtk.POLICY_AUTOMATIC,
                gtk.POLICY_AUTOMATIC)
        mod = gtk.ListStore(str, str)
        tree = gtk.TreeView(model=mod)
        col0 = gtk.TreeViewColumn()
        cr0 = gtk.CellRendererText()
        col0.pack_start(cr0)
        col0.add_attribute(cr0, 'text', 0)
        col1 = gtk.TreeViewColumn()
        cr1 = gtk.CellRendererText()
        col1.pack_start(cr1)
        col1.add_attribute(cr1, 'text', 1)
        tree.append_column(col0)
        tree.append_column(col1)
        tree.set_headers_visible(False)
        sw.add(tree)

        # Fill in the information
        info = self.dbase.GetJobDetails(self._jobid)
        patches = info['patches']
        patchlist = []
        if patches:
            patchlist = patches.split(',')
        mod.append(['Job ID', info['id']])
        mod.append(['Application', info['app']])
        mod.append(['Version', info['ver']])
        mod.append(['Package Release', info['release']])
        mod.append(['Source URI', info['srcURI']])
        mod.append(['Description URI', info['descURI']])
        mod.append(['Source Type', info['type']])
        mod.append(['Install After Build', info['install']=="1"])
        mod.append(['Custom build options', info['config']])
        mod.append(['Post-install script', info['doinstURI']])
        if patchlist:
            mod.append(['Patches to be applied', patchlist[0]])
            for x in range(1, len(patchlist)):
                mod.append(['',patchlist[x]])
        else:
            mod.append(['Patches to be applied', 'None'])

        return sw

class ProgressDialog(gtk.Dialog):
    """small dialog showing a progresssbar while the package is being installed """
    def __init__(self, banner, command):
        gtk.Dialog.__init__(self)
        self.set_title('Installing package')
        lb = gtk.Label(banner)
        self.bannerlabel = lb
        self.job = bottools.Execute(command)
        #self.job.observer.add_callback(self.pulse)
        self.body = self.get_content_area()
        self.body.pack_start(lb, False, True, 2)
        self.pbar = gtk.ProgressBar()
        self.body.pack_start(self.pbar, False, True, 2)
        self.set_has_separator(True)
        self.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CANCEL)
        self.actuator = threading.Thread(target=self.pulse, args=())
        self.show_all()
        self.PULSE=False
        #self.actuator.start()
        #self.job.run()
        #self.PULSE = False
    def __clear_status(self, data):
        if self.job._popen_running:
            pass
        else:
            self.PULSE=False

    def run(self):
        self.PULSE=True
        #self.actuator.start()
        t = threading.Thread(target=self.job.run)
        t.start()
        self.actuator.start()
        return super(ProgressDialog, self).run()

    def pulse(self, widget=None, data=None):
        while self.job._popen_running:
            gtk.gdk.threads_enter()
            self.pbar.pulse()
            self.get_action_area().set_sensitive(False)
            gtk.gdk.threads_leave()
            time.sleep(0.10)
        return self._enable_action_area()

    def _enable_action_area(self):
        self.get_action_area().set_sensitive(True)
        self.pbar.set_fraction(1.0)
        if self.job.popen.returncode > 0 :
            err = message.Error("Package failed to install... ")
            if err.run():
                err.destroy()
        self.bannerlabel.set_property('label', 'Package installed')

class AboutTask(gtk.Dialog):
    """ Informational dialog used to display details about a performed task.
    Similar to AboutJob, but the information for this one comes from the
    history table rather than the queue"""
    def __init__(self, jobid, dbase, title='Task Details', parent=None):
        gtk.Dialog.__init__(self, parent=parent)
        self.jobid = jobid
        self.dbase = dbase
        self.set_title(title)
        self.body = self.get_content_area()
        topbox = gtk.HBox()
        img = gtk.Image()
        img.set_from_stock(gtk.STOCK_INFO, gtk.ICON_SIZE_BUTTON)
        lbl = BoldLabel("Build Task Details".strip())
        lbl.set_property('xalign', 0.0)
        self.jobinfo = self.dbase.GetTaskDetails(self.jobid)
        topbox.pack_start(img, False, False, 2)
        topbox.pack_start(lbl, True, True, 2)
        self.body.pack_start(topbox, False, True, 4)
        self.set_has_separator(True)
        self.set_size_request(500, 400)
        self.body.pack_start(self._get_tree(), True, True, 2)
        actions = self.get_action_area()
        actions.pack_end(self._get_install_button(), False, False, 2)
        self.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
        self.show_all()

    def __check_package_exists(self, widget=None):
        """ Returns true if the package exists, False otherwise"""
        if self.jobinfo['result'] == 'Fail' or not self.jobinfo['stdout']:
            return []
        ret = glob.glob(os.path.join(os.path.dirname(self.jobinfo['stdout']),
                                                     "%s-%s-*-%s*.t?z"%(
            self.jobinfo['app'],
            self.jobinfo['ver'],
            self.jobinfo['release'])))
        return ret

    def __do_install_package(self, widget=None):
        """ install the package after it has been built"""
        pkg = self.__check_package_exists()[0]
        dia = ProgressDialog(banner = 'Installing %s'% os.path.basename(pkg),
                             command = 'installpkg %s'% pkg)
        if dia.run():
            dia.destroy()


    def _get_install_button(self):
        """ Add an install button to the dialog's action area
        but only enable it if the build is successful and the package is there."""
        bt = vButton(stock=gtk.STOCK_EXECUTE,
                     label='Install Package')
        bt.connect('clicked', self.__do_install_package)
        bt.set_sensitive(len(self.__check_package_exists()) > 0)
        return bt

    def _get_tree(self):
        scroll = gtk.ScrolledWindow()
        scroll.set_policy(gtk.POLICY_AUTOMATIC,
                gtk.POLICY_AUTOMATIC)
        mod = gtk.ListStore(str, str)
        col0 = gtk.TreeViewColumn()
        cr0 = gtk.CellRendererText()
        col1 = gtk.TreeViewColumn()
        cr1 = gtk.CellRendererText()
        col0.pack_start(cr0)
        col1.pack_start(cr1)
        col0.add_attribute(cr0, 'text', 0)
        col1.add_attribute(cr1, 'text', 1)
        tree = gtk.TreeView(model = mod)
        tree.set_headers_visible(False)
        tree.append_column(col0)
        tree.append_column(col1)

        # Fill the data
        info = self.dbase.GetTaskDetails(self.jobid)
        patches = info['patches']
        mod.append(['Job ID', info['id']])
        mod.append(['Application', info['app']])
        mod.append(['Version', info['ver']])
        mod.append(['Package Release', info['release']])
        mod.append(['Source URI', info['srcURI']])
        mod.append(['Description URI', info['descURI']])
        mod.append(['Source Type', info['type']])
        mod.append(['Build Started', info['buildstart']])
        mod.append(['Build Ended', info['buildend']])
        mod.append(['Build Result', info['result']])
        mod.append(['Output Log', info['stdout']])
        mod.append(['Custom Build Options', info['config']])
        mod.append(['Post-install script', info['doinstURI']])
        if patches:
            patchlist = patches.split(',')
            patchlist = (['Patches Applied', patchlist[0]])
            for x in range(1, len(patchlist)):
                mod.append(['',patchlist[x]])
        else:
            mod.append(['Patches Applied', 'None'])

        scroll.add(tree)
        return scroll

class About(gtk.AboutDialog):
    """ About dialog for vpackager"""
    def __init__(self):
        gtk.AboutDialog.__init__(self)
        self.set_name('vpackager')
        self.set_version('2.0')
        datadir = os.path.dirname(os.path.abspath(__file__))
        datadir = os.path.join(datadir, 'data')
        self.set_authors(['Moises Henriquez (M0E-Lnx)',
            'Rodrigo Bistolfi (rbistolfi)'])
        f = open(os.path.join(datadir, 'LICENSE'), 'r')
        self.set_license(f.read())
        f.close()
        self.set_website('https://bitbucket.org/m0e_lnx/vpackager')
        self.set_copyright('(c) 2008-2011 Moises Henriquez')
        logo = gtk.gdk.pixbuf_new_from_file(
                os.path.join(datadir, 'vpackager_logo.png'))
        self.set_logo(logo)
        self.set_comments("Compile software from source code.")

class vButton(gtk.Button):
    '''Button class that can use a stock image with a custon label'''
    def __init__(self, stock=None, label=''):
        gtk.Button.__init__(self)
        if stock is not None:
            img = gtk.Image()
            img.set_from_stock(stock, gtk.ICON_SIZE_BUTTON)
            self.set_image(img)

        self.set_label(label)

class AddPatchBox(gtk.Dialog):
    ''' Dialog used to add a patch to a build job'''
    def __init__(self, title='Add Patch', parent=None):
        gtk.Dialog.__init__(self,parent=parent)
        self.set_title('Add patch')
        self.URI = None
        body = self.get_content_area()
        self.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
        self.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
        hb = gtk.HBox()
        lb = gtk.Label('\
                Enter patch URL or browse for local files')
        body.pack_start(lb, False, False, 2)
        body.pack_start(hb, False, True, 2)
        uriEntry = gtk.Entry()
        self.uriEntry = uriEntry
        uriEntry.connect('changed', self._uriEntry_changed)
        btBrowse = vButton(stock=gtk.STOCK_OPEN,
                label='Browse')
        btBrowse.connect('clicked', self._btBrowse_clicked)
        hb.pack_start(uriEntry, True, True, 2)
        hb.pack_start(btBrowse, False, False, 2)
        self.set_size_request(600,100)

        self.show_all()

    def _uriEntry_changed(self, widget=None):
        ''' Set the dialog's URI property'''
        self.URI = widget.get_text()
        return

    def _btBrowse_clicked(self, widget=None):
        ''' Launch a filechooser dialog to select a patch file '''
        dia = FilePicker(title='Select patch file')
        res = dia.run()
        dia.hide()
        if res == gtk.RESPONSE_OK:
            self.uriEntry.set_text(dia.get_filename())
            self.URI=self.uriEntry.get_text()
        return

class FilePicker(gtk.FileChooserDialog):
    ''' File chooser used in vpackager. Based on the gtk.FileChooserDialog but
    has some extra convinience methods.'''
    def __init__(self, title=None, forsrc=False, plaintxt=False):
        _buttons = (gtk.STOCK_OK, gtk.RESPONSE_OK,
                gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
        _filter_src = gtk.FileFilter()
        _filter_src.add_pattern('*.[bgx]z*')
        _filter_src.set_name('Compressed Files')
        _filter_txt = gtk.FileFilter()
        _filter_txt.add_mime_type('text/plain')
        _filter_txt.set_name('Text files')
        _filter_all = gtk.FileFilter()
        _filter_all.set_name('All Files')
        _filter_all.add_pattern('*.*')

        gtk.FileChooserDialog.__init__(self,
                buttons=_buttons)
        self.set_title(title)
        if forsrc:
            self.add_filter(_filter_src)
        elif plaintxt:
            self.add_filter(_filter_txt)
        else:
            self.add_filter(_filter_all)

        self.set_current_folder('/home')

class JobAddDialog(gtk.Dialog):
    '''Dialog window used to add a job to the queue'''
    def __init__(self, title='Add Job', parent=None):
        gtk.Dialog.__init__(self)
        self.SrcURI = None
        self.DescURI = None
        self.app = None
        self.ver = None
        self.patches = []
        self.release = 1
        self.install = False
        self.config_options = ""
        self.doinstURI = ""
        self.advancedbox = self._advancedbox()
        self.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
        self.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
        self.set_has_separator(True)
        self.set_default_response(gtk.RESPONSE_OK)
        body = self.get_content_area()
        self.set_title('Add New Job')
        self.set_size_request(500,320)
        frmSrc = gtk.Frame('Source Archive')
        body.pack_start(frmSrc, False, True, 8)
        hsrc = gtk.HBox()
        frmSrc.add(hsrc)
        self.srcentry = gtk.Entry()
        self.srcentry.set_tooltip_text('Enter path or URL')
        self.srcentry.connect('changed', self._src_entry_event)
        hsrc.pack_start(self.srcentry, True, True, 2)
        self.btBrowse = vButton(stock=gtk.STOCK_OPEN,
                label='Browse')
        self.btBrowse.connect('clicked', self._browse)
        hsrc.pack_start(self.btBrowse, False, False, 2)
        self.okButton = self.get_action_area().get_children()[1]
        self.okButton.set_property('sensitive', False)

        frmDesc = gtk.Frame('Package Description')
        body.pack_start(frmDesc, False, True, 4)
        hbdesc = gtk.HBox()
        frmDesc.add(hbdesc)
        self.descEntry = gtk.Entry()
        self.descEntry.set_tooltip_text('Enter path or URL')
        self.descEntry.connect('changed', self._descURI_change)
        btDescBrowse = vButton(stock=gtk.STOCK_OPEN, label='Browse')
        btDescBrowse.connect('clicked', self._desc_browse)
        hbdesc.pack_start(self.descEntry, True, True, 2)
        hbdesc.pack_start(btDescBrowse, False, True, 2)

        lb = gtk.Label('Application')
        self.appEntry = gtk.Entry()
        bapp = gtk.HBox()
        body.pack_start(bapp, False, True, 4)
        bapp.pack_start(lb, False, False, 2)
        bapp.pack_start(self.appEntry,True, True, 2)

        lbv = gtk.Label('Version')
        self.verEntry = gtk.Entry()
        bapp.pack_start(lbv, False, False, 2)
        bapp.pack_start(self.verEntry, True, True, 2)

        self.appEntry.connect('changed', self._appname_changed)
        self.verEntry.connect('changed', self._appver_changed)

        bbox = gtk.HBox()
        lbuild = gtk.Label('Release')
        rels = gtk.ListStore(int)
        for x in xrange(1, 5):
            rels.append([x])
        cbRel = gtk.ComboBox(rels)
        cr = gtk.CellRendererText()
        cbRel.pack_start(cr)
        cbRel.add_attribute(cr, 'text', 0)
        cbRel.set_active(0)

        lSrcType = gtk.Label('Source Type')
        types = gtk.ListStore(str)
        for _type in ('Auto','Autotools','Python','CMake','Perl','Waf'):
            types.append([_type])
        cbsrcsel = gtk.ComboBox(types)
        self.srcTypeSel = cbsrcsel
        cbsrcsel.connect('changed', self._srctype_changed)
        crt = gtk.CellRendererText()
        cbsrcsel.pack_start(crt)
        cbsrcsel.add_attribute(crt, 'text', 0)
        cbsrcsel.set_active(0)

        bbox.pack_start(lbuild, False, False, 2)
        bbox.pack_start(cbRel, False, False, 2)
        bbox.pack_start(lSrcType, False, False, 2)
        bbox.pack_start(cbsrcsel, False, False, 2)
        body.pack_start(bbox, False, True, 2)
        # Patches box
        #exPatches = gtk.expander_new_with_mnemonic('Patches')
        exPatches = gtk.Expander('Advanced Options')
        exPatches.add(self.advancedbox)
        exPatches.connect('notify::expanded', self._expander_event)
        body.pack_start(exPatches, True, True, 4)

        # Option to install package after building
        cbInstallPkg = gtk.CheckButton(
                label='Install this package after it is compiled')
        cbInstallPkg.connect('toggled', self._cbInstallpkg_changed)
        body.pack_start(cbInstallPkg, False, True, 2)


        cbRel.connect('changed', self._release_changed)

        self.body = body
        body.show_all()

    def set_app(self, data):
        self.app = data
        self.appEntry.set_text((data or ""))

    def set_config(self, data):
        self.configEntry.set_text((data or ""))
        self.config_options = data

    def set_doinst(self, data):
        self.doinstEntry.set_text((data or ""))
        self.doinstURI = data

    def set_src(self, data):
        self.SrcURI = data
        self.srcentry.set_text((data or ""))

    def set_desc(self, data):
        self.DescURI = data
        self.descEntry.set_text((data or ""))

    def set_version(self, data):
        self.ver = data
        self.verEntry.set_text((data or ""))

    def set_patches(self, data):
        for patch in data:
            self.patches.append(patch)
        self.__refresh_patches_tree()

    def _del_patch_event(self, widget=None):
        sel = self.patchestree.get_selection().get_selected()[0][0][0]
        if sel:
            self.patches.remove(sel)
        # Refresh the GUI that shows the patches
        self.__refresh_patches_tree()

    def _add_patch_event(self, widget=None):
        dia = AddPatchBox(parent=self)
        res = dia.run()
        if res == gtk.RESPONSE_OK:
            self.patches.append(dia.URI)
        dia.destroy()
        # Refresh the GUI list that shows the patches
        self.__refresh_patches_tree()

    def __refresh_patches_tree(self, widget=None):
        model = self.patchestree.get_model()
        model.clear()
        for patch in self.patches:
            model.append([patch])
        return

    def _advancedbox(self):
        gbox = gtk.VBox()
        box = gtk.HBox()
        frmpatches = gtk.Frame('Patches')
        rbox = gtk.VBox()
        lst = gtk.ListStore(str)
        cr = gtk.CellRendererText()
        tree = gtk.TreeView(lst)
        col = gtk.TreeViewColumn()
        col.pack_start(cr)
        col.add_attribute(cr, 'text', 0)
        tree.append_column(col)
        self.patchestree = tree
        tree.set_headers_visible(False)
        scrollw = gtk.ScrolledWindow()
        scrollw.set_policy(gtk.POLICY_AUTOMATIC,
                gtk.POLICY_AUTOMATIC)
        scrollw.add(tree)
        box.pack_start(scrollw, True, True, 2)
        box.pack_start(rbox, False, False, 2)
        btAddPatch = vButton(stock=gtk.STOCK_ADD,
                label='Add')
        btAddPatch.connect('clicked', self._add_patch_event)
        btDelPatch = vButton(stock=gtk.STOCK_REMOVE,
                label='Remove')
        btDelPatch.connect('clicked', self._del_patch_event)
        rbox.pack_start(btAddPatch, False ,False, 2)
        rbox.pack_start(btDelPatch, False ,False, 2)
        frmpatches.add(box)

        # Add an area to provide custom configure options.
        lb = gtk.Label("Extra configure options. (Autoconf sources only)")
        lb.set_property('xalign', 0.0)
        entry_conf_options = gtk.Entry()
        self.configEntry = entry_conf_options
        entry_conf_options.connect('changed', self.on_conf_options_change)
        doinstbox = gtk.HBox()
        doinst_lb = gtk.Label('Post Install Script:')
        doinst_lb.set_property('xalign', 0.0)
        gbox.pack_start(doinst_lb, False, True, 2)
        doinst_en = gtk.Entry()
        self.doinstEntry = doinst_en
        doinst_bt = vButton(stock=gtk.STOCK_OPEN, label='Select')
        doinst_bt.connect('clicked', self.on_select_doinst)
        doinst_en.set_tooltip_text('Enter URL, path or click "Select"')
        #doinstbox.pack_start(doinst_lb, False, False, 2)
        doinstbox.pack_start(doinst_en, True, True, 2)
        doinstbox.pack_start(doinst_bt, False, False, 2)
        gbox.pack_start(doinstbox, False, True, 2)
        gbox.pack_start(lb, False, True, 2)
        gbox.pack_start(entry_conf_options, False, True, 2)
        gbox.pack_start(frmpatches, True, True, 2)


        return gbox

    def on_conf_options_change(self, widget=None):
        self.config_options = widget.get_text()

    def on_select_doinst(self, widget=None):
        """Pop a dialog to select the install script"""
        dia = FilePicker(title="Select post-install script",
                         forsrc=False, plaintxt=True)
        res = dia.run()
        dia.hide()
        if res == gtk.STOCK_OK:
            self.doinstEntry.set_text(dia.get_filename())
            self.doinstURI = self.doinstEntry.get_text()
        return


    def _expander_event(self, widget=None, user_data=None):
        ''' Resize the dialog to display the newly added widgets'''
        ht = self.advancedbox.get_allocation()[-2]
        ht = int(max(ht, 820)*0.25)
        wwid,whei =  self.get_size()
        if widget.get_expanded():
            self.advancedbox.show()
            self.resize(wwid, whei + ht)
        else:
            self.advancedbox.hide()
            self.resize(wwid, whei - ht)
        return

    def _cbInstallpkg_changed(self, widget=None):
        self.install = widget.get_active()

    def _srctype_changed(self, widget=None):
        selected = widget.get_model()[widget.get_active()][0].lower()
        if selected in ('auto', 'autotools'):
            self.srctype = 'default'
        else:
            self.srctype = selected

    def _release_changed(self, widget=None):
        self.release = widget.get_model()[widget.get_active()][0]

    def _appname_changed(self, widget=None):
        self.app = widget.get_text()
        self.okButton.set_property('sensitive',
                self.verEntry.get_text() != '')
        return

    def _appver_changed(self, widget=None):
        self.ver = widget.get_text()
        self.okButton.set_property('sensitive',
                self.appEntry.get_text() != '')
        return

    def _descURI_change(self, widget=None):
        self.DescURI = widget.get_text()

    def _desc_browse(self, widget=None):
        dia = FilePicker(
                title='Select description file',
                plaintxt = True)
        res = dia.run()
        dia.hide()
        if res == gtk.RESPONSE_OK:
            self.descEntry.set_text(dia.get_filename())
        dia.destroy()


    def _browse(self, widget=None):
        """ Browse for source archive """
        dia = FilePicker(title='Choose source archive',
                forsrc = True)
        res = dia.run()
        dia.hide()
        if res == gtk.RESPONSE_OK:
            self.SrcURI = dia.get_filename()
            self.srcentry.set_text(self.SrcURI)
            try:
                s = buildutils.Source(self.SrcURI)
                self.appEntry.set_text(s.app)
                self.verEntry.set_text(s.ver)
                del s
            except:
                dia = message.Error(parent = self,
                        text = 'Error creating source object')
                if dia.run():
                    dia.destroy()

        return


    def _src_entry_event(self, widget=None):
        starts = ('http:', 'https:','ftp:')
        ends = ('.tar.gz', '.xz', '.tar.bz2', '.tgz')
        uri = widget.get_text()
        enable = False
        for i in starts:
            if uri.startswith(i):
                #enable = True
                #self.okButton.set_property('sensitive', enable)
                self.SrcURI = widget.get_text()
                return
        for x in ends:
            if uri.endswith(x):
                if os.path.exists(uri):
                    enable = True
                    self.okButton.set_property('sensitive', enable)
                    self.SrcURI = widget.get_text()
                    return
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.