This file is indexed.

/usr/share/pyshared/gluon/widget.py is in python-gluon 1.99.7-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)

The widget is called from web2py.
"""

import sys
import cStringIO
import time
import thread
import re
import os
import socket
import signal
import math
import logging
import newcron
import main

from fileutils import w2p_pack, read_file, write_file
from shell import run, test
from settings import global_settings

try:
    import Tkinter, tkMessageBox
    import contrib.taskbar_widget
    from winservice import web2py_windows_service_handler
except:
    pass

try:
    import gtk
    import gobject
    import contrib.gtk_presentation
except:
    pass

try:
    BaseException
except NameError:
    BaseException = Exception

ProgramName = 'web2py Web Framework'
ProgramAuthor = 'Created by Massimo Di Pierro, Copyright 2007-2011'
ProgramVersion = read_file('VERSION').strip()

ProgramInfo = '''%s
                 %s
                 %s''' % (ProgramName, ProgramAuthor, ProgramVersion)

if not sys.version[:3] in ['2.4', '2.5', '2.6', '2.7']:
    msg = 'Warning: web2py requires Python 2.4, 2.5 (recommended), 2.6 or 2.7 but you are running:\n%s'
    msg = msg % sys.version
    sys.stderr.write(msg)

logger = logging.getLogger("web2py")

class IO(object):
    """   """

    def __init__(self):
        """   """

        self.buffer = cStringIO.StringIO()

    def write(self, data):
        """   """

        sys.__stdout__.write(data)
        if hasattr(self, 'callback'):
            self.callback(data)
        else:
            self.buffer.write(data)


def try_start_browser(url):
    """ Try to start the default browser """

    try:
        import webbrowser
        webbrowser.open(url)
    except:
        print 'warning: unable to detect your browser'


def start_browser(ip, port):
    """ Starts the default browser """
    print 'please visit:'
    print '\thttp://%s:%s' % (ip, port)
    print 'starting browser...'
    try_start_browser('http://%s:%s' % (ip, port))

def setup_gtk(*args):
    
    
    

    class web2pyGtkDialog(gtk.Window):
        """Main gtk window dialog"""
        def __init__(self,options):
            
            super(web2pyGtkDialog, self).__init__()
            gobject.threads_init()
            self.options=options
            httplog = os.path.join(self.options.folder, 'httpserver.log')
            
            self.set_title("web2py server")
            vbox = gtk.VBox(False, 2)
            
            # Building the Menu
            self.menu = gtk.MenuBar()

            servermenu = gtk.Menu()
            severm = gtk.MenuItem("Server")
            severm.set_submenu(servermenu)
           
            item = lambda(x): try_start_browser(httplog)       
            log_item = gtk.MenuItem("View httpserver.log")
            log_item .connect("activate", item)
            quit_item = gtk.MenuItem("Quit (pid: %i)" % os.getpid())
            quit_item.connect("activate", self.quit)
            servermenu.append(log_item)
            servermenu.append(quit_item) 
            self.menu.append(severm)
            
            self.pagesmenu = gtk.Menu()
            pagesm = gtk.MenuItem("Pages")
            pagesm.set_submenu(self.pagesmenu)        
            self.menu.append(pagesm)

            helpmenu = gtk.Menu()
            helpm = gtk.MenuItem("Info")
            helpm.set_submenu(helpmenu)
            self.menu.append(helpm)
            
            # Home Page
            item = lambda(x): try_start_browser('http://www.web2py.com')
            home_item= gtk.MenuItem('Home Page')
            home_item.connect("activate", item)
     
            # About
            about=gtk.AboutDialog()
            about.set_version(ProgramVersion)
            about.set_copyright(ProgramAuthor)
            about.set_program_name(ProgramName)
            item = lambda(x):  self.about_dialog(about)
            about_item= gtk.MenuItem('About')
            about_item.connect("activate", item)     
            helpmenu.append(home_item)
            helpmenu.append(about_item) 

            vbox.pack_start(self.menu, False, False, 0)

            table = gtk.Table(3, 2, True)
            vbox.add(table)
            # IP
            ip_label = gtk.Label('Server IP:')
            ip_label.set_alignment(xalign=0.0, yalign=0.5)
            self.ip = gtk.Entry()
            self.ip.set_text(self.options.ip)
            table.attach(ip_label,0, 1, 0, 1)
            table.attach(self.ip,1, 2, 0, 1)        
            ip_label.show()
            self.ip.show()
          
            # Port
            port_label = gtk.Label('Server Port:')
            port_label.set_alignment(xalign=0.0, yalign=0.5)
            self.port_number = gtk.Entry()
            self.port_number.set_text(str(self.options.port))
            table.attach(port_label,0, 1, 1, 2)
            table.attach(self.port_number,1, 2, 1, 2)        
            port_label.show()
            self.port_number.show()        
          
            # Password
            passwd_label = gtk.Label('Choose Password:')
            passwd_label.set_alignment(xalign=0.0, yalign=0.5)
            self.password  = gtk.Entry()
            self.password.set_visibility(False)
            self.password.connect("activate",  lambda e: self.start())
            table.attach(passwd_label,0, 1, 2, 3)
            table.attach(self.password ,1, 2, 2, 3)        
            passwd_label.show()
            self.password.show()     

            # Prepare the canvas
            self.canvas = gtk.DrawingArea()
            self.canvas.set_size_request(300, 101)
            self.canvas.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("black"))
            vbox.add(self.canvas)
            self.gc = None  # initialized in realize-event handler
            self.canvas.connect('expose-event',  self.on_expose_event)
            self.canvas.connect('realize',       self.on_realize)        
            self.canvas.show()             
            
            # Prepare the frame
            frame = gtk.HButtonBox()
            vbox.add(frame)
            frame.show()
            
            # Start button
            start_image=gtk.Image()
            start_image.set_from_icon_name(gtk.STOCK_EXECUTE,gtk.ICON_SIZE_BUTTON)        
            self.button_start = gtk.Button(label='start server')
            self.button_start.set_image(start_image)
            frame.add(self.button_start)
            self.button_start.show()
            self.button_start.connect("clicked", self.start)
            
            # Stopt button
            stop_image=gtk.Image()
            stop_image.set_from_icon_name(gtk.STOCK_STOP,gtk.ICON_SIZE_BUTTON)
            self.button_stop = gtk.Button(label='stop server')
            self.button_stop.set_image(stop_image)
            self.button_stop.set_sensitive(False)
            frame.add(self.button_stop)
            self.button_stop.show()
            self.button_stop.connect("clicked", self.stop)

            self.add(vbox)
            table.show()
            self.password.grab_focus()
            self.connect("destroy", self.quit)        
            
        def about_dialog(self,dialog):
            dialog.run()
            dialog.hide()

        def error(self, message):
            """ Show error message """
            md = gtk.MessageDialog(self, gtk.DIALOG_DESTROY_WITH_PARENT,
            gtk.MESSAGE_WARNING, gtk.BUTTONS_CLOSE, message)
            md.format_secondary_text('web2py start server')
            md.run()
            md.destroy()        

        def quit(self, menu_item):
            """ Finish the program execution """

            try:
                self.server.stop()
            except:
                pass

            gtk.main_quit()
            sys.exit()
            
        def start(self,item=None):
            """ Start web2py server """

            password = self.password.get_text()

            if not password:
                self.error('no password, no web admin interface')

            ip = self.ip.get_text()

            regexp = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
            if ip and not re.compile(regexp).match(ip):
                return self.error('invalid host ip address')

            try:
                port = int(self.port_number.get_text())
            except:
                return self.error('invalid port number')

            self.url = 'http://%s:%s' % (ip, port)
            self.connect_pages()
            self.button_start.set_sensitive(False)

            try:
                options = self.options
                req_queue_size = options.request_queue_size
                self.server = main.HttpServer(
                    ip,
                    port,
                    password,
                    pid_filename=options.pid_filename,
                    log_filename=options.log_filename,
                    profiler_filename=options.profiler_filename,
                    ssl_certificate=options.ssl_certificate,
                    ssl_private_key=options.ssl_private_key,
                    min_threads=options.minthreads,
                    max_threads=options.maxthreads,
                    server_name=options.server_name,
                    request_queue_size=req_queue_size,
                    timeout=options.timeout,
                    shutdown_timeout=options.shutdown_timeout,
                    path=options.folder,
                    interfaces=options.interfaces)

                thread.start_new_thread(self.server.start, ())
            except Exception, e:
                self.button_start.set_sensitive(True)
                return self.error(str(e))

            self.button_stop.set_sensitive(True)
            if not options.taskbar:
                thread.start_new_thread(start_browser, (ip, port))

            self.password.set_sensitive(False)
            self.ip.set_sensitive(False)
            self.port_number.set_sensitive(False)
            
            gobject.timeout_add(1000, self.update_canvas)
            
        def stop(self,item=None):
            self.button_stop.set_sensitive(False)
            self.button_start.set_sensitive(True)
            self.password.set_sensitive(True)
            self.ip.set_sensitive(True)
            self.port_number.set_sensitive(True)
            self.server.stop()
            
        def connect_pages(self):
            """ Connect pages """
            def get_label(menu_item):
                url=menu_item.get_child().get_label()
                try_start_browser(url)
                
            for arq in os.listdir('applications/'):
                if os.path.exists('applications/%s/__init__.py' % arq):
                    url = self.url + '/' + arq
                    start_browser = lambda u =url: get_label(u)
                    page_item = gtk.MenuItem(url)        
                    page_item.connect("activate", start_browser)
                    page_item.show()
                    self.pagesmenu.append(page_item)
                    
                    
        def update_canvas(self):

            self.queue_draw()
            gobject.timeout_add(1000, self.update_canvas) 
            
        def on_expose_event(self, widget, event):     

            try:
                t1 = os.path.getsize('httpserver.log')

            except:
                gobject.timeout_add(1000, self.update_canvas)
                return
                

            try:
                fp = open('httpserver.log', 'r')
                fp.seek(self.t0)
                data = fp.read(t1 - self.t0)
                fp.close()
                value = self.p0[1:] + [10 +int( 90.0 / math.sqrt(1 + data.count('\n')))]
                self.p0 = value
                points=[]

                for i in xrange(len(self.p0)-1):
                    points.append((i,value[i]))
                
                self.t0 = t1 
                widget.window.draw_lines(self.gc, points)


            except BaseException:
                self.t0 = time.time()
                self.t0 = t1
                self.p0 = [100] * 320


        def on_realize(self, widget):
            self.gc = widget.window.new_gc()
            self.gc.set_rgb_fg_color(gtk.gdk.color_parse("green"))
            self.gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
                                        gtk.gdk.CAP_PROJECTING, gtk.gdk.JOIN_MITER)        
                          
    
    options=args[0]
    mymain=web2pyGtkDialog(options)
    gobject.timeout_add(5000, mymain.show_all)                        
  
  
def presentation(root):
    """ Draw the splash screen Tk"""

    root.withdraw()

    dx = root.winfo_screenwidth()
    dy = root.winfo_screenheight()

    dialog = Tkinter.Toplevel(root, bg='white')
    dialog.geometry('%ix%i+%i+%i' % (500, 300, dx / 2 - 200, dy / 2 - 150))

    dialog.overrideredirect(1)
    dialog.focus_force()

    canvas = Tkinter.Canvas(dialog,
                            background='white',
                            width=500,
                            height=300)
    canvas.pack()
    root.update()

    logo = 'splashlogo.gif'
    if os.path.exists(logo):
        img = Tkinter.PhotoImage(file=logo)
        pnl = Tkinter.Label(canvas, image=img, background='white', bd=0)
        pnl.pack(side='top', fill='both', expand='yes')
        # Prevent garbage collection of img
        pnl.image=img

    def add_label(text='Change Me', font_size=12, foreground='#195866', height=1):
        return Tkinter.Label(
            master=canvas,
            width=250,
            height=height,
            text=text,
            font=('Helvetica', font_size),
            anchor=Tkinter.CENTER,
            foreground=foreground,
            background='white'
            )

    add_label('Welcome to...').pack(side='top')
    add_label(ProgramName, 18, '#FF5C1F', 2).pack()
    add_label(ProgramAuthor).pack()
    add_label(ProgramVersion).pack()

    root.update()
    time.sleep(5)
    dialog.destroy()
    return


class web2pyDialog(object):
    """ Main window dialog """

    def __init__(self, root, options):
        """ web2pyDialog constructor  """

        root.title('web2py server')
        self.root = Tkinter.Toplevel(root)
        self.options = options
        self.menu = Tkinter.Menu(self.root)
        servermenu = Tkinter.Menu(self.menu, tearoff=0)
        httplog = os.path.join(self.options.folder, 'httpserver.log')

        # Building the Menu
        item = lambda: try_start_browser(httplog)
        servermenu.add_command(label='View httpserver.log',
                               command=item)

        servermenu.add_command(label='Quit (pid:%i)' % os.getpid(),
                               command=self.quit)

        self.menu.add_cascade(label='Server', menu=servermenu)

        self.pagesmenu = Tkinter.Menu(self.menu, tearoff=0)
        self.menu.add_cascade(label='Pages', menu=self.pagesmenu)

        helpmenu = Tkinter.Menu(self.menu, tearoff=0)

        # Home Page
        item = lambda: try_start_browser('http://www.web2py.com')
        helpmenu.add_command(label='Home Page',
                             command=item)

        # About
        item = lambda: tkMessageBox.showinfo('About web2py', ProgramInfo)
        helpmenu.add_command(label='About',
                             command=item)

        self.menu.add_cascade(label='Info', menu=helpmenu)

        self.root.config(menu=self.menu)

        if options.taskbar:
            self.root.protocol('WM_DELETE_WINDOW',
                               lambda: self.quit(True))
        else:
            self.root.protocol('WM_DELETE_WINDOW', self.quit)

        sticky = Tkinter.NW

        # IP
        Tkinter.Label(self.root,
                      text='Server IP:',
                      justify=Tkinter.LEFT).grid(row=0,
                                                 column=0,
                                                 sticky=sticky)
        self.ip = Tkinter.Entry(self.root)
        self.ip.insert(Tkinter.END, self.options.ip)
        self.ip.grid(row=0, column=1, sticky=sticky)

        # Port
        Tkinter.Label(self.root,
                      text='Server Port:',
                      justify=Tkinter.LEFT).grid(row=1,
                                                 column=0,
                                                 sticky=sticky)

        self.port_number = Tkinter.Entry(self.root)
        self.port_number.insert(Tkinter.END, self.options.port)
        self.port_number.grid(row=1, column=1, sticky=sticky)

        # Password
        Tkinter.Label(self.root,
                      text='Choose Password:',
                      justify=Tkinter.LEFT).grid(row=2,
                                                 column=0,
                                                 sticky=sticky)

        self.password = Tkinter.Entry(self.root, show='*')
        self.password.bind('<Return>', lambda e: self.start())
        self.password.focus_force()
        self.password.grid(row=2, column=1, sticky=sticky)

        # Prepare the canvas
        self.canvas = Tkinter.Canvas(self.root,
                                     width=300,
                                     height=100,
                                     bg='black')
        self.canvas.grid(row=3, column=0, columnspan=2)
        self.canvas.after(1000, self.update_canvas)

        # Prepare the frame
        frame = Tkinter.Frame(self.root)
        frame.grid(row=4, column=0, columnspan=2)

        # Start button
        self.button_start = Tkinter.Button(frame,
                                           text='start server',
                                           command=self.start)

        self.button_start.grid(row=0, column=0)

        # Stop button
        self.button_stop = Tkinter.Button(frame,
                                          text='stop server',
                                          command=self.stop)

        self.button_stop.grid(row=0, column=1)
        self.button_stop.configure(state='disabled')

        if options.taskbar:
            self.tb = contrib.taskbar_widget.TaskBarIcon()
            self.checkTaskBar()

            if options.password != '<ask>':
                self.password.insert(0, options.password)
                self.start()
                self.root.withdraw()
        else:
            self.tb = None

    def checkTaskBar(self):
        """ Check taskbar status """

        if self.tb.status:
            if self.tb.status[0] == self.tb.EnumStatus.QUIT:
                self.quit()
            elif self.tb.status[0] == self.tb.EnumStatus.TOGGLE:
                if self.root.state() == 'withdrawn':
                    self.root.deiconify()
                else:
                    self.root.withdraw()
            elif self.tb.status[0] == self.tb.EnumStatus.STOP:
                self.stop()
            elif self.tb.status[0] == self.tb.EnumStatus.START:
                self.start()
            elif self.tb.status[0] == self.tb.EnumStatus.RESTART:
                self.stop()
                self.start()
            del self.tb.status[0]

        self.root.after(1000, self.checkTaskBar)

    def update(self, text):
        """ Update app text """

        try:
            self.text.configure(state='normal')
            self.text.insert('end', text)
            self.text.configure(state='disabled')
        except:
            pass  # ## this should only happen in case app is destroyed

    def connect_pages(self):
        """ Connect pages """

        for arq in os.listdir('applications/'):
            if os.path.exists('applications/%s/__init__.py' % arq):
                url = self.url + '/' + arq
                start_browser = lambda u = url: try_start_browser(u)
                self.pagesmenu.add_command(label=url,
                                           command=start_browser)

    def quit(self, justHide=False):
        """ Finish the program execution """

        if justHide:
            self.root.withdraw()
        else:
            try:
                self.server.stop()
            except:
                pass

            try:
                self.tb.Destroy()
            except:
                pass

            self.root.destroy()
            sys.exit(0)

    def error(self, message):
        """ Show error message """

        tkMessageBox.showerror('web2py start server', message)

    def start(self):
        """ Start web2py server """

        password = self.password.get()

        if not password:
            self.error('no password, no web admin interface')

        ip = self.ip.get()

        regexp = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
        if ip and not re.compile(regexp).match(ip):
            return self.error('invalid host ip address')

        try:
            port = int(self.port_number.get())
        except:
            return self.error('invalid port number')

        self.url = 'http://%s:%s' % (ip, port)
        self.connect_pages()
        self.button_start.configure(state='disabled')

        try:
            options = self.options
            req_queue_size = options.request_queue_size
            self.server = main.HttpServer(
                ip,
                port,
                password,
                pid_filename=options.pid_filename,
                log_filename=options.log_filename,
                profiler_filename=options.profiler_filename,
                ssl_certificate=options.ssl_certificate,
                ssl_private_key=options.ssl_private_key,
                min_threads=options.minthreads,
                max_threads=options.maxthreads,
                server_name=options.server_name,
                request_queue_size=req_queue_size,
                timeout=options.timeout,
                shutdown_timeout=options.shutdown_timeout,
                path=options.folder,
                interfaces=options.interfaces)

            thread.start_new_thread(self.server.start, ())
        except Exception, e:
            self.button_start.configure(state='normal')
            return self.error(str(e))

        self.button_stop.configure(state='normal')

        if not options.taskbar:
            thread.start_new_thread(start_browser, (ip, port))

        self.password.configure(state='readonly')
        self.ip.configure(state='readonly')
        self.port_number.configure(state='readonly')

        if self.tb:
            self.tb.SetServerRunning()

    def stop(self):
        """ Stop web2py server """

        self.button_start.configure(state='normal')
        self.button_stop.configure(state='disabled')
        self.password.configure(state='normal')
        self.ip.configure(state='normal')
        self.port_number.configure(state='normal')
        self.server.stop()

        if self.tb:
            self.tb.SetServerStopped()

    def update_canvas(self):
        """ Update canvas """

        try:
            t1 = os.path.getsize('httpserver.log')
        except:
            self.canvas.after(1000, self.update_canvas)
            return

        try:
            fp = open('httpserver.log', 'r')
            fp.seek(self.t0)
            data = fp.read(t1 - self.t0)
            fp.close()
            value = self.p0[1:] + [10 + 90.0 / math.sqrt(1 + data.count('\n'))]
            self.p0 = value

            for i in xrange(len(self.p0) - 1):
                c = self.canvas.coords(self.q0[i])
                self.canvas.coords(self.q0[i],
                                   (c[0],
                                    self.p0[i],
                                    c[2],
                                    self.p0[i + 1]))
            self.t0 = t1
        except BaseException:
            self.t0 = time.time()
            self.t0 = t1
            self.p0 = [100] * 300
            self.q0 = [self.canvas.create_line(i, 100, i + 1, 100,
                       fill='green') for i in xrange(len(self.p0) - 1)]

        self.canvas.after(1000, self.update_canvas)


def console():
    """ Defines the behavior of the console web2py execution """
    import optparse
    import textwrap

    usage = "python web2py.py"

    description = """\
    web2py Web Framework startup script.
    ATTENTION: unless a password is specified (-a 'passwd') web2py will
    attempt to run a GUI. In this case command line options are ignored."""

    description = textwrap.dedent(description)

    parser = optparse.OptionParser(usage, None, optparse.Option, ProgramVersion)

    parser.description = description

    parser.add_option('-i',
                      '--ip',
                      default='127.0.0.1',
                      dest='ip',
                      help='ip address of the server (127.0.0.1)')

    parser.add_option('-p',
                      '--port',
                      default='8000',
                      dest='port',
                      type='int',
                      help='port of server (8000)')

    msg = 'password to be used for administration'
    msg += ' (use -a "<recycle>" to reuse the last password))'
    parser.add_option('-a',
                      '--password',
                      default='<ask>',
                      dest='password',
                      help=msg)

    parser.add_option('-c',
                      '--ssl_certificate',
                      default='',
                      dest='ssl_certificate',
                      help='file that contains ssl certificate')

    parser.add_option('-k',
                      '--ssl_private_key',
                      default='',
                      dest='ssl_private_key',
                      help='file that contains ssl private key')

    parser.add_option('--ca-cert',
                      action='store',
                      dest='ssl_ca_certificate',
                      default=None,
                      help='Use this file containing the CA certificate to validate X509 certificates from clients')

    parser.add_option('-d',
                      '--pid_filename',
                      default='httpserver.pid',
                      dest='pid_filename',
                      help='file to store the pid of the server')

    parser.add_option('-l',
                      '--log_filename',
                      default='httpserver.log',
                      dest='log_filename',
                      help='file to log connections')

    parser.add_option('-n',
                      '--numthreads',
                      default=None,
                      type='int',
                      dest='numthreads',
                      help='number of threads (deprecated)')

    parser.add_option('--minthreads',
                      default=None,
                      type='int',
                      dest='minthreads',
                      help='minimum number of server threads')

    parser.add_option('--maxthreads',
                      default=None,
                      type='int',
                      dest='maxthreads',
                      help='maximum number of server threads')

    parser.add_option('-s',
                      '--server_name',
                      default=socket.gethostname(),
                      dest='server_name',
                      help='server name for the web server')

    msg = 'max number of queued requests when server unavailable'
    parser.add_option('-q',
                      '--request_queue_size',
                      default='5',
                      type='int',
                      dest='request_queue_size',
                      help=msg)

    parser.add_option('-o',
                      '--timeout',
                      default='10',
                      type='int',
                      dest='timeout',
                      help='timeout for individual request (10 seconds)')

    parser.add_option('-z',
                      '--shutdown_timeout',
                      default='5',
                      type='int',
                      dest='shutdown_timeout',
                      help='timeout on shutdown of server (5 seconds)')

    parser.add_option('--socket-timeout',
                      default=5,
                      type='int',
                      dest='socket_timeout',
                      help='timeout for socket (5 second)')

    parser.add_option('-f',
                      '--folder',
                      default=os.getcwd(),
                      dest='folder',
                      help='folder from which to run web2py')

    parser.add_option('-v',
                      '--verbose',
                      action='store_true',
                      dest='verbose',
                      default=False,
                      help='increase --test verbosity')

    parser.add_option('-Q',
                      '--quiet',
                      action='store_true',
                      dest='quiet',
                      default=False,
                      help='disable all output')

    msg = 'set debug output level (0-100, 0 means all, 100 means none;'
    msg += ' default is 30)'
    parser.add_option('-D',
                      '--debug',
                      dest='debuglevel',
                      default=30,
                      type='int',
                      help=msg)

    msg = 'run web2py in interactive shell or IPython (if installed) with'
    msg += ' specified appname (if app does not exist it will be created).'
    msg += ' APPNAME like a/c/f (c,f optional)'
    parser.add_option('-S',
                      '--shell',
                      dest='shell',
                      metavar='APPNAME',
                      help=msg)

    msg = 'run web2py in interactive shell or bpython (if installed) with'
    msg += ' specified appname (if app does not exist it will be created).'
    msg += '\n Use combined with --shell'
    parser.add_option('-B',
                      '--bpython',
                      action='store_true',
                      default=False,
                      dest='bpython',
                      help=msg)

    msg = 'only use plain python shell; should be used with --shell option'
    parser.add_option('-P',
                      '--plain',
                      action='store_true',
                      default=False,
                      dest='plain',
                      help=msg)

    msg = 'auto import model files; default is False; should be used'
    msg += ' with --shell option'
    parser.add_option('-M',
                      '--import_models',
                      action='store_true',
                      default=False,
                      dest='import_models',
                      help=msg)

    msg = 'run PYTHON_FILE in web2py environment;'
    msg += ' should be used with --shell option'
    parser.add_option('-R',
                      '--run',
                      dest='run',
                      metavar='PYTHON_FILE',
                      default='',
                      help=msg)

    msg = 'run scheduled tasks for the specified apps'
    msg += '-K app1,app2,app3'
    msg += 'requires a scheduler defined in the models'
    parser.add_option('-K',
                      '--scheduler',
                      dest='scheduler',
                      default=None,
                      help=msg)

    msg = 'run doctests in web2py environment; ' +\
        'TEST_PATH like a/c/f (c,f optional)'
    parser.add_option('-T',
                      '--test',
                      dest='test',
                      metavar='TEST_PATH',
                      default=None,
                      help=msg)

    parser.add_option('-W',
                      '--winservice',
                      dest='winservice',
                      default='',
                      help='-W install|start|stop as Windows service')

    msg = 'trigger a cron run manually; usually invoked from a system crontab'
    parser.add_option('-C',
                      '--cron',
                      action='store_true',
                      dest='extcron',
                      default=False,
                      help=msg)

    msg = 'triggers the use of softcron'
    parser.add_option('--softcron',
                      action='store_true',
                      dest='softcron',
                      default=False,
                      help=msg)

    parser.add_option('-N',
                      '--no-cron',
                      action='store_true',
                      dest='nocron',
                      default=False,
                      help='do not start cron automatically')

    parser.add_option('-J',
                      '--cronjob',
                      action='store_true',
                      dest='cronjob',
                      default=False,
                      help='identify cron-initiated command')

    parser.add_option('-L',
                      '--config',
                      dest='config',
                      default='',
                      help='config file')

    parser.add_option('-F',
                      '--profiler',
                      dest='profiler_filename',
                      default=None,
                      help='profiler filename')

    parser.add_option('-t',
                      '--taskbar',
                      action='store_true',
                      dest='taskbar',
                      default=False,
                      help='use web2py gui and run in taskbar (system tray)')

    parser.add_option('',
                      '--nogui',
                      action='store_true',
                      default=False,
                      dest='nogui',
                      help='text-only, no GUI')

    parser.add_option('-A',
                      '--args',
                      action='store',
                      dest='args',
                      default=None,
                      help='should be followed by a list of arguments to be passed to script, to be used with -S, -A must be the last option')

    parser.add_option('--no-banner',
                      action='store_true',
                      default=False,
                      dest='nobanner',
                      help='Do not print header banner')


    msg = 'listen on multiple addresses: "ip:port:cert:key:ca_cert;ip2:port2:cert2:key2:ca_cert2;..." (:cert:key optional; no spaces)'
    parser.add_option('--interfaces',
                      action='store',
                      dest='interfaces',
                      default=None,
                      help=msg)

    if '-A' in sys.argv: k = sys.argv.index('-A')
    elif '--args' in sys.argv: k = sys.argv.index('--args')
    else: k=len(sys.argv)
    sys.argv, other_args = sys.argv[:k], sys.argv[k+1:]
    (options, args) = parser.parse_args()
    options.args = [options.run] + other_args
    global_settings.cmd_options = options
    global_settings.cmd_args = args

    if options.quiet:
        capture = cStringIO.StringIO()
        sys.stdout = capture
        logger.setLevel(logging.CRITICAL + 1)
    else:
        logger.setLevel(options.debuglevel)

    if options.config[-3:] == '.py':
        options.config = options.config[:-3]

    if options.cronjob:
        global_settings.cronjob = True  # tell the world
        options.nocron = True   # don't start cron jobs
        options.plain = True    # cronjobs use a plain shell

    options.folder = os.path.abspath(options.folder)

    #  accept --interfaces in the form
    #  "ip:port:cert:key;ip2:port2;ip3:port3:cert3:key3"
    #  (no spaces; optional cert:key indicate SSL)
    if isinstance(options.interfaces, str):
        options.interfaces = [
            interface.split(':') for interface in options.interfaces.split(';')]
        for interface in options.interfaces:
            interface[1] = int(interface[1])    # numeric port
        options.interfaces = [
            tuple(interface) for interface in options.interfaces]

    if options.numthreads is not None and options.minthreads is None:
        options.minthreads = options.numthreads  # legacy

    if not options.cronjob:
        # If we have the applications package or if we should upgrade
        if not os.path.exists('applications/__init__.py'):
            write_file('applications/__init__.py', '')

        if not os.path.exists('welcome.w2p') or os.path.exists('NEWINSTALL'):
            try:
                w2p_pack('welcome.w2p','applications/welcome')
                os.unlink('NEWINSTALL')
            except:
                msg = "New installation: unable to create welcome.w2p file"
                sys.stderr.write(msg)

    return (options, args)

def start_schedulers(options):
    apps = [app.strip() for app in options.scheduler.split(',')]
    try:
        from multiprocessing import Process
    except:
        sys.stderr.write('Sorry, -K only supported for python 2.6-2.7\n')
        return
    processes = []
    code = "from gluon import current; current._scheduler.loop()"
    for app in apps:
        print 'starting scheduler for "%s"...' % app
        args = (app,True,True,None,False,code)
        logging.getLogger().setLevel(logging.DEBUG)
        p = Process(target=run, args=args)
        processes.append(p)
        print "Currently running %s scheduler processes" % (len(processes))
        p.start()
        print "Processes started"
    for p in processes:
        try:
            p.join()
        except KeyboardInterrupt:
            p.terminate()
            p.join()


def start(cron=True):
    """ Start server  """

    # ## get command line arguments

    (options, args) = console()

    if not options.nobanner:
        print ProgramName
        print ProgramAuthor
        print ProgramVersion

    from dal import drivers
    if not options.nobanner:
        print 'Database drivers available: %s' % ', '.join(drivers)


    # ## if -L load options from options.config file
    if options.config:
        try:
            options2 = __import__(options.config, {}, {}, '')
        except Exception:
            try:
                # Jython doesn't like the extra stuff
                options2 = __import__(options.config)
            except Exception:
                print 'Cannot import config file [%s]' % options.config
                sys.exit(1)
        for key in dir(options2):
            if hasattr(options,key):
                setattr(options,key,getattr(options2,key))

    # ## if -T run doctests (no cron)
    if hasattr(options,'test') and options.test:
        test(options.test, verbose=options.verbose)
        return

    # ## if -K
    if options.scheduler:
        try:
            start_schedulers(options)
        except KeyboardInterrupt:
            pass
        return

    # ## if -S start interactive shell (also no cron)
    if options.shell:
        if not options.args is None:
            sys.argv[:] = options.args
        run(options.shell, plain=options.plain, bpython=options.bpython,
            import_models=options.import_models, startfile=options.run)
        return

    # ## if -C start cron run (extcron) and exit
    # ## if -N or not cron disable cron in this *process*
    # ## if --softcron use softcron
    # ## use hardcron in all other cases
    if options.extcron:
        print 'Starting extcron...'
        global_settings.web2py_crontype = 'external'
        extcron = newcron.extcron(options.folder)
        extcron.start()
        extcron.join()
        return
    elif cron and not options.nocron and options.softcron:
        print 'Using softcron (but this is not very efficient)'
        global_settings.web2py_crontype = 'soft'
    elif cron and not options.nocron:
        print 'Starting hardcron...'
        global_settings.web2py_crontype = 'hard'
        newcron.hardcron(options.folder).start()

    # ## if -W install/start/stop web2py as service
    if options.winservice:
        if os.name == 'nt':
            web2py_windows_service_handler(['', options.winservice],
                    options.config)
        else:
            print 'Error: Windows services not supported on this platform'
            sys.exit(1)
        return

    # ## if no password provided and havetk start Tk interface
    # ## or start interface if we want to put in taskbar (system tray)

    try:
        options.taskbar
    except:
        options.taskbar = False

    if options.taskbar and os.name != 'nt':
        print 'Error: taskbar not supported on this platform'
        sys.exit(1)

    root = None

    if not options.nogui:
        try:
            import gtk
            import gobject
            import pango
            havegtk=True
            havetk=False
        except:
            logger.warn('Trying Tk GUI interface because gtk is not installed')
            havegtk=False
            try:
                import Tkinter
                havetk = True
            except ImportError:
                logger.warn('GUI not available because neither gtk nor Tk libraries are not installed')
                havetk = False
        haveUI=havegtk or havetk
		
        splash = None
        if options.password == '<ask>' and haveUI or options.taskbar and haveUI:
            if havegtk:
                splash=contrib.gtk_presentation.Presentation('splashlogo.gif', ProgramName,ProgramAuthor,ProgramVersion)
            else:
                try:
                    root = Tkinter.Tk()
                except:
                    pass
    #if gtk interface:
    if splash:
        # ensure it is rendered immediately
        while gtk.events_pending():
            gtk.main_iteration()

        gobject.timeout_add(5000, splash.hide) # 5*1000 miliseconds                
        gobject.idle_add(setup_gtk,options)

        gtk.main()
        sys.exit()
        
    #if tk interface:
    if root:
        root.focus_force()
        if not options.quiet:
            presentation(root)
        master = web2pyDialog(root, options)
        signal.signal(signal.SIGTERM, lambda a, b: master.quit())

        try:
            root.mainloop()
        except:
            master.quit()

        sys.exit()

    # ## if no tk and no password, ask for a password

    if not root and options.password == '<ask>':
        options.password = raw_input('choose a password:')

    if not options.password and not options.nobanner:
        print 'no password, no admin interface'

    # ## start server

    (ip, port) = (options.ip, int(options.port))

    if not options.nobanner:
        print 'please visit:'
        print '\thttp://%s:%s' % (ip, port)
        print 'use "kill -SIGTERM %i" to shutdown the web2py server' % os.getpid()

    server = main.HttpServer(ip=ip,
                             port=port,
                             password=options.password,
                             pid_filename=options.pid_filename,
                             log_filename=options.log_filename,
                             profiler_filename=options.profiler_filename,
                             ssl_certificate=options.ssl_certificate,
                             ssl_private_key=options.ssl_private_key,
                             ssl_ca_certificate=options.ssl_ca_certificate,
                             min_threads=options.minthreads,
                             max_threads=options.maxthreads,
                             server_name=options.server_name,
                             request_queue_size=options.request_queue_size,
                             timeout=options.timeout,
                             socket_timeout=options.socket_timeout,
                             shutdown_timeout=options.shutdown_timeout,
                             path=options.folder,
                             interfaces=options.interfaces)

    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
    logging.shutdown()