def __create_widgets(self):
        """"""
        #####
        #Box
        self.title_box = gtk.HBox()
        self.box = HIGVBox()

        self.timeline = TLHoder(self.dashboard, self.connector)
        self.timeline.show_all()

        #######
        #Title
        self.title = gtk.Label(
            "<span size='15000' weight='heavy'>\t\t\t\t Timeline Graph Area(%s) </span>"
            % (PEER_ATTRIBUTE))
        self.title.set_use_markup(True)
        self.title.set_selectable(False)

        #########
        #Type Pic
        if "desktop" in PEER_ATTRIBUTE.lower():
            peer_img_str = "normalpeer.png"
        else:
            peer_img_str = "superpeer.png"

        self.peer_img = gtk.Image()
        self.peer_img.set_from_file(os.path.join(IMAGES_DIR, peer_img_str))
    def __create_widgets(self):
        """
        """
        # startup data
        line_filter, start, evts = self.base.grab_data()
        xlabel = self.base.xlabel
        glabel = self.base.title_by_graphmode()
        dlabel = self.base.descr_by_graphmode()

        #Box
        self.box = HIGVBox()

        #graph
        self.graph_box = gtk.HBox()
        self.graph = InteractiveGraph(evts,
                                      start,
                                      x_label=xlabel,
                                      y_label=_('Number of events'),
                                      graph_label=glabel,
                                      descr_label=dlabel,
                                      vdiv_labels=self.base.labels,
                                      line_filter=line_filter,
                                      connector=self.connector)

        #graph toolbar
        self.graphtb = TimeLineGraphToolbar(self.graph, self.connector,
                                            self.base.graph_mode,
                                            self.base.graph_kind, self.base)
class TimeLineGraphViewer(gtk.VBox):
    
    def __init__(self,dashboard = None,connector = None):
        """
        Load timeline for every tab in dashboard window
        """
        gtk.VBox.__init__(self)
        
        self.dashboard = dashboard
        self.connector = connector
        
        self.__create_widgets()
        self.__packed_widgets()
        self.__connected_widgets()
        
    def __create_widgets(self):
        """"""        
        #####
        #Box
        self.title_box = gtk.HBox()
        self.box = HIGVBox()
        
        self.timeline = TLHoder(self.dashboard,self.connector)
        self.timeline.show_all()
        
        #######
        #Title
        self.title = gtk.Label(
            "<span size='15000' weight='heavy'>\t\t\t\t Timeline Graph Area(%s) </span>"%(PEER_ATTRIBUTE))        
        self.title.set_use_markup(True)
        self.title.set_selectable(False)      
        
        #########
        #Type Pic
        if "desktop" in PEER_ATTRIBUTE.lower():
            peer_img_str = "normalpeer.png"
        else:
            peer_img_str = "superpeer.png"
            
        self.peer_img = gtk.Image()
        self.peer_img.set_from_file(os.path.join(IMAGES_DIR,peer_img_str))        
        
        
    def __packed_widgets(self):
        """"""
        self.box._pack_noexpand_nofill(self.title_box)
        self.box._pack_expand_fill(self.timeline)
        
        self.title_box.pack_end(self.peer_img)
        self.title_box.pack_end(self.title)
        

        
        self.add(self.box)
        
        self.show_all()
        
    def __connected_widgets(self):
        """"""
        pass
class TimeLineGraphViewer(gtk.VBox):
    def __init__(self, dashboard=None, connector=None):
        """
        Load timeline for every tab in dashboard window
        """
        gtk.VBox.__init__(self)

        self.dashboard = dashboard
        self.connector = connector

        self.__create_widgets()
        self.__packed_widgets()
        self.__connected_widgets()

    def __create_widgets(self):
        """"""
        #####
        #Box
        self.title_box = gtk.HBox()
        self.box = HIGVBox()

        self.timeline = TLHoder(self.dashboard, self.connector)
        self.timeline.show_all()

        #######
        #Title
        self.title = gtk.Label(
            "<span size='15000' weight='heavy'>\t\t\t\t Timeline Graph Area(%s) </span>"
            % (PEER_ATTRIBUTE))
        self.title.set_use_markup(True)
        self.title.set_selectable(False)

        #########
        #Type Pic
        if "desktop" in PEER_ATTRIBUTE.lower():
            peer_img_str = "normalpeer.png"
        else:
            peer_img_str = "superpeer.png"

        self.peer_img = gtk.Image()
        self.peer_img.set_from_file(os.path.join(IMAGES_DIR, peer_img_str))

    def __packed_widgets(self):
        """"""
        self.box._pack_noexpand_nofill(self.title_box)
        self.box._pack_expand_fill(self.timeline)

        self.title_box.pack_end(self.peer_img)
        self.title_box.pack_end(self.title)

        self.add(self.box)

        self.show_all()

    def __connected_widgets(self):
        """"""
        pass
    def __create_widgets(self):

        #box
        self.all_box = HIGVBox()
        self.input_box = HIGHBox()
        self.buttom_box = HIGHBox()
        self.check_btn_box = gtk.HButtonBox()

        #Add input
        self.title_text = HIGLabel(_("Locations"))
        self.longitude_text = HIGLabel(_("longitude:"))
        self.longitude_entry = HIGTextEntry()
        self.latitude_text = HIGLabel(_("latitude:"))
        self.latitude_entry = HIGTextEntry()

        #Add buttons
        self.get_event_btn = gtk.Button(_("Get Events"))
        self.refresh_btn = gtk.Button(_("Refresh"))

        #status bar
        self.statusbar = gtk.Statusbar()
        self.statusbar.push(0, 'Events in Database')

        self.listmodel = gtk.ListStore(str, str, str, str, str)

        # create the TreeView
        self.treeview = gtk.TreeView()

        # create the TreeViewColumns to display the data
        self.tvcolumn = [None] * len(self.column_names)
        cellpb = gtk.CellRendererText()

        self.tvcolumn[0] = gtk.TreeViewColumn(self.column_names[0], cellpb)
        self.tvcolumn[0].add_attribute(cellpb, 'text', 0)
        #cell = gtk.CellRendererText()
        #self.tvcolumn[0].set_cell_data_func(cell, self.test_type)
        self.treeview.append_column(self.tvcolumn[0])

        for n in range(1, len(self.column_names)):
            cell = gtk.CellRendererText()
            self.tvcolumn[n] = gtk.TreeViewColumn(self.column_names[n], cell)
            self.tvcolumn[n].add_attribute(cell, 'text', n)
            if n == 1:
                cell.set_property('xalign', 1.0)
            #self.tvcolumn[n].set_cell_data_func(cell, cell_data_funcs[n])
            self.treeview.append_column(self.tvcolumn[n])

        #self.treeview.connect('row-activated', self.open_file)
        self.scrolledwindow = gtk.ScrolledWindow()
        self.scrolledwindow.add(self.treeview)
        self.treeview.set_model(self.listmodel)
 def __create_widgets(self):
     """"""        
     #####
     #Box
     self.title_box = gtk.HBox()
     self.box = HIGVBox()
     
     self.timeline = TLHoder(self.dashboard,self.connector)
     self.timeline.show_all()
     
     #######
     #Title
     self.title = gtk.Label(
         "<span size='15000' weight='heavy'>\t\t\t\t Timeline Graph Area(%s) </span>"%(PEER_ATTRIBUTE))        
     self.title.set_use_markup(True)
     self.title.set_selectable(False)      
     
     #########
     #Type Pic
     if "desktop" in PEER_ATTRIBUTE.lower():
         peer_img_str = "normalpeer.png"
     else:
         peer_img_str = "superpeer.png"
         
     self.peer_img = gtk.Image()
     self.peer_img.set_from_file(os.path.join(IMAGES_DIR,peer_img_str))        
    def __create_widgets(self):
        
        #box
        self.all_box = HIGVBox()
        self.input_box = HIGHBox()
        self.buttom_box = HIGHBox()
        self.check_btn_box = gtk.HButtonBox()
        
        #Add input
        self.title_text = HIGLabel(_("Locations"))
        self.longitude_text = HIGLabel(_("longitude:"))
        self.longitude_entry = HIGTextEntry()
        self.latitude_text = HIGLabel(_("latitude:"))
        self.latitude_entry = HIGTextEntry()         
        
        #Add buttons
        self.get_event_btn = gtk.Button(_("Get Events"))
        self.refresh_btn = gtk.Button(_("Refresh"))
          
        #status bar
        self.statusbar = gtk.Statusbar()
        self.statusbar.push(0,'Events in Database')        
                                
        self.listmodel = gtk.ListStore(str, str, str, str, str)

        # create the TreeView
        self.treeview = gtk.TreeView()

        # create the TreeViewColumns to display the data
        self.tvcolumn = [None] * len(self.column_names)
        cellpb = gtk.CellRendererText()

        self.tvcolumn[0] = gtk.TreeViewColumn(self.column_names[0], cellpb)
        self.tvcolumn[0].add_attribute(cellpb, 'text', 0)
        #cell = gtk.CellRendererText()
        #self.tvcolumn[0].set_cell_data_func(cell, self.test_type)
        self.treeview.append_column(self.tvcolumn[0])

        for n in range(1, len(self.column_names)):
            cell = gtk.CellRendererText()
            self.tvcolumn[n] = gtk.TreeViewColumn(self.column_names[n], cell)
            self.tvcolumn[n].add_attribute(cell, 'text', n)
            if n == 1:
                cell.set_property('xalign', 1.0)
            #self.tvcolumn[n].set_cell_data_func(cell, cell_data_funcs[n])
            self.treeview.append_column(self.tvcolumn[n])

        #self.treeview.connect('row-activated', self.open_file)
        self.scrolledwindow = gtk.ScrolledWindow()
        self.scrolledwindow.add(self.treeview)
        self.treeview.set_model(self.listmodel)
 def __create_widgets(self):
     """
     """
     # startup data
     line_filter, start, evts = self.base.grab_data()
     xlabel = self.base.xlabel
     glabel = self.base.title_by_graphmode()
     dlabel = self.base.descr_by_graphmode()
     
     #Box
     self.box = HIGVBox()
     
     #graph
     self.graph_box = gtk.HBox()
     self.graph = InteractiveGraph(evts, start, x_label=xlabel,
         y_label=_('Number of events'), graph_label=glabel,
         descr_label=dlabel, vdiv_labels=self.base.labels,
         line_filter=line_filter, connector=self.connector)
     
     #graph toolbar
     self.graphtb = TimeLineGraphToolbar(self.graph, self.connector,
                                         self.base.graph_mode,self.base.graph_kind,
                                         self.base)
class EventWindow(HIGWindow):
    column_names = [
        'Event Type', 'Test Type', 'Time', 'Since Time', 'Locations'
    ]

    def __init__(self):
        HIGWindow.__init__(self, type=gtk.WINDOW_TOPLEVEL)

        self.location_user = Location()  #user location information
        self.location_user.longitude = 0.0
        self.location_user.latitude = 0.0

        self.set_title(_('Events List'))
        self.set_size_request(720, 580)
        self.set_position(gtk.WIN_POS_CENTER_ALWAYS)

        self.__create_widgets()
        self.__pack_widgets()
        self.__connect_widgets()

        self.__load_events()

    def __connect_widgets(self):

        self.get_event_btn.connect("clicked", lambda w: self._get_event())
        self.refresh_btn.connect("clicked", lambda w: self._refresh_list())

    def __create_widgets(self):

        #box
        self.all_box = HIGVBox()
        self.input_box = HIGHBox()
        self.buttom_box = HIGHBox()
        self.check_btn_box = gtk.HButtonBox()

        #Add input
        self.title_text = HIGLabel(_("Locations"))
        self.longitude_text = HIGLabel(_("longitude:"))
        self.longitude_entry = HIGTextEntry()
        self.latitude_text = HIGLabel(_("latitude:"))
        self.latitude_entry = HIGTextEntry()

        #Add buttons
        self.get_event_btn = gtk.Button(_("Get Events"))
        self.refresh_btn = gtk.Button(_("Refresh"))

        #status bar
        self.statusbar = gtk.Statusbar()
        self.statusbar.push(0, 'Events in Database')

        self.listmodel = gtk.ListStore(str, str, str, str, str)

        # create the TreeView
        self.treeview = gtk.TreeView()

        # create the TreeViewColumns to display the data
        self.tvcolumn = [None] * len(self.column_names)
        cellpb = gtk.CellRendererText()

        self.tvcolumn[0] = gtk.TreeViewColumn(self.column_names[0], cellpb)
        self.tvcolumn[0].add_attribute(cellpb, 'text', 0)
        #cell = gtk.CellRendererText()
        #self.tvcolumn[0].set_cell_data_func(cell, self.test_type)
        self.treeview.append_column(self.tvcolumn[0])

        for n in range(1, len(self.column_names)):
            cell = gtk.CellRendererText()
            self.tvcolumn[n] = gtk.TreeViewColumn(self.column_names[n], cell)
            self.tvcolumn[n].add_attribute(cell, 'text', n)
            if n == 1:
                cell.set_property('xalign', 1.0)
            #self.tvcolumn[n].set_cell_data_func(cell, cell_data_funcs[n])
            self.treeview.append_column(self.tvcolumn[n])

        #self.treeview.connect('row-activated', self.open_file)
        self.scrolledwindow = gtk.ScrolledWindow()
        self.scrolledwindow.add(self.treeview)
        self.treeview.set_model(self.listmodel)

    def __pack_widgets(self):

        self.all_box._pack_noexpand_nofill(self.input_box)
        self.all_box._pack_expand_fill(self.scrolledwindow)
        self.all_box._pack_noexpand_nofill(self.buttom_box)

        self.input_box.pack_start(self.title_text)
        self.input_box.pack_start(self.longitude_text)
        self.input_box.pack_start(self.longitude_entry)
        self.input_box.pack_start(self.latitude_text)
        self.input_box.pack_start(self.latitude_entry)

        self.buttom_box.pack_start(self.statusbar, True, True, 0)
        self.buttom_box.pack_end(self.check_btn_box, False, False, 0)

        self.check_btn_box.set_layout(gtk.BUTTONBOX_END)
        self.check_btn_box.set_spacing(8)
        self.check_btn_box.pack_start(self.get_event_btn)
        self.check_btn_box.pack_start(self.refresh_btn)

        self.add(self.all_box)

    def __load_events(self):
        for event_entry in theApp.event_manager.event_repository:
            if event_entry.EventType == 'CENSOR':
                pass
            elif event_entry.EventType == 'THROTTLING':
                pass
            elif event_entry.EventType == 'OFF_LINE':
                pass
            self.listmodel.append([
                event_entry.EventType, event_entry.TestType,
                time.strftime("%Y-%m-%d %H:%M:%S",
                              time.gmtime(event_entry.TimeUTC)),
                time.strftime("%Y-%m-%d %H:%M:%S",
                              time.gmtime(event_entry.SinceTimeUTC)),
                event_entry.Locations
            ])

    def _get_event(self):
        """
        get events from aggregator by using Aggregator API:get_events
        """
        longtitude = self.longitude_entry.get_text()
        latitude = self.latitude_entry.get_text()

        if longtitude != "" and latitude != "":
            self.location_user.longitude = float(longtitude)
            self.location_user.latitude = float(latitude)
        else:
            #There we should add user preference logitude
            self.location_user.longitude = 0.0
            self.location_user.latitude = 0.0

        defer_ = theApp.aggregator.get_events(self.location_user)
        defer_.addCallback(self.finish_get_events)
        defer_.addErrback(self.handler_error)

    def _refresh_list(self):
        """
        clear and load
        """
        self.listmodel.clear()
        self.__load_events()
        self.statusbar.push(0, _("Refresh the Events List!"))

    def handler_error(self, failure):
        g_logger.error("Error in get events %s" % str(failure))
        self.statusbar.push(0, _("Error in Get Events From Aggregator!"))

    def finish_get_events(self, message):
        if message is None:
            self.statusbar.push(0, _("No new Events from Aggregator!"))
            return

        self.statusbar.push(
            0, _("Get %d Events from Aggregator" % (len(message.events))))

    def test_type(self, column, cell, model, iter):
        #cell.set_property('text', model.get_value(iter, 0))
        return

    def event_type(self, column, cell, model, iter):
        #filename = os.path.join(self.dirname, model.get_value(iter, 0))
        #filestat = os.stat(filename)
        #cell.set_property('text', filestat.st_size)
        return

    def time(self, column, cell, model, iter):
        #filename = os.path.join(self.dirname, model.get_value(iter, 0))
        #filestat = os.stat(filename)
        #cell.set_property('text', oct(stat.S_IMODE(filestat.st_mode)))
        return

    def location(self, column, cell, model, iter):
        #filename = os.path.join(self.dirname, model.get_value(iter, 0))
        #filestat = os.stat(filename)
        #cell.set_property('text', time.ctime(filestat.st_mtime))
        return

    def report(self, column, cell, model, iter):
        return
class EventWindow(HIGWindow):
    column_names = ['Event Type',
                    'Test Type',
                    'Time',
                    'Since Time',
                    'Locations']

    def __init__(self):
        HIGWindow.__init__(self, type=gtk.WINDOW_TOPLEVEL)
        
        self.location_user = Location() #user location information
        self.location_user.longitude = 0.0
        self.location_user.latitude  = 0.0
         
        self.set_title(_('Events List'))
        self.set_size_request(720, 580)
        self.set_position(gtk.WIN_POS_CENTER_ALWAYS)
        
        self.__create_widgets()
        self.__pack_widgets()
        self.__connect_widgets()
        
        self.__load_events()

    def __connect_widgets(self):
        
        self.get_event_btn.connect("clicked",lambda w:self._get_event())
        self.refresh_btn.connect("clicked",lambda w:self._refresh_list())
        
    def __create_widgets(self):
        
        #box
        self.all_box = HIGVBox()
        self.input_box = HIGHBox()
        self.buttom_box = HIGHBox()
        self.check_btn_box = gtk.HButtonBox()
        
        #Add input
        self.title_text = HIGLabel(_("Locations"))
        self.longitude_text = HIGLabel(_("longitude:"))
        self.longitude_entry = HIGTextEntry()
        self.latitude_text = HIGLabel(_("latitude:"))
        self.latitude_entry = HIGTextEntry()         
        
        #Add buttons
        self.get_event_btn = gtk.Button(_("Get Events"))
        self.refresh_btn = gtk.Button(_("Refresh"))
          
        #status bar
        self.statusbar = gtk.Statusbar()
        self.statusbar.push(0,'Events in Database')        
                                
        self.listmodel = gtk.ListStore(str, str, str, str, str)

        # create the TreeView
        self.treeview = gtk.TreeView()

        # create the TreeViewColumns to display the data
        self.tvcolumn = [None] * len(self.column_names)
        cellpb = gtk.CellRendererText()

        self.tvcolumn[0] = gtk.TreeViewColumn(self.column_names[0], cellpb)
        self.tvcolumn[0].add_attribute(cellpb, 'text', 0)
        #cell = gtk.CellRendererText()
        #self.tvcolumn[0].set_cell_data_func(cell, self.test_type)
        self.treeview.append_column(self.tvcolumn[0])

        for n in range(1, len(self.column_names)):
            cell = gtk.CellRendererText()
            self.tvcolumn[n] = gtk.TreeViewColumn(self.column_names[n], cell)
            self.tvcolumn[n].add_attribute(cell, 'text', n)
            if n == 1:
                cell.set_property('xalign', 1.0)
            #self.tvcolumn[n].set_cell_data_func(cell, cell_data_funcs[n])
            self.treeview.append_column(self.tvcolumn[n])

        #self.treeview.connect('row-activated', self.open_file)
        self.scrolledwindow = gtk.ScrolledWindow()
        self.scrolledwindow.add(self.treeview)
        self.treeview.set_model(self.listmodel)
        
    def __pack_widgets(self):
        
        self.all_box._pack_noexpand_nofill(self.input_box)
        self.all_box._pack_expand_fill(self.scrolledwindow) 
        self.all_box._pack_noexpand_nofill(self.buttom_box)  
                
        self.input_box.pack_start(self.title_text)
        self.input_box.pack_start(self.longitude_text)
        self.input_box.pack_start(self.longitude_entry)
        self.input_box.pack_start(self.latitude_text)
        self.input_box.pack_start(self.latitude_entry)
       
        self.buttom_box.pack_start(self.statusbar,True,True,0)
        self.buttom_box.pack_end(self.check_btn_box,False,False,0)
        
        self.check_btn_box.set_layout(gtk.BUTTONBOX_END)
        self.check_btn_box.set_spacing(8)       
        self.check_btn_box.pack_start(self.get_event_btn)
        self.check_btn_box.pack_start(self.refresh_btn)   
        
        self.add(self.all_box)
        
    def __load_events(self):
        for event_entry in theApp.event_manager.event_repository:
            if event_entry.EventType == 'CENSOR':
                pass
            elif event_entry.EventType == 'THROTTLING':
                pass
            elif event_entry.EventType == 'OFF_LINE':
                pass
            self.listmodel.append(
                [event_entry.EventType,
                 event_entry.TestType,
                 time.strftime("%Y-%m-%d %H:%M:%S",
                               time.gmtime(event_entry.TimeUTC)),
                 time.strftime("%Y-%m-%d %H:%M:%S",
                               time.gmtime(event_entry.SinceTimeUTC)),
                 event_entry.Locations])

    
    def _get_event(self):
        """
        get events from aggregator by using Aggregator API:get_events
        """
        longtitude = self.longitude_entry.get_text()
        latitude   = self.latitude_entry.get_text()
        
        if longtitude != "" and latitude != "":
            self.location_user.longitude = float(longtitude)
            self.location_user.latitude  = float(latitude)
        else:
            #There we should add user preference logitude
            self.location_user.longitude = 0.0
            self.location_user.latitude  = 0.0
        
        defer_ = theApp.aggregator.get_events(self.location_user)
        defer_.addCallback(self.finish_get_events)
        defer_.addErrback(self.handler_error)
    
    def _refresh_list(self):
        """
        clear and load
        """
        self.listmodel.clear()
        self.__load_events()
        self.statusbar.push(0,_("Refresh the Events List!"))  
     
    def handler_error(self,failure):
        g_logger.error("Error in get events %s"%str(failure))
        self.statusbar.push(0,_("Error in Get Events From Aggregator!"))         
            
    def finish_get_events(self,message):
        if message is None:
            self.statusbar.push(0,_("No new Events from Aggregator!"))  
            return
        
        self.statusbar.push(0,_("Get %d Events from Aggregator"%(len(message.events))))  
        

    def test_type(self, column, cell, model, iter):
        #cell.set_property('text', model.get_value(iter, 0))
        return

    def event_type(self, column, cell, model, iter):
        #filename = os.path.join(self.dirname, model.get_value(iter, 0))
        #filestat = os.stat(filename)
        #cell.set_property('text', filestat.st_size)
        return

    def time(self, column, cell, model, iter):
        #filename = os.path.join(self.dirname, model.get_value(iter, 0))
        #filestat = os.stat(filename)
        #cell.set_property('text', oct(stat.S_IMODE(filestat.st_mode)))
        return

    def location(self, column, cell, model, iter):
        #filename = os.path.join(self.dirname, model.get_value(iter, 0))
        #filestat = os.stat(filename)
        #cell.set_property('text', time.ctime(filestat.st_mtime))
        return

    def report(self, column, cell, model, iter):
        return
    def _create_widgets(self):
        """"""        
        #vbox
        self.all_box = HIGVBox()
        self.soft_update_info_box = HIGHBox()
        self.soft_update_list_box = HIGVBox()
        self.check_btn_box = gtk.HButtonBox()
        self.soft_update_detail_box = HIGVBox()
        self.bottom_btn_box = gtk.HButtonBox()
            
        #software update information title 
        self.update_icon = gtk.Image()
        self.update_icon.set_from_file(os.path.join(IMAGES_DIR,'software_update.ico'))
        self.version_information_label = HIGLabel(_("The newest open monitor in your computer!"))
        self.latest_time_information_label = HIGLabel(_(self.latest_update_time))
        self.soft_update_table = HIGTable()
             
        #software list
        self.column_names = ['Date','Version','Name']
        
        self.vbox_list = gtk.VBox(False,8)
        self.scroll_window_vbox = gtk.ScrolledWindow()
        self.scroll_window_vbox.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        self.scroll_window_vbox.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
        self.vbox_list.pack_start(self.scroll_window_vbox,True,True,0)
        self.store = gtk.ListStore(str,str,str)
        self.treeview = gtk.TreeView()

        self.treeview.set_rules_hint(True)
        self.treeview.set_sensitive(False)
        self.vbox_list.set_size_request(100,100)
        self.scroll_window_vbox.add(self.treeview)
              
        self._create_colums()
        self.statusbar = gtk.Statusbar()
        self.statusbar.push(0,'No update!')
        
        self.vbox_list.pack_start(self.statusbar,False,False,0)
        
        self.progress_bar = gtk.ProgressBar()
        self.progress_bar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
        self.progress_bar.set_fraction(0.0)
        
        self.vbox_list.pack_start(self.progress_bar,False,False,0)
        #button about the update
        self.check_btn = HIGButton(_("Check"))
        self.install_btn = HIGButton(_("Install"))
        self.install_btn.set_sensitive(False)
        
        #update details 
        self.detail_toggle_button = gtk.ToggleButton(_("Details"))
        self.detail_btn_box = gtk.HButtonBox()
        self.detail_btn_box.set_layout(gtk.BUTTONBOX_START)
        self.details_vbox = HIGVBox()
        self.details_scroll = gtk.ScrolledWindow()
        self.details_textview = gtk.TextView()
        self.details_textview.set_size_request(100,120)
        self.details_textview.set_editable(False)
        self.details_textview.set_buffer(self._set_details_content())
    
        #bottom button
        self.close_btn = HIGButton(_("Close"))
        self.settings_btn = HIGButton(_("Settings"))
class SoftwareUpdateDialog(HIGWindow):
    """"""
    def __init__(self):
        """Constructor"""
        HIGWindow.__init__(self, type=gtk.WINDOW_TOPLEVEL)
        self.set_title(_("Open Monitor Software Update Manager"))
        self.set_position(gtk.WIN_POS_CENTER_ALWAYS)
        self.set_size_request(480,480)
        self.set_keep_above(True)
        self.set_border_width(10)
        
        self._create_record()
        self._create_widgets()
        self._pack_widgets()
        self._connect_widgets() 

    
    def _create_record(self):
        
        self.software_list_dict = {}
        self.software_details_dict ={
                                     "version":"",
                                     "news_date":"",
                                     "software_name":"",
                                     "description":"",
                                     "download_url":"",
                                     "is_update":"",
                                     "check_code":""
                                     } 
        self.current_record = {}
        #get history update information
        self.latest_update_time =  "The lastest update time is " + self._get_value_from_db("update_time")
        
    def _create_widgets(self):
        """"""        
        #vbox
        self.all_box = HIGVBox()
        self.soft_update_info_box = HIGHBox()
        self.soft_update_list_box = HIGVBox()
        self.check_btn_box = gtk.HButtonBox()
        self.soft_update_detail_box = HIGVBox()
        self.bottom_btn_box = gtk.HButtonBox()
            
        #software update information title 
        self.update_icon = gtk.Image()
        self.update_icon.set_from_file(os.path.join(IMAGES_DIR,'software_update.ico'))
        self.version_information_label = HIGLabel(_("The newest open monitor in your computer!"))
        self.latest_time_information_label = HIGLabel(_(self.latest_update_time))
        self.soft_update_table = HIGTable()
             
        #software list
        self.column_names = ['Date','Version','Name']
        
        self.vbox_list = gtk.VBox(False,8)
        self.scroll_window_vbox = gtk.ScrolledWindow()
        self.scroll_window_vbox.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        self.scroll_window_vbox.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
        self.vbox_list.pack_start(self.scroll_window_vbox,True,True,0)
        self.store = gtk.ListStore(str,str,str)
        self.treeview = gtk.TreeView()

        self.treeview.set_rules_hint(True)
        self.treeview.set_sensitive(False)
        self.vbox_list.set_size_request(100,100)
        self.scroll_window_vbox.add(self.treeview)
              
        self._create_colums()
        self.statusbar = gtk.Statusbar()
        self.statusbar.push(0,'No update!')
        
        self.vbox_list.pack_start(self.statusbar,False,False,0)
        
        self.progress_bar = gtk.ProgressBar()
        self.progress_bar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
        self.progress_bar.set_fraction(0.0)
        
        self.vbox_list.pack_start(self.progress_bar,False,False,0)
        #button about the update
        self.check_btn = HIGButton(_("Check"))
        self.install_btn = HIGButton(_("Install"))
        self.install_btn.set_sensitive(False)
        
        #update details 
        self.detail_toggle_button = gtk.ToggleButton(_("Details"))
        self.detail_btn_box = gtk.HButtonBox()
        self.detail_btn_box.set_layout(gtk.BUTTONBOX_START)
        self.details_vbox = HIGVBox()
        self.details_scroll = gtk.ScrolledWindow()
        self.details_textview = gtk.TextView()
        self.details_textview.set_size_request(100,120)
        self.details_textview.set_editable(False)
        self.details_textview.set_buffer(self._set_details_content())
    
        #bottom button
        self.close_btn = HIGButton(_("Close"))
        self.settings_btn = HIGButton(_("Settings"))
        
    def _pack_widgets(self):
        """"""
        self.all_box._pack_noexpand_nofill(self.soft_update_info_box)
        self.all_box._pack_expand_fill(self.soft_update_list_box)   
        self.all_box._pack_noexpand_nofill(self.check_btn_box)
        self.all_box._pack_noexpand_nofill(self.soft_update_detail_box)    
        self.all_box._pack_noexpand_nofill(self.bottom_btn_box)        
        
        self.soft_update_info_box._pack_noexpand_nofill(hig_box_space_holder())
        self.soft_update_info_box._pack_expand_fill(self.soft_update_table)      
        self.soft_update_list_box._pack_expand_fill(self.vbox_list)
                 
        self.soft_update_table.attach_label(self.update_icon,0,2,0,2,)
        self.soft_update_table.attach_label(self.version_information_label,2,4,0,1)
        self.soft_update_table.attach_label(self.latest_time_information_label,2,4,1,2)
        
        self.check_btn_box.set_layout(gtk.BUTTONBOX_END)
        self.check_btn_box.set_spacing(8)       
        self.check_btn_box.pack_start(self.check_btn)
        self.check_btn_box.pack_start(self.install_btn)

        self.detail_btn_box.set_spacing(8)       
        self.detail_btn_box.pack_start(self.detail_toggle_button)
                
        self.details_scroll.add(self.details_textview)
        self.details_vbox._pack_expand_fill(self.details_scroll)
        self.soft_update_detail_box._pack_expand_nofill(self.detail_btn_box) 
        self.soft_update_detail_box._pack_expand_fill(self.details_vbox)         
        
        self.bottom_btn_box.set_layout(gtk.BUTTONBOX_EDGE)
        self.bottom_btn_box.set_spacing(8)  
        self.bottom_btn_box.pack_start(self.settings_btn)         
        self.bottom_btn_box.pack_start(self.close_btn)
        
        self.add(self.all_box)
        
    def _connect_widgets(self):
        """"""
        self.check_btn.connect('clicked',lambda w:self._check_software())
        self.install_btn.connect('clicked',lambda w:self._install_software())
        self.close_btn.connect('clicked',lambda w:self._close()) 
        self.settings_btn.connect('clicked',lambda w:self._settings_windows()) 
        self.detail_toggle_button.connect('clicked',lambda w:self._show_details())
        self.treeview.connect('row-activated',self._on_activated)

    def _load_updates(self):
        """
        load the information from the DB
        """
        self.software_list_dict = {}
        cnt = 0
        #get details from the DB 
        rs = g_db_helper.select("select * from updates where is_update = %d" % no_updated)
        for record in rs:
            self.software_list_dict[cnt] = {}
            self.software_list_dict[cnt]["version"] = record[0]
            self.software_list_dict[cnt]["news_date"] = record[1]
            self.software_list_dict[cnt]["software_name"] = record[2]
            self.software_list_dict[cnt]["description"] = record[3]
            self.software_list_dict[cnt]["download_url"] = record[4] 
            self.software_list_dict[cnt]["is_update"] = record[5]
            self.software_list_dict[cnt]["check_code"] = record[6]
                                                                       
            cnt = cnt + 1    
        g_logger.info("Loaded %d updates from DB." % len(rs))       
        
        #output in the window
        if len(self.software_list_dict) == 0:
            self.install_btn.set_sensitive(False)
            g_logger.info("No new updates from UpdateMoule")
        else:
            self.treeview.set_sensitive(True)
            self.check_btn.set_sensitive(False)
            g_logger.debug("Show the records in the tree-view") 

            self.store.clear()           
            for line in self.software_list_dict.keys():
                self.store.append([self.software_list_dict[line]["news_date"],
                                   self.software_list_dict[line]["version"],
                                   self.software_list_dict[line]["software_name"]])
            
            self.treeview.set_model(self.store) #It must be after the store update
                
    #def create_model(self):
    #    store = gtk.ListStore(str,str,str)
    #    for act in stress:
    #        store.append([act[0],act[1],act[2]])
    #    return store
    
    def _get_value_from_db (self,key):
        """
        get value from the config in DB
        """
        rs = g_db_helper.select("select * from config where key = '%s'" % key)
        if rs == None or len(rs) != 1:
            g_logger.error("Wrong get the value from key:%s in config DB " % (key))   
            return 
        return str(rs[0][1])
    
    def _set_details_content(self,content=None):
        if content == None or content == "":
            content = str(_('Open Monitor Alpha is coming soon!\n Designed by UMIT'))
           
        buf = gtk.TextBuffer()
        buf.set_text(content)
        return buf
    
    def _show_details(self):
        """"""
        if (self.detail_toggle_button.get_active()):
            self.details_vbox.hide_all()
        else:
            self.details_vbox.show_all()
                 
    def _create_colums(self):
        """"""       
        for i in range(0,len(self.column_names)):
            rendererText = gtk.CellRendererText()
            column = gtk.TreeViewColumn(self.column_names[i],rendererText,text = i) #text attributes MUST!
            column.set_sort_column_id(i)
            self.treeview.append_column(column)
    
    def _on_activated(self,widget,row,col):
        """"""
        self.install_btn.set_sensitive(True)
        #choice
        selection = self.treeview.get_selection()
        (model,iter) = selection.get_selected()
        if iter == None:
            return
        else:
            cur_version = self.store.get_value(iter,1)
            #fill self.current_record
            rs = g_db_helper.select("select * from updates where version = '%s'" % cur_version)
            if len(rs) != 1:
                g_logger.error("Record is ERROR in DB!!!! The window will be closed!!!")
                self.destroy()
            self.current_record = {}
            
            self.current_record["version"] = rs[0][0]
            self.current_record["news_date"] = rs[0][1]
            self.current_record["software_name"] = rs[0][2]
            self.current_record["description"] = rs[0][3]
            self.current_record["download_url"] = rs[0][4] 
            self.current_record["is_update"] = rs[0][5]
            self.current_record["check_code"] = rs[0][6]            
              
            
            self.statusbar.push(0,_("You have selected the %s version" % \
                                self.current_record["version"])) 
           
            self.details_textview.set_buffer(self._set_details_content(_(self.current_record["description"] + "\n" + 
                                        "download:"+self.current_record["download_url"] + "\n" +
                                        "Designed by Umit!" 
                                        ))) 
            self.details_textview.show_all()
            g_logger.debug("Selected the item %s" % (self.current_record))              
    
    def _check_software(self):    
        """"""
        defer_ = theApp.aggregator.check_version()
        defer_.addCallback(self._handle_check_software)
        defer_.addErrback(self._handle_errback)
        
        return defer_
    
    def _handle_errback(self,failure):
        g_logger.error("auto check error:%s" % str(failure))          
    
    def _handle_check_software(self,message):
        if message == None:
            return
        
        g_logger.debug("Finish check the software update.")
        self.progress_bar.set_value(100)
        #self.progress_bar = gtk.ProgressBar(100)
        #show the record        
        self._load_updates()
        
    def _handle_errbdownloadURLack(self,failure):
        g_logger.error("Aggregator failure: %s" % str(failure))        
        
    def _check_software_test(self):
        """"""
        p = theApp.aggregator.check_version()
        print p
        self.progress_bar.set_value(100)
        
        #test: create some records
        result = {
                1:{"version":"0.9",
                   "news_date":"2012-1-1",
                   "software_name":"icm-agent",
                   "description":"test software update module icm-agent",
                   "download_url":"http://tianwei-wordpress.stor.sinaapp.com/uploads/2012/05/icm_agent_update.tar.gz",
                   "is_update":"1"},
                2:{"version":"1.1",
                   "news_date":"2012-5-21",
                   "software_name":"open monitor desktop",
                   "description":"test software update module open monitor 1.0",
                   "download_url":"http://tianwei-wordpress.stor.sinaapp.com/uploads/2012/05/icm_agent_update.tar.gz",
                   "is_update":"0"},
                3:{"version":"2.0",
                   "news_date":"2012-8-21",
                   "software_name":"open monitor desktop v2.0",
                   "description":"test software update module open monitor 2.0",
                   "download_url":"http://tianwei-wordpress.stor.sinaapp.com/uploads/2012/05/icm_agent_update.tar.gz",
                   "is_update":"0"},
                }
        #check the db and insert it
        if len(result) == 0:
            self.install_btn.set_sensitive(False)
            g_logger.info("No new updates from UpdateMoule")
            return            
        
        for key in result.keys():
            if not check_update_item_in_db(result[key]["version"]):
                insert_update_item_in_db(result[key])
        
        #show the record        
        self._load_updates()
        
    def _install_software(self):
        """"""
        self.progress_bar.set_value(0)
        if self.current_record == None or len(self.current_record) == 0:
            self.install_btn.set_sensitive(False)
            g_logger.info("No new updates to be installed")
            return

        print self.current_record 
        # download and install 
        if compare_version(self.current_record["version"],VERSION) == higher_version:
            g_logger.debug("The version is right for icm-agent")
            
            download_update(url=self.current_record["download_url"],
                            check_code = self.current_record["check_code"],
                            version=self.current_record["version"])
            self.install_btn.set_sensitive(False)
        else:
            g_logger.debug("The version is low than current icm-agent")
            self.statusbar.push(0,'The current is the lastest version!')
            self.install_btn.set_sensitive(False)
            self.check_btn.set_sensitive(True)
   
    def _close(self):
        """"""
        self.destroy()
    def _settings_windows(self):
        """"""
        theApp.gtk_main.show_preference()
        
    def _auto_update(self):
        """"""
        pass
    def _manually_update(self):
        """"""
        pass
Beispiel #13
0
    def _create_widgets(self):
        """"""
        #vbox
        self.all_box = HIGVBox()
        self.soft_update_info_box = HIGHBox()
        self.soft_update_list_box = HIGVBox()
        self.check_btn_box = gtk.HButtonBox()
        self.soft_update_detail_box = HIGVBox()
        self.bottom_btn_box = gtk.HButtonBox()

        #software update information title
        self.update_icon = gtk.Image()
        self.update_icon.set_from_file(
            os.path.join(IMAGES_DIR, 'software_update.ico'))
        self.version_information_label = HIGLabel(
            _("The newest open monitor in your computer!"))
        self.latest_time_information_label = HIGLabel(
            _(self.latest_update_time))
        self.soft_update_table = HIGTable()

        #software list
        self.column_names = ['Date', 'Version', 'Name']

        self.vbox_list = gtk.VBox(False, 8)
        self.scroll_window_vbox = gtk.ScrolledWindow()
        self.scroll_window_vbox.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        self.scroll_window_vbox.set_policy(gtk.POLICY_AUTOMATIC,
                                           gtk.POLICY_AUTOMATIC)
        self.vbox_list.pack_start(self.scroll_window_vbox, True, True, 0)
        self.store = gtk.ListStore(str, str, str)
        self.treeview = gtk.TreeView()

        self.treeview.set_rules_hint(True)
        self.treeview.set_sensitive(False)
        self.vbox_list.set_size_request(100, 100)
        self.scroll_window_vbox.add(self.treeview)

        self._create_colums()
        self.statusbar = gtk.Statusbar()
        self.statusbar.push(0, 'No update!')

        self.vbox_list.pack_start(self.statusbar, False, False, 0)

        self.progress_bar = gtk.ProgressBar()
        self.progress_bar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
        self.progress_bar.set_fraction(0.0)

        self.vbox_list.pack_start(self.progress_bar, False, False, 0)
        #button about the update
        self.check_btn = HIGButton(_("Check"))
        self.install_btn = HIGButton(_("Install"))
        self.install_btn.set_sensitive(False)

        #update details
        self.detail_toggle_button = gtk.ToggleButton(_("Details"))
        self.detail_btn_box = gtk.HButtonBox()
        self.detail_btn_box.set_layout(gtk.BUTTONBOX_START)
        self.details_vbox = HIGVBox()
        self.details_scroll = gtk.ScrolledWindow()
        self.details_textview = gtk.TextView()
        self.details_textview.set_size_request(100, 120)
        self.details_textview.set_editable(False)
        self.details_textview.set_buffer(self._set_details_content())

        #bottom button
        self.close_btn = HIGButton(_("Close"))
        self.settings_btn = HIGButton(_("Settings"))
Beispiel #14
0
class SoftwareUpdateDialog(HIGWindow):
    """"""
    def __init__(self):
        """Constructor"""
        HIGWindow.__init__(self, type=gtk.WINDOW_TOPLEVEL)
        self.set_title(_("Open Monitor Software Update Manager"))
        self.set_position(gtk.WIN_POS_CENTER_ALWAYS)
        self.set_size_request(480, 480)
        self.set_keep_above(True)
        self.set_border_width(10)

        self._create_record()
        self._create_widgets()
        self._pack_widgets()
        self._connect_widgets()

    def _create_record(self):

        self.software_list_dict = {}
        self.software_details_dict = {
            "version": "",
            "news_date": "",
            "software_name": "",
            "description": "",
            "download_url": "",
            "is_update": "",
            "check_code": ""
        }
        self.current_record = {}
        #get history update information
        self.latest_update_time = "The lastest update time is " + self._get_value_from_db(
            "update_time")

    def _create_widgets(self):
        """"""
        #vbox
        self.all_box = HIGVBox()
        self.soft_update_info_box = HIGHBox()
        self.soft_update_list_box = HIGVBox()
        self.check_btn_box = gtk.HButtonBox()
        self.soft_update_detail_box = HIGVBox()
        self.bottom_btn_box = gtk.HButtonBox()

        #software update information title
        self.update_icon = gtk.Image()
        self.update_icon.set_from_file(
            os.path.join(IMAGES_DIR, 'software_update.ico'))
        self.version_information_label = HIGLabel(
            _("The newest open monitor in your computer!"))
        self.latest_time_information_label = HIGLabel(
            _(self.latest_update_time))
        self.soft_update_table = HIGTable()

        #software list
        self.column_names = ['Date', 'Version', 'Name']

        self.vbox_list = gtk.VBox(False, 8)
        self.scroll_window_vbox = gtk.ScrolledWindow()
        self.scroll_window_vbox.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        self.scroll_window_vbox.set_policy(gtk.POLICY_AUTOMATIC,
                                           gtk.POLICY_AUTOMATIC)
        self.vbox_list.pack_start(self.scroll_window_vbox, True, True, 0)
        self.store = gtk.ListStore(str, str, str)
        self.treeview = gtk.TreeView()

        self.treeview.set_rules_hint(True)
        self.treeview.set_sensitive(False)
        self.vbox_list.set_size_request(100, 100)
        self.scroll_window_vbox.add(self.treeview)

        self._create_colums()
        self.statusbar = gtk.Statusbar()
        self.statusbar.push(0, 'No update!')

        self.vbox_list.pack_start(self.statusbar, False, False, 0)

        self.progress_bar = gtk.ProgressBar()
        self.progress_bar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
        self.progress_bar.set_fraction(0.0)

        self.vbox_list.pack_start(self.progress_bar, False, False, 0)
        #button about the update
        self.check_btn = HIGButton(_("Check"))
        self.install_btn = HIGButton(_("Install"))
        self.install_btn.set_sensitive(False)

        #update details
        self.detail_toggle_button = gtk.ToggleButton(_("Details"))
        self.detail_btn_box = gtk.HButtonBox()
        self.detail_btn_box.set_layout(gtk.BUTTONBOX_START)
        self.details_vbox = HIGVBox()
        self.details_scroll = gtk.ScrolledWindow()
        self.details_textview = gtk.TextView()
        self.details_textview.set_size_request(100, 120)
        self.details_textview.set_editable(False)
        self.details_textview.set_buffer(self._set_details_content())

        #bottom button
        self.close_btn = HIGButton(_("Close"))
        self.settings_btn = HIGButton(_("Settings"))

    def _pack_widgets(self):
        """"""
        self.all_box._pack_noexpand_nofill(self.soft_update_info_box)
        self.all_box._pack_expand_fill(self.soft_update_list_box)
        self.all_box._pack_noexpand_nofill(self.check_btn_box)
        self.all_box._pack_noexpand_nofill(self.soft_update_detail_box)
        self.all_box._pack_noexpand_nofill(self.bottom_btn_box)

        self.soft_update_info_box._pack_noexpand_nofill(hig_box_space_holder())
        self.soft_update_info_box._pack_expand_fill(self.soft_update_table)
        self.soft_update_list_box._pack_expand_fill(self.vbox_list)

        self.soft_update_table.attach_label(
            self.update_icon,
            0,
            2,
            0,
            2,
        )
        self.soft_update_table.attach_label(self.version_information_label, 2,
                                            4, 0, 1)
        self.soft_update_table.attach_label(self.latest_time_information_label,
                                            2, 4, 1, 2)

        self.check_btn_box.set_layout(gtk.BUTTONBOX_END)
        self.check_btn_box.set_spacing(8)
        self.check_btn_box.pack_start(self.check_btn)
        self.check_btn_box.pack_start(self.install_btn)

        self.detail_btn_box.set_spacing(8)
        self.detail_btn_box.pack_start(self.detail_toggle_button)

        self.details_scroll.add(self.details_textview)
        self.details_vbox._pack_expand_fill(self.details_scroll)
        self.soft_update_detail_box._pack_expand_nofill(self.detail_btn_box)
        self.soft_update_detail_box._pack_expand_fill(self.details_vbox)

        self.bottom_btn_box.set_layout(gtk.BUTTONBOX_EDGE)
        self.bottom_btn_box.set_spacing(8)
        self.bottom_btn_box.pack_start(self.settings_btn)
        self.bottom_btn_box.pack_start(self.close_btn)

        self.add(self.all_box)

    def _connect_widgets(self):
        """"""
        self.check_btn.connect('clicked', lambda w: self._check_software())
        self.install_btn.connect('clicked', lambda w: self._install_software())
        self.close_btn.connect('clicked', lambda w: self._close())
        self.settings_btn.connect('clicked',
                                  lambda w: self._settings_windows())
        self.detail_toggle_button.connect('clicked',
                                          lambda w: self._show_details())
        self.treeview.connect('row-activated', self._on_activated)

    def _load_updates(self):
        """
        load the information from the DB
        """
        self.software_list_dict = {}
        cnt = 0
        #get details from the DB
        rs = g_db_helper.select("select * from updates where is_update = %d" %
                                no_updated)
        for record in rs:
            self.software_list_dict[cnt] = {}
            self.software_list_dict[cnt]["version"] = record[0]
            self.software_list_dict[cnt]["news_date"] = record[1]
            self.software_list_dict[cnt]["software_name"] = record[2]
            self.software_list_dict[cnt]["description"] = record[3]
            self.software_list_dict[cnt]["download_url"] = record[4]
            self.software_list_dict[cnt]["is_update"] = record[5]
            self.software_list_dict[cnt]["check_code"] = record[6]

            cnt = cnt + 1
        g_logger.info("Loaded %d updates from DB." % len(rs))

        #output in the window
        if len(self.software_list_dict) == 0:
            self.install_btn.set_sensitive(False)
            g_logger.info("No new updates from UpdateMoule")
        else:
            self.treeview.set_sensitive(True)
            self.check_btn.set_sensitive(False)
            g_logger.debug("Show the records in the tree-view")

            self.store.clear()
            for line in self.software_list_dict.keys():
                self.store.append([
                    self.software_list_dict[line]["news_date"],
                    self.software_list_dict[line]["version"],
                    self.software_list_dict[line]["software_name"]
                ])

            self.treeview.set_model(
                self.store)  #It must be after the store update

    #def create_model(self):
    #    store = gtk.ListStore(str,str,str)
    #    for act in stress:
    #        store.append([act[0],act[1],act[2]])
    #    return store

    def _get_value_from_db(self, key):
        """
        get value from the config in DB
        """
        rs = g_db_helper.select("select * from config where key = '%s'" % key)
        if rs == None or len(rs) != 1:
            g_logger.error("Wrong get the value from key:%s in config DB " %
                           (key))
            return
        return str(rs[0][1])

    def _set_details_content(self, content=None):
        if content == None or content == "":
            content = str(
                _('Open Monitor Alpha is coming soon!\n Designed by UMIT'))

        buf = gtk.TextBuffer()
        buf.set_text(content)
        return buf

    def _show_details(self):
        """"""
        if (self.detail_toggle_button.get_active()):
            self.details_vbox.hide_all()
        else:
            self.details_vbox.show_all()

    def _create_colums(self):
        """"""
        for i in range(0, len(self.column_names)):
            rendererText = gtk.CellRendererText()
            column = gtk.TreeViewColumn(self.column_names[i],
                                        rendererText,
                                        text=i)  #text attributes MUST!
            column.set_sort_column_id(i)
            self.treeview.append_column(column)

    def _on_activated(self, widget, row, col):
        """"""
        self.install_btn.set_sensitive(True)
        #choice
        selection = self.treeview.get_selection()
        (model, iter) = selection.get_selected()
        if iter == None:
            return
        else:
            cur_version = self.store.get_value(iter, 1)
            #fill self.current_record
            rs = g_db_helper.select(
                "select * from updates where version = '%s'" % cur_version)
            if len(rs) != 1:
                g_logger.error(
                    "Record is ERROR in DB!!!! The window will be closed!!!")
                self.destroy()
            self.current_record = {}

            self.current_record["version"] = rs[0][0]
            self.current_record["news_date"] = rs[0][1]
            self.current_record["software_name"] = rs[0][2]
            self.current_record["description"] = rs[0][3]
            self.current_record["download_url"] = rs[0][4]
            self.current_record["is_update"] = rs[0][5]
            self.current_record["check_code"] = rs[0][6]


            self.statusbar.push(0,_("You have selected the %s version" % \
                                self.current_record["version"]))

            self.details_textview.set_buffer(
                self._set_details_content(
                    _(self.current_record["description"] + "\n" + "download:" +
                      self.current_record["download_url"] + "\n" +
                      "Designed by Umit!")))
            self.details_textview.show_all()
            g_logger.debug("Selected the item %s" % (self.current_record))

    def _check_software(self):
        """"""
        defer_ = theApp.aggregator.check_version()
        defer_.addCallback(self._handle_check_software)
        defer_.addErrback(self._handle_errback)

        return defer_

    def _handle_errback(self, failure):
        g_logger.error("auto check error:%s" % str(failure))

    def _handle_check_software(self, message):
        if message == None:
            return

        g_logger.debug("Finish check the software update.")
        self.progress_bar.set_value(100)
        #self.progress_bar = gtk.ProgressBar(100)
        #show the record
        self._load_updates()

    def _handle_errbdownloadURLack(self, failure):
        g_logger.error("Aggregator failure: %s" % str(failure))

    def _check_software_test(self):
        """"""
        p = theApp.aggregator.check_version()
        print p
        self.progress_bar.set_value(100)

        #test: create some records
        result = {
            1: {
                "version": "0.9",
                "news_date": "2012-1-1",
                "software_name": "icm-agent",
                "description": "test software update module icm-agent",
                "download_url":
                "http://tianwei-wordpress.stor.sinaapp.com/uploads/2012/05/icm_agent_update.tar.gz",
                "is_update": "1"
            },
            2: {
                "version": "1.1",
                "news_date": "2012-5-21",
                "software_name": "open monitor desktop",
                "description": "test software update module open monitor 1.0",
                "download_url":
                "http://tianwei-wordpress.stor.sinaapp.com/uploads/2012/05/icm_agent_update.tar.gz",
                "is_update": "0"
            },
            3: {
                "version": "2.0",
                "news_date": "2012-8-21",
                "software_name": "open monitor desktop v2.0",
                "description": "test software update module open monitor 2.0",
                "download_url":
                "http://tianwei-wordpress.stor.sinaapp.com/uploads/2012/05/icm_agent_update.tar.gz",
                "is_update": "0"
            },
        }
        #check the db and insert it
        if len(result) == 0:
            self.install_btn.set_sensitive(False)
            g_logger.info("No new updates from UpdateMoule")
            return

        for key in result.keys():
            if not check_update_item_in_db(result[key]["version"]):
                insert_update_item_in_db(result[key])

        #show the record
        self._load_updates()

    def _install_software(self):
        """"""
        self.progress_bar.set_value(0)
        if self.current_record == None or len(self.current_record) == 0:
            self.install_btn.set_sensitive(False)
            g_logger.info("No new updates to be installed")
            return

        print self.current_record
        # download and install
        if compare_version(self.current_record["version"],
                           VERSION) == higher_version:
            g_logger.debug("The version is right for icm-agent")

            download_update(url=self.current_record["download_url"],
                            check_code=self.current_record["check_code"],
                            version=self.current_record["version"])
            self.install_btn.set_sensitive(False)
        else:
            g_logger.debug("The version is low than current icm-agent")
            self.statusbar.push(0, 'The current is the lastest version!')
            self.install_btn.set_sensitive(False)
            self.check_btn.set_sensitive(True)

    def _close(self):
        """"""
        self.destroy()

    def _settings_windows(self):
        """"""
        theApp.gtk_main.show_preference()

    def _auto_update(self):
        """"""
        pass

    def _manually_update(self):
        """"""
        pass
class TLHoder(gtk.VBox):
    
    def __init__(self,dashboard,connector=None): #maybe import some kinds(report,task,connection,Throttled,Service)
        """
        Load timeline for every report(sent or unsent), test successful or failed (website or service)
        task (done or not), Throttled details(different charts)
        """ 
        
        gtk.VBox.__init__(self)
        
        self.connector = connector
        self.dashboard = dashboard
        
        self.base = TimeLineBase(self.connector,self.dashboard)    #Maybe add some items
        
        self.__create_widgets()
        self.__packed_widgets()
        self.__connect_widgets()
        
    def __create_widgets(self):
        """
        """
        # startup data
        line_filter, start, evts = self.base.grab_data()
        xlabel = self.base.xlabel
        glabel = self.base.title_by_graphmode()
        dlabel = self.base.descr_by_graphmode()
        
        #Box
        self.box = HIGVBox()
        
        #graph
        self.graph_box = gtk.HBox()
        self.graph = InteractiveGraph(evts, start, x_label=xlabel,
            y_label=_('Number of events'), graph_label=glabel,
            descr_label=dlabel, vdiv_labels=self.base.labels,
            line_filter=line_filter, connector=self.connector)
        
        #graph toolbar
        self.graphtb = TimeLineGraphToolbar(self.graph, self.connector,
                                            self.base.graph_mode,self.base.graph_kind,
                                            self.base)
        
        #TODO: Add Display Bar in the further
    
    def __packed_widgets(self):
        """
        """
        self.graph_box.add(self.graph)
        
        self.box._pack_noexpand_nofill(self.graphtb)
        self.box._pack_expand_fill(self.graph_box)
        
        self.add(self.box)
                
        self.show_all()
        
    def __connect_widgets(self):
        """
        Handle the connector signals
        """
        self.connector.connect('data_update',self._update_graph)
        #TODO: we should add signals for the changes of left treeview
    
    def _update_graph(self,obj,*args):
        """
        New graph data arrived
        """    
        line_filter, start, evts, labels, xlabel, glabel, dlabel = args
        
        # new graph data
        self.graph.start_pts_data = start
        self.graph.graph_data = evts
        
        # find new max value
        self.graph.find_max_value()
        
        # update graph labels
        self.graph.xlabel = xlabel
        self.graph.graph_label = glabel
        self.graph.descr_label = dlabel
        self.graph.vdiv_labels = labels
        
        # do graph animation with new data
        self.graph.do_animation()                                        
class TLHoder(gtk.VBox):
    def __init__(
        self,
        dashboard,
        connector=None
    ):  #maybe import some kinds(report,task,connection,Throttled,Service)
        """
        Load timeline for every report(sent or unsent), test successful or failed (website or service)
        task (done or not), Throttled details(different charts)
        """

        gtk.VBox.__init__(self)

        self.connector = connector
        self.dashboard = dashboard

        self.base = TimeLineBase(self.connector,
                                 self.dashboard)  #Maybe add some items

        self.__create_widgets()
        self.__packed_widgets()
        self.__connect_widgets()

    def __create_widgets(self):
        """
        """
        # startup data
        line_filter, start, evts = self.base.grab_data()
        xlabel = self.base.xlabel
        glabel = self.base.title_by_graphmode()
        dlabel = self.base.descr_by_graphmode()

        #Box
        self.box = HIGVBox()

        #graph
        self.graph_box = gtk.HBox()
        self.graph = InteractiveGraph(evts,
                                      start,
                                      x_label=xlabel,
                                      y_label=_('Number of events'),
                                      graph_label=glabel,
                                      descr_label=dlabel,
                                      vdiv_labels=self.base.labels,
                                      line_filter=line_filter,
                                      connector=self.connector)

        #graph toolbar
        self.graphtb = TimeLineGraphToolbar(self.graph, self.connector,
                                            self.base.graph_mode,
                                            self.base.graph_kind, self.base)

        #TODO: Add Display Bar in the further

    def __packed_widgets(self):
        """
        """
        self.graph_box.add(self.graph)

        self.box._pack_noexpand_nofill(self.graphtb)
        self.box._pack_expand_fill(self.graph_box)

        self.add(self.box)

        self.show_all()

    def __connect_widgets(self):
        """
        Handle the connector signals
        """
        self.connector.connect('data_update', self._update_graph)
        #TODO: we should add signals for the changes of left treeview

    def _update_graph(self, obj, *args):
        """
        New graph data arrived
        """
        line_filter, start, evts, labels, xlabel, glabel, dlabel = args

        # new graph data
        self.graph.start_pts_data = start
        self.graph.graph_data = evts

        # find new max value
        self.graph.find_max_value()

        # update graph labels
        self.graph.xlabel = xlabel
        self.graph.graph_label = glabel
        self.graph.descr_label = dlabel
        self.graph.vdiv_labels = labels

        # do graph animation with new data
        self.graph.do_animation()