From 5dbf07a311e9e3ef32cecc7b0ea055765e381c95 Mon Sep 17 00:00:00 2001 From: Manuel Cortez Date: Wed, 24 Jan 2018 17:43:35 -0600 Subject: [PATCH] Added basic app functionality --- src/controller/__init__.py | 0 src/controller/mainController.py | 129 ++++++++++++++++++++++ src/controller/player.py | 114 ++++++++++++++++++++ src/i18n.py | 8 ++ src/main.py | 21 ++++ src/utils.py | 46 ++++++++ src/widgetUtils/__init__.py | 5 + src/widgetUtils/__init__.pyc | Bin 0 -> 223 bytes src/widgetUtils/wxUtils.py | 176 +++++++++++++++++++++++++++++++ src/widgetUtils/wxUtils.pyc | Bin 0 -> 8718 bytes src/wxUI/__init__.py | 0 src/wxUI/mainWindow.py | 73 +++++++++++++ 12 files changed, 572 insertions(+) create mode 100644 src/controller/__init__.py create mode 100644 src/controller/mainController.py create mode 100644 src/controller/player.py create mode 100644 src/i18n.py create mode 100644 src/main.py create mode 100644 src/utils.py create mode 100644 src/widgetUtils/__init__.py create mode 100644 src/widgetUtils/__init__.pyc create mode 100644 src/widgetUtils/wxUtils.py create mode 100644 src/widgetUtils/wxUtils.pyc create mode 100644 src/wxUI/__init__.py create mode 100644 src/wxUI/mainWindow.py diff --git a/src/controller/__init__.py b/src/controller/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/controller/mainController.py b/src/controller/mainController.py new file mode 100644 index 0000000..6426482 --- /dev/null +++ b/src/controller/mainController.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +""" main controller for MusicDL""" +import wx +import logging +import widgetUtils +import utils +from pubsub import pub +from wxUI import mainWindow +from extractors import zaycev +from . import player + +log = logging.getLogger("controller.main") + +class Controller(object): + + def __init__(self): + super(Controller, self).__init__() + log.debug("Starting main controller...") + # Setting up the player object + player.setup() + # Instantiate the only available extractor for now. + self.extractor = zaycev.interface() + # Get main window + self.window = mainWindow.mainWindow() + log.debug("Main window created") + self.window.change_status(_("Ready")) + # Here we will save results for searches as song objects. + self.results = [] + self.connect_events() + # Shows window. + self.window.Show() + + def get_status_info(self): + """ Formatting string for status bar messages """ + if len(self.results) > 0: + results = _("Showing {0} results.").format(len(self.results)) + else: + results = "" + final = results+" " + return final + + def connect_events(self): + """ connects all widgets to their corresponding events.""" + widgetUtils.connect_event(self.window.search, widgetUtils.BUTTON_PRESSED, self.on_search) + widgetUtils.connect_event(self.window.list, widgetUtils.LISTBOX_ITEM_ACTIVATED, self.on_activated) + widgetUtils.connect_event(self.window.list, widgetUtils.KEYPRESS, self.on_keypress) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_play_pause, menuitem=self.window.player_play) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_next, menuitem=self.window.player_next) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_previous, menuitem=self.window.player_previous) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_play_all, menuitem=self.window.player_play_all) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_stop, menuitem=self.window.player_stop) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_volume_down, menuitem=self.window.player_volume_down) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_volume_up, menuitem=self.window.player_volume_up) + widgetUtils.connect_event(self.window, widgetUtils.MENU, self.on_mute, menuitem=self.window.player_mute) + pub.subscribe(self.change_status, "change_status") + + # Event functions. These functions will call other functions in a thread and are bound to widget events. + def on_search(self, *args, **kwargs): + utils.call_threaded(self.search) + + def on_activated(self, *args, **kwargs): + utils.call_threaded(self.play) + + def on_keypress(self, ev): + if ev.GetKeyCode() == wx.WXK_RETURN: + utils.call_threaded(self.play) + ev.Skip() + + def on_play_pause(self, *args, **kwargs): + if player.player.check_is_playing() != False: + return player.player.pause() + return utils.call_threaded(self.play) + + def on_next(self, *args, **kwargs): + item = self.window.get_item() + if item <= len(self.results): + self.window.list.SetSelection(item+1) + else: + self.window.list.SetSelection(0) + return utils.call_threaded(self.play) + + def on_previous(self, *args, **kwargs): + item = self.window.get_item() + if item > 0: + self.window.list.SetSelection(item-1) + else: + self.window.list.SetSelection(len(self.results)-1) + return utils.call_threaded(self.play) + + def on_play_all(self, *args, **kwargs): + pass + + def on_stop(self, *args, **kwargs): + player.player.stop() + + def on_volume_down(self, *args, **kwargs): + player.player.volume = player.player.volume-5 + + def on_volume_up(self, *args, **kwargs): + player.player.volume = player.player.volume+5 + + def on_mute(self, *args, **kwargs): + player.player.volume = 0 + + def change_status(self, status): + """ Function used for changing the status bar from outside the main controller module.""" + self.window.change_status("{0} {1}".format(status, self.get_status_info())) + + # real functions. These functions really are doing the work. + def search(self, *args, **kwargs): + text = self.window.get_text() + if text == "": + return + self.window.list.Clear() + self.change_status(_("Searching {0}... ").format(text,)) + self.extractor.search(text) + self.results = self.extractor.results + for i in self.results: + self.window.list.Append(i.format_track()) + self.change_status("") + + def play(self): + self.change_status(_("Loading song...")) + url = self.extractor.get_download_url(self.results[self.window.get_item()].url) + player.player.play(url) + + def play_audios(self, audios): + player.player.play_all(audios, shuffle=self.window.player_shuffle.IsChecked()) + diff --git a/src/controller/player.py b/src/controller/player.py new file mode 100644 index 0000000..d5f6025 --- /dev/null +++ b/src/controller/player.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- +import random +import sound_lib +import logging +from sound_lib.stream import URLStream +from sound_lib.main import BassError +from sound_lib.output import Output +from pubsub import pub +from utils import RepeatingTimer + +player = None +log = logging.getLogger("player") + +def setup(): + global player + if player == None: + Output() + player = audioPlayer() + +class audioPlayer(object): + + def __init__(self): + self.is_playing = False + self.stream = None + self.vol = 100 + self.is_working = False + self.queue = [] + self.stopped = True + + def play(self, url): + if self.stream != None and self.stream.is_playing == True: + try: + self.stream.stop() + except BassError: + log.exception("error when stopping the file") + self.stream = None + self.stopped = True + if hasattr(self, "worker") and self.worker != None: + self.worker.cancel() + self.worker = None + self.queue = [] + # Make sure there are no other sounds trying to be played. + if self.is_working == False: + self.is_working = True + try: + self.stream = URLStream(url=url) + except BassError: + log.debug("Error when playing the file {0}".format(url,)) + pub.sendMessage("change_status", status=_("Error playing last file")) + return + self.stream.volume = self.vol/100.0 + self.stream.play() + self.stopped = False + self.is_working = False + + def stop(self): + if self.stream != None and self.stream.is_playing == True: + self.stream.stop() + self.stopped = True + if hasattr(self, "worker") and self.worker != None: + self.worker.cancel() + self.worker = None + self.queue = [] + + def pause(self): + if self.stream != None: + if self.stream.is_playing == True: + self.stream.pause() + self.stopped = True + else: + try: + self.stream.play() + self.stopped = False + except BassError: + pass + + @property + def volume(self): + if self.stream != None: + return self.vol + + @volume.setter + def volume(self, vol): + if vol <= 100 and vol >= 0: + self.vol = vol + if self.stream != None: + self.stream.volume = self.vol/100.0 + + def play_all(self, list_of_urls, shuffle=False): + self.stop() + self.queue = list_of_urls + if shuffle: + random.shuffle(self.queue) + self.play(self.queue[0]) + self.queue.remove(self.queue[0]) + self.worker = RepeatingTimer(5, self.player_function) + self.worker.start() + + def player_function(self): + if self.stream != None and self.stream.is_playing == False and self.stopped == False and len(self.stream) == self.stream.position: + if len(self.queue) == 0: + self.worker.cancel() + return + self.play(self.queue[0]) + self.queue.remove(self.queue[0]) + + def check_is_playing(self): + if self.stream == None: + return False + if self.stream != None and self.stream.is_playing == False: + return False + else: + return True + diff --git a/src/i18n.py b/src/i18n.py new file mode 100644 index 0000000..e896765 --- /dev/null +++ b/src/i18n.py @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +import os +import gettext +import locale +from platform_utils import paths + +def setup(): + gettext.install("music-dl", localedir=os.path.join(paths.app_path(), "locales")) \ No newline at end of file diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..6312114 --- /dev/null +++ b/src/main.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +import i18n +import widgetUtils +import logging +import application +from platform_utils import paths + +logging.basicConfig() +log = logging.getLogger("main") + +def setup(): + log.debug("Starting music-dl %s" % (application.version,)) + log.debug("Application path is %s" % (paths.app_path(),)) + i18n.setup() + from controller import mainController + app = widgetUtils.mainLoopObject() + log.debug("Created Application mainloop object") + r = mainController.Controller() + app.run() + +setup() diff --git a/src/utils.py b/src/utils.py new file mode 100644 index 0000000..6a6b2d4 --- /dev/null +++ b/src/utils.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +import threading +import logging + +log = logging.getLogger("utils") + +def call_threaded(func, *args, **kwargs): + #Call the given function in a daemonized thread and return the thread. + def new_func(*a, **k): + func(*a, **k) + thread = threading.Thread(target=new_func, args=args, kwargs=kwargs) + thread.start() + return thread + +class RepeatingTimer(threading.Thread): + """Call a function after a specified number of seconds, it will then repeat again after the specified number of seconds + Note: If the function provided takes time to execute, this time is NOT taken from the next wait period + + t = RepeatingTimer(30.0, f, args=[], kwargs={}) + t.start() + t.cancel() # stop the timer's actions + """ + + def __init__(self, interval, function, daemon=True, *args, **kwargs): + threading.Thread.__init__(self) + self.daemon = daemon + self.interval = float(interval) + self.function = function + self.args = args + self.kwargs = kwargs + self.finished = threading.Event() + + def cancel(self): + """Stop the timer if it hasn't finished yet""" + log.debug("Stopping repeater for %s" % (self.function,)) + self.finished.set() + stop = cancel + + def run(self): + while not self.finished.is_set(): + self.finished.wait(self.interval) + if not self.finished.is_set(): #In case someone has canceled while waiting + try: + self.function(*self.args, **self.kwargs) + except: + log.exception("Execution failed. Function: %r args: %r and kwargs: %r" % (self.function, self.args, self.kwargs)) diff --git a/src/widgetUtils/__init__.py b/src/widgetUtils/__init__.py new file mode 100644 index 0000000..87f95ff --- /dev/null +++ b/src/widgetUtils/__init__.py @@ -0,0 +1,5 @@ +import platform +#if platform.system() == "Windows": +from .wxUtils import * +#elif platform.system() == "Linux": +# from gtkUtils import * diff --git a/src/widgetUtils/__init__.pyc b/src/widgetUtils/__init__.pyc new file mode 100644 index 0000000000000000000000000000000000000000..460139a4141b9c243fe5e35acfd8c83648f547eb GIT binary patch literal 223 zcmYLDOA5k344t+MMf3umU~u7DL_|=iD>t?aB~WTR%D}W!CMi{~?Ey4X1s}=FOF}-; zYcg6S;#7zqLXI1DoHCVcfiOaxzd95q5DAx#GUB#=GY&FfNuFlXPt%a8F*#kWt7yPU zcTY(hlq|)cFy?f-gcOxSsPej126nb+D^(LhtZCm~0Bxajqo2wFx&k^~-W2ugAj@>E XDa+=~qrbVTY}p#M_OGD-WE_3~+*dV} literal 0 HcmV?d00001 diff --git a/src/widgetUtils/wxUtils.py b/src/widgetUtils/wxUtils.py new file mode 100644 index 0000000..fb7bcc1 --- /dev/null +++ b/src/widgetUtils/wxUtils.py @@ -0,0 +1,176 @@ +import wx + +toolkit = "wx" + +### Code responses for WX dialogs. + +# this is when an user presses OK on a dialogue. +OK = wx.ID_OK + +# This is when an user presses cancel on a dialogue. +CANCEL = wx.ID_CANCEL + +# This is when an user closes the dialogue or an id to create the close button. +CLOSE = wx.ID_CLOSE + +# The response for a "yes" Button pressed on a dialogue. +YES = wx.ID_YES + +# This is when the user presses No on a default dialogue. +NO = wx.ID_NO + +###events + +# This is raised when the application must be closed. +CLOSE_EVENT = wx.EVT_CLOSE + +# This is activated when a button is pressed. +BUTTON_PRESSED = wx.EVT_BUTTON + +# This is raised when a checkbox changes its status. +CHECKBOX = wx.EVT_CHECKBOX + +# This is activated when an user enter text on an edit box. +ENTERED_TEXT = wx.EVT_TEXT + +# This is raised when a user activates a menu. +MENU = wx.EVT_MENU + +# This is raised when a user presses any key in the control. +KEYPRESS = wx.EVT_CHAR_HOOK + +# This is raised when a user releases a key in the control. +KEYUP = wx.EVT_KEY_UP + +# This happens when a notebook tab is changed, It is used in Treebooks too. +NOTEBOOK_PAGE_CHANGED = wx.EVT_TREEBOOK_PAGE_CHANGED + +# This happens when a radiobutton group changes its status. +RADIOBUTTON = wx.EVT_RADIOBUTTON + +# Taskbar mouse clicks. +#TASKBAR_RIGHT_CLICK = wx.EVT_TASKBAR_RIGHT_DOWN +#TASKBAR_LEFT_CLICK = wx.EVT_TASKBAR_LEFT_DOWN +LISTBOX_CHANGED = wx.EVT_LISTBOX +LISTBOX_ITEM_ACTIVATED = wx.EVT_LIST_ITEM_ACTIVATED + +def exit_application(): + """ Closes the current window cleanly. """ + wx.GetApp().ExitMainLoop() + +def connect_event(parent, event, func, menuitem=None, *args, **kwargs): + """ Connects an event to a function. + parent wx.window: The widget that will listen for the event. + event widgetUtils.event: The event that will be listened for the parent. The event should be one of the widgetUtils events. + function func: The function that will be connected to the event.""" + if menuitem == None: + return getattr(parent, "Bind")(event, func, *args, **kwargs) + else: + return getattr(parent, "Bind")(event, func, menuitem, *args, **kwargs) + +def connectExitFunction(exitFunction): + """ This connect the events in WX when an user is turning off the machine.""" + wx.GetApp().Bind(wx.EVT_QUERY_END_SESSION, exitFunction) + wx.GetApp().Bind(wx.EVT_END_SESSION, exitFunction) + +class BaseDialog(wx.Dialog): + def __init__(self, *args, **kwargs): + super(BaseDialog, self).__init__(*args, **kwargs) + + def get_response(self): + return self.ShowModal() + + def get(self, control): + if hasattr(self, control): + control = getattr(self, control) + if hasattr(control, "GetValue"): return getattr(control, "GetValue")() + elif hasattr(control, "GetLabel"): return getattr(control, "GetLabel")() + else: return -1 + else: return 0 + + def set(self, control, text): + if hasattr(self, control): + control = getattr(self, control) + if hasattr(control, "SetValue"): return getattr(control, "SetValue")(text) + elif hasattr(control, "SetLabel"): return getattr(control, "SetLabel")(text) + elif hasattr(control, "ChangeValue"): return getattr(control, "ChangeValue")(text) + else: return -1 + else: return 0 + + def destroy(self): + self.Destroy() + + def set_title(self, title): + self.SetTitle(title) + + def get_title(self): + return self.GetTitle() + + def enable(self, control): + getattr(self, control).Enable(True) + + def disable(self, control): + getattr(self, control).Enable(False) + +class mainLoopObject(wx.App): + + def __init__(self): + self.app = wx.App() +# self.lc = wx.Locale() +# lang=languageHandler.getLanguage() +# wxLang=self.lc.FindLanguageInfo(lang) +# if not wxLang and '_' in lang: +# wxLang=self.lc.FindLanguageInfo(lang.split('_')[0]) +# if hasattr(sys,'frozen'): +# self.lc.AddCatalogLookupPathPrefix(paths.app_path("locales")) +# if wxLang: +# self.lc.Init(wxLang.Language) + + def run(self): + self.app.MainLoop() + +class list(object): + def __init__(self, parent, *columns, **listArguments): + self.columns = columns + self.listArguments = listArguments + self.create_list(parent) + + def set_windows_size(self, column, characters_max): + self.list.SetColumnWidth(column, characters_max*2) + + def set_size(self): + self.list.SetSize((self.list.GetBestSize()[0], 1000)) + + def create_list(self, parent): + self.list = wx.ListCtrl(parent, -1, **self.listArguments) + for i in range(0, len(self.columns)): + self.list.InsertColumn(i, u"%s" % (self.columns[i])) + + def insert_item(self, reversed, *item): + """ Inserts an item on the list.""" + if reversed == False: items = self.list.GetItemCount() + else: items = 0 + self.list.InsertItem(items, item[0]) + for i in range(1, len(self.columns)): + self.list.SetItem(items, i, item[i]) + + def remove_item(self, pos): + """ Deletes an item from the list.""" + if pos > 0: self.list.Focus(pos-1) + self.list.DeleteItem(pos) + + def clear(self): + self.list.DeleteAllItems() + + def get_selected(self): + return self.list.GetFocusedItem() + + def select_item(self, pos): + self.list.Focus(pos) + + def get_count(self): + selected = self.list.GetItemCount() + if selected == -1: + return 0 + else: + return selected diff --git a/src/widgetUtils/wxUtils.pyc b/src/widgetUtils/wxUtils.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80fdee1af34dd2bff5388c425dbce2ac04f42e27 GIT binary patch literal 8718 zcmcgx-E$jP6~8OVj+HpyX;L?7vTf2vrL9|L3Y1VnZCQ>rapbU)^PzEPyI!sBwb#4u z-c{{%lBZfG=1ea^iq|Ks@4 zPdnBLUktvIHI~! z0#sG^r~t=QcUpkss(V6!ld5}4fYYjbMu4-bdrpAYRQJ397gYCk0cKS94FN8y?j-@< zRNc!0Tv1(HfVWilZ2_*T?ll44QQdb{udJSdmg^*{S5ePE%X_LfA)Vh*J%jN3Y6GK3 z*!fhchusfU&k*pT3{(dLv#JMzK9b&JgWiw1dAl|Z7KZ=CUn?sC+&>sF7;IH_GWZ;- z46L$v&UT5lC2P4rUqfZrqeKVV&b9*E@26=HXZC&=_mX|vj{+}_9?jaVS{XAP6qQY) zx)o$|dwUtrZybc#9WRW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