Пример #1
0
    def get_root_id():
        # Check to see which root id we are getting
        key   = KEY_CLOUD_ROOT_ID
        title = "Cloud ID Missing"
        if Dev.get("ALT_LOCATION"):
            key   = KEY_CLOUD_ROOT_ID_DEV
            title = "Cloud DEVELOPMENT ID Missing"

        # Get the ID from Settings
        result = Settings.get_key(key)

        # If the ID doesnt exist in settings, lets ask for it!
        if not result:
            dialog = Dialog(
                title = title,
                body  = [
                    f'The Cloud root ID is currently missing.. So lets find it!',
                    f'\n',
                    f'\n',
                    f'Ask your administrator for the "Cloud Root Filepath" and',
                    f'enter that path below.',
                    f'\n',
                    f'\n',
                ]
            )
            ans = dialog.get_result("Filepath")

            result = Drive.get_id(search=ans, root="root")

            if not result:
                raise Exception("There was a problem with getting the Cloud Root ID..")

            Settings.set_key(key, result)

        return result
Пример #2
0
 def rememberPositioning(self):
     # This approach have a small bug.
     #    1. Maximize window
     #    2. Exit
     #    3. Reopen
     #    4. Re-maximize
     # Result is that window stays with maximized height and width, 
     # but is not maximized.
     # TODO: FIX: cache all sizes when resizing and not in maximized mode.
     Settings.set("Width", self.GetSize()[0])
     Settings.set("Height", self.GetSize()[1])
     Settings.set("LocX", self.GetScreenPositionTuple()[0])
     Settings.set("LocY", self.GetScreenPositionTuple()[1])
     Settings.set("Maximized", self.IsMaximized())
Пример #3
0
    def set_slack_endpoints():
        if not Settings.check_slack_endpoints():
            drive = Drive()

            Settings.set_key(key=Settings.slack_prod_key,
                             data=drive.get_json_key(
                                 remote_file=f'{LOFSM_DIR_PATH}/db.json',
                                 local_filepath=f'temp/db.json',
                                 key=Settings.slack_prod_key))

            Settings.set_key(key=Settings.slack_dev_key,
                             data=drive.get_json_key(
                                 remote_file=f'{LOFSM_DIR_PATH}/db.json',
                                 local_filepath=f'temp/db.json',
                                 key=Settings.slack_dev_key))
Пример #4
0
 def set_dirty(self):
     username = Settings.get_username(capitalize=True)
     if username not in self.entry.data["is_dirty"]:
         self.entry.data["is_dirty"].append(username)
         self.entry.update()
         return True
     return False
Пример #5
0
 def __init__(self, parent):
     Tkinter.Toplevel.__init__(self, parent)
     self.parent = parent
     self.settings = Settings()
     self.settings.copy_from(parent.settings)
     self.transient(parent)
     self.initialize()
Пример #6
0
 def __init__(self):
     Tkinter.Tk.__init__(self)
     self.attributes('-alpha', 0.0)
     self.thread = None
     self.threadLock = thread.allocate_lock()
     self.settings = Settings()
     self.initialize()
Пример #7
0
 def remove_dirty(self):
     username = Settings.get_username(capitalize=True)
     if username in self.entry.data["is_dirty"]:
         self.entry.data["is_dirty"].remove(username)
         self.entry.update()
         return True
     return False
Пример #8
0
 def remove_lock(self):
     # Lets undo the mutex lock
     # Only unlock if we were the ones to lock it first!
     if self.is_locked() == Settings.get_username(capitalize=True):
         self.entry.data["is_locked"] = None
         self.entry.update()
         return True
     return False
Пример #9
0
 def set_lock(self):
     # Lets mutex lock this beach
     # Only lock if there is no lock currently
     if not self.is_locked():
         self.entry.data["is_locked"] = Settings.get_username(
             capitalize=True)
         self.entry.update()
         return True
     return False
Пример #10
0
    def run(self):
        filename = os.path.join(self.API.path, Settings.get('blockly_location'))
        host = Settings.get('blockly_host')
        port = int(Settings.get('blockly_port'))
        con1, con2 = Pipe()
        p1 = Process(target = listen, args = (host, port, con2, True))
        p1.daemon = False
        p1.name = "Socket listening thread"

        try:
            p1.start()
            self.printLine("Service started successfully.")
            if p1.is_alive():
                # Damn linux
                if os.name == 'posix':
                    Popen(['xdg-open', filename])
                # other OS
                else:
                    webbrowser.open_new_tab(filename)
            else:
                self.printLine("Failed to open {}:{}, port might be in use.".format(host, port))
            lastSync = time.time() + 20
            self.API.onExit.append(p1.terminate)
            while p1.is_alive() and self.active:
                if con1.poll(0.1):
                    data = con1.recv()
                    if data != "Sync recieved":
                        self.handleRecievedCode(data)
                    lastSync = time.time()
                if time.time() - lastSync > 20:
                    self.printLine("No sync for 20 sec.\nTerminating...")
                    self.API.onExit.remove(p1.terminate)
                    p1.terminate()
                    break
                wx.YieldIfNeeded()
            if p1.is_alive():
                self.printLine("Service terminated successfully.")
                self.API.onExit.remove(p1.terminate)
                p1.terminate()
        except:
            self.printLine("Exception occurred, terminating...")
            if p1.terminate in self.API.onExit:
                self.API.onExit.remove(p1.terminate)
Пример #11
0
    def check_slack_endpoints():
        settings = Settings.get_all()

        if not Settings.slack_prod_key in settings or \
           not Settings.slack_dev_key in settings:
            return False

        if settings[Settings.slack_prod_key] == "" or \
           settings[Settings.slack_dev_key] == "":
            return False

        return True
Пример #12
0
    def run_migrations():
        migrations = glob("migrations/*")
        migrations.sort()
        migrations = [Path(x) for x in migrations]
        current_version = Settings.get_version()
        result = True

        for migration in migrations:
            migration_version = Decimal(migration.stem.replace("_", "."))

            if migration_version > current_version:
                Update.install_pip_packages()

                ans = Run.prg("python",
                              migration.absolute(),
                              useSubprocess=True)

                if ans == 0:
                    Slack.upload_log()
                    Log(
                        f'There was a problem loading this migration file!\n "{migration.absolute()}"',
                        "warning")
                    Log.press_enter()
                    # If there was an issue upgrading the migration, we don't want to set the new version
                    return False
                elif ans != 1:
                    Log("You must restart the program to finish the update!",
                        "notice")
                    Log.press_enter()
                    result = False

                Settings.set_version(migration_version)

                # Push a notification to Slack
                Slack(
                    f'{Settings.get_username(capitalize=True)} has upgraded to V{migration_version}!'
                )

        return result
Пример #13
0
    def loadPositioning(self):
        width = Settings.get("Width")
        if width == '':
            width = 800
        else:
            width = int(width)

        height = Settings.get("Height")
        if height == '':
            height = 600
        else:
            height = int(height)

        self.SetSize((width, height))

        locX = Settings.get("LocX")
        if locX == '':
            # Center
            locX = (wx.GetDisplaySize()[0] - width) / 2
        else:
            locX = int(locX)

        locY = Settings.get("LocY")
        if locY == '':
            # Center
            locY = (wx.GetDisplaySize()[1] - height) / 2
        else:
            locY = int(locY)

        self.SetPosition((locX, locY))

        maximized = Settings.get("Maximized")
        if maximized == '':
            maximized = False
        else:
            maximized = bool(maximized == "True")

        self.Maximize(maximized)
Пример #14
0
    def translate(data, lang=''):
        # This happens when no language is set
        if lang == '':
            lang = Settings.get("active_language")

        if lang != '':
            if type(data) is str or type(data) is unicode:
                if data in Translater.translations[lang]:
                    return Translater.translations[lang][data]
            elif type(data) is list:
                retVal = list()
                for val in data:
                    retVal.append(localize(str(val)))
                return retVal

        # Don't log ENG, because it's not ment to be translated
        if lang != "ENG":
            Translater.parent.logMsg(
                LOG_WARNING, "No translation for '{}':'{}'".format(lang, data))

        return data
Пример #15
0
    def translate(data, lang = ''):
        # This happens when no language is set
        if lang == '':
            lang = Settings.get("active_language")


        if lang != '':
            if type(data) is str or type(data) is unicode:
                if data in Translater.translations[lang]:
                    return Translater.translations[lang][data]
            elif type(data) is list:
                retVal = list()
                for val in data:
                    retVal.append(localize(str(val)))
                return retVal

        # Don't log ENG, because it's not ment to be translated
        if lang != "ENG":
            Translater.parent.logMsg(LOG_WARNING, "No translation for '{}':'{}'".format(lang, data))

        return data
Пример #16
0
    async def start(self,
                    ctx,
                    pomodoro=20,
                    short_break=5,
                    long_break=15,
                    intervals=4):
        if not await Settings.is_valid(ctx, pomodoro, short_break, long_break,
                                       intervals):
            return
        if session_manager.active_sessions.get(
                session_manager.session_id_from(ctx.channel)):
            await ctx.send(u_msg.ACTIVE_SESSION_EXISTS_ERR)
            return
        if not ctx.author.voice:
            await ctx.send('Join a voice channel to use Pomomo!')
            return

        session = Session(
            bot_enum.State.POMODORO,
            Settings(pomodoro, short_break, long_break, intervals), ctx)
        await session_controller.start(session)
Пример #17
0
    def loadRememberedTabs(self):
        tabs = Settings.get('openedTabs').split(';')

        # Remove automatically created first page
        self.DeletePage(0)

        if tabs != ['']:
            # Add all Tabs
            for x in tabs:
                self.addPage(x)
            return

        # Open default files if no tabs were saved
        path = join(self.API.path, "../../apps/seal/Empty/")
        if exists(path):
            filename = self.API.frame.findFirstSourceFile(path)
            if filename:
                self.addPage(filename)
                return

        self.addPage('sampleCode.sl')
Пример #18
0
 async def edit(self,
                ctx,
                pomodoro: int,
                short_break: int = None,
                long_break: int = None,
                intervals: int = None):
     session = await session_manager.get_session(ctx)
     if session.state == bot_enum.State.COUNTDOWN:
         ctx.send(f'Countdowns cannot be edited. '
                  f'Use {config.CMD_PREFIX}countdown to start a new one.')
     if session:
         if not await Settings.is_valid(ctx, pomodoro, short_break,
                                        long_break, intervals):
             return
         await session_controller.edit(
             session, Settings(pomodoro, short_break, long_break,
                               intervals))
         session.timer.set_time_remaining()
         if session.state == bot_enum.State.COUNTDOWN:
             await countdown.update_msg(session)
         await session_controller.resume(session)
Пример #19
0
    async def countdown(self,
                        ctx,
                        duration: int,
                        title='Countdown',
                        audio_alert=None):
        session = session_manager.active_sessions.get(
            session_manager.session_id_from(ctx.channel))
        if session:
            await ctx.send('There is an active session running. '
                           'Are you sure you want to start a countdown? (y/n)')
            response = await self.client.wait_for('message', timeout=60)
            if not response.content.lower()[0] == 'y':
                await ctx.send('OK, cancelling new countdown.')
                return

        if not 0 < duration <= 180:
            await ctx.send(u_msg.NUM_OUTSIDE_ONE_AND_MAX_INTERVAL_ERR)
        session = Session(bot_enum.State.COUNTDOWN, Settings(duration), ctx)
        await countdown.handle_connection(session, audio_alert)
        session_manager.activate(session)
        await session_messenger.send_countdown_msg(session, title)
        await countdown.start(session)
Пример #20
0
def menu_project_options(project):
    options = []

    options.append(["Open", project.open_project])
    # options.append(["Change Name", None])
    # options.append(["Duplicate", None])

    if not project.is_remote() or project.is_dirty():
        options.append(["Upload", project.upload_project])

    if project.is_remote():
        if not project.is_up_to_date():
            options.append(["Download", project.download_and_extract])
        options.append(["Change Category", project.change_category])

    mutex = project.is_locked()
    if mutex and mutex == Settings.get_username(capitalize=True):
        options.append(["Unlock", project.remove_lock])

    if project.is_local():
        options.append(["Duplicate", project.duplicate])

    options.append(["Delete", project.delete_project])

    menu = Menu(title=f'Project "{project.entry.name}"',
                options=[x[0] for x in options])

    result = menu.get_result()

    if result == "back":
        return True
    else:
        if options[result][0] == "Delete":
            return options[result][1]()

        if not options[result][1]():
            return False

        return menu_project_options(project)
Пример #21
0
    def open_project(self):
        Log(f'Opening project "{self.entry.name}"..')

        # - Download any new updates / Download new project
        if not self.is_up_to_date():
            Log("Project Update Available!")
            if not self.download_and_extract():
                return False

        # Check for mutex lock
        mutex = self.is_locked()
        if mutex and mutex != Settings.get_username(capitalize=True):
            # Provide dialog to alert user that they can't save
            if not self.dialog_project_locked():
                return True
        else:
            # Lets mutex lock this beach
            self.set_lock()

        # - Open Studio One Project
        if not self.open_studio_one():
            return False

        if not self.is_remote():
            # Lets ask if user wants to upload project
            if self.dialog_upload_new_project():
                if not self.upload_project():
                    Log("An error occurred when trying to upload the project!","warning")
                    Log.press_enter()
                    return False

        elif self.is_dirty():
            # Check for mutex lock
            mutex = self.is_locked()

            if mutex and mutex != Settings.get_username(capitalize=True):
                # Project was locked by someone else
                # Remove any saved changes
                Log("Resetting project.. Undoing changes..")
                self.extract_project()
            else:
                ans = self.dialog_upload_clear_cancel()
                if ans == "y":
                    # Lets upload our changes!
                    if not self.upload_project():
                        Log("An error occurred when trying to upload the project!","warning")
                        Log.press_enter()
                        self.remove_lock()
                        return False
                    # Remove our name from the dirty list if it exists
                    self.remove_dirty()
                elif ans == "clear":
                    self.extract_project()
                    # Remove our name from the dirty list if it exists
                    self.remove_dirty()
                else:
                    # The user is not uploading new changes..
                    # Make sure to set the project to dirty!
                    self.set_dirty()

        # Remove the lock we placed on when opening the project
        self.remove_lock()

        return True
Пример #22
0
 def settings(self):
     """open editor settings changer"""
     _s = self.input.prompt_bar(":")
     setting = Settings(self)
     setting.execute(_s)
Пример #23
0
# this is required to access 'src' modules
import os, sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
##########################################

from src.Settings import Settings
from src.TERMGUI.Log import Log
from src.TERMGUI.Dialog import Dialog
from src.FileManagement.File import File

if __name__ == "__main__":
    # Before we finish the update, we need to update the core files
    if not Settings.get_key("update_git"):
        Settings.set_key("update_git", True)

        dialog = Dialog(
            title="Upgrading to V1.3!",
            body=[
                f'Welcome to a new friendly update!  Hopefully everything goes nice',
                f'and smooth, haha! .... #justkiddingbutseriously',
                f'\n',
                f'\n',
                f'The main fix for this update solves the slow-down issues while trying',
                f'to open up a project.',
                f'\n',
                f'\n',
                f'There also was some significant code improvements on both local and remote',
                f'servers to allow for new features, yay!  Features such',
Пример #24
0
    def to_mp3(self, folderpath, username_ignore=False):
        folderpath = Path(folderpath)

        wav = self.filepath
        mp3 = Path(f'{folderpath.absolute()}/{wav.stem}.mp3')
        username = Settings.get_username()

        if "_old" in wav.name:
            Dialog(
                title="Warning! Can't Upload *_old* Audio File!",
                body=[
                    f'It appears that you have not yet resolved the audio file',
                    f'conflict for "{wav.name}"!  You must either delete this file,',
                    f'or re-name it and re-link it in Studio One!',
                    f'\n',
                    f'\n',
                ],
                clear=False).press_enter()
            return False

        if not mp3.is_file():
            if not username in wav.name.lower() and not username_ignore:
                dialog = Dialog(
                    title="Warning! Where Is Your Name?!",
                    body=[
                        f'It appears that the file',
                        f'\n',
                        f'\n',
                        f' - {wav.parent.absolute().name}/{wav.name}',
                        f'\n',
                        f'\n',
                        f'does not contain your name.. Are you sure you recorded',
                        f'on the correct track?!  Doing this can cause serious',
                        f'version control issues!!',
                        f'\n',
                        f'\n',
                        f'Since you have already removed unused audio files from',
                        f'the pool, AND selected the checkbox to delete those',
                        f'audio files..  You should go back into your Studio One',
                        f'project, remove this clip from the timeline, OR rename',
                        f'this clip to include your name, and then re-run the',
                        f'upload!',
                        f'\n',
                        f'\n',
                        f'If you are ABSOLUTELY SURE that this is in error, aka',
                        f'uploading a project from band practice, then type "yes"',
                        f'at the prompt, or "yesall" to ignore all other warnings',
                        f'for this.',
                        f'\n',
                        f'\n',
                        f'If you want to exit now, type "no" at the prompt.',
                        f'\n',
                        f'\n',
                    ],
                    clear=False)
                ans = dialog.get_mult_choice(["yes", "yesall", "no"])

                if ans == "no":
                    return False
                elif ans == "yesall":
                    username_ignore = True

        else:
            Log(f'Keeping cached file "{mp3.name}"')
            return True

        Run.ffmpeg(args="-i",
                   source=wav.absolute(),
                   destination=mp3.absolute(),
                   codec="")

        if username_ignore:
            return {"username_ignore": True}
        return True
Пример #25
0
 def reset_slack_endpoints():
     Settings.set_key(Settings.slack_prod_key, "")
     Settings.set_key(Settings.slack_dev_key, "")
     Settings.set_slack_endpoints()
Пример #26
0
class Application(Tkinter.Tk):
    def __init__(self):
        Tkinter.Tk.__init__(self)
        self.attributes('-alpha', 0.0)
        self.thread = None
        self.threadLock = thread.allocate_lock()
        self.settings = Settings()
        self.initialize()

    def initialize(self):

        self.title(TITLE)
        self.config(background=COLOR_BG)

        # HACK: set application icon
        # see http://stackoverflow.com/a/11180300
        icon = open_photoimage(resource_path('resources', 'icon.png'))
        self.tk.call('wm', 'iconphoto', self._w, icon)

        # create application frame
        self.frame = AppFrame(self)
        self.frame.pack(fill=Tkinter.BOTH, expand=1)

        # Specific modifications for Mac OS X systems
        if OS_DARWIN:

            # Add an empty main menu.
            menu = Tkinter.Menu(self)
            try:
                self.config(menu=menu)
            except AttributeError:
                # master is a toplevel window (Python 1.4/Tkinter 1.63)
                self.tk.call(self, 'config', '-menu', menu)

            # Register about dialog.
            self.createcommand('tkAboutDialog', self.show_about_dialog)

        # event on window close
        self.protocol('WM_DELETE_WINDOW', self.shutdown)

        # close window with ESC
        #self.bind('<Escape>', lambda e: self.on_close())

        # set window size
        #self.resizable(False,False)
        #self.resizable(width=False, height=False)
        w = get_configuration_int('gui', 'application-window-width', 500)
        h = get_configuration_int('gui', 'application-window-height', 300)
        self.geometry('%sx%s' % (w, h))

    def mainloop(self, n=0):
        self.attributes('-alpha', 1.0)
        Tkinter.Tk.mainloop(self, n=n)

    def set_connected(self):
        if self.threadLock.locked(): return
        try:
            self.threadLock.acquire()
            self.frame.set_connected()
        finally:
            self.threadLock.release()

    def set_connecting(self):
        if self.threadLock.locked(): return
        try:
            self.threadLock.acquire()
            self.frame.set_connecting()
        finally:
            self.threadLock.release()

    def set_disconnected(self, show_message=True):
        if self.threadLock.locked(): return
        try:
            self.threadLock.acquire()
            self.frame.set_disconnected(show_message=show_message)
        finally:
            self.threadLock.release()

    def set_error(self, msg=None):
        if self.threadLock.locked(): return
        try:
            self.threadLock.acquire()
            self.frame.set_error(msg=msg)
        finally:
            self.threadLock.release()

    def show_about_dialog(self):
        dlg = AboutDialog(self)
        #self.eval('tk::PlaceWindow %s center' % dlg.winfo_pathname(dlg.winfo_id()))

        x = self.winfo_rootx()
        y = self.winfo_rooty()
        w = get_configuration_int('gui', 'about-window-width', 550)
        h = get_configuration_int('gui', 'about-window-height', 350)
        dlg.geometry('%sx%s+%d+%d' % (w, h, x+25, y+25))

        dlg.grab_set()
        self.wait_window(dlg)

    def show_extended_settings_dialog(self):
        dlg = SettingsDialog(self)
        #self.eval('tk::PlaceWindow %s center' % dlg.winfo_pathname(dlg.winfo_id()))

        x = self.winfo_rootx()
        y = self.winfo_rooty()
        w = get_configuration_int('gui', 'settings-window-width', 550)
        h = get_configuration_int('gui', 'settings-window-height', 350)
        dlg.geometry('%sx%s+%d+%d' % (w, h, x+25, y+25))

        dlg.grab_set()
        self.wait_window(dlg)

    def shutdown(self):
        self.stop_thread()
        self.destroy()

    def start_thread(self):
        self.stop_thread(False)

        # validate hostname
        host = self.settings.get_host()
        if host is None:
            self.set_error(msg=_('The address in invalid.'))
            return

        # validate port number
        port = self.settings.get_port()
        if port is None:
            self.set_error(msg=_('The port number is invalid.'))
            return
        if port < 0 or port > 65535:
            self.set_error(_('The port number is not in the interval from {0} to {1}.').format(1, 65535))
            return

        #print 'connecting to %s:%s' % (host, port)
        self.set_connecting()
        self.thread = VNC(self, self.settings)
        self.thread.start()

    def stop_thread(self, show_message=True):
        if not self.thread is None:
            self.thread.kill()
        self.thread = None
        self.set_disconnected(show_message)
Пример #27
0
 def get_nice_username():
     return Settings.get_username(capitalize=True)
Пример #28
0
 def _get_endpoint_key(self, endpoint):
     if endpoint == "dev":
         return Settings.get_key(Settings.slack_dev_key)
     elif endpoint == "prod":
         return Settings.get_key(Settings.slack_prod_key)
Пример #29
0
 def rememberOpenedTabs(self):
     result = ''
     for x in self.API.editors:
         if type(x) is EditorManager:
             result += x.filePath + ";"
     Settings.set('openedTabs', result.strip(";"))
Пример #30
0
    def generateMenu(self):
        fileMenu = wx.Menu()
        new = fileMenu.Append(wx.ID_NEW, '&' + localize('New') + '\tCtrl+N',
                              localize('Create empty document'))
        open_ = fileMenu.Append(wx.ID_OPEN, '&' + localize('Open') + '\tCtrl+O',
                              localize('Open document'))
        save = fileMenu.Append(wx.ID_SAVE, '&' + localize('Save') + '\tCtrl+S',
                              localize('Save document'))
        saveAs = fileMenu.Append(wx.ID_SAVEAS, '&' + localize('Save as') + '\t',
                              localize('Save document as'))
        upload = fileMenu.Append(wx.ID_ANY, '&' + localize('Upload') + '\tCtrl+U',
                              localize('Open upload window'))
        recent = wx.Menu()
        fileMenu.AppendMenu(wx.ID_ANY, '&' + localize('Recently used files'),
                               recent, localize('Recently used files'))
        close = fileMenu.Append(wx.ID_EXIT, '&' + localize('Exit') + '\tCtrl+Q',
                              localize('Exit application'))

        self.fileHistory = wx.FileHistory(int(Settings.get('recently_opened_count')))
        self.fileHistory.Load(self.API.config)
        self.fileHistory.UseMenu(recent)
        self.fileHistory.AddFilesToMenu()
        self.Bind(wx.EVT_MENU_RANGE, self.on_file_history, id = wx.ID_FILE1, id2 = wx.ID_FILE9)

        # show menu with mansos demo & test applications
        exampleMenu = wx.Menu()
        pathToMansosApps = self.API.path + os.path.normcase("/../../apps/")
        self.addExampleMenuItems(exampleMenu, pathToMansosApps, maxDepth = 2)

        optionMenu = wx.Menu()
        language = wx.Menu()
        self.langs = []
        for i in Translater.translations.keys():
            self.langs.append(language.Append(wx.ID_ANY,
                    Translater.translations[i]['langName'], i, kind = wx.ITEM_RADIO))
            if i == Settings.get("active_language"):
                language.Check(self.langs[-1].GetId(), True)
            self.Bind(wx.EVT_MENU, self.changeLanguage, self.langs[-1])

        optionMenu.AppendMenu(wx.ID_ANY, localize('Change language'), language)

        output = optionMenu.Append(wx.ID_ANY, '&' + localize('Configure upload and compile') + '\tCtrl+R',
                              localize('Open read output window'))
        windowMenu = wx.Menu()
        addMenu = wx.Menu()
        showMenu = wx.Menu()
        windowMenu.AppendMenu(wx.ID_ANY, localize('Add window'), addMenu)
        #windowMenu.AppendMenu(wx.ID_ANY, localize('Show window'), showMenu)
        listen = addMenu.Append(wx.ID_ANY, '&' + localize('Add listen window'),
                              localize('Add listen window'))
        self.blocklyCheck = showMenu.AppendCheckItem(wx.ID_ANY, '&' + localize('Show blockly window'),
                              localize('Show blockly window'))
        self.editCheck = showMenu.AppendCheckItem(wx.ID_ANY, '&' + localize('Show edit window'),
                              localize('Show edit window'))

        helpMenu = wx.Menu()
        sealHelp = helpMenu.Append(wx.ID_ANY, '&' + localize('Seal documentation'),
                              localize('About'))
        mansosHelp = helpMenu.Append(wx.ID_ANY, '&' + localize('MansOS documentation'),
                              localize('About'))
        about = helpMenu.Append(wx.ID_ABOUT, '&' + localize('About') + '\tCtrl+H',
                              localize('About'))
        # Check if we need to update existing menubar(for translate)
        if self.menubar == None:
            self.menubar = wx.MenuBar()
        else:
            for i in range(0, self.menubar.GetMenuCount()):
                self.menubar.Remove(0)

        self.menubar.Append(fileMenu, '&' + localize('File'))
        self.menubar.Append(exampleMenu, '&' + localize('Examples'))
        self.menubar.Append(optionMenu, '&' + localize('Options'))
        self.menubar.Append(windowMenu, '&' + localize('Windows'))
        self.menubar.Append(helpMenu, '&' + localize('Help'))
        self.SetMenuBar(self.menubar)

        # First bind to menu
        self.Bind(wx.EVT_MENU, self.OnQuit, close)
        self.Bind(wx.EVT_MENU, self.OnOpen, open_)
        self.Bind(wx.EVT_MENU, self.OnSave, save)
        self.Bind(wx.EVT_MENU, self.OnSaveAs, saveAs)
        self.Bind(wx.EVT_MENU, self.OnUpload, upload)
        self.Bind(wx.EVT_MENU, self.OnOutput, output)
        self.Bind(wx.EVT_MENU, self.OnNew, new)
        self.Bind(wx.EVT_MENU, self.OnAbout, about)
        self.Bind(wx.EVT_MENU, self.OnSealHelp, sealHelp)
        self.Bind(wx.EVT_MENU, self.OnMansosHelp, mansosHelp)

        self.Bind(wx.EVT_MENU, self.API.addListenWindow, listen)
        self.Bind(wx.EVT_MENU, self.API.showBlocklyWindow, self.blocklyCheck)
        self.Bind(wx.EVT_MENU, self.API.showEditWindow, self.editCheck)
Пример #31
0
 def changeLanguage(self, event):
     for i in self.langs:
         if i.IsChecked() == True:
             Settings.set("active_language", i.GetHelp())
             self.initUI()
Пример #32
0
class SettingsDialog(Tkinter.Toplevel):
    def __init__(self, parent):
        Tkinter.Toplevel.__init__(self, parent)
        self.parent = parent
        self.settings = Settings()
        self.settings.copy_from(parent.settings)
        self.transient(parent)
        self.initialize()

    def initialize(self):
        self.title(_('Extended Settings'))
        self.config(background=COLOR_BG, padx=0, pady=0)

        self.sidebar = open_photoimage(resource_path('resources', 'sidebar_settings.png'), self.winfo_rgb(COLOR_BG))
        Tkinter.Label(self, image=self.sidebar, background=COLOR_BG, padx=0, pady=0, borderwidth=0)\
            .grid(row=0, column=0, rowspan=11, sticky='nw')

        # settings form
        self.form = SettingsDialogForm(self)
        self.form.grid(row=0, column=1, padx=5, pady=5, sticky='nwe')

        # growing separator
        Tkinter.Label(self, font=FONT_SMALL, background=COLOR_BG)\
            .grid(row=1, column=1, sticky='we')

        # buttons
        buttons = Tkinter.Frame(self, background=COLOR_BG)
        Tkinter.Button(buttons, text=_('Submit'), command=self.on_click_submit, background=COLOR_BG, font=FONT_BUTTON)\
            .grid(row=0, column=1, padx=5, pady=5)
        Tkinter.Button(buttons, text=_('Cancel'), command=self.on_click_cancel, background=COLOR_BG, font=FONT_BUTTON)\
            .grid(row=0, column=2, padx=5, pady=5)
        buttons.grid(row=2, column=1, columnspan=2, sticky='e')

        # layout grid
        self.grid_columnconfigure(index=0, weight=0)
        self.grid_columnconfigure(index=1, weight=1)
        self.grid_rowconfigure(index=1, weight=1)

        # close dialog with ESC
        self.bind('<Escape>', lambda e: self.destroy())

        # Fokus auf dem Textfeld anfordern
        self.form.focus_set()

    def on_click_cancel(self):
        self.destroy()

    def on_click_submit(self):

        messages = []
        self.form.validate(messages)
        if len(messages) > 0:
            txt = _('Incorrect settings!')
            txt += '\n- '
            txt += '\n- '.join(messages)
            tkMessageBox.showerror(title=_('Incorrect settings!'), message=txt, parent=self)
            return

        # copy values into application settings
        self.parent.settings.copy_from(self.settings)

        # unregister VNC application, if the default application is enabled
        if self.form.is_custom_vnc_app():
            self.parent.settings.vnc_application.set('')

        self.destroy()
Пример #33
0
import traceback,sys
from src.Slack import Slack
from src.Update import Update
from src.Settings import Settings
from src.TERMGUI.Log import Log
from src.FileManagement.Folder import Folder
from src.menus.menu_main import menu_main

# MAIN FUNCTION
if __name__ == '__main__':

    # Create file structure if it doesn't exist
    Folder.create("compressed_songs")
    Folder.create("extracted_songs")
    Folder.create("temp")
    Folder.create("templates")

    # Create settings file if it doesn't exist
    Settings.create()

    # Start main menu
    try:
        menu_main()
    except Exception as e:
        Log(traceback.format_exc(),"warning")
        # 0 = there was a problem
        # 1 = exit gracefully
        sys.exit(0)
Пример #34
0
def settings():
    '''Create azure resources and deploy function for e2e test'''
    print('Starting creation of infra for E2E testing...')

    # Load settingr from environment
    load_dotenv(find_dotenv())
    rand = random.randint(1, 999999)

    resource_group_name = os.getenv('RESOURCE_GROUP_NAME',
                                    f'AzureImageSizerE2E{rand}')
    location = os.getenv('LOCATION', 'westus2')
    storage_account_name = os.getenv('STORAGE_ACCOUNT_NAME', f'aise2e{rand}')
    function_app_name = os.getenv('FUNCTION_APP_NAME', f'aise2e{rand}')

    print(
        f'Executing e2e test on resource group {resource_group_name} at location {location} with storage account {storage_account_name} and function app {function_app_name}'
    )

    # Create resource group if it doesn't exist
    execute_process_report_error(
        f'az group create --name {resource_group_name} --location {location}')

    # Create storage account if it doesn't exist
    execute_process_report_error(
        f'az storage account create --resource-group {resource_group_name} --name {storage_account_name} --location {location}'
    )
    storage_connection_string = execute_process_report_error(
        f'az storage account show-connection-string --name {storage_account_name} --resource-group {resource_group_name} --output tsv'
    )

    # Creating settings object
    settings = Settings({
        'StorageAccountConnectionString': storage_connection_string,
        'ImageSizes': '480,768,1200,1400,1700,2000,2436',
        'ImageContainerName': f'image{rand}',
        'MetadataContainerName': f'metadata{rand}'
    })

    # Create storage containers
    execute_process_report_error(
        f'az storage container create --account-name {storage_account_name} --name {settings.image_container_name}'
    )
    execute_process_report_error(
        f'az storage container create --account-name {storage_account_name} --name {settings.metadata_container_name}'
    )

    # Create Azure function
    execute_process_report_error(
        f'az functionapp create --resource-group {resource_group_name} --consumption-plan-location {location} --runtime python --runtime-version 3.8 --functions-version 3 --name {function_app_name} --storage-account {storage_account_name} --os-type linux --disable-app-insights true'
    )

    # Deployment slots currently do not support Linux functions
    # Switch to slots once this is supported https://feedback.azure.com/forums/355860-azure-functions/suggestions/38891209-slots-for-linux-consumption-plan
    # execute_process_report_error(f'az functionapp deployment slot create --name {function_app_name} --slot {data.function_app_slot}')

    # Create function app deployment from local zip
    execute_process_report_error(
        f'az functionapp deployment source config-zip --name {function_app_name} --resource-group {resource_group_name} --src azure_web_img_dwnszr.zip',
        True)

    # Set function settings
    execute_process_report_error(
        f'az functionapp config appsettings set --name {function_app_name} --resource-group {resource_group_name} --settings "ImageSizes={",".join(map(str, settings.image_sizes))}"'
    )
    execute_process_report_error(
        f'az functionapp config appsettings set --name {function_app_name} --resource-group {resource_group_name} --settings "StorageAccountConnectionString={settings.storage_connection_string}"'
    )
    execute_process_report_error(
        f'az functionapp config appsettings set --name {function_app_name} --resource-group {resource_group_name} --settings "ImageContainerName={settings.image_container_name}"'
    )
    execute_process_report_error(
        f'az functionapp config appsettings set --name {function_app_name} --resource-group {resource_group_name} --settings "MetadataContainerName={settings.metadata_container_name}"'
    )

    # Create event trigger on image blob
    function_app_id = execute_process_report_error(
        f'az functionapp show --name {function_app_name} --resource-group {resource_group_name} --output tsv --query "id"'
    )
    function_id = f'{function_app_id}/functions/azure_web_img_dwnszr'
    storage_account_id = execute_process_report_error(
        f'az storage account show --name {storage_account_name} --resource-group {resource_group_name} --output tsv --query "id"'
    )
    execute_process_report_error(
        f'az eventgrid event-subscription create --name e2etest{rand} --source-resource-id {storage_account_id} --endpoint-type azurefunction --endpoint {function_id} --included-event-types "Microsoft.Storage.BlobCreated" --advanced-filter subject StringContains "{settings.image_container_name}"'
    )

    # Tests will run here, passing settings to test cases (data)
    print("E2E testing infra created!")
    yield settings
    print("Starting destruction of infra for E2E testing...")

    # Delete event trigger
    execute_process_report_error(
        f'az eventgrid event-subscription delete --name e2etest{rand} --source-resource-id {storage_account_id}'
    )

    # Delete function app (if not provided by env)
    if 'FUNCTION_APP_NAME' not in os.environ:
        execute_process_report_error(
            f'az functionapp delete --resource-group {resource_group_name} --name {function_app_name}'
        )

    # Delete containers
    execute_process_report_error(
        f'az storage container delete --account-name {storage_account_name} --name {settings.image_container_name}'
    )
    execute_process_report_error(
        f'az storage container delete --account-name {storage_account_name} --name {settings.metadata_container_name}'
    )

    # Delete storage account (if not provided by env)
    if 'STORAGE_ACCOUNT_NAME' not in os.environ:
        execute_process_report_error(
            f'az storage account delete --resource-group {resource_group_name} --name {storage_account_name} --yes'
        )

    # Delete the resource group (if not provided by env)
    if 'RESOURCE_GROUP_NAME' not in os.environ:
        execute_process_report_error(
            f'az group delete --name {resource_group_name}')

    print("E2E testing infra destroyed!")
Пример #35
0
            f'Note:',
            f'\n',
            f'  This update requires a full restart of LOFSongManager.  When',
            f'this update has completed, the software should shut down on its',
            f'own.  If it does not, please restart the software.',
            f'\n',
            f'\n',
            f'  Please ignore the next warning, "src.env.VERSION does not match"..',
            f'This is expected and gets fixed by this update.',
            f'\n',
            f'\n',
            f'For more information, please refer to the repository commits.',
            f'\n',
            f'\n',
        ])
    dialog.press_enter()

    File.delete("development.py")
    File.delete("compressed_songs/db.json")

    # Change 'user' key to 'username' in settings
    Settings.set_key("username", Settings.get_key("user"))

    # just to make sure we have the right ones
    Settings.reset_slack_endpoints()

    # 0 = there was a problem upgrading
    # 1 = do not restart core
    # 2 = restart core is necessary
    sys.exit(2)