#Boa:Frame:TunapieFrame
#TunaPie (c)2005-2008 James Stone. Released under the GNU GPL.
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
#Written using Boa-Constructor.
#http://boa-constructor.sourceforge.net/
#
#Version 2.0.15 10/10/08

import wx
from wx.lib.anchors import LayoutAnchors
import wx.grid
import tuner
import RecordTime
import TunerPrefs
import AboutTuner
import RecordQueue
import TunerInfoDialog
import AddStream
import os
import socket
import time
import thread
import urllib
import getpass
import TunaSearch
import commands
import select

searchname=""

def create(parent):
    return TunapieFrame(parent)

[wxID_TUNAPIEFRAME, wxID_TUNAPIEFRAMEFAVELISTCTRL, 
 wxID_TUNAPIEFRAMEFAVESPLITTER, wxID_TUNAPIEFRAMEGENREBOX, 
 wxID_TUNAPIEFRAMEMAINLISTCTRL, wxID_TUNAPIEFRAMEMAINSPLITTER, 
 wxID_TUNAPIEFRAMETUNAPIESTATUS, wxID_TUNAPIEFRAMETUNAPIETOOLBAR, 
] = [wx.NewId() for _init_ctrls in range(8)]

[wxID_FRAME1TOOLBAR1TOOLS0, wxID_FRAME1TOOLBAR1TOOLS1, 
 wxID_FRAME1TOOLBAR1TOOLS2, 
] = [wx.NewId() for _init_coll_toolBar1_Tools in range(3)]

[wxID_TUNAPIEFRAMETUNAPIETOOLBARADDFAVE, wxID_TUNAPIEFRAMETUNAPIETOOLBARFIND, 
 wxID_TUNAPIEFRAMETUNAPIETOOLBARINFO, wxID_TUNAPIEFRAMETUNAPIETOOLBARPLAY, 
 wxID_TUNAPIEFRAMETUNAPIETOOLBARRADIO, wxID_TUNAPIEFRAMETUNAPIETOOLBARREC, 
 wxID_TUNAPIEFRAMETUNAPIETOOLBARREMFAVE, wxID_TUNAPIEFRAMETUNAPIETOOLBARSTOP, 
 wxID_TUNAPIEFRAMETUNAPIETOOLBARTV, 
] = [wx.NewId() for _init_coll_TunapieToolBar_Tools in range(9)]

[wxID_TUNAPIEFRAMEMAINCONTEXTADDFAVE, wxID_TUNAPIEFRAMEMAINCONTEXTINFO, 
 wxID_TUNAPIEFRAMEMAINCONTEXTPLAY, wxID_TUNAPIEFRAMEMAINCONTEXTRECORD, 
] = [wx.NewId() for _init_coll_maincontext_Items in range(4)]

[wxID_TUNAPIEFRAMEFAVECONTEXTINFO, wxID_TUNAPIEFRAMEFAVECONTEXTPLAY, 
 wxID_TUNAPIEFRAMEFAVECONTEXTRECORD, wxID_TUNAPIEFRAMEFAVECONTEXTREMOVE,
 wxID_TUNAPIEFRAMEFAVECONTEXTADDURL] = [wx.NewId() for _init_coll_favecontext_Items in range(5)]

[wxID_TUNAPIEFRAMEFILEMENUPREFERENCES, wxID_TUNAPIEFRAMEFILEMENUQUIT, 
 wxID_TUNAPIEFRAMEFILEMENURECORDQUEUE, wxID_TUNAPIEFRAMEFILEMENURELOAD, 
] = [wx.NewId() for _init_coll_Filemenu_Items in range(4)]

[wxID_TUNAPIEFRAMEHELPMENUABOUT] = [wx.NewId() for _init_coll_Helpmenu_Items in range(1)]

class TunapieFrame(wx.Frame):
    def _init_coll_maincontext_Items(self, parent):
        # generated method, don't edit

        parent.Append(help='', id=wxID_TUNAPIEFRAMEMAINCONTEXTPLAY,
              kind=wx.ITEM_NORMAL, text=u'Play')
        parent.Append(help='', id=wxID_TUNAPIEFRAMEMAINCONTEXTINFO,
              kind=wx.ITEM_NORMAL, text=u'Info')
        parent.Append(help='', id=wxID_TUNAPIEFRAMEMAINCONTEXTRECORD,
              kind=wx.ITEM_NORMAL, text=u'Record')
        parent.Append(help='', id=wxID_TUNAPIEFRAMEMAINCONTEXTADDFAVE,
              kind=wx.ITEM_NORMAL, text=u'Add to Favorites')
        self.Bind(wx.EVT_MENU, self.OnMaincontextAddfaveMenu,
              id=wxID_TUNAPIEFRAMEMAINCONTEXTADDFAVE)
        self.Bind(wx.EVT_MENU, self.OnMaincontextPlayMenu,
              id=wxID_TUNAPIEFRAMEMAINCONTEXTPLAY)
        self.Bind(wx.EVT_MENU, self.OnMaincontextRecordMenu,
              id=wxID_TUNAPIEFRAMEMAINCONTEXTRECORD)
        self.Bind(wx.EVT_MENU, self.OnMaincontextInfoMenu,
              id=wxID_TUNAPIEFRAMEMAINCONTEXTINFO)

    def _init_coll_favecontext_Items(self, parent):
        # generated method, don't edit

        parent.Append(help='', id=wxID_TUNAPIEFRAMEFAVECONTEXTPLAY,
              kind=wx.ITEM_NORMAL, text=u'Play')
        parent.Append(help='', id=wxID_TUNAPIEFRAMEFAVECONTEXTINFO,
              kind=wx.ITEM_NORMAL, text=u'Info')
        parent.Append(help='', id=wxID_TUNAPIEFRAMEFAVECONTEXTRECORD,
              kind=wx.ITEM_NORMAL, text=u'Record')
        parent.Append(help='', id=wxID_TUNAPIEFRAMEFAVECONTEXTREMOVE,
              kind=wx.ITEM_NORMAL, text=u'Remove From Favorites')
        parent.Append(help='', id=wxID_TUNAPIEFRAMEFAVECONTEXTADDURL,
              kind=wx.ITEM_NORMAL, text=u'Add User Defined Station')
        self.Bind(wx.EVT_MENU, self.OnFavecontextPlayMenu,
              id=wxID_TUNAPIEFRAMEFAVECONTEXTPLAY)
        self.Bind(wx.EVT_MENU, self.OnFavecontextRemoveMenu,
              id=wxID_TUNAPIEFRAMEFAVECONTEXTREMOVE)
        self.Bind(wx.EVT_MENU, self.OnFavecontextRecordMenu,
              id=wxID_TUNAPIEFRAMEFAVECONTEXTRECORD)
        self.Bind(wx.EVT_MENU, self.OnFavecontextInfoMenu,
              id=wxID_TUNAPIEFRAMEFAVECONTEXTINFO)
        self.Bind(wx.EVT_MENU, self.OnFavecontextURLMenu,
              id=wxID_TUNAPIEFRAMEFAVECONTEXTADDURL)

    def _init_coll_menuBar1_Menus(self, parent):
        # generated method, don't edit

        parent.Append(menu=self.Filemenu, title=u'File')
        parent.Append(menu=self.Helpmenu, title=u'Help')

    def _init_coll_Helpmenu_Items(self, parent):
        # generated method, don't edit

        parent.Append(help='', id=wxID_TUNAPIEFRAMEHELPMENUABOUT,
              kind=wx.ITEM_NORMAL, text=u'About')
        self.Bind(wx.EVT_MENU, self.OnHelpmenuAboutMenu,
              id=wxID_TUNAPIEFRAMEHELPMENUABOUT)

    def _init_coll_Filemenu_Items(self, parent):
        # generated method, don't edit

        parent.Append(help='', id=wxID_TUNAPIEFRAMEFILEMENUPREFERENCES,
              kind=wx.ITEM_NORMAL, text=u'Preferences')
        parent.Append(help='', id=wxID_TUNAPIEFRAMEFILEMENURECORDQUEUE,
              kind=wx.ITEM_NORMAL, text=u'Record Queue')
        parent.Append(help='', id=wxID_TUNAPIEFRAMEFILEMENURELOAD,
              kind=wx.ITEM_NORMAL, text=u'Reload')
        parent.Append(help='', id=wxID_TUNAPIEFRAMEFILEMENUQUIT,
              kind=wx.ITEM_NORMAL, text=u'Quit')
        self.Bind(wx.EVT_MENU, self.OnFilemenuPreferencesMenu,
              id=wxID_TUNAPIEFRAMEFILEMENUPREFERENCES)
        self.Bind(wx.EVT_MENU, self.OnFilemenuRecordqueueMenu,
              id=wxID_TUNAPIEFRAMEFILEMENURECORDQUEUE)
        self.Bind(wx.EVT_MENU, self.OnFilemenuReloadMenu,
              id=wxID_TUNAPIEFRAMEFILEMENURELOAD)
        self.Bind(wx.EVT_MENU, self.OnFilemenuQuitMenu,
              id=wxID_TUNAPIEFRAMEFILEMENUQUIT)

    def _init_coll_MainListCtrl_Columns(self, parent):
        # generated method, don't edit

        parent.InsertColumn(col=0, format=wx.LIST_FORMAT_LEFT,
              heading=u'Station Name', width=200)
        parent.InsertColumn(col=1, format=wx.LIST_FORMAT_LEFT, heading=u'Genre',
              width=150)
        parent.InsertColumn(col=2, format=wx.LIST_FORMAT_LEFT,
              heading=u'Bitrate', width=100)
        parent.InsertColumn(col=3, format=wx.LIST_FORMAT_LEFT,
              heading=u'Listeners', width=100)
        parent.InsertColumn(col=4, format=wx.LIST_FORMAT_LEFT,
              heading=u'TV/Radio', width=100)
        parent.InsertColumn(col=5, format=wx.LIST_FORMAT_LEFT,
              heading=u'Now Playing', width=150)

    def _init_coll_TunapieStatus_Fields(self, parent):
        # generated method, don't edit
        parent.SetFieldsCount(1)

        parent.SetStatusText(number=0, text=u'')

        parent.SetStatusWidths([-1])

    def _init_coll_FaveListCtrl_Columns(self, parent):
        # generated method, don't edit

        parent.InsertColumn(col=0, format=wx.LIST_FORMAT_LEFT,
              heading=u'Favorites', width=200)
        parent.InsertColumn(col=1, format=wx.LIST_FORMAT_LEFT, heading=u'Genre',
              width=150)
        parent.InsertColumn(col=2, format=wx.LIST_FORMAT_LEFT,
              heading=u'Bitrate', width=100)
        parent.InsertColumn(col=3, format=wx.LIST_FORMAT_LEFT,
              heading=u'Listeners', width=100)
        parent.InsertColumn(col=4, format=wx.LIST_FORMAT_LEFT,
              heading=u'TV/Radio', width=100)
        parent.InsertColumn(col=5, format=wx.LIST_FORMAT_LEFT,
              heading=u'Now Playing', width=150)

    def _init_coll_GenreBox_Columns(self, parent):
        # generated method, don't edit

        parent.InsertColumn(col=0, format=wx.LIST_FORMAT_LEFT, heading=u'Genre',
              width=400)

    def _init_coll_TunapieToolBar_Tools(self, parent):
        # generated method, don't edit

        parent.DoAddTool(bitmap=wx.Bitmap(u'play.png', wx.BITMAP_TYPE_PNG),
              bmpDisabled=wx.NullBitmap, id=wxID_TUNAPIEFRAMETUNAPIETOOLBARPLAY,
              kind=wx.ITEM_NORMAL, label='', longHelp='', shortHelp=u'Play')
        parent.DoAddTool(bitmap=wx.Bitmap(u'stop.png', wx.BITMAP_TYPE_PNG),
              bmpDisabled=wx.NullBitmap, id=wxID_TUNAPIEFRAMETUNAPIETOOLBARSTOP,
              kind=wx.ITEM_NORMAL, label='', longHelp='', shortHelp=u'Stop')
        parent.DoAddTool(bitmap=wx.Bitmap(u'rec.png', wx.BITMAP_TYPE_PNG),
              bmpDisabled=wx.NullBitmap, id=wxID_TUNAPIEFRAMETUNAPIETOOLBARREC,
              kind=wx.ITEM_NORMAL, label='', longHelp='', shortHelp=u'Record')
        parent.DoAddTool(bitmap=wx.Bitmap(u'radio.png', wx.BITMAP_TYPE_PNG),
              bmpDisabled=wx.NullBitmap,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARRADIO, kind=wx.ITEM_NORMAL,
              label='', longHelp='', shortHelp=u'Radio')
        parent.DoAddTool(bitmap=wx.Bitmap(u'tv.png', wx.BITMAP_TYPE_PNG),
              bmpDisabled=wx.NullBitmap, id=wxID_TUNAPIEFRAMETUNAPIETOOLBARTV,
              kind=wx.ITEM_NORMAL, label='', longHelp='', shortHelp=u'TV')
        parent.DoAddTool(bitmap=wx.Bitmap(u'fave.png', wx.BITMAP_TYPE_PNG),
              bmpDisabled=wx.NullBitmap,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARADDFAVE, kind=wx.ITEM_NORMAL,
              label='', longHelp='', shortHelp=u'Add To Favorites')
        parent.DoAddTool(bitmap=wx.Bitmap(u'remfave.png', wx.BITMAP_TYPE_PNG),
              bmpDisabled=wx.NullBitmap,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARREMFAVE, kind=wx.ITEM_NORMAL,
              label='', longHelp='', shortHelp=u'Remove From Favorites')
        parent.DoAddTool(bitmap=wx.Bitmap(u'find.png', wx.BITMAP_TYPE_PNG),
              bmpDisabled=wx.NullBitmap, id=wxID_TUNAPIEFRAMETUNAPIETOOLBARFIND,
              kind=wx.ITEM_NORMAL, label=u'', longHelp='', shortHelp=u'Search')
        parent.DoAddTool(bitmap=wx.Bitmap(u'info.png', wx.BITMAP_TYPE_PNG),
              bmpDisabled=wx.NullBitmap, id=wxID_TUNAPIEFRAMETUNAPIETOOLBARINFO,
              kind=wx.ITEM_NORMAL, label='', longHelp='',
              shortHelp=u'Stream Info')
        self.Bind(wx.EVT_TOOL, self.OnTunapieToolBarRadioTool,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARRADIO)
        self.Bind(wx.EVT_TOOL, self.OnTunapieToolBarTvTool,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARTV)
        self.Bind(wx.EVT_TOOL, self.OnTunapieToolBarPlayTool,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARPLAY)
        self.Bind(wx.EVT_TOOL, self.OnTunapieToolBarStopTool,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARSTOP)
        self.Bind(wx.EVT_TOOL, self.OnTunapieToolBarRecTool,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARREC)
        self.Bind(wx.EVT_TOOL, self.OnTunapieToolBarAddfaveTool,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARADDFAVE)
        self.Bind(wx.EVT_TOOL, self.OnTunapieToolBarRemfaveTool,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARREMFAVE)
        self.Bind(wx.EVT_TOOL, self.OnTunapieToolBarFindTool,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARFIND)
        self.Bind(wx.EVT_TOOL, self.OnTunapieToolBarInfoTool,
              id=wxID_TUNAPIEFRAMETUNAPIETOOLBARINFO)

        parent.Realize()

    def _init_utils(self):
        # generated method, don't edit
        self.menuBar1 = wx.MenuBar()

        self.Filemenu = wx.Menu(title=u'')

        self.maincontext = wx.Menu(title=u'')

        self.favecontext = wx.Menu(title='')

        self.Helpmenu = wx.Menu(title='')

        self._init_coll_menuBar1_Menus(self.menuBar1)
        self._init_coll_Filemenu_Items(self.Filemenu)
        self._init_coll_maincontext_Items(self.maincontext)
        self._init_coll_favecontext_Items(self.favecontext)
        self._init_coll_Helpmenu_Items(self.Helpmenu)

    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_TUNAPIEFRAME, name=u'TunapieFrame',
              parent=prnt, pos=wx.Point(105, 147), size=wx.Size(600, 400),
              style=wx.DEFAULT_FRAME_STYLE, title=u'Tunapie2')
        self._init_utils()
        self.SetClientSize(wx.Size(600, 400))
        self.SetAutoLayout(True)
        self.SetMenuBar(self.menuBar1)
        self.SetIcon(wx.Icon('../pixmaps/tplogo.xpm',wx.BITMAP_TYPE_XPM))
        self.Bind(wx.EVT_KEY_UP, self.OnTunapieFrameKeyUp)
        self.Bind(wx.EVT_CLOSE, self.OnTunapieFrameClose)

        self.TunapieStatus = wx.StatusBar(id=wxID_TUNAPIEFRAMETUNAPIESTATUS,
              name=u'TunapieStatus', parent=self,
              style=wx.ST_SIZEGRIP | wx.RAISED_BORDER)
        self.TunapieStatus.SetFieldsCount(1)
        self._init_coll_TunapieStatus_Fields(self.TunapieStatus)
        self.SetStatusBar(self.TunapieStatus)
        
        if commands.getoutput("uname")=='Darwin':
            mainsize=380
        else:
            mainsize=348
        
        self.mainsplitter = wx.SplitterWindow(id=wxID_TUNAPIEFRAMEMAINSPLITTER,
              name=u'mainsplitter', parent=self, pos=wx.Point(0, 0),
              size=wx.Size(600,mainsize), style=wx.SP_3D)
        self.mainsplitter.SetMinimumPaneSize(2)
        self.mainsplitter.SetConstraints(LayoutAnchors(self.mainsplitter, True,
              True, True, True))
        self.mainsplitter.SetThemeEnabled(True)

        self.favesplitter = wx.SplitterWindow(id=wxID_TUNAPIEFRAMEFAVESPLITTER,
              name=u'favesplitter', parent=self.mainsplitter, pos=wx.Point(352,
              -24), size=wx.Size(200, 200), style=wx.SP_3D)
        self.favesplitter.SetMinimumPaneSize(2)
        self.favesplitter.SetThemeEnabled(True)

        self.FaveListCtrl = wx.ListCtrl(id=wxID_TUNAPIEFRAMEFAVELISTCTRL,
              name=u'FaveListCtrl', parent=self.favesplitter, pos=wx.Point(8,
              120), size=wx.Size(200, 200),
              style=wx.LC_SINGLE_SEL | wx.LC_REPORT)
        self.FaveListCtrl.SetThemeEnabled(True)
        self.FaveListCtrl.SetMinSize(wx.Size(0, 0))
        self._init_coll_FaveListCtrl_Columns(self.FaveListCtrl)
        self.FaveListCtrl.Bind(wx.EVT_LIST_COL_CLICK,
              self.OnFaveListCtrlListColClick,
              id=wxID_TUNAPIEFRAMEFAVELISTCTRL)
        self.FaveListCtrl.Bind(wx.EVT_LEFT_DCLICK,
              self.OnFaveListCtrlLeftDclick)
        self.FaveListCtrl.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK,
              self.OnFaveListCtrlListItemRightClick,
              id=wxID_TUNAPIEFRAMEFAVELISTCTRL)
        self.FaveListCtrl.Bind(wx.EVT_SET_FOCUS, self.OnFaveListCtrlSetFocus)

        self.MainListCtrl = wx.ListCtrl(id=wxID_TUNAPIEFRAMEMAINLISTCTRL,
              name=u'MainListCtrl', parent=self.mainsplitter, pos=wx.Point(-104,
              -72), size=wx.Size(200, 200),
              style=wx.LC_SINGLE_SEL | wx.LC_REPORT)
        self.MainListCtrl.SetThemeEnabled(True)
        self.MainListCtrl.SetMinSize(wx.Size(0, 0))
        self.MainListCtrl.SetLabel(u'')
        self._init_coll_MainListCtrl_Columns(self.MainListCtrl)
        self.MainListCtrl.Bind(wx.EVT_LIST_COL_CLICK,
              self.OnMainListCtrlListColClick,
              id=wxID_TUNAPIEFRAMEMAINLISTCTRL)
        self.MainListCtrl.Bind(wx.EVT_LEFT_DCLICK,
              self.OnMainListCtrlLeftDclick)
        self.MainListCtrl.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK,
              self.OnMainListCtrlListItemRightClick,
              id=wxID_TUNAPIEFRAMEMAINLISTCTRL)
        self.MainListCtrl.Bind(wx.EVT_SET_FOCUS, self.OnMainListCtrlSetFocus)

        self.TunapieToolBar = wx.ToolBar(id=wxID_TUNAPIEFRAMETUNAPIETOOLBAR,
              name=u'TunapieToolBar', parent=self, pos=wx.Point(0,
              27), size=wx.Size(365, 35),
              style=wx.TB_DOCKABLE | wx.TB_HORIZONTAL | wx.NO_BORDER)
        self.SetToolBar(self.TunapieToolBar)

        self.GenreBox = wx.ListCtrl(id=wxID_TUNAPIEFRAMEGENREBOX,
              name=u'GenreBox', parent=self.favesplitter, pos=wx.Point(56, 32),
              size=wx.Size(200, 100),
              style=wx.LC_NO_HEADER | wx.LC_SINGLE_SEL | wx.LC_REPORT)
        self.GenreBox.SetThemeEnabled(True)
        self.GenreBox.SetMinSize(wx.Size(0, 0))
        self._init_coll_GenreBox_Columns(self.GenreBox)
        self.GenreBox.Bind(wx.EVT_SET_FOCUS, self.OnGenreBoxSetFocus)
        self.GenreBox.Bind(wx.EVT_LIST_ITEM_SELECTED,
              self.OnGenreBoxListItemSelected, id=wxID_TUNAPIEFRAMEGENREBOX)

        self._init_coll_TunapieToolBar_Tools(self.TunapieToolBar)

    def __init__(self, parent):
        self._init_ctrls(parent)
        #Note: remember to check splitter size=816x448
        #self.SetClientSize(wx.Size(200, 200))
        self.home=os.environ.get('HOME')
        self.mainsplitter.SplitVertically(self.MainListCtrl,self.favesplitter)
        self.favesplitter.SplitHorizontally(self.FaveListCtrl,self.GenreBox)
        try: 
            geomfile=open(self.home+'/.tunapie/geom','r')
            geometry=geomfile.read().split('\n')
            size=geometry[0].split(' ')
            self.SetSize(wx.Size(int(size[0]),int(size[1])))
            pos=geometry[1].split(' ')
            self.SetPosition(wx.Point(int(pos[0]),int(pos[1])))
            self.mainsplitter.SetSashPosition(int(geometry[2]))
            self.favesplitter.SetSashPosition(int(geometry[3]))
            maincolumnwidths=geometry[4].split(' ')
            for i in range(6):
                self.MainListCtrl.SetColumnWidth(i,int(maincolumnwidths[i]))
            favecolumnwidths=geometry[5].split(' ')
            for i in range(6):
                self.FaveListCtrl.SetColumnWidth(i,int(favecolumnwidths[i]))
        except IOError:
            pass          
        self.radioselected=1 #radioselected? Needed??
        self.radiobutton=wxID_TUNAPIEFRAMETUNAPIETOOLBARRADIO
        self.tvbutton=wxID_TUNAPIEFRAMETUNAPIETOOLBARTV
        self.running=0 # pid of external player
        self.reloading=0 # set when contacting server (has to be set now or 
                         # get error on first startup due to OnGenreBoxListItemSelected 
                         # being called before files exist.
        self.downloading=0 #set when downloading from server
        self.startup=1
        self.downloadedshoutcast=0
        self.lastmod=-1 # tv or radio last modality when browsing favs?    
        self.reverse=0
        self.fcol="name"
        self.mcol="name"
        self.nstreamname,self.ngenre,self.nbitrate,self.nlisteners,self.nmod,self.nnowplaying=\
            0,1,2,3,4,5
        self.adult=tuner.adultset()
        self.rdir=self.home+'/.tunapie/streamripper'
        self.shoutice=1 #0 is icecast server 1 is shoutcast
        self.maxd=100
        self.newsize=8
        self.setgenreboxradio()
        #note: when change tv -> radio, change genres
        try: os.mkdir(self.home+'/.tunapie')
        except OSError:
            pass
        try: self.favname,self.favurl,self.favgen,self.favplay,\
                        self.favbit,self.favlist,self.favmod=\
                        tuner.decode(self.home+'/.tunapie/favorites',1,1,1)
        except IOError:
            self.favname,self.favurl,self.favmod,self.favlist,self.favplay,\
                self.favbit,self.favgen=[],[],[],[],[],[],[]
        self.favname,self.favlist, self.favgen, self.favbit, self.favurl, \
         self.favplay, self.favmod=self.sort("name",self.favname,self.favlist,\
         self.favgen, self.favbit, self.favurl, self.favplay,0, self.favmod)
        self.addtolistctrl(self.FaveListCtrl, self.favname,self.favgen,self.favbit,self.favlist,self.favplay,self.favmod)
        self.mediaplayer,self.videoplayer,self.term,self.ripper,self.rdir,\
            self.shoutice,self.maxd,self.newsize,self.browser=tuner.readprefs\
            (self.home, self.rdir,self.shoutice,self.maxd,self.newsize)
        missing_players=[]
        if self.mediaplayer=="":
            if commands.getoutput("which audacious").find("audacious")>-1:
                self.mediaplayer='audacious'
            elif commands.getoutput("which xmms").find("xmms")>-1:
                self.mediaplayer='xmms'
            elif commands.getoutput("which beep-media-player").find("beep")>-1:
                self.mediaplayer='beep-media-player'
            else:
                print("No audioplayer found.\n")
                missing_players.append("No audioplayer found.")
        if self.videoplayer=='':
            if commands.getoutput("which vlc").find("vlc")>-1:
                self.videoplayer='vlc'
            elif commands.getoutput("which gxine").find("gxine")>-1:
                self.videoplayer='gxine'
            elif commands.getoutput("which totem").find("totem")>-1:
                self.videoplayer='totem'  
            elif commands.getoutput("which mplayer").find("mplayer")>-1:
                self.videoplayer='mplayer'
            elif commands.getoutput("which xine").find("xine")>-1:
                self.videoplayer='xine'
            else:
                print("No videoplayer found\n")
                missing_players.append("No videoplayer found.")
        if self.term=="":
            if commands.getoutput("which xterm").find("xterm")>-1:
                self.term='xterm'
            elif commands.getoutput("which aterm").find("aterm")>-1:
                self.term='aterm'
            elif commands.getoutput("which Eterm").find("Eterm")>-1:
                self.term='Eterm'
            elif commands.getoutput("which rxvt").find("rxvt")>-1:
                self.term='rxvt'
            elif commands.getoutput("which x-terminal-emulator").find("x-terminal-emulator")>-1:
                self.term='x-terminal-emulator'
            else:
                print("No xterm found\n")
                missing_players.append("No xterm found.")
        if self.ripper=="":
            if commands.getoutput("which streamripper").find("streamripper")>-1:
                self.ripper='streamripper -t -u winamp2 -o never'
            else:
                print("Streamripper not installed. Recording will not work\n")
                missing_players.append("Streamripper not found. Recording will not work.")
        if self.browser=="":
            if commands.getoutput("which firefox").find("firefox")>-1:
                self.browser='firefox'
            if commands.getoutput("which iceweasel").find("iceweasel")>-1:
                self.browser='iceweasel'
            elif commands.getoutput("which mozilla").find("mozilla")>-1:
                self.browser='mozilla'
            elif commands.getoutput("which iceape").find("iceape")>-1:
                self.browser='iceape'
            elif commands.getoutput("which konqueror").find("konqueror")>-1:
                self.browser='konqueror'
            elif commands.getoutput("which x-www-browser").find("x-www-browser")>-1:
                self.browser='x-www-browser'
            else:
                print("Web browser not found.\n")
                missing_players.append("Web browser not found.")
        tuner.writeprefs(self.home,self.mediaplayer,self.videoplayer,self.term,\
            self.ripper,self.rdir,self.shoutice,self.maxd,self.newsize,\
            self.browser)
        self.setfontsize()
        if missing_players:
            missing_players.append("Please edit preferences manually.")
            #self.OnTunapieToolBarInfoTool(1,missing_players)
            print missing_players
        socket.setdefaulttimeout(20)
        wx.CallAfter(self.download)
        
    def setfontsize(self):
        size=int(self.newsize)
        self.SetFont(wx.Font(size, wx.SWISS, wx.NORMAL, wx.NORMAL, False,u'Sans'))
        self.FaveListCtrl.SetFont(wx.Font(size, wx.SWISS, wx.NORMAL, wx.NORMAL, False,u'Sans'))
        self.MainListCtrl.SetFont(wx.Font(size, wx.SWISS, wx.NORMAL, wx.NORMAL, False,u'Sans'))
        self.GenreBox.SetFont(wx.Font(size, wx.SWISS, wx.NORMAL, wx.NORMAL, False,u'Sans'))
        self.TunapieToolBar.SetFont(wx.Font(size, wx.SWISS, wx.NORMAL, wx.NORMAL, False,u'Sans'))
        self.TunapieStatus.SetFont(wx.Font(size, wx.SWISS, wx.NORMAL, wx.NORMAL, False,u'Sans'))
        
    
    def download(self):
        #called by at automatic download points
        #only calls reload (which does the real downloading)
        #if has not already been done this session
        #self.radioselected=1
        self.startup=0
        if int(self.shoutice):
            if not(self.downloadedshoutcast):
                self.downloadedshoutcast=1
                self.reloading=1
                thread.start_new_thread(self.reload,(3,))
                self.checkfilesize() 
        else:
            try: #updates pane if icecast has been downloaded recently
                if time.time()-os.stat(self.home+'/.tunapie/icecast')[8]<86400:
                    self.parsefiles()
                    self.updatemain()
                    self.MainListCtrl.Select(0)
                    self.MainListCtrl.SetFocus()
                    return
            except OSError:
                pass
            self.reloading=1
            thread.start_new_thread(self.reload,(5,))
            self.checkfilesize()
        #self.OnRadioradioRadiobutton(1)
        #??other stuff that this command does..
    
    def reporthook(self,b,c,d): 
            if (b):
                self.downloading=1    
    
    def reload(self,type,searchquery=""):    #type: reload 1=radio 2=tv 3=both 4=search 5=icecast
        if(type==1)|(type==3):
            try: radiofile=urllib.urlretrieve('http://www.shoutcast.com/sbin/newxml.phtml?genre=Top500',self.home+'/.tunapie/radiolist',self.reporthook)
            except IOError:
                self.downloading=2
                return
            except AttributeError:
                self.downloading=2
                return
        if(type==2)|(type==3):
            try: tvfile=urllib.urlretrieve('http://www.shoutcast.com/sbin/newtvlister.phtml?alltv=1',self.home+'/.tunapie/tvlist',self.reporthook)
            except IOError:
                self.downloading=2
                return
            except AttributeError:
                self.downloading=2
                return
        if(type==4): #search
            try: searchfile=urllib.urlretrieve('http://www.shoutcast.com/sbin/newxml.phtml?search='+searchquery.replace(" ","%20"),self.home+'/.tunapie/search',self.reporthook)
            except IOError:
                self.downloading=2
                return
            except AttributeError:
                self.downloading=2
                return
        if(type==5): #icecast
            try: icfile=urllib.urlretrieve('http://dir.xiph.org/yp.xml',self.home+'/.tunapie/icecast',self.reporthook)
            except IOError:
                self.downloading=2
                return
            except AttributeError:
                self.downloading=2
                return
        self.downloading=3
        #self.addtolistctrl(self.MainListCtrl, self.name,self.genre,self.bitrate,self.listeners,self.playing)
        self.reloading=0
        return
    
    def updatefavs(self):
        #need to call this after new update to db.
        #not same as updatemain. This one just updates the 
        #url associated with a particular stream
        currentmod=self.TunapieToolBar.GetToolState(self.radiobutton)
        #print currentmod
        i=0
        while 1:
            #loads either tv or radio listings
            ret=self.parsefiles()
            if ret==-1:
                return
            j=-1
            for name in self.favname:
                j+=1
                namenew,genrenew,playingnew,listenersnew,bitratenew,urlnew=\
                    self.find(name.lower())
                k=-1
                for newname in namenew:
                    k+=1
                    if (name==newname):
                        if (self.favbit[j]==bitratenew[k]):
                            self.favurl[j]=urlnew[k]
                            self.favplay[j]=playingnew[k]
                            self.favlist[j]=listenersnew[k]
                            break
            if i==0:
                #runs through one set of listings first, then does the other (tv or radio)
                currentmod=not(currentmod)
                i=1
                continue
            return

    def parsefiles(self):
        if not(int(self.shoutice)):
            filename='/.tunapie/icecast'
            try: 
                self.url,self.name,self.genre,self.playing,self.bitrate,\
                 self.listeners=tuner.decodeice(self.home+filename,self.radioselected)
            except IOError:
                return -1
            return 0
        if(self.radioselected==True):
            filename='/.tunapie/radiolist'
        else:
            filename='/.tunapie/tvlist'
        try: self.url,self.name,self.genre,self.playing,self.bitrate,\
              self.listeners=tuner.decode(self.home+filename,self.radioselected,self.adult)
        except IOError:
            return -1
        return 0
    
    def updatemain(self, selection="", sortby="listeners"):
        self.name,self.genre,self.playing,self.listeners,\
            self.bitrate,self.url=self.find(selection)
        self.sort(sortby,self.name,self.listeners,\
            self.genre,self.bitrate,self.url,self.playing)
        self.addtolistctrl(self.MainListCtrl, self.name, self.genre,\
            self.bitrate, self.listeners, self.playing)
        #self.MainListCtrl.SetFocus()
        #self.MainListCtrl.Select(0)
    
    def contacterror(self):
        self.SetStatusText('Error: cannot contact server')
        print 'Error: cannot contact server.'
        wx.Yield()
        time.sleep(2)
        self.SetStatusText('')
        
    def setgenreboxradio(self):    
        self.GenreBox.DeleteAllItems()
        self.GenreBox.InsertStringItem(0,"Top Radio Streams")
        self.GenreBox.InsertStringItem(1,"Alternative")
        self.GenreBox.InsertStringItem(2,"Ambient")
        self.GenreBox.InsertStringItem(3,"Blues")
        self.GenreBox.InsertStringItem(4,"Classical")
        self.GenreBox.InsertStringItem(5,"Country")
        self.GenreBox.InsertStringItem(6,"Electronic")
        self.GenreBox.InsertStringItem(7,"Hip Hop")
        self.GenreBox.InsertStringItem(8,"Jazz")
        self.GenreBox.InsertStringItem(9,"Rock")
        self.GenreBox.InsertStringItem(10,"Rap")
        self.GenreBox.InsertStringItem(11,"Soul")
        self.GenreBox.InsertStringItem(12,"Spiritual")
        self.GenreBox.InsertStringItem(13,"Spoken")
        self.GenreBox.InsertStringItem(14,"World")
        self.GenreBox.Select(0)
        self.GenreBox.EnsureVisible(0)
        
    def setgenreboxtv(self):    
        self.GenreBox.DeleteAllItems()
        i=0
        self.GenreBox.InsertStringItem(i,"Top TV Streams")
        if self.adult:
            i+=1
            self.GenreBox.InsertStringItem(i,"Adult")
        i+=1
        self.GenreBox.InsertStringItem(i,"Anime")
        i+=1
        self.GenreBox.InsertStringItem(i,"Cartoon")
        i+=1
        self.GenreBox.InsertStringItem(i,"Dance")
        i+=1
        self.GenreBox.InsertStringItem(i,"Movie")
        i+=1
        self.GenreBox.InsertStringItem(i,"Music")
        i+=1
        self.GenreBox.InsertStringItem(i,"Oldies")
        i+=1
        self.GenreBox.InsertStringItem(i,"Pop")
        if self.adult:
            i+=1
            self.GenreBox.InsertStringItem(i,"Porn")
        i+=1
        self.GenreBox.InsertStringItem(i,"Rock")
        i+=1
        self.GenreBox.InsertStringItem(i,"Sci Fi")
        i+=1
        self.GenreBox.InsertStringItem(i,"SWC")
        i+=1
        self.GenreBox.InsertStringItem(i,"Trance")
        i+=1
        self.GenreBox.InsertStringItem(i,"TV")
        i+=1
        self.GenreBox.InsertStringItem(i,"Video")
        if self.adult:
            i+=1
            self.GenreBox.InsertStringItem(i,"XXX")
        self.GenreBox.Select(0)
        self.GenreBox.EnsureVisible(0)
        
    def find(self, selection='', namesearch=1):
        namenew,genrenew,playingnew,listenersnew,bitratenew,urlnew=\
            [],[],[],[],[],[]
        i=-1
        if selection=="top radio streams" or selection=="top tv streams":
            selection=""
        if(selection):
            for item in self.genre:
                i+=1
                genre=item.lower()
                if(genre.find(selection)>-1):
                    namenew.append(self.name[i])
                    genrenew.append(self.genre[i])
                    playingnew.append(self.playing[i])
                    listenersnew.append(self.listeners[i])
                    bitratenew.append(self.bitrate[i])
                    urlnew.append(self.url[i])
                    continue
                if namesearch==1:
                    try:
                        uppername=self.name[i]
                    except IndexError:
                        pass
                        #Not downloaded the listing properly!
			continue
                    name=uppername.lower()
                    try:
                        if(name.find(selection)>-1):
                            namenew.append(self.name[i])
                            genrenew.append(self.genre[i])
                            playingnew.append(self.playing[i])
                            listenersnew.append(self.listeners[i])
                            bitratenew.append(self.bitrate[i])
                            urlnew.append(self.url[i])
                            continue
                    except UnicodeDecodeError:
                        pass
                    try:
                        #not sure this is really necessary!!
                        upperplaying=self.playing[i]
                    except IndexError:
                        continue
                    lowerplaying=upperplaying.lower()
                    try:
                        if(lowerplaying.find(selection)>-1):
                            namenew.append(self.name[i])
                            genrenew.append(self.genre[i])
                            playingnew.append(self.playing[i])
                            listenersnew.append(self.listeners[i])
                            bitratenew.append(self.bitrate[i])
                            urlnew.append(self.url[i])
                            continue
                    except UnicodeDecodeError:
                            continue                        
        else:
            streamlist=int(self.maxd)
            try:
                if len(self.name)<int(self.maxd):
                    streamlist=len(self.name)
            except AttributeError:
                pass
            for i in range(streamlist):
                namenew.append(self.name[i])
                genrenew.append(self.genre[i])
                playingnew.append(self.playing[i])
                listenersnew.append(self.listeners[i])
                bitratenew.append(self.bitrate[i])
                urlnew.append(self.url[i])
        return(namenew,genrenew,playingnew,listenersnew,bitratenew,urlnew)
    
    def sort(self, sortby,name,listeners,genre,bitrate,url,playing,reverse=0,mod=[]):
        if mod==[]:
            for item in name:
                mod.append(0)
        if sortby=='name':
            lowername=[x.lstrip().lower() for x in name]
            directory=zip(lowername, name, listeners, genre, bitrate,\
                url, playing, mod)
            directory.sort()
            if reverse:
                directory.reverse()
            listeners,genre,bitrate,url,playing,\
                name, mod=[],[],[],[],[],[],[]
            for i in directory:
                name.append(i[1])
                listeners.append(i[2])
                genre.append(i[3])
                bitrate.append(i[4])
                url.append(i[5])
                playing.append(i[6])
                mod.append(i[7])
        elif sortby=='genre':
            lowergen=[x.lstrip().lower() for x in genre]
            directory=zip(lowergen , genre, listeners,  name, bitrate,\
                url, playing, mod)
            directory.sort()
            if reverse:
                directory.reverse()
            listeners,genre,bitrate,url,playing,\
                name, mod=[],[],[],[],[],[],[]
            for i in directory:
                genre.append(i[1])
                listeners.append(i[2])
                name.append(i[3])
                bitrate.append(i[4])
                url.append(i[5])
                playing.append(i[6])
                mod.append(i[7])
        elif sortby=='playing':
            lowerplay=[x.lstrip().lower() for x in playing]
            directory=zip(lowerplay ,playing, listeners,  name, bitrate,\
                url, genre, mod)
            directory.sort()
            if reverse:
                directory.reverse()
            listeners,genre,bitrate,url,playing,\
                name, mod=[],[],[],[],[],[],[]
            for i in directory:
                playing.append(i[1])
                listeners.append(i[2])
                name.append(i[3])
                bitrate.append(i[4])
                url.append(i[5])
                genre.append(i[6])
                mod.append(i[7])
        elif sortby=='modality':
            directory=zip(mod, name, listeners, genre, bitrate,\
                url, playing)
            directory.sort()
            if reverse:
                directory.reverse()
            listeners,genre,bitrate,url,playing,\
                name, mod=[],[],[],[],[],[],[]
            for i in directory:
                mod.append(i[0])
                name.append(i[1])
                listeners.append(i[2])
                genre.append(i[3])
                bitrate.append(i[4])
                url.append(i[5])
                playing.append(i[6])
        elif sortby=='bitrate':
            bitratenew=[]
            for i in bitrate:
                bitratenew.append(int(i))
            bitrate=bitratenew
            directory=zip(bitrate, listeners,  genre, name,\
                url, playing, mod)
            directory.sort()
            if reverse:
                directory.reverse()
            listeners,genre,bitrate,url,playing,\
                name, mod=[],[],[],[],[],[],[]
            for i in directory:
                bitrate.append(str(i[0]))
                listeners.append(i[1])
                genre.append(i[2])
                name.append(i[3])
                url.append(i[4])
                playing.append(i[5])
                mod.append(i[6])
        else: #Sort by listeners is default
            #//this bit to get the lines sorted as int rather than str
            listenersnew=[]
            for i in listeners:
                listenersnew.append(int(i))
            listeners=listenersnew
            #//
            directory=zip(listeners, name,  genre, bitrate,\
                url, playing, mod)
            directory.sort()
            if reverse:
                directory.reverse()
            listeners,genre,bitrate,url,playing,\
                name, mod=[],[],[],[],[],[],[]
            for i in directory:
                listeners.append(str(i[0]))
                name.append(i[1])
                genre.append(i[2])
                bitrate.append(i[3])
                url.append(i[4])
                playing.append(i[5])
                mod.append(i[6])
        return name,listeners,genre,bitrate,url,playing,mod
    
    def addtolistctrl(self,listctrl,name,genre,bitrate,listeners,playing,mod=[]):
        listctrl.DeleteAllItems()
        i=0
        newmod=[]
        if mod==[]:
            if self.radioselected:
                modality="Radio"
            else:
                modality="TV"
            for x in name:
                newmod.append(modality)
        else:
            for item in mod:
                if item==1:
                    newmod.append("Radio")
                else: 
                    newmod.append("TV")
        for item in name:
            listctrl.InsertStringItem(i,item)
            listctrl.SetStringItem(i,self.ngenre,genre[i])
            listctrl.SetStringItem(i,self.nmod,newmod[i])
            listctrl.SetStringItem(i,self.nbitrate,bitrate[i])
            listctrl.SetStringItem(i,self.nlisteners,listeners[i])
            listctrl.SetStringItem(i, self.nnowplaying,playing[i])
            i+=1      

    def OnFaveListCtrlListColClick(self, event):
        if event.GetColumn()==-1:
            return
        if event.GetColumn()==self.nstreamname:
            if self.fcol=="name":
                self.reverse=not(self.reverse)
            self.fcol="name"
        if event.GetColumn()==self.nbitrate:
            if self.fcol=="bitrate":
                self.reverse=not(self.reverse)
            self.fcol="bitrate"
        if event.GetColumn()==self.nlisteners:
            if self.fcol=="listeners":
                self.reverse=not(self.reverse)
            self.fcol="listeners"
        if event.GetColumn()==self.ngenre:
            if self.fcol=="genre":
                self.reverse=not(self.reverse)
            self.fcol="genre"
        if event.GetColumn()==self.nnowplaying:
            if self.fcol=="playing":
                self.reverse=not(self.reverse)
            self.fcol="playing"
        if event.GetColumn()==self.nmod:
            if self.fcol=="modality":
                self.reverse=not(self.reverse)
            self.fcol="modality"
        self.favname,self.favlist, self.favgen, self.favbit, self.favurl, \
         self.favplay, self.favmod=self.sort(self.fcol,self.favname,self.favlist,\
         self.favgen, self.favbit, self.favurl, self.favplay, self.reverse, self.favmod)
        self.addtolistctrl(self.FaveListCtrl, self.favname,self.favgen,self.favbit,self.favlist,self.favplay,self.favmod)
     
    def checkfilesize(self):
        print 'Waiting for server'
        while 1:
            self.SetStatusText('Waiting for server.')
            time.sleep(0.4)
            wx.Yield()
            self.SetStatusText('Waiting for server..')
            time.sleep(0.4)
            wx.Yield()
            self.SetStatusText('Waiting for server...')
            time.sleep(0.4)
            wx.Yield()
            if (self.downloading>0):
                if(self.downloading==2):
                    self.downloading=0
                    self.reloading=0
                    self.contacterror()
                    return
                break
        print 'Downloading...'
        while 1:
            self.SetStatusText('Downloading...-')
            time.sleep(0.2)
            wx.Yield()
            self.SetStatusText('Downloading...\\')
            time.sleep(0.2)
            wx.Yield()
            self.SetStatusText('Downloading...|')
            time.sleep(0.2)
            wx.Yield()
            self.SetStatusText('Downloading.../')
            time.sleep(0.2)
            wx.Yield()
            if (self.downloading==3):
                self.SetStatusText('')
                self.downloading=0
                while 1:
                    time.sleep(0.2)
                    wx.Yield()
                    if (self.reloading==0):
                        self.SetStatusText('')
                        self.parsefiles()
                        self.updatefavs()
                        self.updatemain()
                        self.MainListCtrl.Select(0)
                        self.MainListCtrl.SetFocus()
                        return

    def OnMainListCtrlListColClick(self, event):
        if event.GetColumn()==-1:
            return
        if event.GetColumn()==self.nstreamname:
            if self.mcol=="name":
                self.reverse=not(self.reverse)
            self.mcol="name"
        if event.GetColumn()==self.nbitrate:
            if self.mcol=="bitrate":
                self.reverse=not(self.reverse)
            self.mcol="bitrate"
        if event.GetColumn()==self.nlisteners:
            if self.mcol=="listeners":
                self.reverse=not(self.reverse)
            self.mcol="listeners"
        if event.GetColumn()==self.ngenre:
            if self.mcol=="genre":
                self.reverse=not(self.reverse)
            self.mcol="genre"
        if event.GetColumn()==self.nnowplaying:
            if self.mcol=="playing":
                self.reverse=not(self.reverse)
            self.mcol="playing"
        self.name,self.listeners, self.genre, self.bitrate, self.url, \
         self.playing, not_needed=self.sort(self.mcol,self.name,self.listeners,\
         self.genre, self.bitrate, self.url, self.playing, self.reverse)
        self.addtolistctrl(self.MainListCtrl, self.name,self.genre,self.bitrate,self.listeners,self.playing)

    def OnTunapieToolBarRadioTool(self, event):
        if self.reloading==1:
            return
        self.setgenreboxradio()
        self.lastmod=1
        self.radioselected=1
        self.parsefiles()
        self.updatemain()
        self.MainListCtrl.Select(0)
        self.MainListCtrl.SetFocus()
                    
    def OnTunapieToolBarTvTool(self, event):
        if self.reloading==1:
            return
        self.setgenreboxtv()
        self.lastmod=0
        self.radioselected=0
        self.parsefiles()
        self.updatemain()
        self.MainListCtrl.Select(0)
        self.MainListCtrl.SetFocus()
        
        
#NOTE: The following can be seriously simplified now it uses threads..
#Need to look at this again when have the chance!        
    def OnTunapieToolBarPlayTool(self, event):
        if self.reloading==1:
            return
        if(self.running):
            if (self.videoplayer.find("totem")<0 or self.radioselected):
                wasrunning=tuner.pkill(self.videoplayer[self.videoplayer.rfind("/")+1:self.videoplayer.find((' '),self.videoplayer.rfind("/")+1)])
            if ((self.mediaplayer.find("xmms")<0 and self.mediaplayer.find("audacious")<0 
                    and self.mediaplayer.find("beep-media-player")<0)
                    or not(self.radioselected)):
                tuner.pkill(self.mediaplayer[self.mediaplayer.rfind("/")+1:self.mediaplayer.rfind("/")+16])
            #if not(self.radioselected):
            #    try:
            #        if int(wasrunning):
            #            return
            #    except: 
            #        pass
        selection=self.MainListCtrl.GetFirstSelected()
        if selection==-1:
            selection=self.FaveListCtrl.GetFirstSelected()
            if selection==-1:
                return
            if not(self.favmod[selection]):
                tuner.pkill(self.mediaplayer[self.mediaplayer.rfind("/")+1:self.mediaplayer.rfind("/")+16])
                self.lastmod=0
                videoplayer=self.videoplayer
                if videoplayer.find("mplayer")>-1:
                    if ((self.favgen[selection].lower().find('porn')>-1)|\
                        (self.favgen[selection].lower().find('swctv')>-1)):
                        videoplayer+=' -demuxer 35'
                try: 
                    #self.running,output,outputfd=tuner.playvid(videoplayer,self.favurl[selection])
                    self.running=1
                    tuner.playvid(videoplayer,self.favurl[selection])
                except IOError:
                    self.contacterror()
                #try: 
                #    self.printout(output,outputfd)
                #except UnboundLocalError:
                #    pass
                return
            else:
                self.lastmod=1
                try:
                    self.running=1
                    tuner.playselection(self.mediaplayer,self.favurl[selection])
                except IOError:
                    self.contacterror()
            return
        if not(self.radioselected):
            videoplayer=self.videoplayer
            if videoplayer.find("mplayer")>-1:
                if ((self.genre[selection].lower().find('porn')>-1)|\
                    (self.genre[selection].lower().find('swctv')>-1)):\
                    videoplayer+=' -demuxer 35'
            try:
                self.running=1
                #thread.start_new_thread(tuner.playvid,(videoplayer,self.url[selection]))
                tuner.playvid(videoplayer,self.url[selection])
            except IOError:
                self.contacterror()
            #self.printout(output,outputfd)
            return
        if(self.radioselected):
            try: 
                self.running=1
                tuner.playselection(self.mediaplayer,self.url[selection])
            except IOError: #if try to play empty stream!
                self.contacterror()
        return


#Maybe we can reuse this called from tuner.playselection.
#as it is really just mplayer specific I am not too sorry to see it go.    
#    def printout(self,pipe,pipefd):
#        if (self.videoplayer.find("mplayer")<0):
#            return
#        i=0
#        output=''
#        print 'Contacting server'
#        self.SetStatusText('Contacting server')
#        while 1:
#            select.select([pipefd],[],[])
#            outchunk=pipe.read()
#            output+=outchunk
#            if i>3:
#                output=output[len(outchunk):]
#            if outchunk=='':
#                try:
#                    self.SetStatusText('')
#                    return
#                except wx.PyDeadObjectError:
#                    return
#            wx.Yield()
#            i+=1
#            print (output)
#            if (output.find('Cache')>-1):
#                self.SetStatusText('Downloading')
#            if (output.find('playback')>-1):
#                self.SetStatusText('Playing')
#            if (output.find('full')>-1):
#                print 'Server full'
#                self.SetStatusText('Server full')
#                for wait in range(5):
#                    time.sleep(0.2)
#                    wx.Yield()
#                self.SetStatusText('')
#                return
#            if (output.find('Exiting... (End of file)')>-1):
#                print 'Error'
#                self.SetStatusText('Error')
#                for wait in range(5):
#                    time.sleep(0.2)
#                    wx.Yield()
#                self.SetStatusText('')
#                return

    def OnTunapieToolBarStopTool(self, event):
        tuner.pkill(self.videoplayer[self.videoplayer.rfind("/")+1:len(self.videoplayer)])
        tuner.pkill(self.mediaplayer[self.mediaplayer.rfind("/")+1:self.mediaplayer.rfind("/")+16])
   

    def OnTunapieToolBarRecTool(self, event):
        try: os.listdir(self.rdir)
        except OSError:
            try: os.makedirs(self.rdir)
            except OSError:
                print 'Cannot create rip directory!'
                self.SetStatusText('Cannot create rip directory!')
                for wait in range(5):
                        time.sleep(0.2)
                        wx.Yield()
                self.SetStatusText('')
                return
        selection=self.MainListCtrl.GetFirstSelected()
        if selection==-1:
            selection=self.FaveListCtrl.GetFirstSelected()
            if selection==-1:
                return
            recordoptions=[self.term,self.ripper,self.favurl[selection],self.rdir]
        else:
            recordoptions=[self.term,self.ripper,self.url[selection],self.rdir]
        dlg=RecordTime.RecordStream(self)
        dlg.setfontsize(self.newsize)
        dlg.setoptions(recordoptions)
        try:
            if dlg.ShowModal()==1:
                seq.reset()
                self.retrievedata()
        finally:
            dlg.Destroy()

    def OnFaveListCtrlLeftDclick(self, event):
        self.OnTunapieToolBarPlayTool(1)

    def OnMainListCtrlLeftDclick(self, event):
        self.OnTunapieToolBarPlayTool(1)

    def OnTunapieToolBarAddfaveTool(self, event):
        selection=self.MainListCtrl.GetFirstSelected()
        if (selection<0):
            return
        i=-1
        for name in self.favname:
            i+=1
            if (name==self.name[selection]):
                if (self.favbit[i]==self.bitrate[selection]):
                    if (self.favurl[i]==self.url[selection]):
                        print "Duplicate entry"
                        self.SetStatusText('Duplicate entry!')
                        for wait in range(5):
                            time.sleep(0.2)
                            wx.Yield()
                        self.SetStatusText('')
                        return
        self.favname.append(self.name[selection])
        self.favurl.append(self.url[selection])
        self.favmod.append(int(self.radioselected))
        self.favplay.append(self.playing[selection])
        self.favbit.append(self.bitrate[selection])
        self.favgen.append(self.genre[selection])
        self.favlist.append(self.listeners[selection])
        self.favname,self.favlist, self.favgen, self.favbit, self.favurl, \
         self.favplay, self.favmod=self.sort(self.fcol,self.favname,self.favlist,\
         self.favgen, self.favbit, self.favurl, self.favplay, self.reverse, self.favmod)
        self.addtolistctrl(self.FaveListCtrl, self.favname,self.favgen,self.favbit,self.favlist,self.favplay,self.favmod)
        i=-1
        for name in self.favname:
            i+=1
            if (name==self.name[selection]):
                if (self.favbit[i]==self.bitrate[selection]):
                    if (self.favurl[i]==self.url[selection]):
                        newitem=i
        self.FaveListCtrl.Select(newitem)
        self.FaveListCtrl.SetFocus()
        self.FaveListCtrl.EnsureVisible(newitem)
        self.MainListCtrl.Select(self.MainListCtrl.GetFirstSelected(),False)
        tuner.savefavorites(self.home,self.favname,self.favurl,self.favlist,\
            self.favplay,self.favbit,self.favgen,self.favmod)

    def OnTunapieToolBarRemfaveTool(self, event):
        selection=self.FaveListCtrl.GetFirstSelected()
        if selection<0:
            return
        newurl,newname,newmod,newlist,newplay,newbit,newgen=[],[],[],[],[],[],[]
        for i in range(len(self.favname)):
            if i!=selection:
                newurl.append(self.favurl[i])
                newname.append(self.favname[i])
                newmod.append(self.favmod[i])
                newlist.append(self.favlist[i])
                newplay.append(self.favplay[i])
                newbit.append(self.favbit[i])
                newgen.append(self.favgen[i])
        self.favname,self.favurl,self.favmod,self.favlist,self.favplay,\
            self.favbit,self.favgen=newname,newurl,newmod,newlist,newplay\
            ,newbit,newgen
        self.favname,self.favlist, self.favgen, self.favbit, self.favurl, \
         self.favplay, self.favmod=self.sort(self.fcol,self.favname,self.favlist,\
         self.favgen, self.favbit, self.favurl, self.favplay, self.reverse, self.favmod)
        self.addtolistctrl(self.FaveListCtrl, self.favname,self.favgen,self.favbit,self.favlist,self.favplay, self.favmod)
        tuner.savefavorites(self.home,self.favname,self.favurl,self.favlist,\
            self.favplay,self.favbit,self.favgen,self.favmod)
        self.FaveListCtrl.Select(0)
        #self.FaveListCtrl.SetFocus()
        
    def OnMainListCtrlListItemRightClick(self, event):
        if self.reloading==1:
            return
        self.PopupMenu(self.maincontext)

    def OnMaincontextPlayMenu(self, event):
        self.OnTunapieToolBarPlayTool(1)

    def OnMaincontextAddfaveMenu(self, event):
        self.OnTunapieToolBarAddfaveTool(1)

    def OnFavecontextPlayMenu(self, event):
        self.OnTunapieToolBarPlayTool(1)

    def OnFavecontextRemoveMenu(self, event):
        self.OnTunapieToolBarRemfaveTool(1)
        
    def OnFaveListCtrlListItemRightClick(self, event):
        if self.reloading==1:
            return
        self.PopupMenu(self.favecontext)
    
    def OnTunapieFrameKeyUp(self, event):
        try: key=event.GetUnicodeKey()
        except: key=event.GetKeyCode()
        #print key
        if key==318:
            self.FaveListCtrl.SetFocus()
        if key==316:
            self.MainListCtrl.SetFocus()
        if key==13:
            self.OnTunapieToolBarPlayTool(1)
        if key==82:
            self.OnTunapieToolBarRadioTool(1)
        if key==84:
            self.OnTunapieToolBarTvTool(1)
        if key==47:
            self.OnTunapieToolBarFindTool(1)
        if key==73:
            self.OnTunapieToolBarInfoTool(1)
            

    def OnFavecontextRecordMenu(self, event):
        self.OnTunapieToolBarRecTool(1)

    def OnMaincontextRecordMenu(self, event):
        self.OnTunapieToolBarRecTool(1)

    def OnTunapieToolBarFindTool(self, event):
        if self.reloading==1:
            return
        dlg=TunaSearch.Search(self)
        dlg.setfontsize(int(self.newsize))
        try:
            if dlg.ShowModal()==1:
                seq.reset()
                self.retrievedata()
        finally:
            dlg.Destroy()
        if searchname:
            self.onlinesearch()
            
    def onlinesearch(self):
        selection=searchname.lower()
        selection=tuner.fixunicode(selection)
        #new server-based search for shoutcast radio
        if (self.radioselected):
            if(int(self.shoutice)):
                if (len(selection)<3 or selection=="the"):
                    return
                self.reloading=1
                self.downloading=0
                thread.start_new_thread(self.reload,(4,selection))
                self.checkfilesize()
                self.url,self.name,self.genre,self.playing,self.bitrate,\
                    self.listeners=tuner.decode(self.home+'/.tunapie/search',1,0)
                self.updatemain()
                return
        #old style search for shoutcast tv
        self.parsefiles()
        self.updatemain(selection)

    def OnTunapieToolBarInfoTool(self, event, info=""):
        if self.reloading==1:
            return
        dlg=TunerInfoDialog.StreamInfo(self)
        dlg.setfontsize(self.newsize)
        if not(info):
            selection=self.MainListCtrl.GetFirstSelected()
            fav=0
            if (selection==-1):
                selection=self.FaveListCtrl.GetFirstSelected()
                if (selection==-1):
                    return
                fav=1
        #self.reloading=1
        #    thread.start_new_thread(self.reload,(3,))
        #    self.checkfilesize()
        if info:
            dlg.FillInfo(info, self.browser)
        elif (fav==1):
            try:dlg.FillInfo(tuner.playselection(self.mediaplayer,self.favurl[selection],1)\
                            ,self.browser)
            except IOError: 
                pass
        else:
            try: dlg.FillInfo(tuner.playselection(self.mediaplayer,self.url[selection],1)\
                            ,self.browser)
            except IOError: 
                pass
        #dlg.setvars(self.mediaplayer,self.videoplayer\
        #   ,self.term,self.ripper,self.home,self.maxdl)
        try:
            if info:
                dlg.SetTitle("Warning")
                dlg.infobuttonhide()
            if dlg.ShowModal()==1:
                seq.reset()
                self.retrievedata()
        finally:
            dlg.Destroy()
        #self.SetStatusText('Ready')

    def OnFilemenuPreferencesMenu(self, event):
        if self.reloading==1:
            return
        dlg=TunerPrefs.preferences(self)
        dlg.setfontsize(self.newsize)
        dlg.setvars(self.mediaplayer,self.videoplayer\
            ,self.term,self.ripper,self.home,self.rdir,self.shoutice,self.maxd,\
            self.newsize,self.browser)
        try:
            if dlg.ShowModal()==1:
                seq.reset()
                self.retrievedata()
        finally:
            dlg.Destroy()
        self.mediaplayer,self.videoplayer,self.term,self.ripper,self.rdir,\
            self.shoutice,self.maxd,self.newsize,self.browser=tuner.readprefs\
            (self.home,self.rdir,self.shoutice,self.maxd,self.newsize)
        self.setfontsize()
        self.download()

    def OnFilemenuRecordqueueMenu(self, event):
        if self.reloading==1:
            return
        dlg=RecordQueue.recqueue(self)
        dlg.setfontsize(self.newsize)
        try:
            if dlg.ShowModal()==1:
                seq.reset()
                self.retrievedata()
        finally:
            dlg.Destroy()

    def OnFilemenuReloadMenu(self, event):
        if self.reloading==1:
            return
        if self.running:
            tuner.pkill(self.videoplayer[self.videoplayer.rfind("/")+1:len(self.videoplayer)])
            tuner.pkill(self.mediaplayer[self.mediaplayer.rfind("/")+1:self.mediaplayer.rfind("/")+16])
        self.reloading=1
        self.downloading=0
        self.setgenreboxradio()
        self.radioselected=1
        if (int(self.shoutice)==1):
            thread.start_new_thread(self.reload,(3,))
        else:
            thread.start_new_thread(self.reload,(5,))
        self.checkfilesize()
        event.Skip()
        #get top 100:
        #self.find('')

    def OnFilemenuQuitMenu(self, event):
        self.OnTunapieFrameClose(1)

    def OnFavecontextInfoMenu(self, event):
        self.OnTunapieToolBarInfoTool(1)
    
    def OnFavecontextURLMenu(self, event):
        if self.reloading==1:
            return
        dlg=AddStream.AddURL(self)
        dlg.setfontsize(self.newsize)
        try:
            if dlg.ShowModal()==1:
                seq.reset()
                self.retrievedata()
        finally:
            dlg.Destroy()

    def OnMaincontextInfoMenu(self, event):
        self.OnTunapieToolBarInfoTool(1)

    def OnFaveListCtrlSetFocus(self, event):
        #if self.FaveListCtrl.GetFirstSelected()<0:
        self.MainListCtrl.Select(self.MainListCtrl.GetFirstSelected(),False)
            #self.FaveListCtrl.Select(0)
            #self.FaveListCtrl.EnsureVisible(0)
        event.Skip()
        
    def OnMainListCtrlSetFocus(self, event):
        #if self.MainListCtrl.GetFirstSelected()<0:
        self.FaveListCtrl.Select(self.FaveListCtrl.GetFirstSelected(),False)
            #self.MainListCtrl.Select(0)
            #self.MainListCtrl.EnsureVisible(0)
        event.Skip()

    def OnGenreBoxSetFocus(self, event):
        self.FaveListCtrl.Select(self.FaveListCtrl.GetFirstSelected(),False)
        self.MainListCtrl.Select(self.MainListCtrl.GetFirstSelected(),False)
        event.Skip()

    def OnTunapieFrameClose(self, event):
        try: os.remove('/tmp/'+getpass.getuser()+'_tunapie_temp.pls')
        except OSError:
            pass
        geomfile=open(self.home+'/.tunapie/geom','w')
        size=self.GetSize()
        geomfile.write(str(size[0])+' '+str(size[1])+'\n')
        pos=self.GetPosition()
        geomfile.write(str(pos[0])+' '+str(pos[1])+'\n')
        geomfile.write(str(self.mainsplitter.GetSashPosition())+'\n')
        geomfile.write(str(self.favesplitter.GetSashPosition())+'\n')
        for i in range(5):
            geomfile.write(str(self.MainListCtrl.GetColumnWidth(i))+' ')
        geomfile.write(str(self.MainListCtrl.GetColumnWidth(5))+'\n')
        for i in range(5):
            geomfile.write(str(self.FaveListCtrl.GetColumnWidth(i))+' ')
        geomfile.write(str(self.FaveListCtrl.GetColumnWidth(5))+'\n')
        self.Destroy()

    def OnHelpmenuAboutMenu(self, event):
        if self.reloading==1:
            return
        dlg=AboutTuner.About(self)
        dlg.setfontsize(self.newsize)
        try:
            if dlg.ShowModal()==1:
                seq.reset()
                self.retrievedata()
        finally:
            dlg.Destroy()

    def OnGenreBoxListItemSelected(self, event):
        if self.reloading==1 or self.startup==1:
            return
        self.parsefiles()
        try: self.updatemain(event.GetLabel().lower())
        except AttributeError:
            pass
        event.Skip()
