#!/usr/bin/python
#
# Graphical Hardware Management interface for Kudzu
# Copyright (c) 2001 Red Hat, Inc. All rights reserved.
#
# This software may be freely redistributed under the terms of the GNU
# public license.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Author: Jonathan Blandford <jrb@redhat.com>


import os, sys
import signal
import gobject

if __name__ == "__main__":
    signal.signal (signal.SIGINT, signal.SIG_DFL)

##
## I18N
## 
from rhpl.translate import _, N_
import rhpl.translate as translate
domain = 'hwbrowser'
translate.textdomain (domain)

(read, write) = os.pipe ()
(read2, write2) = os.pipe()
pid = os.fork ()
if pid == 0:
    os.close (write)
    os.close (read2)
    import gtk
    import gnome.ui
    def input_callback (*args):
        os._exit (0)
        
    gtk.input_add (read, gtk.gdk.INPUT_READ, input_callback)
    dialog = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO,
                                gtk.BUTTONS_CANCEL,
                                _("Searching for hardware...\n\nNOTE: This may take a while, and your system may\nbecome unresponsive during this operation."))
    if (dialog.run() == gtk.RESPONSE_CANCEL):
        os.write(write2, "die")
    os._exit(0)

def input_callback (*args):
    os._exit (0)
        
import gtk
gtk.input_add (read2, gtk.gdk.INPUT_READ, input_callback)
from gtk import TRUE, FALSE
import gtk.glade
import kudzu
import string
import parted
import DeviceGeneric
import DeviceDisk

import gnome
gnome.program_init("hwbrowser", "0.15")

gtk.glade.bindtextdomain(domain)

class DeviceList (type({})):
    type_mapping = {
        kudzu.CLASS_AUDIO : _("Sound cards"),
        kudzu.CLASS_CAPTURE : _("Capture devices"),
        kudzu.CLASS_CDROM : _("CD-ROM Drives"),
        kudzu.CLASS_FIREWIRE : _("Firewire"),
        kudzu.CLASS_FLOPPY : _("Floppy Disks"),
        kudzu.CLASS_HD : _("Hard Drives"),
        kudzu.CLASS_IDE : _("IDE Controllers"),
        kudzu.CLASS_KEYBOARD : _("Keyboards"),
        kudzu.CLASS_MODEM : _("Modems"),
        kudzu.CLASS_MONITOR : _("Monitors"),
        kudzu.CLASS_MOUSE : _("Pointing devices"),
        kudzu.CLASS_NETWORK : _("Network devices"),
        kudzu.CLASS_OTHER : _("System devices"),
        kudzu.CLASS_PRINTER : _("Printers"),
        kudzu.CLASS_RAID : _("RAID devices"),
        kudzu.CLASS_SCANNER : _("Scanners"),
        kudzu.CLASS_SCSI : _("SCSI devices"),
        kudzu.CLASS_SOCKET : _("PCMCIA/PC-Card devices"),
        kudzu.CLASS_TAPE : _("Tape Drives"),
        kudzu.CLASS_UNSPEC : _("Unknown devices"),
        kudzu.CLASS_USB : _("USB devices"),
        kudzu.CLASS_VIDEO : _("Video cards"),
        }

    def __init__ (self):
        self.data = {}
        self.hardware_read ()

    def get_category_string (self, key):
        return self.type_mapping[key]

    def hardware_read (self):
        for kudzu_device in kudzu.probe(kudzu.CLASS_UNSPEC, kudzu.BUS_UNSPEC, kudzu.PROBE_SAFE):
            device = DeviceType (kudzu_device)
            try:
                self[kudzu_device.deviceclass].append (device)
            except KeyError:
                self[kudzu_device.deviceclass] = [device]

    def hydrate_key (self, key):
        notebook = xml.get_widget ('category_notebook')
        if key == kudzu.CLASS_HD:
            notebook.set_current_page (1)
#        elif key == kudzu.CLASS_VIDEO:
#            notebook.set_page (2)
        else:
            notebook.set_current_page (0)
            DeviceGeneric.hydrate (self[key])
        
class DeviceType:
    def __init__ (self, kudzu_device):
        self.kudzu_device = kudzu_device

    def get_name (self):
        if string.find (self.kudzu_device.desc, "|") != -1:
            dummy, desc = string.split (self.kudzu_device.desc, "|")
        else:
            desc = self.kudzu_device.desc
        return desc


try:
    gladepath = "hwbrowser.glade"
    if not os.path.exists (gladepath):
        gladepath = "/usr/share/hwbrowser/" + gladepath
    xml = gtk.glade.XML (gladepath, domain="hwbrowser")
    hardware = DeviceList ()
except:
    os.write (write, "die")
    dialog = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR,
                                gtk.BUTTONS_CLOSE,
                                _("An error occurred while searching for hardware."))
    dialog.run ()
    os._exit (0)

while (gtk.events_pending()):
    gtk.mainiteration()

if pid != 0:
    os.write (write, "die")
    os.close (write)
    
def reread_device_type_list ():
    tree_view= xml.get_widget ('device_type_treeview')
    list = tree_view.get_model ()
    list.clear ()
    for key in hardware.keys ():
        iter = list.append ()
        list.set (iter, 0, hardware.get_category_string (key), 1, key)
    tree_view.get_selection().select_path ((0,))

def setup_disk_view ():
    pass

def on_device_type_select_row (selection):
    (model, iter) = selection.get_selected ()
    key = model.get_value (iter, 1)
    hardware.hydrate_key (key)
#    key = clist.get_row_data (row)
#    if key == None:
#        return
#    hardware.hydrate_key (key)

def setup_ui ():
    try:
        DeviceGeneric.initialize (xml, hardware)
        DeviceDisk.initialize (xml, hardware)
    except:
        import traceback
        dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL,
                                   gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,
                                   string.join(traceback.format_exception(sys.exc_info()[0],
                                                                          sys.exc_info()[1],
                                                                          sys.exc_info()[2])))
        dialog.run()
        gtk.mainquit()
        os._exit(1)
        

def on_delete_event (*args):
    gtk.mainquit ()

if __name__ == "__main__":
    signal.signal (signal.SIGINT, signal.SIG_DFL)
    setup_ui ()
    xml.signal_autoconnect ({
        "on_delete_event" : on_delete_event
        })
#        "on_device_type_clist_select_row" : on_device_type_clist_select_row,

    tree_view = xml.get_widget ('device_type_treeview')
    tree_view.get_selection ().set_mode (gtk.SELECTION_BROWSE)
    tree_view.get_selection ().connect ("changed", on_device_type_select_row)
    model = gtk.ListStore (gobject.TYPE_STRING, gobject.TYPE_INT)
    model.set_sort_column_id (0, gtk.SORT_ASCENDING)
    tree_view.set_model (model)
    column = gtk.TreeViewColumn ()
    renderer = gtk.CellRendererText ()
    column.pack_start (renderer, TRUE)
    column.add_attribute (renderer, "text", 0)
    tree_view.append_column (column)
    reread_device_type_list ()
    xml.get_widget("main_window").show_all()
    gtk.mainloop ()
