Пример #1
0
 def OnNewButton(self, event=None):
     # handle click on New project button
     self.DisableKeypresses()
     # get project filename extension
     SettingsMgr = SettingsManager()
     ProjFileExt = SettingsMgr.get_config('ProjFileExt')
     OpenSuccess = False  # whether valid project files are identified for opening
     # let the user select a template
     DialogueBox = SelectTemplateDialogue(
         parent=self,
         title=_('Vizop: Choose a template'),
         ColourScheme=self.ColourScheme,
         ProjTemplates=self.ProjTemplates)
     if DialogueBox.ShowModal() == wx.ID_OK:
         # get the template file and project filename to create from the user
         TargetTemplateFile, ProjFilename, SaveOnFly = DialogueBox.ReturnData
         # force the project filename to have expected extension
         ProjFilename = EnsureFilenameHasExtension(ProjFilename,
                                                   ProjFileExt)
         CreatableProjFiles, ProjOpenData = self.HandleNewFileRequest(
             [TargetTemplateFile],
             NewFilenames=[ProjFilename],
             NewProjects=True,
             SaveOnFly=SaveOnFly)
         OpenSuccess = bool(CreatableProjFiles)
     # allow user to continue working in Welcome Frame if no projects can be created. TODO give user feedback
     if not OpenSuccess:
         self.ReinstateKeypresses()
	def __init__(self, user_ID=None):
		#voice control can be activated or deactivated
		self.is_active = True
		
		#create MQTT address 
		MQTT_IP_ADDR = "localhost"
		MQTT_PORT = 1883
		self.mqtt_address = "{}:{}".format(MQTT_IP_ADDR, str(MQTT_PORT))

		#save the user that started the voicecontrol
		self.user_ID = user_ID

		#start the logging process
		LoggingManager.start_logging()
		LoggingManager.log_event('Start logging of incoming events...')
				
		#start SettingsManager and ControlsCommunicator
		self.settingsmanager = SettingsManager.SettingsManager(parent=self)
		self.settingsmanager.activate_voice_control()
		
		self.controlscommunicator = ControlsCommunicator.ControlsCommunicator(parent=self, user_ID=self.user_ID)
 		
		#add contacts to vocabulary
		add_doctors(self.user_ID)
		add_emergency_contacts(self.user_ID)
		
		#subscribe to master intent and intent not recognized
		#self.subscribe_actions()
		
		#reset alarm confirmation settings
		ControlsCommunicator.set_confirmation_started_by_voice(False)
		ControlsCommunicator.set_alarm_confirmed_by_voice(False)
Пример #3
0
def InitializeVizop():
    """Runs all the initialisation tasks needed for Vizop startup.
	Tasks like loading state information, setting up callbacks for config
	changes etc. should all go in this function.
	"""
    #	UserProfileFilename = {'Linux': '%s/.vizop/profile', 'Windows': '%s\\AppData\\Local\\Vizop\\profile.config',
    #						   'Darwin': '%s./Vizop/profile'}.get(system(), '') % UserHomeDirectory
    #	try:
    #		# where to find datafiles needed at runtime
    #		RuntimeFileDirectory = {'Linux': '%s/Documents/Computing/Vizop/Runtime',
    #							'Windows': '%s\\AppData\\Local\\Vizop\\Runtime',
    #							'Darwin': '%s/.vizop/Runtime'}[system()] % UserHomeDirectory
    #	except KeyError:
    #		RuntimeFileDirectory = ''
    #		print("Vizop: WARNING: Unknown platform - don't know where to find Runtime files (problem code: ST62)")
    #in case the config files have been changed since the last program exit, update the
    #size of the recent projects list

    #register callback functions to deal with config changes during program execution
    sm = SettingsManager()
    sm.register_config_change_callback('RecentProjectsListMaxSize',
                                       ResizeRecentProjectsList)
    # set UserHomeDir to user's home directory, e.g. /Users/peter
    sm.set_value('UserHomeDir',
                 os.path.expanduser('~' + getuser()))  # Beazley p283

    #add our art provider to the stack of providers. We add it to the bottom, so that
    #default icons will be used in preference to our own. It also means that GetSizeHint()
    #will query a built-in provider rather than ours
    #	wx.ArtProvider.Insert(art.ArtProvider())
    wx.ArtProvider.PushBack(art.ArtProvider())
Пример #4
0
def StoreValueInUserConfig(ConfigName, Value):
    # store Value (str) in user's config data for ConfigName (str)
    assert isinstance(ConfigName, str)
    assert isinstance(Value, str)
    sm = SettingsManager()
    ce = sm.get_config_editor()
    ce.set_config(ConfigName, Value)
    ce.apply_changes()  # save config changes in SettingsManager
Пример #5
0
    def onInit(self):
        # Check if we already added views because after
        # exiting music vis this gets called again.
        if self.__view_manager.num_views() == 0:
            #Get the startup view from the settings
            startup_screen = SettingsManager().get_misc_startup_screen()
            if startup_screen == StartupScreen.Playlists:
                self._init_playlists()

            #Always display new stuff as a fallback
            else:
                self._init_new_stuff()
Пример #6
0
def ResizeRecentProjectsList():
    """
	Updates the length of the recent projects list
	to the size specified by the 'RecentProjectsListMaxSize' config.
	"""
    sm = SettingsManager()
    new_size = sm.get_config('RecentProjectsListMaxSize')

    try:
        old_list = sm.get_config('RecentProjectsList')
    except KeyError:
        old_list = []
    sm.set_value('RecentProjectsList', old_list[:new_size])
Пример #7
0
 def OnStoreButton(self, event=None):
     # handle 'Start new file from template and store my work' request
     global KeyPressHash
     self.DisableKeypresses()
     # retrieve the target template filename from the dropdown box
     SettingsMgr = SettingsManager()
     TargetTemplateStub = self.tc.GetStringSelection()
     TargetTemplateFile = self.avail_templates[TargetTemplateStub]
     if IsReadableFile(TargetTemplateFile):
         # get a default directory in which to store the project
         try:
             DefDir = SettingsMgr.get_config('NewProjDir')
         except KeyError:
             # No default dir found in settings: store one
             DefDir = SettingsMgr.get_value('UserHomeDir')
             SettingsMgr.set_value('NewProjDir', DefDir)
         # get default extension for project files
         ProjFileExt = SettingsMgr.get_config('ProjFileExt')
         # get a filename to store the project
         (StoreLocOK, ProjFilename) = GetFilenameForSave(
             DialogueParentFrame=self,
             DialogueTitle=_('Vizop needs a filename for your new project'),
             DefaultDir=DefDir,
             DefaultFile='',
             Wildcard='',
             DefaultExtension=ProjFileExt)
         if StoreLocOK:
             # set dialogue box's return data: TargetTemplateFile (str), ProjFilename (str), SaveOnFly (bool)
             self.ReturnData = (TargetTemplateFile, ProjFilename, True)
             SettingsMgr.set_value('NewProjDir',
                                   os.path.dirname(ProjFilename))
             # close the template selection dialogue box
             self.EndModal(wx.ID_OK)
         else:  # we're returning to template selection dialogue: reinstate keyboard shortcuts
             self.ReinstateKeypresses()
     else:  # there was a problem with the template file; pop up a message
         i = wx.MessageBox(
             _('Vizop says sorry'),
             (_("Template %s can't be opened") % TargetTemplateStub),
             style=wx.OK)
Пример #8
0
    def onInit(self):
        # Check if we already added views because after
        # exiting music vis this gets called again.
        if self.__view_manager.num_views() == 0:
            #Get the startup view from the settings
            startup_screen = SettingsManager().get_misc_startup_screen()
            if startup_screen == StartupScreen.Playlists:
                self._init_playlists()

            #Always display new stuff as a fallback
            else:
                self._init_new_stuff()

        #Otherwise show the current view
        else:
            self._set_active_tab()
            self.__view_manager.show()

        #Store current window id
        manager = self.__application.get_var('info_value_manager')
        manager.set_infolabel('spotimc_window_id',
                              xbmcgui.getCurrentWindowId())
Пример #9
0
def select_file_from_all(message='',
                         default_path=None,
                         wildcard='*',
                         allow_multi_files=False,
                         parent_frame=None,
                         **Args):
    """
	Provide generic file selection dialogue. Allows user to select any file(s)
	from the filesystem.
	Returns list of full file paths selected (or [] if none were selected)
	"""
    # **Args is to soak up obsolete arg read_only (no longer recognised by wxPython)
    # force MacOS to apply filter in wildcard
    wx.SystemOptions.SetOption(u"osx.openfiledialog.always-show-types", 1)
    # get default directory to show in dialogue
    if default_path is None:
        sm = SettingsManager()
        try:  # get saved path from config file
            default_path = sm.get_config('UserWorkingDir')
        except KeyError:  # no path saved; select user's home folder
            default_path = os.path.expanduser('~')

    dialogue = wx.FileDialog(message=message,
                             defaultDir=default_path,
                             wildcard='Vizop project files (*.vip)|*.vip',
                             style=((wx.FD_MULTIPLE * allow_multi_files)
                                    | wx.FD_OPEN),
                             parent=parent_frame,
                             pos=(100, 100))

    if dialogue.ShowModal() == wx.ID_OK:  # dialogue box exited with OK button
        if allow_multi_files:
            return dialogue.GetPaths()
        else:
            return [dialogue.GetPath()]
    else:
        # dialogue box exited with Cancel button
        return []
Пример #10
0
def main(addon_dir):
    #Check needed directories first
    data_dir, cache_dir, settings_dir = check_dirs()
    
    #Instantiate the settings obj
    settings_obj = SettingsManager()
    
    #Show legal warning
    show_legal_warning(settings_obj)
    
    #Start checking the version
    check_addon_version(settings_obj)
    
    #Don't set cache folder if it's disabled
    if not settings_obj.get_cache_status():
        cache_dir = ''
    
    #Initialize spotify stuff
    ml = MainLoop()
    buf = BufferManager(get_audio_buffer_size())
    logout_event = Event()
    callbacks = SpotimcCallbacks(ml, buf, logout_event)
    sess = Session(
        callbacks,
        app_key=appkey,
        user_agent="python ctypes bindings",
        settings_location=settings_dir,
        cache_location=cache_dir,
        initially_unload_playlists=False,
    )
    
    #Now that we have a session, set settings
    set_settings(settings_obj, sess)
    
    #Initialize libspotify's main loop handler on a separate thread
    ml_runner = MainLoopRunner(ml, sess)
    ml_runner.start()
   
    #If login was successful start main window
    if do_login(sess, addon_dir, "DefaultSkin"):
        proxy_runner = ProxyRunner(sess, buf, host='127.0.0.1')
        proxy_runner.start()
        
        print 'port: %s' % proxy_runner.get_port()
        
        #Instantiate the playlist manager
        playlist_manager = playback.PlaylistManager(proxy_runner)
        
        #Set the track preloader callback
        preloader_cb = get_preloader_callback(sess, playlist_manager, buf)
        proxy_runner.set_stream_end_callback(preloader_cb)
        
        #Start main window and enter it's main loop
        mainwin = windows.MainWindow("main-window.xml", addon_dir, "DefaultSkin")
        mainwin.initialize(sess, proxy_runner, playlist_manager)
        mainwin.doModal()
        
        #Playback and proxy deinit sequence
        proxy_runner.clear_stream_end_callback()
        player = xbmc.Player()
        player.stop()
        proxy_runner.stop()
        buf.cleanup()
        
        #Clear some vars and collect garbage
        proxy_runner = None
        preloader_cb = None
        playlist_manager = None
        mainwin = None
        gc.collect()
        
        #from _spotify.utils.moduletracker import _tracked_modules
        #print "tracked modules after: %d" % len(_tracked_modules)
        
        #import objgraph
        #objgraph.show_backrefs(_tracked_modules, max_depth=10)
        
        #Logout
        sess.logout()
        logout_event.wait(10)
    
    #Stop main loop
    ml_runner.stop()
Пример #11
0
def GetValueFromUserConfig(ConfigName):
    # retrieve and return config value for ConfigName (str) from the user's config data (stored in config file)
    # returns default (see settings module) if no key has been stored
    sm = SettingsManager()
    return sm.get_config(ConfigName)
Пример #12
0
 def __init__(self):
     self.organization = OrganizationManager()
     self.queue = QueueManager()
     self.group = QueueGroupManager()
     self.settings = SettingsManager()
Пример #13
0
def gui_main(addon_dir):
    #Initialize app var storage
    app = Application()
    logout_event = Event()
    connstate_event = Event()
    info_value_manager = InfoValueManager()
    app.set_var('logout_event', logout_event)
    app.set_var('login_last_error', ErrorType.Ok)
    app.set_var('connstate_event', connstate_event)
    app.set_var('exit_requested', False)
    app.set_var('info_value_manager', info_value_manager)

    #Check needed directories first
    data_dir, cache_dir, settings_dir = check_dirs()

    #Instantiate the settings obj
    settings_obj = SettingsManager()

    #Show legal warning
    show_legal_warning(settings_obj)

    #Start checking the version
    check_addon_version(settings_obj)

    #Don't set cache folder if it's disabled
    if not settings_obj.get_cache_status():
        cache_dir = ''

    #Initialize spotify stuff
    ml = MainLoop()
    buf = BufferManager(get_audio_buffer_size())
    callbacks = SpotimcCallbacks(ml, buf, app)
    sess = Session(
        callbacks,
        app_key=appkey,
        user_agent="python ctypes bindings",
        settings_location=settings_dir,
        cache_location=cache_dir,
        initially_unload_playlists=False,
    )

    #Now that we have a session, set settings
    set_settings(settings_obj, sess)

    #Initialize libspotify's main loop handler on a separate thread
    ml_runner = MainLoopRunner(ml, sess)
    ml_runner.start()

    #Stay on the application until told to do so
    while not app.get_var('exit_requested'):

        #Set the exit flag if login was cancelled
        if not do_login(sess, addon_dir, "DefaultSkin", app):
            app.set_var('exit_requested', True)

        #Otherwise block until state is sane, and continue
        elif wait_for_connstate(sess, app, ConnectionState.LoggedIn):

            proxy_runner = ProxyRunner(sess,
                                       buf,
                                       host='127.0.0.1',
                                       allow_ranges=True)
            proxy_runner.start()
            log_str = 'starting proxy at port {0}'.format(
                proxy_runner.get_port())
            get_logger().info(log_str)

            #Instantiate the playlist manager
            playlist_manager = playback.PlaylistManager(proxy_runner)
            app.set_var('playlist_manager', playlist_manager)

            #Set the track preloader callback
            preloader_cb = get_preloader_callback(sess, playlist_manager, buf)
            proxy_runner.set_stream_end_callback(preloader_cb)

            hide_busy_dialog()
            mainwin = windows.MainWindow("main-window.xml", addon_dir,
                                         "DefaultSkin")
            mainwin.initialize(sess, proxy_runner, playlist_manager, app)
            app.set_var('main_window', mainwin)
            mainwin.doModal()
            show_busy_dialog()

            #Playback and proxy deinit sequence
            proxy_runner.clear_stream_end_callback()
            playlist_manager.stop()
            proxy_runner.stop()
            buf.cleanup()

            #Join all the running tasks
            tm = TaskManager()
            tm.cancel_all()

            #Clear some vars and collect garbage
            proxy_runner = None
            preloader_cb = None
            playlist_manager = None
            mainwin = None
            app.remove_var('main_window')
            app.remove_var('playlist_manager')
            gc.collect()

            #Logout
            if sess.user() is not None:
                sess.logout()
                logout_event.wait(10)

    #Stop main loop
    ml_runner.stop()

    #Some deinitializations
    info_value_manager.deinit()
Пример #14
0
    def __init__(self, parent, ID, title, ColourScheme):
        global KeyPressHash
        self.ColourScheme = ColourScheme
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(600, 400))
        self.settings_manager = SettingsManager()
        self.Centre(
        )  # places window in centre of screen, Rappin p235. TODO need to place in centre of primary display

        # set up sizers to contain the objects on the welcome frame
        self.sizer1 = wx.BoxSizer(wx.HORIZONTAL)

        # set up logo
        self.sizer1.Add(LogoPanel(self, self.ColourScheme), 1,
                        wx.ALIGN_LEFT | wx.EXPAND)
        # set up button area
        # set correct shortcut key text for 'Exit' key
        ExitShortcutKey = {
            'Linux': 'Ctrl + Q',
            'Windows': 'Ctrl + Q',
            'Darwin': info.CommandSymbol + 'Q'
        }.get(system(), 'Ctrl + Q')
        # info per button: (text in button, x and y location, handling routine, keyboard shortcut, internal name)
        ButtonInfo = [
            (_('Open recent project | R'), 40, 40, self.OnOpenRecentButton,
             ord('r'), 'Recent'),
            (_('Open existing project | O'), 40, 90, self.OnOpenExistingButton,
             ord('o'), 'Existing'),
            (_('Start new project | N'), 40, 140, self.OnNewButton, ord('n'),
             'New'),
            (_('Join a project collaboration | J'), 40, 190,
             self.OnJoinCollaborationButton, ord('j'), 'Join'),
            (_('About Vizop | T'), 40, 240, self.OnAbout, ord('t'), 'About'),
            (_('Exit | ' + ExitShortcutKey), 40, 290, self.OnExitButton,
             [wx.WXK_CONTROL, ord('q')], 'Exit')
        ]

        # get the current recent project list, or create a new one if it doesn't exist
        try:
            RecentProjList = self.settings_manager.get_config(
                'RecentProjectsList')
        except KeyError:
            RecentProjList = []
        # get filename of all available project templates
        self.ProjTemplates = GetAvailProjTemplates()

        panel3 = wx.Panel(self)  # panel to hold the buttons
        panel3.SetBackgroundColour(ColourScheme.BackBright)
        KeyPressHash = ClearKeyPressRegister(KeyPressHash)
        for (ButtonText, x, y, ButtonHandler, Key, Name) in ButtonInfo:
            # set up each button in the welcome frame
            RegisterKey = True  # whether to register the keypress
            b = wx.Button(panel3, -1, ButtonText, pos=(x, y), size=(220, 40))
            b.Bind(wx.EVT_BUTTON, ButtonHandler)
            b.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.NORMAL))
            b.SetForegroundColour('navy')
            if (Name == 'Recent') and not RecentProjList:
                b.Disable()  # disable Recent projects button if none available
                RegisterKey = False
            if (Name == 'New') and not self.ProjTemplates:
                b.Disable(
                )  # disable New project button if no templates available
                RegisterKey = False
            if RegisterKey:
                KeyPressHash = RegisterKeyPressHandler(KeyPressHash, Key,
                                                       ButtonHandler)

        panel3.SetFocus()  # enable button bar to handle Tab, Space, Enter keys
        self.sizer1.Add(panel3, 1, wx.EXPAND)
        self.sizer1.SetItemMinSize(1, (300, 400))

        self.Bind(wx.EVT_IDLE, self.OnIdle)
        # Lay out sizers
        self.SetMinSize((600, 400))
        self.SetSizer(self.sizer1)  # assigns sizer1 to fill Welcome frame
        self.SetAutoLayout(True)
        self.sizer1.FitInside(self)
        self.Show(True)
Пример #15
0
#!/usr/bin/python
from praytimes import PrayTimes
from settings import SettingsManager
from alarmdaemon import AlarmDaemon
from datetime import date

import configparser
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject

prayTimes = PrayTimes()
settingsmgr = SettingsManager()
cfg = configparser.ConfigParser()

# TODO make setup simpler than Settings Dialog
#class SetupDialog(Gtk.Dialog):
#    def __init__(self, parent):
#        Gtk.Dialog.__init__(self, "Setup", parent, 0,
#                (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
#                 Gtk.STOCK_OK, Gtk.ResponseType.OK))
#        self.set_default_size(300,100)
#
#        self.grid = Gtk.Grid()
#        self.grid.set_hexpand(True)
#        self.grid.set_vexpand(True)
#        self.get_content_area().add(self.grid)


class SettingsDialog(Gtk.Dialog):