Exemplo n.º 1
0
	def _makeListView (self, parent):
		if self.config.groupByGenre:
			listView = GroupListView (parent, wx.ID_ANY, style = wx.LC_REPORT | wx.SUNKEN_BORDER, useAlternateBackColors = False)
		else:
			listView = ObjectListView (parent, wx.ID_ANY, style = wx.LC_REPORT | wx.SUNKEN_BORDER, useAlternateBackColors = False)

		listView.rowFormatter = self.rowFormatter
		listView.SetEmptyListMsg ("No transducers found")

		# COLUMNS:
		# Normal: DR
		# Grp: D(G)R
		# Det: DNGSR
		# Det+Grp: DN(G)SR
		cols = ([
			ColumnDefn ("Description", "left", 220, "smartName"),
			ColumnDefn ("Reading", "right", 100, "lastRead", isSpaceFilling = True),
		])

		if self.config.viewDetails:
			cols.insert (1, ColumnDefn ("Name", "center", 50, "name"))
			if self.config.groupByGenre:
				# This col is only used for grouping, use 0 width and make entries empty to hide it
				cols.insert (2, ColumnDefn ("Genre", "center", 0, "genre", maximumWidth = 0, stringConverter = lambda g: "", groupKeyConverter = lambda g: "Sensors" if g == Sensoria.SENSOR else "Actuators"))
			else:
				cols.insert (2, ColumnDefn ("Genre", "center", 100, "genre", stringConverter = lambda g: "Sensor" if g == Sensoria.SENSOR else "Actuator"))
			cols.insert (3, ColumnDefn ("Stereo", "center", 50, "stereotype"))
		elif self.config.groupByGenre:
				# This col is only used for grouping, use 0 width and make entries empty to hide it
				cols.insert (2, ColumnDefn ("Genre", "center", 50, "genre", maximumWidth = 0, stringConverter = lambda g: "", groupKeyConverter = lambda g: "Sensors" if g == Sensoria.SENSOR else "Actuators"))

		listView.SetColumns (cols)

		if self.config.groupByGenre:
			listView.showItemCounts = False
			listView.SetShowGroups = True
			listView.alwaysGroupByColumnIndex = 3			# col 0 is expansion icon
			listView.SetSortColumn (listView.columns[1])
		else:
			listView.SetSortColumn (listView.columns[0])

		listView.Bind (wx.EVT_LIST_ITEM_ACTIVATED, self.onItemDoubleClicked)
		listView.Bind (wx.EVT_LIST_ITEM_RIGHT_CLICK, self.onItemRightClicked)

		return listView
Exemplo n.º 2
0
class MyFrame(wx.Frame):
    results = []
    downloads = []

    def __init__(self, *args, **kwds):
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        font = wx.Font(9,
                       wx.FONTFAMILY_DEFAULT,
                       style=wx.FONTSTYLE_NORMAL,
                       weight=wx.FONTWEIGHT_NORMAL)
        self.lbl_query = wx.StaticText(self,
                                       -1,
                                       "  Song:  ",
                                       style=wx.ALIGN_CENTRE)
        self.lbl_query.SetFont(font)
        self.txt_query = wx.TextCtrl(self, 1, "", style=wx.TE_PROCESS_ENTER)
        self.fb = wx.StaticBitmap(self,
                                  bitmap=wx.BitmapFromImage(
                                      wx.ImageFromStream(
                                          fbicon, wx.BITMAP_TYPE_PNG)),
                                  size=(22, 22))
        self.folder_chooser = wx.Button(
            self,
            -1,
            "Choose Destination",
            size=[-1, self.txt_query.GetSize().GetHeight()])
        self.lst_results = ObjectListView(self, -1, style=wx.LC_REPORT)
        self.lst_downloads = GroupListView(self, -1, style=wx.LC_REPORT)
        self.lst_artists = ObjectListView(self, -1, style=wx.LC_REPORT)
        self.lst_albums = ObjectListView(self, -1, style=wx.LC_REPORT)
        self.lst_songs = ObjectListView(self, -1, style=wx.LC_REPORT)
        self.frame_statusbar = self.CreateStatusBar(1, wx.SB_RAISED)
        self.__set_properties()
        self.__do_layout()
        self.Bind(EVT_EXEC_FUNC, self._ExecFunc)
        self.Bind(wx.EVT_TEXT_ENTER, self._TextEnter, self.txt_query)
        self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self._ResultsContext,
                  self.lst_results)
        self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self._ResultsContext,
                  self.lst_songs)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._DoubleClick,
                  self.lst_results)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._DoubleClick,
                  self.lst_songs)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._DoubleClick,
                  self.lst_downloads)
        self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self._DownloadsContext,
                  self.lst_downloads)
        self.Bind(wx.EVT_BUTTON, self._ChooseFolder, self.folder_chooser)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._ObjectSelected,
                  self.lst_artists)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self._ObjectSelected,
                  self.lst_albums)
        self.fb.Bind(wx.EVT_LEFT_DOWN, self._FBClick)
        self.txt_query.Bind(wx.EVT_KEY_DOWN, self._Tab)
        self.Bind(wx.EVT_CLOSE, self._Close)
        self.menu_results = {}
        self.menu_downloads = {}
        self.menu_results[ID_DOWNLOAD] = "Download"
        self.menu_downloads[ID_REMOVE] = "Remove"
        self.artists = []
        if sys.platform == 'win32':
            self.SetIcon(wx.Icon(sys.executable, wx.BITMAP_TYPE_ICO))
        else:
            if os.path.exists("groove.ico"):
                self.SetIcon(wx.Icon("groove.ico", wx.BITMAP_TYPE_ICO))

    def __set_properties(self):
        self.SetTitle("JTR's Grooveshark Downloader v" + version)
        self.SetSize((600, 400))
        self.frame_statusbar.SetStatusWidths([-1])
        frame_statusbar_fields = [""]
        columns = [
            ColumnDefn("Title",
                       "left",
                       0,
                       valueGetter="SongName",
                       isSpaceFilling=True),
            ColumnDefn("Album",
                       "center",
                       0,
                       valueGetter="AlbumName",
                       isSpaceFilling=True),
            ColumnDefn("Artist",
                       "center",
                       0,
                       valueGetter="ArtistName",
                       isSpaceFilling=True)
        ]
        columns[0].freeSpaceProportion = 2
        columns[1].freeSpaceProportion = columns[2].freeSpaceProportion = 1
        self.lst_results.SetColumns(columns)
        self.lst_results.SetObjects(self.results)
        self.lst_results.SetEmptyListMsg(emptylistmsg)
        self.lst_results._ResizeSpaceFillingColumns()
        self.lst_results.useAlternateBackColors = False
        columns = [
            ColumnDefn("Title",
                       "left",
                       160,
                       valueGetter="filename",
                       groupKeyGetter="album",
                       isSpaceFilling=True),
            ColumnDefn("Bitrate", "center", 60, valueGetter="bitrate"),
            ColumnDefn("Speed", "center", 75, valueGetter="speed"),
            ColumnDefn("Done/Total", "center", 100, valueGetter="size"),
            ColumnDefn("Progress", "center", 80, valueGetter="progress")
        ]
        self.lst_downloads.SetColumns(columns)
        self.lst_downloads.SetObjects(self.downloads)
        self.lst_downloads.SetEmptyListMsg("N/A")
        self.lst_downloads.SortBy(1)
        self.lst_downloads.useAlternateBackColors = False
        self.lst_downloads.putBlankLineBetweenGroups = False
        self.lst_downloads.SetShowGroups(False)
        columns = [
            ColumnDefn("Artist",
                       "center",
                       100,
                       valueGetter="name",
                       isSpaceFilling=True)
        ]
        self.lst_artists.SetColumns(columns)
        self.lst_artists.SetEmptyListMsg("N/A")
        self.lst_artists.useAlternateBackColors = False
        columns = [
            ColumnDefn("Album",
                       "center",
                       100,
                       valueGetter="name",
                       isSpaceFilling=True)
        ]
        self.lst_albums.SetColumns(columns)
        self.lst_albums.SetEmptyListMsg("N/A")
        self.lst_albums.useAlternateBackColors = False
        columns = [
            ColumnDefn("Song",
                       "center",
                       100,
                       valueGetter="Name",
                       isSpaceFilling=True)
        ]
        self.lst_songs.SetColumns(columns)
        self.lst_songs.SetEmptyListMsg("N/A")
        self.lst_songs.useAlternateBackColors = False
        for i in range(len(frame_statusbar_fields)):
            self.frame_statusbar.SetStatusText(frame_statusbar_fields[i], i)
        self.frame_statusbar.SetStatusStyles([wx.SB_FLAT])
        self.list_by_mode = self.lst_results

    def __do_layout(self):
        self.sizer_1 = wx.BoxSizer(wx.VERTICAL)
        self.sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer_2.Add(self.lbl_query, 0, wx.ALIGN_CENTER, 0)
        self.sizer_2.Add(self.txt_query, 2, 0, 0)
        self.sizer_2.Add(self.folder_chooser, 0, wx.ALIGN_CENTER, 0)
        self.sizer_2.Add(self.fb, 0, wx.ALIGN_CENTER, 0)
        self.sizer_1.Add(self.sizer_2, 0, wx.EXPAND, 0)
        self.sizer_1.Add(self.lst_results, 2, wx.EXPAND, 0)
        self.sizer_1.Add(self.sizer_3, 2, wx.EXPAND, 0)
        self.sizer_1.Add(self.lst_downloads, 1, wx.EXPAND, 0)
        self.sizer_3.Add(self.lst_artists, 1, wx.EXPAND, 0)
        self.sizer_3.Add(self.lst_albums, 1, wx.EXPAND, 0)
        self.sizer_3.Add(self.lst_songs, 2, wx.EXPAND, 0)
        self.SetSizer(self.sizer_1)
        self.sizer_1.Show(self.sizer_3, False)
        self.Layout()

    def _TextEnter(self, event):
        self.artists = []
        if self.lbl_query.GetLabel() == "  Artist:  ":
            self.lst_albums.DeleteAllItems()
            self.lst_songs.DeleteAllItems()
            search_thread = t_search_object(self, _query=event.GetString())
        elif self.lbl_query.GetLabel() == "  Song:  ":
            search_thread = t_search_flat(self, event.GetString())
        search_thread.start()

    def _ExecFunc(self, event):
        event.func(self, event)

    def _FBClick(self, event):
        webbrowser.open_new_tab('http://www.facebook.com/groove.dl')

    def _ResultsContext(self, event):
        menu = wx.Menu()
        menu.Append(ID_DOWNLOAD, "Download")
        wx.EVT_MENU(menu, ID_DOWNLOAD, self._ContextSelection)
        if self.lbl_query.GetLabel() == "  Song:  ":
            lst = self.lst_results
        elif self.lbl_query.GetLabel() == "  Artist:  ":
            lst = self.lst_songs
        self.PopupMenu(menu, event.GetPoint() + lst.GetPosition())
        menu.Destroy()

    def _DownloadsContext(self, event):
        menu = wx.Menu()
        for (id, title) in self.menu_downloads.items():
            menu.Append(id, title)
            wx.EVT_MENU(menu, id, self._ContextSelection)
        self.PopupMenu(menu,
                       event.GetPoint() + self.lst_downloads.GetPosition())
        menu.Destroy()

    def _DoubleClick(self, event):
        if event.GetEventObject() in [self.lst_results, self.lst_songs]:
            self._ContextSelection(ID_DOWNLOAD)
        elif event.GetEventObject() == self.lst_downloads:
            try:
                path = os.path.join(
                    dest,
                    self.lst_downloads.GetSelectedObjects()[0]["filename"])
                if sys.platform == 'win32': os.startfile(path)
                elif sys.platform == 'linux2':
                    subprocess.Popen(['xdg-open', path])
            except:
                pass

    def _ContextSelection(self, event, flag=None):
        if (event == ID_DOWNLOAD) or (event.GetId() == ID_DOWNLOAD):
            if self.lbl_query.GetLabel() == "  Song:  ":
                lst = self.lst_results
                name = 'SongName'
            elif self.lbl_query.GetLabel() == "  Artist:  ":
                lst = self.lst_songs
                name = 'Name'
            for song in lst.GetSelectedObjects():
                filename = format
                filename = filename.replace(
                    'artist', strip(song["ArtistName"], "<>:\"/\|?*"))
                filename = filename.replace('title',
                                            strip(song[name], "<>:\"/\|?*"))
                filename = filename.replace(
                    'album', strip(song["AlbumName"], "<>:\"/\|?*"))
                c = 2
                while os.path.exists(os.path.join(dest, filename + '.mp3')):
                    filename = filename + ' (%d)' % c
                    c += 1
                filename += '.mp3'
                t = t_download(self, song)
                t.download = {
                    "progress": "Initializing",
                    "thread": t,
                    "filename": filename,
                    "album": song["AlbumName"]
                }
                self.downloads.append(t.download)
                self.lst_downloads.SetObjects(self.downloads)
                t.start()
        elif (flag != None and flag.flag == ID_REMOVE) or (event.GetId()
                                                           == ID_REMOVE):
            for d in self.lst_downloads.GetSelectedObjects():
                d["thread"].cancelled = True
                self.downloads.remove(d)
            self.lst_downloads.RemoveObjects(
                self.lst_downloads.GetSelectedObjects())

    def _ChooseFolder(self, event):
        global dest
        dialog = wx.DirDialog(
            None, "Please choose the destination directory:",
            os.getenv('USERPROFILE')
            if sys.platform == 'win32' else os.getenv('HOME'))
        if dialog.ShowModal() == wx.ID_OK:
            dest = dialog.GetPath()
        dialog.Destroy()

    def _Tab(self, event):
        if event.GetKeyCode() == 9:
            if self.lbl_query.GetLabel() == "  Song:  ":
                self.sizer_1.Show(self.sizer_3, True)
                self.sizer_1.Show(self.lst_results, False)
                self.sizer_1.Layout()
                self.lbl_query.SetLabel("  Artist:  ")
                self.list_by_mode = self.lst_artists
                self.lst_downloads.SetShowGroups(True)
                self.lst_downloads._ResizeSpaceFillingColumns()
            elif self.lbl_query.GetLabel() == "  Artist:  ":
                self.sizer_1.Show(self.sizer_3, False)
                self.sizer_1.Show(self.lst_results, True)
                self.sizer_1.Layout()
                self.lbl_query.SetLabel("  Song:  ")
                self.list_by_mode = self.lst_results
                self.lst_downloads.SetShowGroups(False)
                self.lst_downloads._ResizeSpaceFillingColumns()
        event.Skip()

    def _ObjectSelected(self, event):
        if event.GetEventObject() == self.lst_artists:
            self.lst_albums.DeleteAllItems()
            self.lst_songs.DeleteAllItems()
            obj = self.lst_artists.GetSelectedObject()
            artist_thread = t_search_object(self, obj)
            artist_thread.start()
        elif event.GetEventObject() == self.lst_albums:
            self.lst_songs.SetObjects(
                self.lst_albums.GetSelectedObject().Songs)

    def _Close(self, event):
        l = 0
        for i in self.downloads:
            if i["progress"] != "Completed" and i["progress"] != "Error":
                l += 1
        if l > 0:
            if wx.MessageDialog(
                    self,
                    "There are currently %d active downloads. Are you sure you want to cancel them and exit ?"
                    % l, "Active downloads",
                    wx.YES_NO | wx.CENTRE).ShowModal() == wx.ID_NO:
                return
        print "BWAH"
        for d in self.downloads:
            d["thread"].cancelled = True
        config = ConfigParser.RawConfigParser()
        config.add_section("groove-dl")
        config.set("groove-dl", "dest", dest)
        print "BWAH"
        config.set("groove-dl", "format", format)
        config.write(open(os.path.join(conf, "settings.ini"), "wb"))
        sys.stdout.close()
        sys.stderr.close()
        while (threading.active_count() > 3):
            time.sleep(0.1)
        os._exit(0)