Beispiel #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()
Beispiel #2
0
 def configure():
     logging.basicConfig(filename=SettingsManager.get_instance(
     ).get_logging_settings.log_file,
                         level=SettingsManager.get_instance(
                         ).get_logging_settings.log_level,
                         format=SettingsManager.get_instance().
                         get_logging_settings.log_format)
Beispiel #3
0
def main(addon_dir):
    #Check needed directories first
    data_dir, cache_dir, settings_dir = check_dirs()
    
    #Instantiate the settings obj
    settings_obj = SettingsManager()
    
    #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()
    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()
        
        #Start main window and enter it's main loop
        mainwin = windows.MainWindow("main-window.xml", addon_dir, "DefaultSkin")
        mainwin.initialize(sess, proxy_runner)
        mainwin.doModal()
        
        #Deinit sequence
        player = xbmc.Player()
        player.stop()
        proxy_runner.stop()
        
        #Logout
        sess.logout()
        logout_event.wait(10)
    
    #Stop main loop
    ml_runner.stop()
    return sess
Beispiel #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
Beispiel #5
0
def is_authenticated(token):
    try:
        decoded_token = decode_string(
            token,
            SettingsManager.get_instance().get_application_settings.key,
            SettingsManager.get_instance().get_application_settings.algorithm)

        return decoded_token is not None
    except Exception as err:
        raise err
Beispiel #6
0
def get_token(data):
    try:
        payload = json.loads(
            data.decode(SettingsManager.get_instance().
                        get_application_settings.encoding))
        return encode(
            payload,
            SettingsManager.get_instance().get_application_settings.key,
            SettingsManager.get_instance().get_application_settings.algorithm)
    except Exception as err:
        raise err
Beispiel #7
0
  def move_file_and_test(self, src_f, targ_f):
    """Helper function that performs a dupe file move and tests it."""
    # Initial state
    self.cr_load("dupes-initial")
    sm = SettingsManager(self.loc_in_cr('kpawebgen.json'))
    db_path = os.path.join(sm.abspath('kpa_dir'), shadow)
    index_p = self.loc_in_cr("KPA/index.xml")
    kpa_p = self.loc_in_cr("KPA")
    self.cr_nexist(db_path)

    # Create shadow DB
    u = Updater(sm.abspath('kpa_dir'), shadow)
    did = u.update()
    self.assertTrue(did)

    conn = sqlite3.connect(db_path)
    def getall(q, args=()):
      return conn.execute(q, args).fetchall()
    def count_images():
      return getall("""SELECT COUNT(*) FROM image_id""")[0][0]

    (srcID, srcMD5) = getall(
      """SELECT imageID, md5 FROM image_id WHERE path = ?""",
      (src_f,))[0]
    oldCount = count_images()

    # Move a file (in filesystem and XML)
    with open(index_p, 'r') as f:
      xml = f.read()
    xml = xml.replace(src_f, targ_f)
    with open(index_p, 'w') as f:
      f.write(xml)
    os.rename(os.path.join(kpa_p, src_f),
              os.path.join(kpa_p, targ_f))

    # Update shadow DB
    u = Updater(sm.abspath('kpa_dir'), shadow)
    did = u.update()
    self.assertTrue(did)

    # Verify move in shadow DB
    self.assertEqual(getall("""
      SELECT action, oldPath, newPath
      FROM changelog
      WHERE changelog.logID = (SELECT MAX(logID) FROM changelog);"""),
      [('move', src_f, targ_f)])
    (targID, targMD5) = getall(
        """SELECT imageID, md5 FROM image_id WHERE path = ?""",
        (targ_f,))[0]
    self.assertEqual(targID, srcID)
    self.assertEqual(targMD5, srcMD5)
    self.assertEqual(count_images(), oldCount)

    conn.close()
	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)
Beispiel #9
0
    def post(self):
        try:
            token = request.data.decode(SettingsManager.get_instance().
                                        get_application_settings.encoding)

            return adapt_one_success(is_authenticated(token))
        except Exception as err:
            return adapt_critical('Error: ' + str(err.args))
Beispiel #10
0
    def get(self):
        try:
            token = get_token(
                request.data).decode(SettingsManager.get_instance().
                                     get_application_settings.encoding)

            return adapt_one_success(token)
        except Exception as err:
            return adapt_critical('Error: ' + str(err.args))
Beispiel #11
0
  def test_read_standard(self):
    """Read a KPA database and check that the result makes sense."""
    self.cr_load("standard")
    sm = SettingsManager(self.loc_in_cr('kpawebgen.json'))
    r = Reader(sm.abspath('kpa_dir'))
    m = r.read_latest_data()

    self.assertEqual(7, len(m.images))
    beetle = (i for i in m.images if i['path'] == 'IMG_5179.JPG').next()
    beetle_tags = beetle['tags']
    del beetle['tags']
    beetle_timestamp = datetime.datetime(2009, 6, 25, 7, 45, 50)
    expected_beetle = {'imageID':None,
                       'md5':'34f7adfce54bd34bf5f0266dd2c7b800',
                       'path':'IMG_5179.JPG',
                       'width':800,
                       'height':600,
                       'angle':0,
                       'label':'IMG_5179',
                       'description':'Regular public.',
                       'stackOrder':None,
                       'stackID':None,
                       'startDate':beetle_timestamp,
                       'endDate':beetle_timestamp}
    self.assertEqual(beetle, expected_beetle)

    # next() throws if no match
    locat = (i for i in m.cats if i['catName'] == 'Location').next()
    inn_tag = (i for i in m.tags if i['tagName'] == 'Orange Hill Beach Inn' and
                                    i['catID'] == locat['catID']).next()
    island_tag = (i for i in m.tags
                          if i['catID'] == locat['catID'] and
                             i['tagName'] == 'San Salvador Island').next()
    
    self.assertEqual(11, len(beetle_tags)) # no inherit
    beetle_tags.index({'tagID':inn_tag['tagID'],
                       'catID':locat['catID']})

    self.assertEqual(3, len(m.tag_tags))
    m.tag_tags.index({'catID':locat['catID'],
                      'setID':island_tag['tagID'],
                      'tagID':inn_tag['tagID']})
Beispiel #12
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()
Beispiel #13
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())
Beispiel #14
0
def main(root, text, menubar):
    objFormat = Format(text)

    fontoptions = families(root)
    font = Font(family="Arial", size=10)
    text.configure(font=font)

    SettingsManager.setup(objFormat, font) # setup the settings

    formatMenu = Menu(menubar, tearoff=False)

    fsubmenu = Menu(formatMenu, tearoff=False)
    ssubmenu = Menu(formatMenu, tearoff=False)

    for option in fontoptions:
        fsubmenu.add_command(label=option, command=lambda option=option: SettingsManager.change_font(font, "font_family", option))
    for value in range(1, 31):
        ssubmenu.add_command(label=str(value), command=lambda value=value: SettingsManager.change_font(font, "font_size", value))

    formatMenu.add_command(label="Change Background", command=objFormat.changeBg)
    formatMenu.add_command(label="Change Font Color", command=objFormat.changeFg)
    formatMenu.add_cascade(label="Font", underline=0, menu=fsubmenu)
    formatMenu.add_cascade(label="Size", underline=0, menu=ssubmenu)
    formatMenu.add_command(label="Bold", command=objFormat.bold, accelerator="Ctrl+B")
    formatMenu.add_command(label="Italic", command=objFormat.italic, accelerator="Ctrl+I")
    formatMenu.add_command(label="Underline", command=objFormat.underline, accelerator="Ctrl+U")
    formatMenu.add_command(label="Overstrike", command=objFormat.overstrike, accelerator="Ctrl+T")
    formatMenu.add_command(label="Add Date", command=objFormat.addDate)
    menubar.add_cascade(label="Format", menu=formatMenu)

    root.bind_all("<Control-b>", objFormat.bold)
    root.bind_all("<Control-i>", objFormat.italic)
    root.bind_all("<Control-u>", objFormat.underline)
    root.bind_all("<Control-T>", objFormat.overstrike)

    root.grid_columnconfigure(0, weight=1)
    root.resizable(True, True)

    root.config(menu=menubar)
Beispiel #15
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 []
Beispiel #16
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)
Beispiel #17
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])
Beispiel #18
0
class TestSettingsManager(TestBase):
  
  #== Util ==#
  
  s = None
  """SettingsManager for main testing config file."""
  
  def setUp(self):
    self.s = SettingsManager('unit/settings/various.json', self.get_dir())
  
  #== Tests ==#
  
  def test_missing(self):
    """Missing config files must throw an error."""
    self.expect_error(lambda:SettingsManager('does_not_exist.json'), 'Invalid path to settings file')
  
  def test_override(self):
    """User properties must override defaults."""
    self.assertEqual(self.s.require('gal_db_path'), 'foo.bar')
  
  def test_require(self):
    """Retrieval of required non-empty properties."""
    self.expect_error(lambda: self.s.require('12345'), 'missing key',
                      'Require throws error for missing key')
    self.assertEqual(self.s.require('data_dir'), 'data')
  
  def test_catlist(self):
    """Retrieval of lists."""
    self.assertEqual(self.s.require('cats_unconditional', list), ['Foo','*Bar  '])
  
  def test_default_string(self):
    """String is expected by default."""
    self.expect_error(lambda:self.s.require('cats_unconditional'),
                      "Config file needed <type")
  
  def test_abspath(self):
    """Computation of absolute path from absolute and relative paths."""
    self.assertEqual(self.s.abspath('test/abs'), '/tmp')
    
    actual = self.s.abspath('test/rel')
    expected = os.path.join(self.get_dir(), 'unit/settings/beyond')
    self.assertEqual(os.path.realpath(actual), os.path.realpath(expected))
Beispiel #19
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())
Beispiel #20
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()
Beispiel #21
0
def main(addon_dir):
    #Initialize app var storage
    app = Application()
    logout_event = Event()
    app.set_var('logout_event', logout_event)
    app.set_var('exit_requested', False)
    
    #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 continue normal operation
        else:
            #TODO: Wrap this inside a function
            ip_list = ['127.0.0.1', xbmc.getInfoLabel('Network.IPAddress')]
            proxy_runner = ProxyRunner(sess, buf, host='0.0.0.0', allowed_ips=ip_list)
            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, app)
            app.set_var('main_window', mainwin)
            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
            app.remove_var('main_window')
            gc.collect()
            
            #Logout
            if sess.user() is not None:
                sess.logout()
                logout_event.wait(10)
    
    #Stop main loop
    ml_runner.stop()
Beispiel #22
0
 def changeFg(self):
     (triple, hexstr) = askcolor()
     if hexstr:
         SettingsManager.change_setting("font_color", hexstr) #update settings
         self.text.config(fg=hexstr)
from neo4j.v1 import GraphDatabase
from neo4j.v1 import basic_auth

from logger import Logger
from settings import SettingsManager
from query_builder import *
from entities import Hashtag

driver = GraphDatabase.driver(
    SettingsManager.get_instance().get_database_settings.host,
    auth=basic_auth(
        SettingsManager.get_instance().get_database_settings.user,
        SettingsManager.get_instance().get_database_settings.password))


def retrieve():
    result = []
    session = driver.session()

    try:
        query = build_get_query()
        data = session.run(query)

        for item in data:
            hashtag = Hashtag()
            hashtag.id = item['h']['id']
            hashtag.text = item['h']['text']

            result.append(hashtag)

        return result
Beispiel #24
0
class KPAWebGen(object):
  """Core code for gallery generator."""
  
  #== Setup ==#

  # A sequence is an array of 1 or more actions.
  # Actions can be specified by names.
  
  def __init__(self):
    # source of lookup table
    actions = [('read', self.act_read),
               ('localweb', self.act_localweb),
               ('publish', self.act_publish)]
    # save off the ordered names and the lookup table 
    self.action_names = zip(*actions)[0]
    self.action_lookup = dict(actions)
    # TODO: Python subproject shouldn't know about global directory structure
    root = '../../..'
    self.clj_path = ResourceManager.locate(root + '/clj')

  action_names = None
  """Names of program actions, in order."""
  action_lookup = None
  """Dict of action names to functions."""
  sequence_all = 'all'
  """Specifies that all actions should be taken (in order.)"""

  clj_path = None
  """Location of Clojure jar."""
  settings = None
  """SettingsManager object."""
  
  # String -> List<String>
  def get_sequence(self, seq_name):
    """Expand requested sequence into action names. If invalid sequence name,
    throw error with message about allowed names."""
    if seq_name == self.sequence_all:
      return self.action_names
    if seq_name not in self.action_names:
      ls = ", ".join(list(self.action_names)+[self.sequence_all])
      raise Exception("Sequence must be one of: %s" % (ls,))
    return [seq_name]
  
  # String List<String> ->
  def dispatch(self, config_loc, sequence):
    """Dispatch on action names."""
    self.settings = SettingsManager(config_loc)
    for name in sequence:
      print("Running action: %s" % name, file=sys.stdout)
      self.action_lookup[name]()

  def invoke_clojure_action(self, task):
    # We have to use lein instead of launching an uberjar since some of
    # the integration tests are in Clojure, and therefore need to call
    # the .py script...
    # Once everything is in Clojure, this won't be an issue.
    subprocess.check_call(['lein', 'trampoline', 'run',
                           '--task', task,
                           '--config', self.settings.config['_config_path'],
                           '--debug', str(Global.debug).lower()],
                           shell=False, cwd=self.clj_path)
  
  #== Actions ==#
  
  def act_read(self):
    """Update our DB with the latest KPA data."""
    did = Updater(self.settings.abspath('kpa_dir'),
                  self.settings.require('shadow_path')).update(self.force_read)
    if not did:
      print("Skipping read since DB has not changed.", file=sys.stdout)
  
  def act_localweb(self):
    """Generate local website."""
    self.invoke_clojure_action('localweb')
  
  def act_publish(self):
    """Publish to remote website."""
    self.invoke_clojure_action('publish-s3')
  
  #== Interfaces ==#

  force_read = False

  def main(self, args):
    """Validate arguments (minus script name) and call core code."""
    logging.debug('Main args: %s' % args)
    
    if len(args) < 2:
      if len(args) != 1 or args[0] != '--help':
        print("Wrong number of arguments.", file=sys.stderr)
      self.die_usage()
    config_loc = args[0]
    sequence_name = args[1]
    if len(args) == 3 and args[2] == '--force-read':
      self.force_read = True
    
    try:
      sequence = self.get_sequence(sequence_name)
    except Exception as e:
      KPAWebGen.die_top("Could not determine requested action: " + str(e),
                        Constants.ERR_ACTION_INVALID)
    
    try:
      self.dispatch(config_loc, sequence)
    except Exception as e:
      msg = "Error(%s): %s" % (e.__class__.__name__, e)
      KPAWebGen.die_top(msg, Constants.ERR_UNKNOWN_REASON)
  
  @staticmethod
  def die_usage():
    usage = """Usage:
kpawebgen --help
kpawebgen config-file sequence [options]

Options:
--force-read
  Update the shadow DB even if it dopesn't appear to need it."""
    KPAWebGen.die_top(usage, Constants.ERR_BAD_ARGS, isExc=False)
  
  @staticmethod
  def die_top(msgs=None, code=Constants.ERR_NORMAL_EXIT, isExc=True):
    """Die at the top level. Do not call from core code."""
    if Global.debug and isExc:
      traceback.print_exc(file=sys.stdout)
    if isinstance(msgs, basestring):
      msgs = [msgs]
    if msgs:
      for m in msgs:
        print(m, file=sys.stderr)
    sys.exit(code)
Beispiel #25
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)
Beispiel #26
0
class NoProjectOpenFrame(wx.Frame):
    # Define the welcome window that appears whenever no project is open, including at launch of vizop

    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)

    def OnIdle(
        self, Event
    ):  # during idle time, handle keystrokes for shortcuts. This procedure is repeated in module datacore
        global KeyPressHash
        # initialise storage object used to remember keys pressed last time, for chord detection in correct order
        if not hasattr(self, 'PrevChordKeys'): self.PrevChordKeys = []
        KeysDownThisTime = [
        ]  # prepare list of key codes that are 'hit' and match any keys in KeyPressHash
        KeyPressIndexHit = None  # which item (index in KeyPressHash) is to be invoked
        for (HashIndex, (KeyStroke, Handler, Args)) in enumerate(
                KeyPressHash
        ):  # check each keystroke registered in KeyPressHash
            if type(KeyStroke) is int:
                if wx.GetKeyState(KeyStroke):
                    KeysDownThisTime.append(KeyStroke)
                    if not (KeyStroke in self.PrevChordKeys):
                        KeyPressIndexHit = HashIndex  # KeyStroke has been detected this time, but not last time
            elif type(KeyStroke) is list:  # key chord handling
                ChordFulfilled = True
                for k in KeyStroke:  # check each key in KeyStroke
                    if wx.GetKeyState(k): KeysDownThisTime.append(k)
                    else: ChordFulfilled = False
                # check that (1) all keys in KeyStroke are pressed, AND
                # (2) not all of them were pressed last time (i.e. >=1 of them is newly pressed)
                if ChordFulfilled and not set(KeyStroke).issubset(
                        set(self.PrevChordKeys)):
                    KeyPressIndexHit = HashIndex  # invoke handler if keystroke detected
        self.PrevChordKeys = KeysDownThisTime  # store currently-pressed keys for comparison next time
        # Must do the line above BEFORE invoking Handler - else KeyStrokes newly defined in Handler may falsely activate
        if (KeyPressIndexHit is not None):
            (KeyStroke, Handler, Args) = KeyPressHash[KeyPressIndexHit]
            Handler(**Args)  # invoke handler

    def WrapUpAfterOpeningProjects(self,
                                   ProjFiles,
                                   TemplateFiles,
                                   RequestToQuit=False,
                                   SaveOnFly=True):
        # after successful opening of project file(s) from welcome frame, perform tidying up
        # ProjFiles is list of paths of valid project files to be opened or created (str)
        # TemplateFiles is list of paths of valid template files to be used to create new projects, using the filepaths
        # in ProjFiles (str)
        # RequestToQuit (bool): whether vizop should quit now, on user's request
        # SaveOnFly (bool): whether new project should be saved on the fly
        # set return values
        NoProjectOpenFrameData.Data = {
            'ProjectFilesToOpen': ProjFiles,
            'TemplateFilesToSpawnFrom': TemplateFiles,
            'RequestToQuit': RequestToQuit,
            'SaveOnFly': SaveOnFly
        }
        self.Destroy()  # destroy welcome frame

    def WrapUpAfterJoinCollaborationRequest(self):
        # perform tidying up and exit welcome frame after receiving request to collaborate on remote project
        # similar to WrapUpAfterOpeningProjects() except there's no open project to handle
        NoProjectOpenFrameData.Data = {
            'ProjectFilesToOpen': [],
            'TemplateFilesToSpawnFrom': [],
            'RequestToQuit': False,
            'SaveOnFly': False,
            'OpenCollaboration': True
        }
        self.Destroy()  # destroy welcome frame

    def DisableKeypresses(
        self
    ):  # temporarily suppress all keypress handlers, to avoid inadvertent behaviour
        global KeyPressHash
        self.OldKPR = KeyPressHash[:]
        KeyPressHash = ClearKeyPressRegister(
            KeyPressHash)  # to avoid inadvertent behaviour from key presses

    def ReinstateKeypresses(self):  # reinstate keyboard shortcuts
        global KeyPressHash
        KeyPressHash = self.OldKPR

    def HandleNewFileRequest(self,
                             Filenames,
                             NewFilenames=[],
                             NewProjects=False,
                             SaveOnFly=True):
        # Check NewFilenames can be opened.
        # Check whether Filenames (list of paths) contains openable project templates.
        # NewFilename: full paths of files to create for new project
        # NewProjects (bool): whether the Filenames are templates to use for creation of new projects (always True)
        # SaveOnFly (bool): if creating new project, whether work should be saved on the fly
        # If any openable projects, call WrapUpAfterOpeningProjects() to close Welcome Frame and send data to datacore.
        # Return values: OpenableProjFiles (list of paths that contain valid and openable projects)
        #       ProjOpenData (list of dict of data for each file, returned from projects.TestProjectsOpenable)
        ProjOpenData = projects.TestProjectsOpenable(
            Filenames,
            ReadOnly=False)  # find out if the projects can be opened
        # expected return value (ProjOpenData): a list of dict, one for each project file in Filenames
        # dict keys are: Openable (bool), Comment (str) - explaining why project is not openable (for user feedback)
        # make list of openable/creatable project files
        OpenableProjFiles = [
            Filenames[i] for i in range(len(Filenames))
            if ProjOpenData[i]['Openable']
            if (IsWritableLocation(os.path.dirname(NewFilenames[i]))
                or not SaveOnFly)
        ]
        # Note, the writability check is duplicated in projects.SaveEntireProject() and might be redundant here
        if OpenableProjFiles:  # can any of the selected project files be opened?
            if NewProjects:  # tidy up and exit Welcome Frame
                self.WrapUpAfterOpeningProjects(
                    ProjFiles=NewFilenames,
                    TemplateFiles=OpenableProjFiles,
                    SaveOnFly=SaveOnFly)
            else:
                self.WrapUpAfterOpeningProjects(ProjFiles=OpenableProjFiles,
                                                TemplateFiles=[])
        return OpenableProjFiles, ProjOpenData

    def HandleOpenFileRequest(self,
                              Filenames,
                              NewFilenames=[],
                              NewProjects=False,
                              SaveOnFly=True):
        # Check whether Filenames (list of existing paths) contains openable projects.
        # NewFilename: full paths of files to create for new project (redundant, now using HandleNewFileRequest() )
        # NewProjects (bool): whether the Filenames are templates to use for creation of new projects - always False
        # SaveOnFly (bool): if creating new project, whether work should be saved on the fly
        # If any openable projects, call WrapUpAfterOpeningProjects() to close Welcome Frame and send data to datacore.
        # Return values: OpenableProjFiles (list of paths that contain valid and openable projects)
        #       ProjOpenData (list of dict of data for each file, returned from projects.TestProjectsOpenable)
        ProjOpenData = projects.TestProjectsOpenable(
            Filenames,
            ReadOnly=False)  # find out if the projects can be opened
        # expected return value (ProjOpenData): a list of dict, one for each project file in Filenames
        # dict keys are: Openable (bool), Comment (str) - explaining why project is not openable (for user feedback)
        # make list of openable/creatable project files
        OpenableProjFiles = [
            Filenames[i] for i in range(len(Filenames))
            if ProjOpenData[i]['Openable']
            if (IsWritableLocation(os.path.dirname(Filenames[i]))
                or not SaveOnFly)
        ]
        # Note, the writability check is duplicated in projects.SaveEntireProject() and might be redundant here
        if OpenableProjFiles:  # can any of the selected project files be opened?
            if NewProjects:  # tidy up and exit Welcome Frame
                self.WrapUpAfterOpeningProjects(
                    ProjFiles=NewFilenames,
                    TemplateFiles=OpenableProjFiles,
                    SaveOnFly=SaveOnFly)
            else:
                self.WrapUpAfterOpeningProjects(ProjFiles=OpenableProjFiles,
                                                TemplateFiles=[])
        return OpenableProjFiles, ProjOpenData

    def OnOpenRecentButton(self,
                           event=None
                           ):  # handle user request to Open Recent Project
        self.DisableKeypresses()
        OpenSuccess = False  # whether valid project files are identified for opening
        # read recent projects list from cache file
        try:
            recent_projects_list = self.settings_manager.get_config(
                'RecentProjectsList')
        except KeyError:
            #recent_projects_list does not exist - so create it
            recent_projects_list = []
            self.settings_manager.set_value('RecentProjectsList',
                                            recent_projects_list)

        RPDisplayList = [
        ]  # build list of recent projects in display-friendly format
        for ProjFilename in reversed(recent_projects_list):
            RPDisplayList.append(
                _('%s in %s') % (os.path.basename(ProjFilename),
                                 os.path.dirname(ProjFilename)))
        DialogueBox = wx.MultiChoiceDialog(
            self, _('Which project(s) would you like to open?'),
            _('Choose a vizop project file to open'),
            RPDisplayList)  # set up standard selection dialogue
        if DialogueBox.ShowModal() == wx.ID_OK:  # user clicked OK
            FilenamesSelected = []  # make list of filenames selected
            for index in DialogueBox.GetSelections():
                FilenamesSelected.append(recent_projects_list[index])
            OpenableProjFiles, ProjOpenData = self.HandleOpenFileRequest(
                FilenamesSelected)
            OpenSuccess = bool(OpenableProjFiles)
        # allow user to continue working in Welcome Frame if no projects can be opened. TODO give user feedback
        if not OpenSuccess:
            self.ReinstateKeypresses()

    def OnOpenExistingButton(self, Event=None):
        # handle click on Open Existing button
        self.DisableKeypresses()
        FilenamesSelected = projects.GetProjectFilenamesToOpen(self)
        if FilenamesSelected:  # did user select any files to open?
            OpenableProjFiles, ProjOpenData = self.HandleOpenFileRequest(
                FilenamesSelected)
            OpenSuccess = bool(
                OpenableProjFiles
            )  # using OpenSuccess for consistency with other handlers
        else:
            OpenSuccess = False
        # allow user to continue working in Welcome Frame if no projects can be opened. TODO give user feedback
        if not OpenSuccess:
            self.ReinstateKeypresses()

    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 OnJoinCollaborationButton(
            self, Event=None):  # handle user request to join collaboration%%%
        DialogueBox = JoinCollaborationDialogue(
            parent=self,
            title=_('Vizop: Join a collaboration'),
            ColourScheme=self.ColourScheme)
        if DialogueBox.ShowModal() == wx.ID_OK: pass

    def OnAbout(self, event=None):
        OnAboutRequest(Parent=self, event=None)

    def OnExitButton(self, event=None):
        self.DisableKeypresses()
        NoProjectOpenFrameData.Data = {
            'RequestToQuit': True
        }  # store return data used by 'heart' module
        self.Destroy()
Beispiel #27
0
 def __init__(self):
     self.organization = OrganizationManager()
     self.queue = QueueManager()
     self.group = QueueGroupManager()
     self.settings = SettingsManager()
Beispiel #28
0
 def setUp(self):
   self.s = SettingsManager('unit/settings/various.json', self.get_dir())
Beispiel #29
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)
Beispiel #30
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()
Beispiel #31
0
  def test_firstrun(self):
    """Must create a DB3 if none exists."""
    self.cr_load("firstrun")
    sm = SettingsManager(self.loc_in_cr('kpawebgen.json'))
    db_path = os.path.join(sm.abspath('kpa_dir'), shadow)
    u = Updater(sm.abspath('kpa_dir'), shadow)
    self.cr_nexist(db_path)
    did = u.update()
    self.assertTrue(did)

    self.cr_exist(db_path)
    conn = sqlite3.connect(db_path)

    def getall(q):
      return conn.execute(q).fetchall()
    
    self.assertNotEqual(getall('SELECT xmlChecksum FROM metadata')[0][0], None)
    self.assertEqual(getall('SELECT nextImageID FROM metadata'), [(7,)])
    self.assertEqual(getall('SELECT count(*) FROM image_id'), [(7,)])
    self.assertEqual(getall('SELECT min(imageID) FROM image_id'), [(0,)])
    self.assertEqual(getall('SELECT max(imageID) FROM image_id'), [(6,)])
    self.assertEqual(getall('SELECT count(*) FROM image_int'), [(7,)])
    self.assertEqual(getall('SELECT count(*) FROM image_ext'), [(7,)])
    self.assertEqual(getall('SELECT count(*) FROM changelog'), [(7,)])
    self.assertEqual(getall('SELECT DISTINCT oldPath, oldMD5 FROM changelog'),
                      [(None,None)])
    hornetID = getall("""SELECT imageID FROM image_id
                         WHERE path='IMG_9610.JPG'""")[0][0]
    hornetInt = conn.execute("SELECT * FROM image_int WHERE imageID=?",
                             (hornetID,)).fetchall()[0]
    conn.close()

    # Create the baseline for several changes
    self.dump_db(db_path, 'baseline.dump')
    db_backup = self.loc_in_cr('shadow.db3.firstrun')
    subprocess.call(['cp', db_path, db_backup])

    # No changes yet
    u = Updater(sm.abspath('kpa_dir'), shadow)
    did = u.update()
    self.assertFalse(did) # Don't update if nothing has changed

    # Alter index: Delete and move
    self.patch("KPA/index.xml", "patches/delete+move.index.xml.patch")
    u = Updater(sm.abspath('kpa_dir'), shadow)
    did = u.update()
    self.assertTrue(did)
    self.dump_db(db_path, 'delete+move.dump')
    self.validate_diff("baseline.dump", "patches/delete+move.dump.patch",
                       "delete+move.dump")
    self.patch("KPA/index.xml", "patches/delete+move.index.xml.patch",
               undo=True)
    subprocess.call(['rm', db_path])
    subprocess.call(['cp', db_backup, db_path])

    # Alter index: Create and edit
    self.patch("KPA/index.xml", "patches/create+edit.index.xml.patch")
    u = Updater(sm.abspath('kpa_dir'), shadow)
    did = u.update()
    self.assertTrue(did)
    self.dump_db(db_path, 'create+edit.dump')
    self.validate_diff("baseline.dump", "patches/create+edit.dump.patch",
                       "create+edit.dump")
    self.patch("KPA/index.xml", "patches/create+edit.index.xml.patch",
               undo=True)
    subprocess.call(['rm', db_path])
    subprocess.call(['cp', db_backup, db_path])
Beispiel #32
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()
Beispiel #33
0
 def dispatch(self, config_loc, sequence):
   """Dispatch on action names."""
   self.settings = SettingsManager(config_loc)
   for name in sequence:
     print("Running action: %s" % name, file=sys.stdout)
     self.action_lookup[name]()
Beispiel #34
0
'''Fortroute Mapper takes screenshots of Fortnite BR minimap to map out a route through a match.'''

import cv2
import json
import requests
import numpy as np
import os, sys, time
from shutil import copyfile
from PIL import ImageGrab
from collections import Counter

from subregions import SubregionManager
from settings import SettingsManager

settings = SettingsManager.initialize_settings()

MY_RESOLUTION = settings['resolution']
LOCATION_FOLDER = settings['location_folder']

TEST_SIZE = (133, 133)
MAP_SIZE = (1010, 1010)
MAP_FILE = './fortnite_map.png'
BACKUP_MAP_FILE = 'https://raw.githubusercontent.com/paularcoleo/fortroute-mapper/master/fortnite_map.png'
METHODS = [
    'cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR_NORMED',
    'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED'
]
LINE_COLOR_BGR = (0, 100, 255)

if not os.path.isfile(MAP_FILE):
    reset_default_map()
Beispiel #35
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):
Beispiel #36
0
 def changeBg(self):
     (triple, hexstr) = askcolor()
     if hexstr:
         SettingsManager.change_setting("background_color", hexstr) #update settings
         self.text.config(bg=hexstr)