Exemplo n.º 1
0
    def Run(self):

        self._app = wx.App()

        self._app.locale = wx.Locale(
            wx.LANGUAGE_DEFAULT
        )  # Very important to init this here and keep it non garbage collected

        # do not import locale here and try anything clever--assume that bad locale formatting is due to OS-level mess-up, not mine
        # wx locale is supposed to set it all up nice, so if someone's doesn't, explore that and find the external solution

        HydrusData.Print('booting controller\u2026')

        self.frame_icon = wx.Icon(
            os.path.join(HC.STATIC_DIR, 'hydrus_32_non-transparent.png'),
            wx.BITMAP_TYPE_PNG)

        self.CreateSplash()

        self.CallToThreadLongRunning(self.THREADBootEverything)

        self._app.MainLoop()

        HydrusData.Print('shutting down controller\u2026')
Exemplo n.º 2
0
 def _setLocale(self, language):
     ''' Try to set the locale, trying possibly multiple localeStrings. '''
     if not operating_system.isGTK():
         locale.setlocale(locale.LC_ALL, '')
     # Set the wxPython locale:
     for localeString in self._localeStrings(language):
         languageInfo = wx.Locale.FindLanguageInfo(localeString)
         if languageInfo:
             self.__locale = wx.Locale(languageInfo.Language)  # pylint: disable=W0201
             # Add the wxWidgets message catalog. This is really only for
             # py2exe'ified versions, but it doesn't seem to hurt on other
             # platforms...
             localeDir = os.path.join(
                 wx.StandardPaths_Get().GetResourcesDir(), 'locale')
             self.__locale.AddCatalogLookupPathPrefix(localeDir)
             self.__locale.AddCatalog('wxstd')
             break
     if operating_system.isGTK():
         try:
             locale.setlocale(locale.LC_ALL, '')
         except locale.Error:
             # Mmmh. wx will display a message box later, so don't do anything.
             pass
     self._fixBrokenLocales()
Exemplo n.º 3
0
def main():
    """NVDA's core main loop.
	This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI.
	Then it initialises the wx application object and sets up the core pump,
	which checks the queues and executes functions when requested.
	Finally, it starts the wx main loop.
	"""
    log.debug("Core starting")

    ctypes.windll.user32.SetProcessDPIAware()

    import config
    if not globalVars.appArgs.configPath:
        globalVars.appArgs.configPath = config.getUserDefaultConfigPath(
            useInstalledPathIfExists=globalVars.appArgs.launcher)
    #Initialize the config path (make sure it exists)
    config.initConfigPath()
    log.info(f"Config dir: {globalVars.appArgs.configPath}")
    log.debug("loading config")
    import config
    config.initialize()
    if config.conf['development']['enableScratchpadDir']:
        log.info("Developer Scratchpad mode enabled")
    if not globalVars.appArgs.minimal and config.conf["general"][
            "playStartAndExitSounds"]:
        try:
            nvwave.playWaveFile(
                os.path.join(globalVars.appDir, "waves", "start.wav"))
        except:
            pass
    logHandler.setLogLevelFromConfig()
    try:
        lang = config.conf["general"]["language"]
        import languageHandler
        log.debug("setting language to %s" % lang)
        languageHandler.setLanguage(lang)
    except:
        log.warning("Could not set language to %s" % lang)
    log.info(f"Windows version: {winVersion.getWinVer()}")
    log.info("Using Python version %s" % sys.version)
    log.info("Using comtypes version %s" % comtypes.__version__)
    import configobj
    log.info("Using configobj version %s with validate version %s" %
             (configobj.__version__, configobj.validate.__version__))
    # Set a reasonable timeout for any socket connections NVDA makes.
    import socket
    socket.setdefaulttimeout(10)
    log.debug("Initializing add-ons system")
    addonHandler.initialize()
    if globalVars.appArgs.disableAddons:
        log.info("Add-ons are disabled. Restart NVDA to enable them.")
    import appModuleHandler
    log.debug("Initializing appModule Handler")
    appModuleHandler.initialize()
    import NVDAHelper
    log.debug("Initializing NVDAHelper")
    NVDAHelper.initialize()
    log.debug("Initializing tones")
    import tones
    tones.initialize()
    import speechDictHandler
    log.debug("Speech Dictionary processing")
    speechDictHandler.initialize()
    import speech
    log.debug("Initializing speech")
    speech.initialize()
    if not globalVars.appArgs.minimal and (time.time() -
                                           globalVars.startTime) > 5:
        log.debugWarning("Slow starting core (%.2f sec)" %
                         (time.time() - globalVars.startTime))
        # Translators: This is spoken when NVDA is starting.
        speech.speakMessage(_("Loading NVDA. Please wait..."))
    import wx
    import six
    log.info("Using wx version %s with six version %s" %
             (wx.version(), six.__version__))

    class App(wx.App):
        def OnAssert(self, file, line, cond, msg):
            message = "{file}, line {line}:\nassert {cond}: {msg}".format(
                file=file, line=line, cond=cond, msg=msg)
            log.debugWarning(message, codepath="WX Widgets", stack_info=True)

        def InitLocale(self):
            # Backport of `InitLocale` from wx Python 4.1.2 as the current version tries to set a Python
            # locale to an nonexistent one when creating an instance of `wx.App`.
            # This causes a crash when running under a particular version of Universal CRT (#12160)
            import locale
            locale.setlocale(locale.LC_ALL, "C")

    app = App(redirect=False)

    # We support queryEndSession events, but in general don't do anything for them.
    # However, when running as a Windows Store application, we do want to request to be restarted for updates
    def onQueryEndSession(evt):
        if config.isAppX:
            # Automatically restart NVDA on Windows Store update
            ctypes.windll.kernel32.RegisterApplicationRestart(None, 0)

    app.Bind(wx.EVT_QUERY_END_SESSION, onQueryEndSession)

    def onEndSession(evt):
        # NVDA will be terminated as soon as this function returns, so save configuration if appropriate.
        config.saveOnExit()
        speech.cancelSpeech()
        if not globalVars.appArgs.minimal and config.conf["general"][
                "playStartAndExitSounds"]:
            try:
                nvwave.playWaveFile(os.path.join(globalVars.appDir, "waves",
                                                 "exit.wav"),
                                    asynchronous=False)
            except:
                pass
        log.info("Windows session ending")

    app.Bind(wx.EVT_END_SESSION, onEndSession)
    log.debug("Initializing braille input")
    import brailleInput
    brailleInput.initialize()
    import braille
    log.debug("Initializing braille")
    braille.initialize()
    import vision
    log.debug("Initializing vision")
    vision.initialize()
    import displayModel
    log.debug("Initializing displayModel")
    displayModel.initialize()
    log.debug("Initializing GUI")
    import gui
    gui.initialize()
    import audioDucking
    if audioDucking.isAudioDuckingSupported():
        # the GUI mainloop must be running for this to work so delay it
        wx.CallAfter(audioDucking.initialize)

    # #3763: In wxPython 3, the class name of frame windows changed from wxWindowClassNR to wxWindowNR.
    # NVDA uses the main frame to check for and quit another instance of NVDA.
    # To remain compatible with older versions of NVDA, create our own wxWindowClassNR.
    # We don't need to do anything else because wx handles WM_QUIT for all windows.
    import windowUtils

    class MessageWindow(windowUtils.CustomWindow):
        className = u"wxWindowClassNR"
        # Windows constants for power / display changes
        WM_POWERBROADCAST = 0x218
        PBT_APMPOWERSTATUSCHANGE = 0xA
        UNKNOWN_BATTERY_STATUS = 0xFF
        AC_ONLINE = 0X1
        NO_SYSTEM_BATTERY = 0X80
        #States for screen orientation
        ORIENTATION_NOT_INITIALIZED = 0
        ORIENTATION_PORTRAIT = 1
        ORIENTATION_LANDSCAPE = 2

        def __init__(self, windowName=None):
            super(MessageWindow, self).__init__(windowName)
            self.oldBatteryStatus = None
            self.orientationStateCache = self.ORIENTATION_NOT_INITIALIZED
            self.orientationCoordsCache = (0, 0)
            self.handlePowerStatusChange()

        def windowProc(self, hwnd, msg, wParam, lParam):
            post_windowMessageReceipt.notify(msg=msg,
                                             wParam=wParam,
                                             lParam=lParam)
            if msg == self.WM_POWERBROADCAST and wParam == self.PBT_APMPOWERSTATUSCHANGE:
                self.handlePowerStatusChange()
            elif msg == winUser.WM_DISPLAYCHANGE:
                self.handleScreenOrientationChange(lParam)

        def handleScreenOrientationChange(self, lParam):
            import ui
            import winUser
            # Resolution detection comes from an article found at https://msdn.microsoft.com/en-us/library/ms812142.aspx.
            #The low word is the width and hiword is height.
            width = winUser.LOWORD(lParam)
            height = winUser.HIWORD(lParam)
            self.orientationCoordsCache = (width, height)
            if width > height:
                # If the height and width are the same, it's actually a screen flip, and we do want to alert of those!
                if self.orientationStateCache == self.ORIENTATION_LANDSCAPE and self.orientationCoordsCache != (
                        width, height):
                    return
                #Translators: The screen is oriented so that it is wider than it is tall.
                ui.message(_("Landscape"))
                self.orientationStateCache = self.ORIENTATION_LANDSCAPE
            else:
                if self.orientationStateCache == self.ORIENTATION_PORTRAIT and self.orientationCoordsCache != (
                        width, height):
                    return
                #Translators: The screen is oriented in such a way that the height is taller than it is wide.
                ui.message(_("Portrait"))
                self.orientationStateCache = self.ORIENTATION_PORTRAIT

        def handlePowerStatusChange(self):
            #Mostly taken from script_say_battery_status, but modified.
            import ui
            import winKernel
            sps = winKernel.SYSTEM_POWER_STATUS()
            if not winKernel.GetSystemPowerStatus(
                    sps) or sps.BatteryFlag is self.UNKNOWN_BATTERY_STATUS:
                return
            if sps.BatteryFlag & self.NO_SYSTEM_BATTERY:
                return
            if self.oldBatteryStatus is None:
                #Just initializing the cache, do not report anything.
                self.oldBatteryStatus = sps.ACLineStatus
                return
            if sps.ACLineStatus == self.oldBatteryStatus:
                #Sometimes, this double fires. This also fires when the battery level decreases by 3%.
                return
            self.oldBatteryStatus = sps.ACLineStatus
            if sps.ACLineStatus & self.AC_ONLINE:
                #Translators: Reported when the battery is plugged in, and now is charging.
                ui.message(
                    _("Charging battery. %d percent") % sps.BatteryLifePercent)
            else:
                #Translators: Reported when the battery is no longer plugged in, and now is not charging.
                ui.message(
                    _("Not charging battery. %d percent") %
                    sps.BatteryLifePercent)

    import versionInfo
    messageWindow = MessageWindow(versionInfo.name)

    # initialize wxpython localization support
    locale = wx.Locale()
    wxLang = getWxLangOrNone()
    if hasattr(sys, 'frozen'):
        locale.AddCatalogLookupPathPrefix(
            os.path.join(globalVars.appDir, "locale"))
    if wxLang:
        try:
            locale.Init(wxLang.Language)
        except:
            log.error("Failed to initialize wx locale", exc_info=True)
        finally:
            # Revert wx's changes to the python locale
            languageHandler.setLocale(languageHandler.curLang)

    log.debug("Initializing garbageHandler")
    garbageHandler.initialize()

    import api
    import winUser
    import NVDAObjects.window
    desktopObject = NVDAObjects.window.Window(
        windowHandle=winUser.getDesktopWindow())
    api.setDesktopObject(desktopObject)
    api.setFocusObject(desktopObject)
    api.setNavigatorObject(desktopObject)
    api.setMouseObject(desktopObject)
    import JABHandler
    log.debug("initializing Java Access Bridge support")
    try:
        JABHandler.initialize()
        log.info("Java Access Bridge support initialized")
    except NotImplementedError:
        log.warning("Java Access Bridge not available")
    except:
        log.error("Error initializing Java Access Bridge support",
                  exc_info=True)
    import winConsoleHandler
    log.debug("Initializing legacy winConsole support")
    winConsoleHandler.initialize()
    import UIAHandler
    log.debug("Initializing UIA support")
    try:
        UIAHandler.initialize()
    except RuntimeError:
        log.warning("UIA disabled in configuration")
    except:
        log.error("Error initializing UIA support", exc_info=True)
    import IAccessibleHandler
    log.debug("Initializing IAccessible support")
    IAccessibleHandler.initialize()
    log.debug("Initializing input core")
    import inputCore
    inputCore.initialize()
    import keyboardHandler
    log.debug("Initializing keyboard handler")
    keyboardHandler.initialize()
    import mouseHandler
    log.debug("initializing mouse handler")
    mouseHandler.initialize()
    import touchHandler
    log.debug("Initializing touchHandler")
    try:
        touchHandler.initialize()
    except NotImplementedError:
        pass
    import globalPluginHandler
    log.debug("Initializing global plugin handler")
    globalPluginHandler.initialize()
    if globalVars.appArgs.install or globalVars.appArgs.installSilent:
        import gui.installerGui
        wx.CallAfter(gui.installerGui.doSilentInstall,
                     copyPortableConfig=globalVars.appArgs.copyPortableConfig,
                     startAfterInstall=not globalVars.appArgs.installSilent)
    elif globalVars.appArgs.portablePath and (
            globalVars.appArgs.createPortable
            or globalVars.appArgs.createPortableSilent):
        import gui.installerGui
        wx.CallAfter(
            gui.installerGui.doCreatePortable,
            portableDirectory=globalVars.appArgs.portablePath,
            silent=globalVars.appArgs.createPortableSilent,
            startAfterCreate=not globalVars.appArgs.createPortableSilent)
    elif not globalVars.appArgs.minimal:
        try:
            # Translators: This is shown on a braille display (if one is connected) when NVDA starts.
            braille.handler.message(_("NVDA started"))
        except:
            log.error("", exc_info=True)
        if globalVars.appArgs.launcher:
            from gui.startupDialogs import LauncherDialog
            LauncherDialog.run()
            # LauncherDialog will call doStartupDialogs() afterwards if required.
        else:
            wx.CallAfter(doStartupDialogs)
    import queueHandler
    # Queue the handling of initial focus,
    # as API handlers might need to be pumped to get the first focus event.
    queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus)
    import watchdog
    import baseObject

    # Doing this here is a bit ugly, but we don't want these modules imported
    # at module level, including wx.
    log.debug("Initializing core pump")

    class CorePump(gui.NonReEntrantTimer):
        "Checks the queues and executes functions."

        def run(self):
            global _isPumpPending
            _isPumpPending = False
            watchdog.alive()
            try:
                if touchHandler.handler:
                    touchHandler.handler.pump()
                JABHandler.pumpAll()
                IAccessibleHandler.pumpAll()
                queueHandler.pumpAll()
                mouseHandler.pumpAll()
                braille.pumpAll()
                vision.pumpAll()
            except:
                log.exception("errors in this core pump cycle")
            baseObject.AutoPropertyObject.invalidateCaches()
            watchdog.asleep()
            if _isPumpPending and not _pump.IsRunning():
                # #3803: Another pump was requested during this pump execution.
                # As our pump is not re-entrant, schedule another pump.
                _pump.Start(PUMP_MAX_DELAY, True)

    global _pump
    _pump = CorePump()
    requestPump()

    log.debug("Initializing watchdog")
    watchdog.initialize()
    try:
        import updateCheck
    except RuntimeError:
        updateCheck = None
        log.debug("Update checking not supported")
    else:
        log.debug("initializing updateCheck")
        updateCheck.initialize()
    log.info("NVDA initialized")

    # Queue the firing of the postNVDAStartup notification.
    # This is queued so that it will run from within the core loop,
    # and initial focus has been reported.
    def _doPostNvdaStartupAction():
        log.debug("Notify of postNvdaStartup action")
        postNvdaStartup.notify()

    queueHandler.queueFunction(queueHandler.eventQueue,
                               _doPostNvdaStartupAction)

    log.debug("entering wx application main loop")
    app.MainLoop()

    log.info("Exiting")
    # If MainLoop is terminated through WM_QUIT, such as starting an NVDA instance older than 2021.1,
    # triggerNVDAExit has not been called yet
    if triggerNVDAExit():
        log.debug("NVDA not already exiting, hit catch-all exit trigger."
                  " This likely indicates NVDA is exiting due to WM_QUIT.")
        queueHandler.pumpAll()
    _terminate(gui)
    config.saveOnExit()

    try:
        if globalVars.focusObject and hasattr(globalVars.focusObject,
                                              "event_loseFocus"):
            log.debug("calling lose focus on object with focus")
            globalVars.focusObject.event_loseFocus()
    except:
        log.exception("Lose focus error")
    try:
        speech.cancelSpeech()
    except:
        pass

    import treeInterceptorHandler
    _terminate(treeInterceptorHandler)
    _terminate(IAccessibleHandler, name="IAccessible support")
    _terminate(UIAHandler, name="UIA support")
    _terminate(winConsoleHandler, name="Legacy winConsole support")
    _terminate(JABHandler, name="Java Access Bridge support")
    _terminate(appModuleHandler, name="app module handler")
    _terminate(tones)
    _terminate(NVDAHelper)
    _terminate(touchHandler)
    _terminate(keyboardHandler, name="keyboard handler")
    _terminate(mouseHandler)
    _terminate(inputCore)
    _terminate(vision)
    _terminate(brailleInput)
    _terminate(braille)
    _terminate(speech)
    _terminate(addonHandler)
    _terminate(garbageHandler)
    # DMP is only started if needed.
    # Terminate manually (and let it write to the log if necessary)
    # as core._terminate always writes an entry.
    try:
        import diffHandler
        diffHandler._dmp._terminate()
    except Exception:
        log.exception("Exception while terminating DMP")

    if not globalVars.appArgs.minimal and config.conf["general"][
            "playStartAndExitSounds"]:
        try:
            nvwave.playWaveFile(os.path.join(globalVars.appDir, "waves",
                                             "exit.wav"),
                                asynchronous=False)
        except:
            pass
    # #5189: Destroy the message window as late as possible
    # so new instances of NVDA can find this one even if it freezes during exit.
    messageWindow.destroy()
    log.debug("core done")
Exemplo n.º 4
0
                text + u"\n")
            self.logger.info(text)


if __name__ == '__main__':
    if sys.platform.startswith('win'):
        multiprocessing.freeze_support()  # multiprcessing workaround

    app = wx.PySimpleApp(False)

    #---------------------------------------------
    # locale
    #basepath = os.path.abspath(os.path.dirname(sys.argv[0]))
    #localedir = os.path.join(basepath, "locale")
    langid = wx.LANGUAGE_DEFAULT
    mylocale = wx.Locale(langid)
    mylocale.AddCatalogLookupPathPrefix('./locale')
    mylocale.AddCatalog('messages')
    _ = wx.GetTranslation

    # override
    import __builtin__
    __builtin__._ = wx.GetTranslation

    # override wxobject
    import wxobject
    wxobject._ = wx.GetTranslation

    #---------------------------------------------

    frm = FF(None)
Exemplo n.º 5
0
        @param default: The default item to show in the combo box

        """
        lang_ids = GetLocaleDict(GetAvailLocales()).values()
        lang_items = langlist.CreateLanguagesResourceLists(langlist.LC_ONLY, \
                                                           lang_ids)
        wx.combo.BitmapComboBox.__init__(self, parent, id_,
                                         size=wx.Size(250, 26),
                                         style=wx.CB_READONLY)
        for lang_d in lang_items[1]:
            bit_m = lang_items[0].GetBitmap(lang_items[1].index(lang_d))
            self.Append(lang_d, bit_m)

        if default:
            self.SetValue(default)

#-----------------------------------------------------------------------------#
if __name__ == '__main__':
    APP = wx.PySimpleApp(False)
    # Print a list of Cannonical names usefull for seeing what codes to
    # use when naming po files
    OUT = list()
    for LANG in [x for x in dir(wx) if x.startswith("LANGUAGE")]:
        LOC_I = wx.Locale(wx.LANGUAGE_DEFAULT).\
                         GetLanguageInfo(getattr(wx, LANG))
        if LOC_I:
            OUT.append(LOC_I.CanonicalName)

    for LANG in sorted(OUT):
        print LANG
Exemplo n.º 6
0
                key = unicode(base64.b64encode(os.urandom(8), 'zZ'))
                key = wx.GetUserName() + key
                profiler.Profile_Set('SESSION_KEY', key)
                profiler.Profile_Set('ISBINARY', hasattr(sys, 'frozen'))
                path = profiler.Profile_Get('MYPROFILE')
                profiler.Profile().Write(path)
                self._server = ed_ipc.EdIpcServer(
                    self, profiler.Profile_Get('SESSION_KEY'))
                self._server.start()
                self._isfirst = True
        else:
            self._isfirst = True

        # Setup Locale
        locale.setlocale(locale.LC_ALL, '')
        self.locale = wx.Locale(ed_i18n.GetLangId(
            profiler.Profile_Get('LANG')))
        if self.locale.GetCanonicalName() in ed_i18n.GetAvailLocales():
            self.locale.AddCatalogLookupPathPrefix(ed_glob.CONFIG['LANG_DIR'])
            self.locale.AddCatalog(ed_glob.PROG_NAME)
        else:
            del self.locale
            self.locale = None

        # Setup the Error Reporter
        if profiler.Profile_Get('REPORTER', 'bool', True):
            sys.excepthook = dev_tool.ExceptionHook

        #---- Bind Events ----#
        self.Bind(wx.EVT_ACTIVATE_APP, self.OnActivate)
        self.Bind(wx.EVT_MENU, self.OnNewWindow, id=ed_glob.ID_NEW_WINDOW)
        self.Bind(wx.EVT_MENU, self.OnCloseWindow)
Exemplo n.º 7
0
Arquivo: logsim.py Projeto: ip342/GF2
def main(arg_list):
    """Parse the command line options and arguments specified in arg_list.

    Run either the command line user interface, the graphical user interface,
    or display the usage message.
    """
    usage_message = ("Usage:\n"
                     "Show help: logsim.py -h\n"
                     "Command line user interface: logsim.py -c <file path>\n"
                     "Graphical user interface: logsim.py <file path>")
    try:
        options, arguments = getopt.getopt(arg_list, "hc:")
    except getopt.GetoptError:
        print("Error: invalid command line arguments\n")
        print(usage_message)
        sys.exit()

    for option, path in options:
        if option == "-h":  # print the usage message
            print(usage_message)
            sys.exit()
        elif option == "-c":  # use the command line user interface
            names = Names()
            devices = Devices(names)
            network = Network(names, devices)
            monitors = Monitors(names, devices, network)
            scanner = Scanner(path, names)
            parser = Parser(names, devices, network, monitors, scanner)
            if parser.parse_network():
                error_list = scanner.error_list
                for error in error_list:
                    print(error)
                # Initialise an instance of the userint.UserInterface() class
                userint = UserInterface(names, devices, network, monitors)
                userint.command_interface()
            else:
                error_list = scanner.error_list
                for error in error_list:
                    print(error)

    if not options:  # no option given, use the graphical user interface

        path = None
        names = None
        devices = None
        network = None
        monitors = None
        filename = None
        app = wx.App()

        # Internationalisation
        builtins._ = wx.GetTranslation
        locale = wx.Locale()
        locale.Init(wx.LANGUAGE_DEFAULT)
        locale.AddCatalogLookupPathPrefix('./locale')
        locale.AddCatalog('messages')

        gui = Gui(_("பனி Logic Simulator"), path, names, devices, network,
                  monitors, filename, True)
        gui.Show(True)
        gui.startup_load()
        app.MainLoop()

        while gui.load_new is True:
            path = gui.current_pathname
            filename = gui.current_filename
            names = Names()
            devices = Devices(names)
            network = Network(names, devices)
            monitors = Monitors(names, devices, network)
            scanner = Scanner(path, names)
            parser = Parser(names, devices, network, monitors, scanner)
            if parser.parse_network():
                # Initialise an instance of the gui.Gui() class
                gui = Gui(
                    _("பனி Logic Simulator - {}").format(filename), path,
                    names, devices, network, monitors, filename)
                gui.Show(True)
                app.MainLoop()
Exemplo n.º 8
0
    def __init__(self, parent, title, dirname, filename):
        sys.excepthook = self.exception_hook
        self.copied_animations = None
        self.copied_bones = None
        self.copied_bone_info = None
        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)

        # A "-1" in the size parameter instructs wxWidgets to use the default size.
        # In this case, we select 200px width and the default height.
        wx.Frame.__init__(self, parent, title=title, size=(1200, 800))
        self.statusbar = self.CreateStatusBar(
        )  # A Statusbar in the bottom of the window

        # Setting up the menu.
        filemenu = wx.Menu()
        menu_about = filemenu.Append(wx.ID_ABOUT)
        menu_exit = filemenu.Append(wx.ID_EXIT)

        # Creating the menubar.
        menu_bar = wx.MenuBar()
        menu_bar.Append(filemenu,
                        "&File")  # Adding the "filemenu" to the MenuBar
        self.SetMenuBar(menu_bar)  # Adding the MenuBar to the Frame content.

        # Publisher
        pub.subscribe(self.open_main_file, 'open_main_file')
        pub.subscribe(self.load_main_file, 'load_main_file')
        pub.subscribe(self.open_side_file, 'open_side_file')
        pub.subscribe(self.load_side_file, 'load_side_file')
        pub.subscribe(self.save_ean, 'save_ean')
        pub.subscribe(self.save_esk, 'save_esk')
        pub.subscribe(self.copy_bone_info, 'copy_bone_info')

        # Events
        self.Bind(wx.EVT_MENU, self.on_exit, menu_exit)
        self.Bind(wx.EVT_MENU, self.on_about, menu_about)

        # Tabs
        self.main_notebook = wx.Notebook(self)

        self.ean_main_notebook = wx.Notebook(self.main_notebook)
        self.ean_main_notebook.SetBackgroundColour(wx.Colour('grey'))
        self.esk_main_notebook = wx.Notebook(self.main_notebook)
        self.main_notebook.AddPage(self.ean_main_notebook, "EAN")
        self.main_notebook.AddPage(self.esk_main_notebook, "ESK")

        self.anim_main_panel = AnimMainPanel(self.ean_main_notebook, self)
        self.bone_main_panel = BoneMainPanel(self.ean_main_notebook, self,
                                             "EAN")
        self.ean_main_notebook.AddPage(self.anim_main_panel, "Animation List")
        self.ean_main_notebook.AddPage(self.bone_main_panel, "Bone List")

        self.esk_main_panel = BoneMainPanel(self.esk_main_notebook, self,
                                            "ESK")
        self.esk_main_notebook.AddPage(self.esk_main_panel, "Bone List")

        # Other view
        self.side_notebook = wx.Notebook(self)

        self.ean_side_notebook = wx.Notebook(self.side_notebook)
        self.ean_side_notebook.SetBackgroundColour(wx.Colour('grey'))
        self.esk_side_notebook = wx.Notebook(self.side_notebook)
        self.side_notebook.AddPage(self.ean_side_notebook, "EAN")
        self.side_notebook.AddPage(self.esk_side_notebook, "ESK")

        self.anim_side_panel = AnimSidePanel(self.ean_side_notebook, self)
        self.bone_side_panel = BoneSidePanel(self.ean_side_notebook, self,
                                             "EAN")
        self.ean_side_notebook.AddPage(self.anim_side_panel, "Animation List")
        self.ean_side_notebook.AddPage(self.bone_side_panel, "Bone List")

        self.esk_side_panel = BoneSidePanel(self.esk_side_notebook, self,
                                            "ESK")
        self.esk_side_notebook.AddPage(self.esk_side_panel, "Bone List")

        # Sizer
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer.Add(self.main_notebook, 1, wx.ALL | wx.EXPAND)
        self.sizer.Add(self.side_notebook, 1, wx.ALL | wx.EXPAND)
        self.SetSizer(self.sizer)
        self.SetAutoLayout(1)

        # Lists
        self.main = {
            'dirname': '',
            'ean': None,
            'esk': None,
            'notebook': self.main_notebook,
            'anim_panel': self.anim_main_panel,
            'ean_bone_panel': self.bone_main_panel,
            'esk_bone_panel': self.esk_main_panel,
            'anim_list': self.anim_main_panel.anim_list,
            'ean_bone_list': self.bone_main_panel.bone_list,
            'esk_bone_list': self.esk_main_panel.bone_list
        }

        self.side = {
            'dirname': '',
            'ean': None,
            'esk': None,
            'notebook': self.side_notebook,
            'anim_panel': self.anim_side_panel,
            'ean_bone_panel': self.bone_side_panel,
            'esk_bone_panel': self.esk_side_panel,
            'anim_list': self.anim_side_panel.anim_list,
            'ean_bone_list': self.bone_side_panel.bone_list,
            'esk_bone_list': self.esk_side_panel.bone_list
        }

        self.sizer.Layout()
        self.Show()

        if filename:
            self.load_main_file(dirname, filename)
Exemplo n.º 9
0
            dict(key=str(uuid.uuid1()), datum="22-08-1965"),
            dict(key=str(uuid.uuid1()), datum="28-04-1971")
        ]


class MetingController(Controller):
    @property
    def meting(self):
        return self.binder.buffers.data

    def view_changed(self, src, msg):
        print("meting gewijzigd")


app = wx.App(redirect=False)
locale = wx.Locale(wx.LANGUAGE_DUTCH)  # belangrijk voor o.a. DatePickerCtrl
frame = wx.Frame(None, title="Template Test", size=(900, 600))
sizer = wx.BoxSizer()
frame.SetSizer(sizer)

######################################################################
r = Registry(".")
view = BoxPanel(frame, name="patient")
b = MockPatientBinder(r.get_template("patient"), model_cls=PatientModel)
mb = MockMetingBinder(r.get_template("meting"))
mb.buffers = b.buffers  # zorg dat patient.behandelingen.metingen beschikbaar komt.
controller = PatientController(b, view=view)
m_controller = MetingController(mb)
controller.register_controller("patient/behandelingen/metingen", m_controller)
key = Select("patient/key")
naam = Select("patient/naam")
Exemplo n.º 10
0
# EventGhost is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with EventGhost. If not, see <http://www.gnu.org/licenses/>.

import wx
from wx import SystemSettings_GetColour as GetColour
from wx.lib import masked

# Local imports
import eg

l = wx.Locale()
l.Init2(language=wx.LANGUAGE_DEFAULT, flags=wx.LOCALE_LOAD_DEFAULT)
THOUSANDS_SEP = l.GetInfo(wx.LOCALE_THOUSANDS_SEP)
DECIMAL_POINT = l.GetInfo(wx.LOCALE_DECIMAL_POINT)


class SpinNumCtrl(wx.Window):
    """
    A wx.Control that shows a fixed width floating point value and spin
    buttons to let the user easily input a floating point value.
    """
    _defaultArgs = {
        "integerWidth": 3,
        "fractionWidth": 2,
        "allowNegative": False,
        "min": 0,
Exemplo n.º 11
0
 def OnInit(self):
     self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)
     self.frame = MAIN(None, wx.ID_ANY, "")
     self.SetTopWindow(self.frame)
     self.frame.Show()
     return True
Exemplo n.º 12
0
    def __init__(self, parent, title, dirname, filename):
        sys.excepthook = self.exception_hook
        self.dirname = ''
        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)

        # A "-1" in the size parameter instructs wxWidgets to use the default size.
        # In this case, we select 200px width and the default height.
        wx.Frame.__init__(self, parent, title=title, size=(1300, 950))
        self.statusbar = self.CreateStatusBar(
        )  # A Statusbar in the bottom of the window

        # Panels
        self.main_panel = MainPanel(self)
        self.entry_panel = EntryPanel(self)

        # Setting up the menu.
        file_menu = wx.Menu()
        file_menu.Append(wx.ID_OPEN)
        file_menu.Append(wx.ID_SAVE)
        file_menu.Append(wx.ID_CONVERT, "Convert for Skill Creator")
        file_menu.Append(wx.ID_ABOUT)
        file_menu.Append(wx.ID_EXIT)

        edit_menu = wx.Menu()
        edit_menu.Append(wx.ID_FIND)
        edit_menu.Append(wx.ID_REPLACE)

        # Creating the menubar.
        menu_bar = wx.MenuBar()
        menu_bar.Append(file_menu,
                        "&File")  # Adding the "filemenu" to the MenuBar
        menu_bar.Append(edit_menu, "&Edit")
        self.SetMenuBar(menu_bar)  # Adding the MenuBar to the Frame content.

        # Publisher
        pub.subscribe(self.open_bdm, 'open_bdm')
        pub.subscribe(self.load_bdm, 'load_bdm')
        pub.subscribe(self.save_bdm, 'save_bdm')
        pub.subscribe(self.set_status_bar, 'set_status_bar')

        # Events.
        self.Bind(wx.EVT_MENU, self.open_bdm, id=wx.ID_OPEN)
        self.Bind(wx.EVT_MENU, self.save_bdm, id=wx.ID_SAVE)
        self.Bind(wx.EVT_MENU, self.on_find, id=wx.ID_FIND)
        self.Bind(wx.EVT_MENU, self.on_replace, id=wx.ID_REPLACE)
        self.Bind(wx.EVT_MENU, self.on_convert, id=wx.ID_CONVERT)
        self.Bind(wx.EVT_MENU, self.on_about, id=wx.ID_ABOUT)
        self.Bind(wx.EVT_MENU, self.on_exit, id=wx.ID_EXIT)
        self.Bind(wx.EVT_MENU, self.main_panel.on_add, id=wx.ID_ADD)
        self.Bind(wx.EVT_MENU, self.main_panel.on_new, id=wx.ID_NEW)
        self.Bind(wx.EVT_MENU, self.main_panel.on_delete, id=wx.ID_DELETE)
        self.Bind(wx.EVT_MENU, self.main_panel.on_copy, id=wx.ID_COPY)
        self.Bind(wx.EVT_MENU, self.main_panel.on_paste, id=wx.ID_PASTE)
        accelerator_table = wx.AcceleratorTable([
            (wx.ACCEL_CTRL, ord('n'), wx.ID_NEW),
            (wx.ACCEL_CTRL, ord('o'), wx.ID_OPEN),
            (wx.ACCEL_CTRL, ord('s'), wx.ID_SAVE),
            (wx.ACCEL_CTRL, ord('f'), wx.ID_FIND),
            (wx.ACCEL_CTRL, ord('h'), wx.ID_REPLACE),
        ])
        self.SetAcceleratorTable(accelerator_table)
        self.SetDropTarget(FileDropTarget(self, "load_bdm"))

        # Name
        self.name = wx.StaticText(self, -1, '(No file loaded)')
        font = wx.Font(10, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL,
                       wx.FONTWEIGHT_BOLD)
        self.name.SetFont(font)

        # Buttons
        open_button = wx.Button(self, wx.ID_OPEN, "Load")
        open_button.Bind(wx.EVT_BUTTON, self.open_bdm)

        save_button = wx.Button(self, wx.ID_SAVE, "Save")
        save_button.Bind(wx.EVT_BUTTON, self.save_bdm)

        hyperlink = HyperLinkCtrl(
            self,
            -1,
            "What do all these things mean?",
            URL="https://docs.google.com/document/d/"
            "18gaAbNCeJyTgizz5IvvXzjWcH9K5Q1wvUHTeWnp8M-E/edit#heading=h.tx82dphejin1"
        )

        # Sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        button_sizer = wx.BoxSizer()
        button_sizer.Add(open_button)
        button_sizer.AddSpacer(10)
        button_sizer.Add(save_button)
        button_sizer.Add(hyperlink, 0, wx.ALL, 10)

        panel_sizer = wx.BoxSizer()
        panel_sizer.Add(self.main_panel, 1, wx.ALL | wx.EXPAND)
        panel_sizer.Add(self.entry_panel, 3, wx.ALL | wx.EXPAND)

        sizer.Add(self.name, 0, wx.CENTER)
        sizer.Add(button_sizer, 0, wx.ALL, 10)
        sizer.Add(panel_sizer, 1, wx.ALL | wx.EXPAND)

        self.SetBackgroundColour('white')
        self.SetSizer(sizer)
        self.SetAutoLayout(1)

        # Lists
        self.entry_list = self.main_panel.entry_list

        # Dialogs
        self.find = FindDialog(self, self.entry_list, self.entry_panel, -1)
        self.replace = ReplaceDialog(self, self.entry_list, self.entry_panel,
                                     -1)

        sizer.Layout()
        self.Show()

        if filename:
            self.load_bdm(dirname, filename)
Exemplo n.º 13
0
def _select_game_popup(game_infos):
    import wx as _wx
    from .balt import Resources
    from .gui import Label, TextAlignment, WindowFrame, VLayout, \
        ImageDropDown, LayoutOptions, SearchBar, VBoxedLayout, TextField, \
        HLayout, QuitButton, ImageButton, HorizontalLine, Stretch, DropDown, \
        CENTER
    ##: Decouple game icon paths and move to popups.py once balt is refactored
    # enough
    class SelectGamePopup(WindowFrame):
        _def_size = (500, 400)

        def __init__(self, game_infos, callback):
            super(SelectGamePopup, self).__init__(
                None, title=_(u'Select Game'), icon_bundle=Resources.bashRed)
            self._callback = callback
            self._sorted_games = sorted(g.displayName for g in game_infos)
            self._game_to_paths = {g.displayName: ps for g, ps
                                  in game_infos.iteritems()}
            self._game_to_info = {g.displayName: g for g in game_infos}
            self._game_to_bitmap = {
                g.displayName: _wx.Bitmap(bass.dirs[u'images'].join(
                    g.game_icon % 32).s) for g in game_infos}
            # Construction of the actual GUI begins here
            game_search = SearchBar(self)
            game_search.on_text_changed.subscribe(self._perform_search)
            self._game_dropdown = ImageDropDown(self, value=u'', choices=[u''])
            self._game_dropdown.on_combo_select.subscribe(self._select_game)
            self._lang_dropdown = DropDown(self, value=u'', choices=[u''])
            self._lang_dropdown.on_combo_select.subscribe(self._select_lang)
            self._game_path = TextField(self, editable=False)
            quit_button = QuitButton(self)
            quit_button.on_clicked.subscribe(self._handle_quit)
            launch_img = bass.dirs[u'images'].join(u'bash_32_2.png').s
            self._launch_button = ImageButton(self, _wx.Bitmap(launch_img),
                                              btn_label=_(u'Launch'))
            self._launch_button.on_clicked.subscribe(self._handle_launch)
            # Start out with an empty search and the alphabetically first game
            # selected
            self._perform_search(search_str=u'')
            VLayout(item_expand=True, border=6, spacing=12, items=[
                Label(self, _(u'Please choose a game to manage.'),
                      alignment=TextAlignment.CENTER),
                game_search, self._game_dropdown,
                (VBoxedLayout(self, title=_(u'Game Details'), item_expand=True,
                              spacing=12, items=[
                    HLayout(spacing=6, items=[
                        (Label(self, _(u'Variant:')),
                         LayoutOptions(v_align=CENTER)),
                        (self._lang_dropdown,
                         LayoutOptions(expand=True, weight=1)),
                    ]),
                    HLayout(spacing=6, items=[
                        (Label(self, _(u'Install Path:')),
                         LayoutOptions(v_align=CENTER)),
                        (self._game_path,
                         LayoutOptions(expand=True, weight=1)),
                    ]),
                ]), LayoutOptions(weight=3)),
                HorizontalLine(self),
                (HLayout(item_expand=True, item_weight=1, items=[
                    quit_button, Stretch(), self._launch_button,
                ]), LayoutOptions(weight=1)),
            ]).apply_to(self)

        @property
        def _chosen_path(self):
            avail_paths = self._game_to_paths[self._game_dropdown.get_value()]
            if len(avail_paths) == 1:
                return avail_paths[0]
            else:
                chosen_lang = self._lang_dropdown.get_value()
                for p in avail_paths:
                    if chosen_lang in p.s:
                        return p
                return None # Should never happen

        def _perform_search(self, search_str):
            prev_choice = self._game_dropdown.get_value()
            search_lower = search_str.lower().strip()
            filtered_games = [g for g in self._sorted_games
                              if search_lower in g.lower()]
            with self._game_dropdown.pause_drawing():
                self._game_dropdown.set_choices(filtered_games)
                self._game_dropdown.set_bitmaps([self._game_to_bitmap[g]
                                                 for g in filtered_games])
                # Check if the previous choice can be restored now, otherwise
                # select the first game
                try:
                    new_choice = filtered_games.index(prev_choice)
                except ValueError:
                    new_choice = 0
                self._game_dropdown.set_selection(new_choice)
            # Enable the Launch button only if a game is selected
            new_selection = self._game_dropdown.get_value()
            self._launch_button.enabled = bool(new_selection)
            # Finally, update the game details to match the newly active game
            self._select_game(new_selection)

        def _select_game(self, selected_game):
            if not selected_game:
                # No game selected, clear the details
                self._lang_dropdown.set_choices([_(u'N/A')])
                self._lang_dropdown.set_selection(0)
                self._lang_dropdown.enabled = False
                self._game_path.text_content = u''
            else:
                # Enable the Language dropdown only if we >1 path for the newly
                # active game
                available_paths = self._game_to_paths[selected_game]
                if len(available_paths) > 1:
                    self._lang_dropdown.set_choices([p.stail for p
                                                     in available_paths])
                    self._lang_dropdown.set_selection(0)
                    self._lang_dropdown.enabled = True
                else:
                    self._lang_dropdown.set_choices([_(u'N/A')])
                    self._lang_dropdown.set_selection(0)
                    self._lang_dropdown.enabled = False
                # Set the path based on the default language
                self._select_lang()

        def _select_lang(self, _selected_lang=None):
            self._game_path.text_content = self._chosen_path.s

        def _handle_quit(self):
            self._callback(None)
            self.close_win(force_close=True)

        def _handle_launch(self):
            self._callback((self._game_dropdown.get_value(),
                            self._chosen_path))
            self.close_win(force_close=True)
    _app = _wx.App(False)
    _app.locale = _wx.Locale(_wx.LANGUAGE_DEFAULT)
    retCode = _AppReturnCode()
    frame = SelectGamePopup(game_infos, retCode.set)
    frame.show_frame()
    frame._native_widget.Center() # TODO(inf) de-wx!
    _app.MainLoop()
    del _app
    return retCode.get()
 def OnInit(self):
     self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)
     return True
Exemplo n.º 15
0
def Main(reinicio = False):
    '''Función principal de lanzamiento de aplicación wxPython.'''
    # Comprobamos versión de Python.
    version = sys.version_info
    if version[0] != 2:
        try:
            print("Se necesita Python 2.6 o 2.7 para lanzar vipera")
        except: pass
        return
    if version[1] < 6:
        try:
            print("Se necesita Python >= 2.6 para lanzar vipera")
        except: pass
        return
    # Por defecto el idioma en español.
    idioma = SPANISH
    # Instanciación de la aplicación wxPython.
    app = wx.PySimpleApp()
    # wxPython también en español.
    wx.Locale(wx.LANGUAGE_SPANISH)
    # Si no se reinicia hay que comprobar parámetros de entrada.
    if not reinicio:
        # Opciones de lanzamiento de la aplicación.
        if len(sys.argv) > 1:
            # Eliminamos fichero de configuración de la aplicación.
            if '-r' in sys.argv[1:]:
                try:
                    os.remove(proy_por_defecto['nfich_conf'])
                except: 
                    print u"El fichero de configuración no existe o no se puede eliminar. Continuando la carga..."
            # Iniciamos la aplicación en inglés.
            if '-en' in sys.argv[1:]:
                idioma = ENGLISH
            # Ayuda de la aplicación.
            if sys.argv[1] in ['--help', '-h', '-H', '?', '/?', '-help', '--h', '--H']:
                msj = '%s %s %s%s%s' % (proy_por_defecto['NOMBRE_APLIC'], 
                                      proy_por_defecto['VERSION'],
                                      t(proy_por_defecto['FECHA_CREACION'],idioma),  
                                      enter * 2, info)
                print msj
                sys.exit(0)
            # Mostramos licencia.
            if sys.argv[1] in ['-l', '--l', '--license', '-license']:
                print licencia
                sys.exit(0)
    # Configuración de la aplicación.
    conf_vipera_p = conf_vipera()
    try:
        conf_vipera_p.abrir_fichero()
    except:
        msj = t(u'No se puede abrir el fichero de configuración',1)
        wx.MessageBox(msj, t(u"Atención",1), wx.OK)
        del app
        return False
    datos_conf = conf_vipera_p.recuperar_datos()
    # Idioma...
    if idioma == SPANISH and datos_conf['idioma'] == 'English':
        idioma = ENGLISH
        wx.Locale(wx.LANGUAGE_ENGLISH)
    if idioma == ENGLISH and datos_conf['idioma'] == u'Español':
        idioma = ENGLISH
        wx.Locale(wx.LANGUAGE_ENGLISH)
    # Mensaje de inicio...
    mensaje = t(u"Inicializando vipera...",idioma)
    busy = PBI.PyBusyInfo(mensaje, parent=None, title=t("Un momento...",idioma))
    wx.Yield()
    # Inicializamos el OGL.
    ogl.OGLInitialize()
    # Instanciamos frontend de la aplicación.
    f1 = fp(datos_conf, idioma)
    # Mostramos el frame.
    f1.Show()
    # Eliminamos mensaje de inicio.
    del busy
    # Mostramos consejos de inicio...
    if datos_conf['activar_tips']:
        fichero = os.path.realpath(proy_por_defecto['fich_tips'])
        # Número de líneas.
        try:
            f = open(fichero,'r')
            nlineas = len(f.readlines())
            f.close()
        except: nlineas = 0
        # Número al azar entre el total de líneas.
        numero = int(random.uniform(1,nlineas))
        # Creamos mensaje de consejos.
        tp = wx.CreateFileTipProvider(os.path.realpath(fichero), numero)
        # Y lo mostramos...
        showTip = wx.ShowTip(f1, tp, True)
    else: showTip = False
    # Guardamos el cambio de estado.
    f1.conf_vipera.m_checkBox_tips.Set3StateValue(showTip)
    # Si el idioma es diferente al español habrá que cambiar en todos los widgets.
    if idioma == ENGLISH: f1.conf_vipera.m_choice_idioma.SetStringSelection('English')
    if idioma == SPANISH: f1.conf_vipera.m_choice_idioma.SetStringSelection('Español')
    # Creamos fichero de log del día.
    fichero_log = proy_por_defecto['fichero_log']
    # Redireccionamos salida y errores de la aplicación al fichero log.
    app.RedirectStdio(fichero_log)
    # ¡Y esperamos a los eventos!.
    app.MainLoop()
    # Comprobamos si hay que reiniciar la aplicación.
    if os.path.exists(proy_por_defecto['file_restart_app']):
        try:
            # Eliminamos fichero.
            os.remove(proy_por_defecto['file_restart_app'])
            # Llamamos a la función con flag de reinicio activado.
            Main(True)
        except:
            msj = t(u'No se pudo reiniciar. Elimine manualmente el fichero ', idioma) + \
                proy_por_defecto['file_restart_app']
            wx.MessageBox(msj, t(u'Atención', idioma))
Exemplo n.º 16
0
    def OnInit(self):
        Preferences.initScreenVars()

        # i18n support
        self.locale = wx.Locale(Preferences.i18nLanguage)
        wx.Locale.AddCatalogLookupPathPrefix(os.path.join(Preferences.pyPath, 'locale'))
        if hasattr(sys, 'frozen'):
            self.locale.AddCatalog('wxstd')   
        self.locale.AddCatalog('boa') 

        wx.ToolTip.Enable(True)
        if Preferences.debugMode == 'release':
            self.SetAssertMode(wx.PYAPP_ASSERT_SUPPRESS)
        elif Preferences.debugMode == 'development':
            self.SetAssertMode(wx.PYAPP_ASSERT_EXCEPTION)


        conf = Utils.createAndReadConfig('Explorer')
        if not conf.has_section('splash'):
            conf.add_section('splash')
            modTot = 1
        else:
            modTot = conf.getint('splash', 'modulecount')
        fileTot = len(eval(conf.get('editor', 'openfiles'), {}))

        abt = About.createSplash(None, modTot, fileTot)
        try:
            abt.Show()
            abt.Update()
            # Let the splash screen repaint
            wx.Yield()

            # Imported here to initialise core features and plug-ins
            import PaletteMapping

            print 'creating Palette'
            import Palette
            self.main = Palette.BoaFrame(None, -1, self)

            print 'creating Inspector'
            import Inspector
            inspector = Inspector.InspectorFrame(self.main)

            print 'creating Editor'
            import Editor
            editor = Editor.EditorFrame(self.main, -1, inspector, wx.Menu(),
                self.main.componentSB, self, self.main)
            self.SetTopWindow(editor)

            inspector.editor = editor

            conf.set('splash', 'modulecount', str(len(sys.modules)))
            try:
                Utils.writeConfig(conf)
            except IOError, err:
                startupErrors.append(_('Error writing config file: %s\nPlease '
              'ensure that the Explorer.*.cfg file is not read only.')% str(err))

            if not emptyEditor:
                editor.restoreEditorState()

            self.main.initPalette(inspector, editor)

    ##            editor.setupToolBar()

            import Help
            if not Preferences.delayInitHelp:
                print 'initialising help'
                Help.initHelp()

            global constricted
            constricted = constricted or Preferences.suBoaConstricted

            print 'showing main frames <<100/100>>'
            if constricted:
                editor.CenterOnScreen()
                inspector.CenterOnScreen()
                inspector.initSashes()
            else:
                self.main.Show()
                inspector.Show()
                # For some reason the splitters have to be visible on GTK before they
                # can be sized.
                inspector.initSashes()

            editor.Show()
            editor.doAfterShownActions()

            # Call startup files after complete editor initialisation
            global startupfile
            if Preferences.suExecPythonStartup and startupEnv:
                startupfile = startupEnv

            if editor.shell:
                editor.shell.execStartupScript(startupfile)
Exemplo n.º 17
0
        else:
            error = "No start frequency specified"
    elif args.file is not None:
        args.dirname, args.filename = os.path.split(args.file)

    if error is not None:
        print "Error: {}".format(error)
        parser.exit(1)

    return isGui, (args)


if __name__ == '__main__':
    print APP_NAME + "\n"

    isGui, args = __arguments()
    if isGui:
        app = RtlSdrScanner()
        app.SetClassName(APP_NAME)
        wx.Locale().Init2()
        frame = FrameMain(APP_NAME)
        if args.file is not None:
            frame.open(os.path.abspath(args.dirname), args.filename)
        app.MainLoop()
    else:
        try:
            Cli(args)
        except KeyboardInterrupt:
            print '\nAborted'
            exit(1)
Exemplo n.º 18
0
def main():
    """NVDA's core main loop.
This initializes all modules such as audio, IAccessible, keyboard, mouse, and GUI. Then it initialises the wx application object and sets up the core pump, which checks the queues and executes functions when requested. Finally, it starts the wx main loop.
"""
    log.debug("Core starting")

    try:
        # Windows >= Vista
        ctypes.windll.user32.SetProcessDPIAware()
    except AttributeError:
        pass

    import config
    if not globalVars.appArgs.configPath:
        globalVars.appArgs.configPath = config.getUserDefaultConfigPath(
            useInstalledPathIfExists=globalVars.appArgs.launcher)
    #Initialize the config path (make sure it exists)
    config.initConfigPath()
    log.info("Config dir: %s" % os.path.abspath(globalVars.appArgs.configPath))
    log.debug("loading config")
    import config
    config.initialize()
    if not globalVars.appArgs.minimal and config.conf["general"][
            "playStartAndExitSounds"]:
        try:
            nvwave.playWaveFile("waves\\start.wav")
        except:
            pass
    logHandler.setLogLevelFromConfig()
    logHandler.setPlayErrorSoundFromConfig()
    try:
        lang = config.conf["general"]["language"]
        import languageHandler
        log.debug("setting language to %s" % lang)
        languageHandler.setLanguage(lang)
    except:
        log.warning("Could not set language to %s" % lang)
    import versionInfo
    log.info("NVDA version %s" % versionInfo.version)
    log.info("Using Windows version %s" % winVersion.winVersionText)
    log.info("Using Python version %s" % sys.version)
    log.info("Using comtypes version %s" % comtypes.__version__)
    # Set a reasonable timeout for any socket connections NVDA makes.
    import socket
    socket.setdefaulttimeout(10)
    log.debug("Initializing add-ons system")
    addonHandler.initialize()
    if globalVars.appArgs.disableAddons:
        log.info("Add-ons are disabled. Restart NVDA to enable them.")
    import appModuleHandler
    log.debug("Initializing appModule Handler")
    appModuleHandler.initialize()
    import NVDAHelper
    log.debug("Initializing NVDAHelper")
    NVDAHelper.initialize()
    import speechDictHandler
    log.debug("Speech Dictionary processing")
    speechDictHandler.initialize()
    import speech
    log.debug("Initializing speech")
    speech.initialize()
    if not globalVars.appArgs.minimal and (time.time() -
                                           globalVars.startTime) > 5:
        log.debugWarning("Slow starting core (%.2f sec)" %
                         (time.time() - globalVars.startTime))
        # Translators: This is spoken when NVDA is starting.
        speech.speakMessage(_("Loading NVDA. Please wait..."))
    import wx
    log.info("Using wx version %s" % wx.version())

    class App(wx.App):
        def OnAssert(self, file, line, cond, msg):
            message = "{file}, line {line}:\nassert {cond}: {msg}".format(
                file=file, line=line, cond=cond, msg=msg)
            log.debugWarning(message, codepath="WX Widgets", stack_info=True)

    app = App(redirect=False)
    # We do support QueryEndSession events, but we don't want to do anything for them.
    app.Bind(wx.EVT_QUERY_END_SESSION, lambda evt: None)

    def onEndSession(evt):
        # NVDA will be terminated as soon as this function returns, so save configuration if appropriate.
        config.saveOnExit()
        speech.cancelSpeech()
        if not globalVars.appArgs.minimal and config.conf["general"][
                "playStartAndExitSounds"]:
            try:
                nvwave.playWaveFile("waves\\exit.wav", async=False)
            except:
                pass
        log.info("Windows session ending")

    app.Bind(wx.EVT_END_SESSION, onEndSession)
    import braille
    log.debug("Initializing braille")
    braille.initialize()
    log.debug("Initializing braille input")
    import brailleInput
    brailleInput.initialize()
    import displayModel
    log.debug("Initializing displayModel")
    displayModel.initialize()
    log.debug("Initializing GUI")
    import gui
    gui.initialize()
    import audioDucking
    if audioDucking.isAudioDuckingSupported():
        # the GUI mainloop must be running for this to work so delay it
        wx.CallAfter(audioDucking.initialize)

    # #3763: In wxPython 3, the class name of frame windows changed from wxWindowClassNR to wxWindowNR.
    # NVDA uses the main frame to check for and quit another instance of NVDA.
    # To remain compatible with older versions of NVDA, create our own wxWindowClassNR.
    # We don't need to do anything else because wx handles WM_QUIT for all windows.
    import windowUtils

    class MessageWindow(windowUtils.CustomWindow):
        className = u"wxWindowClassNR"

    messageWindow = MessageWindow(unicode(versionInfo.name))

    # initialize wxpython localization support
    locale = wx.Locale()
    lang = languageHandler.getLanguage()
    wxLang = locale.FindLanguageInfo(lang)
    if not wxLang and '_' in lang:
        wxLang = locale.FindLanguageInfo(lang.split('_')[0])
    if hasattr(sys, 'frozen'):
        locale.AddCatalogLookupPathPrefix(os.path.join(os.getcwdu(), "locale"))
    if wxLang:
        try:
            locale.Init(wxLang.Language)
        except:
            log.error("Failed to initialize wx locale", exc_info=True)
    else:
        log.debugWarning("wx does not support language %s" % lang)

    import api
    import winUser
    import NVDAObjects.window
    desktopObject = NVDAObjects.window.Window(
        windowHandle=winUser.getDesktopWindow())
    api.setDesktopObject(desktopObject)
    api.setFocusObject(desktopObject)
    api.setNavigatorObject(desktopObject)
    api.setMouseObject(desktopObject)
    import JABHandler
    log.debug("initializing Java Access Bridge support")
    try:
        JABHandler.initialize()
    except NotImplementedError:
        log.warning("Java Access Bridge not available")
    except:
        log.error("Error initializing Java Access Bridge support",
                  exc_info=True)
    import winConsoleHandler
    log.debug("Initializing winConsole support")
    winConsoleHandler.initialize()
    import UIAHandler
    log.debug("Initializing UIA support")
    try:
        UIAHandler.initialize()
    except NotImplementedError:
        log.warning("UIA not available")
    except:
        log.error("Error initializing UIA support", exc_info=True)
    import IAccessibleHandler
    log.debug("Initializing IAccessible support")
    IAccessibleHandler.initialize()
    log.debug("Initializing input core")
    import inputCore
    inputCore.initialize()
    import keyboardHandler
    log.debug("Initializing keyboard handler")
    keyboardHandler.initialize()
    import mouseHandler
    log.debug("initializing mouse handler")
    mouseHandler.initialize()
    import touchHandler
    log.debug("Initializing touchHandler")
    try:
        touchHandler.initialize()
    except NotImplementedError:
        pass
    import globalPluginHandler
    log.debug("Initializing global plugin handler")
    globalPluginHandler.initialize()
    if globalVars.appArgs.install or globalVars.appArgs.installSilent:
        import wx
        import gui.installerGui
        wx.CallAfter(gui.installerGui.doSilentInstall,
                     startAfterInstall=not globalVars.appArgs.installSilent)
    elif not globalVars.appArgs.minimal:
        try:
            # Translators: This is shown on a braille display (if one is connected) when NVDA starts.
            braille.handler.message(_("NVDA started"))
        except:
            log.error("", exc_info=True)
        if globalVars.appArgs.launcher:
            gui.LauncherDialog.run()
            # LauncherDialog will call doStartupDialogs() afterwards if required.
        else:
            wx.CallAfter(doStartupDialogs)
    import queueHandler
    # Queue the handling of initial focus,
    # as API handlers might need to be pumped to get the first focus event.
    queueHandler.queueFunction(queueHandler.eventQueue, _setInitialFocus)
    import watchdog
    import baseObject

    # Doing this here is a bit ugly, but we don't want these modules imported
    # at module level, including wx.
    log.debug("Initializing core pump")

    class CorePump(wx.Timer):
        "Checks the queues and executes functions."

        def Notify(self):
            global _isPumpPending
            _isPumpPending = False
            watchdog.alive()
            try:
                if touchHandler.handler:
                    touchHandler.handler.pump()
                JABHandler.pumpAll()
                IAccessibleHandler.pumpAll()
                queueHandler.pumpAll()
                mouseHandler.pumpAll()
                braille.pumpAll()
            except:
                log.exception("errors in this core pump cycle")
            baseObject.AutoPropertyObject.invalidateCaches()
            watchdog.asleep()
            if _isPumpPending and not _pump.IsRunning():
                # #3803: A pump was requested, but the timer was ignored by a modal loop
                # because timers aren't re-entrant.
                # Therefore, schedule another pump.
                _pump.Start(PUMP_MAX_DELAY, True)

    global _pump
    _pump = CorePump()
    requestPump()

    log.debug("Initializing watchdog")
    watchdog.initialize()
    try:
        import updateCheck
    except RuntimeError:
        updateCheck = None
        log.debug("Update checking not supported")
    else:
        log.debug("initializing updateCheck")
        updateCheck.initialize()
    log.info("NVDA initialized")

    log.debug("entering wx application main loop")
    app.MainLoop()

    log.info("Exiting")
    if updateCheck:
        _terminate(updateCheck)

    _terminate(watchdog)
    _terminate(globalPluginHandler, name="global plugin handler")
    _terminate(gui)
    config.saveOnExit()

    try:
        if globalVars.focusObject and hasattr(globalVars.focusObject,
                                              "event_loseFocus"):
            log.debug("calling lose focus on object with focus")
            globalVars.focusObject.event_loseFocus()
    except:
        log.exception("Lose focus error")
    try:
        speech.cancelSpeech()
    except:
        pass

    import treeInterceptorHandler
    _terminate(treeInterceptorHandler)
    _terminate(IAccessibleHandler, name="IAccessible support")
    _terminate(UIAHandler, name="UIA support")
    _terminate(winConsoleHandler, name="winConsole support")
    _terminate(JABHandler, name="Java Access Bridge support")
    _terminate(appModuleHandler, name="app module handler")
    _terminate(NVDAHelper)
    _terminate(touchHandler)
    _terminate(keyboardHandler, name="keyboard handler")
    _terminate(mouseHandler)
    _terminate(inputCore)
    _terminate(brailleInput)
    _terminate(braille)
    _terminate(speech)
    _terminate(addonHandler)

    if not globalVars.appArgs.minimal and config.conf["general"][
            "playStartAndExitSounds"]:
        try:
            nvwave.playWaveFile("waves\\exit.wav", async=False)
        except:
            pass
    # #5189: Destroy the message window as late as possible
    # so new instances of NVDA can find this one even if it freezes during exit.
    messageWindow.destroy()
    log.debug("core done")
Exemplo n.º 19
0
    def __init__(self,
                 parent=None,
                 id=wx.ID_ANY,
                 style=wx.DEFAULT_FRAME_STYLE):

        #
        # GRASS variables
        #
        self.gisbase = os.getenv("GISBASE")
        self.grassrc = sgui.read_gisrc()
        self.gisdbase = self.GetRCValue("GISDBASE")

        #
        # list of locations/mapsets
        #
        self.listOfLocations = []
        self.listOfMapsets = []
        self.listOfMapsetsSelectable = []

        wx.Frame.__init__(self, parent=parent, id=id, style=style)

        self.locale = wx.Locale(language=wx.LANGUAGE_DEFAULT)

        # scroll panel was used here but not properly and is probably not need
        # as long as it is not high too much
        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)

        # i18N

        #
        # graphical elements
        #
        # image
        try:
            if os.getenv('ISISROOT'):
                name = os.path.join(globalvar.GUIDIR, "images",
                                    "startup_banner_isis.png")
            else:
                name = os.path.join(globalvar.GUIDIR, "images",
                                    "startup_banner.png")
            self.hbitmap = wx.StaticBitmap(
                self.panel, wx.ID_ANY,
                wx.Bitmap(name=name, type=wx.BITMAP_TYPE_PNG))
        except:
            self.hbitmap = wx.StaticBitmap(
                self.panel, wx.ID_ANY, BitmapFromImage(wx.EmptyImage(530,
                                                                     150)))

        # labels
        # crashes when LOCATION doesn't exist
        # get version & revision
        grassVersion, grassRevisionStr = sgui.GetVersion()

        self.gisdbase_box = StaticBox(
            parent=self.panel,
            id=wx.ID_ANY,
            label=" %s " % _("1. Select GRASS GIS database directory"))
        self.location_box = StaticBox(parent=self.panel,
                                      id=wx.ID_ANY,
                                      label=" %s " %
                                      _("2. Select GRASS Location"))
        self.mapset_box = StaticBox(parent=self.panel,
                                    id=wx.ID_ANY,
                                    label=" %s " % _("3. Select GRASS Mapset"))

        self.lmessage = StaticText(parent=self.panel)
        # It is not clear if all wx versions supports color, so try-except.
        # The color itself may not be correct for all platforms/system settings
        # but in http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html
        # there is no 'warning' color.
        try:
            self.lmessage.SetForegroundColour(wx.Colour(255, 0, 0))
        except AttributeError:
            pass

        self.gisdbase_panel = wx.Panel(parent=self.panel)
        self.location_panel = wx.Panel(parent=self.panel)
        self.mapset_panel = wx.Panel(parent=self.panel)

        self.ldbase = StaticText(
            parent=self.gisdbase_panel,
            id=wx.ID_ANY,
            label=_("GRASS GIS database directory contains Locations."))

        self.llocation = StaticWrapText(
            parent=self.location_panel,
            id=wx.ID_ANY,
            label=_("All data in one Location is in the same "
                    " coordinate reference system (projection)."
                    " One Location can be one project."
                    " Location contains Mapsets."),
            style=wx.ALIGN_LEFT)

        self.lmapset = StaticWrapText(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            label=_("Mapset contains GIS data related"
                    " to one project, task within one project,"
                    " subregion or user."),
            style=wx.ALIGN_LEFT)

        try:
            for label in [self.ldbase, self.llocation, self.lmapset]:
                label.SetForegroundColour(
                    wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
        except AttributeError:
            # for explanation of try-except see above
            pass

        # buttons
        self.bstart = Button(parent=self.panel,
                             id=wx.ID_ANY,
                             label=_("Start &GRASS session"))
        self.bstart.SetDefault()
        self.bexit = Button(parent=self.panel, id=wx.ID_EXIT)
        self.bstart.SetMinSize((180, self.bexit.GetSize()[1]))
        self.bhelp = Button(parent=self.panel, id=wx.ID_HELP)
        self.bbrowse = Button(parent=self.gisdbase_panel,
                              id=wx.ID_ANY,
                              label=_("&Browse"))
        self.bmapset = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC New mapset
            label=_("&New"))
        self.bmapset.SetToolTip(_("Create a new Mapset in selected Location"))
        self.bwizard = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC New location
            label=_("N&ew"))
        self.bwizard.SetToolTip(
            _("Create a new location using location wizard."
              " After location is created successfully,"
              " GRASS session is started."))
        self.rename_location_button = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC Rename location
            label=_("Ren&ame"))
        self.rename_location_button.SetToolTip(_("Rename selected location"))
        self.delete_location_button = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC Delete location
            label=_("De&lete"))
        self.delete_location_button.SetToolTip(_("Delete selected location"))
        self.download_location_button = Button(parent=self.location_panel,
                                               id=wx.ID_ANY,
                                               label=_("Do&wnload"))
        self.download_location_button.SetToolTip(_("Download sample location"))

        self.rename_mapset_button = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC Rename mapset
            label=_("&Rename"))
        self.rename_mapset_button.SetToolTip(_("Rename selected mapset"))
        self.delete_mapset_button = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC Delete mapset
            label=_("&Delete"))
        self.delete_mapset_button.SetToolTip(_("Delete selected mapset"))

        # textinputs
        self.tgisdbase = TextCtrl(parent=self.gisdbase_panel,
                                  id=wx.ID_ANY,
                                  value="",
                                  size=(300, -1),
                                  style=wx.TE_PROCESS_ENTER)

        # Locations
        self.lblocations = GListBox(parent=self.location_panel,
                                    id=wx.ID_ANY,
                                    size=(180, 200),
                                    choices=self.listOfLocations)
        self.lblocations.SetColumnWidth(0, 180)

        # TODO: sort; but keep PERMANENT on top of list
        # Mapsets
        self.lbmapsets = GListBox(parent=self.mapset_panel,
                                  id=wx.ID_ANY,
                                  size=(180, 200),
                                  choices=self.listOfMapsets)
        self.lbmapsets.SetColumnWidth(0, 180)

        # layout & properties, first do layout so everything is created
        self._do_layout()
        self._set_properties(grassVersion, grassRevisionStr)

        # events
        self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
        self.bstart.Bind(wx.EVT_BUTTON, self.OnStart)
        self.bexit.Bind(wx.EVT_BUTTON, self.OnExit)
        self.bhelp.Bind(wx.EVT_BUTTON, self.OnHelp)
        self.bmapset.Bind(wx.EVT_BUTTON, self.OnCreateMapset)
        self.bwizard.Bind(wx.EVT_BUTTON, self.OnWizard)

        self.rename_location_button.Bind(wx.EVT_BUTTON, self.RenameLocation)
        self.delete_location_button.Bind(wx.EVT_BUTTON, self.DeleteLocation)
        self.download_location_button.Bind(wx.EVT_BUTTON,
                                           self.DownloadLocation)
        self.rename_mapset_button.Bind(wx.EVT_BUTTON, self.RenameMapset)
        self.delete_mapset_button.Bind(wx.EVT_BUTTON, self.DeleteMapset)

        self.lblocations.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectLocation)
        self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMapset)
        self.lbmapsets.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnStart)
        self.tgisdbase.Bind(wx.EVT_TEXT_ENTER, self.OnSetDatabase)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
Exemplo n.º 20
0
# Import module for cf_internationalization
import gettext
import __builtin__

# Get folder containing translation files
localedir = os.path.join(ScriptDirectory, "locale")
# Get the default language
langid = wx.LANGUAGE_DEFAULT
# Define translation cf_domain (name of translation files)
domain = "objdictgen"

# Define locale for wx
loc = __builtin__.__dict__.get('loc', None)
if loc is None:
    loc = wx.Locale(langid)
    __builtin__.__dict__['loc'] = loc
# Define location for searching translation files
loc.AddCatalogLookupPathPrefix(localedir)
# Define locale cf_domain
loc.AddCatalog(domain)

if __name__ == '__main__':
    __builtin__.__dict__['_'] = wx.GetTranslation

from nodelist import *
from nodemanager import *
from networkeditortemplate import NetworkEditorTemplate
from doc_index.DS301_index import *

try:
Exemplo n.º 21
0
import psychopy.constants

import wx

# need a wx App for wx.Locale:
try:
    wx.Dialog(None, -1)
except wx._core.PyNoAppError:
    if wx.version() < '2.9':
        tmpApp = wx.PySimpleApp()
    else:
        tmpApp = wx.App(False)

# Get a dict of locale aliases from wx.Locale() -- same cross-platform
# (Win 7, Mac 10.9)
locale = wx.Locale()
aliases = {u'English (U.S.)': 'en_US'}
# set defaults because locale.GetLanguageInfo(0) can return None on some
# systems:
wxIdFromCode = {'en_US': wx.LANGUAGE_DEFAULT}  # int: 0 default, 2-229
# used in directory names e.g. ja_JP; never JPN ala Windows
codeFromWxId = {wx.LANGUAGE_DEFAULT: 'en_US'}
for i in range(230):
    info = locale.GetLanguageInfo(i)
    if info:
        # mix of forms: ja or ja_JP
        aliases[info.Description] = info.CanonicalName
        wxIdFromCode[info.CanonicalName] = i
        codeFromWxId[i] = info.CanonicalName

# read all known mappings cross-platform from a file:
Exemplo n.º 22
0
def main(argv):
    """
    Основная запускающая функция.
    @param argv: Список параметров коммандной строки.
    """
    # Инициализоция системы журналирования
    log.init(config)

    # Разбираем аргументы командной строки
    try:
        options, args = getopt.getopt(argv, 'h?vdVEDpPES', [
            'help', 'version', 'debug', 'log', 'viewer', 'editor', 'postprint',
            'postpreview', 'postexport', 'print=', 'preview=', 'export=',
            'select=', 'gen=', 'db=', 'sql=', 'stylelib=', 'var=', 'path=',
            'no_gui'
        ])
    except getopt.error as err:
        log.error(err.msg, bForcePrint=True)
        log.warning('For help use --help option', bForcePrint=True)
        sys.exit(2)

    # Параметры запуска генерации отчета из коммандной строки
    report_filename = None
    db = None
    sql = None
    do_cmd = None
    stylelib = None
    vars = dict()
    path = None
    mode = 'default'
    mode_arg = None

    for option, arg in options:
        if option in ('-h', '--help', '-?'):
            print(__doc__)
            sys.exit(0)
        elif option in ('-v', '--version'):
            print('icReport version: %s' %
                  '.'.join([str(ver) for ver in __version__]))
            sys.exit(0)
        elif option in ('-d', '--debug'):
            config.set_glob_var('DEBUG_MODE', True)
        elif option in ('-l', '--log'):
            config.set_glob_var('LOG_MODE', True)
        elif option in ('-V', '--viewer'):
            mode = 'view'
        elif option in ('-E', '--editor'):
            mode = 'edit'
        elif option in ('-p', '--print'):
            mode = 'print'
            mode_arg = arg
        elif option in ('-P', '--preview'):
            mode = 'preview'
            mode_arg = arg
        elif option in ('-E', '--export'):
            mode = 'export'
            mode_arg = arg
        elif option in ('-S', '--select'):
            mode = 'select'
            mode_arg = arg
        elif option in ('--gen', ):
            report_filename = arg
        elif option in ('--db', ):
            db = arg
        elif option in ('--sql', ):
            sql = arg
        elif option in ('--postprint', ):
            do_cmd = do_report.DO_COMMAND_PRINT
        elif option in ('--postpreview', ):
            do_cmd = do_report.DO_COMMAND_PREVIEW
        elif option in ('--postexport', ):
            do_cmd = do_report.DO_COMMAND_EXPORT
        elif option in ('--stylelib', ):
            stylelib = arg
        elif option in ('--var', ):
            var_name = arg.split('=')[0].strip()
            var_value = arg.split('=')[-1].strip()
            vars[var_name] = var_value
            log.debug(u'Дополнительная переменная <%s>. Значение [%s]' %
                      (unicode(var_name, config.DEFAULT_ENCODING),
                       unicode(var_value, config.DEFAULT_ENCODING)))
        elif option in ('--path', ):
            path = arg
        elif option in ('--no_gui', ):
            config.set_glob_var('NO_GUI_MODE', True)

    # ВНИМАНИЕ! Небходимо добавить путь к папке отчетов,
    # чтобы проходили импорты модулей отчетов
    if path is None:
        path = DEFAULT_REPORTS_PATH
    if os.path.exists(path) and os.path.isdir(path) and path not in sys.path:
        sys.path.append(path)

    # Внимание! Приложение создается для
    # управления диалоговыми окнами отчетов
    app = wx.PySimpleApp()
    # ВНИМАНИЕ! Выставить русскую локаль
    # Это необходимо для корректного отображения календарей,
    # форматов дат, времени, данных и т.п.
    locale = wx.Locale()
    locale.Init(wx.LANGUAGE_RUSSIAN)

    if mode == 'default':
        if report_filename:
            # Запустить генерацию отчета из комадной строки
            do_report.doReport(report_filename=report_filename,
                               report_dir=path,
                               db_url=db,
                               sql=sql,
                               command=do_cmd,
                               stylelib_filename=stylelib,
                               variables=vars)
    elif mode == 'view':
        do_report.ReportViewer(report_dir=path)
    elif mode == 'edit':
        do_report.ReportEditor(report_dir=path)
    elif mode == 'print':
        do_report.ReportPrint(report_filename=mode_arg,
                              report_dir=path,
                              db_url=db,
                              sql=sql,
                              command=do_cmd,
                              stylelib_filename=stylelib,
                              variables=vars)
    elif mode == 'preview':
        do_report.ReportPreview(report_filename=mode_arg,
                                report_dir=path,
                                db_url=db,
                                sql=sql,
                                command=do_cmd,
                                stylelib_filename=stylelib,
                                variables=vars)
    elif mode == 'export':
        do_report.ReportExport(report_filename=mode_arg,
                               report_dir=path,
                               db_url=db,
                               sql=sql,
                               command=do_cmd,
                               stylelib_filename=stylelib,
                               variables=vars)
    elif mode == 'select':
        do_report.ReportSelect(report_filename=mode_arg,
                               report_dir=path,
                               db_url=db,
                               sql=sql,
                               command=do_cmd,
                               stylelib_filename=stylelib,
                               variables=vars)

    app.MainLoop()
Exemplo n.º 23
0
        self.SetSize((10, 10))  # make sure save/load at the same place.
        if os.path.exists(CONFIG):
            with open(CONFIG) as f:
                xy = eval(f.read())
                self.SetPosition(xy)
        else:
            self.Center()

    def SetSizeCenter(self, size):
        x, y = self.GetPosition()
        w1, h1 = self.GetSize()
        w2, h2 = size
        self.SetPosition((x - 1 + (w1 - w2) // 2, y - 1 + (h1 - h2) // 2))
        self.SetSize((w2 + 2, h2 + 2))
        # self.SetSize(size) # while no border

    def OnClose(self, evt):
        self.SetSizeCenter((10, 10))  # make sure save/load at the same place.
        xy = str(self.GetPosition())  # prevent generate 0 byte file.
        with open(CONFIG, 'w') as f:
            f.write(xy)
        self.monitor.close()
        self.icon.Destroy()  # only `RemoveIcon` will still run in mainloop.
        self.Destroy()


app = wx.App()
locale = wx.Locale(wx.LANGUAGE_ENGLISH)
frm = MyFrame()
app.MainLoop()
Exemplo n.º 24
0
    def InitUI(self):
        if self.mode == "DEBUG":
            print "In DischargeMeasurementsPanel"
        self.layoutSizer = wx.GridBagSizer(0, 0)
        self.locale = wx.Locale(self.lang)

        #Start Time Info
        startTimePanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        startTimePanel.SetBackgroundColour(self.BGColour)
        startTimeSizer = wx.BoxSizer(wx.VERTICAL)
        startTimeSizerH = wx.BoxSizer(wx.HORIZONTAL)

        startTimeTxt = wx.StaticText(startTimePanel,
                                     1,
                                     label=self.startTimeLbl,
                                     style=wx.ALIGN_CENTRE_HORIZONTAL,
                                     size=(-1, self.height))
        startTimeTxt.Wrap(self.wrapLength)
        # self.startTimeCtrl = masked.TimeCtrl(startTimePanel, 2, size=(-1, self.ctrlHeight), displaySeconds=False, fmt24hr = True)
        # # self.startTimeCtrl.SetValue(wx.DateTime_Now().FormatTime())
        # self.startTimeCtrl.Bind(wx.EVT_KEY_DOWN, self.OnResetTime)

        self.startTimeCtrl = DropdownTime(False,
                                          parent=startTimePanel,
                                          id=2,
                                          size=(-1, self.ctrlHeight))
        startTimeSizer.Add(startTimeTxt, 1, wx.EXPAND)
        startTimeSizer.Add(self.startTimeCtrl, 1, wx.EXPAND)
        startTimeSizerH.Add(startTimeSizer, 1, wx.EXPAND, 0)

        startTimePanel.SetSizer(startTimeSizerH)

        #End Time Info
        endTimePanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        endTimePanel.SetBackgroundColour(self.BGColour)
        endTimeSizer = wx.BoxSizer(wx.VERTICAL)
        endTimeSizerH = wx.BoxSizer(wx.HORIZONTAL)

        endTimeTxt = wx.StaticText(endTimePanel,
                                   3,
                                   label=self.endTimeLbl,
                                   style=wx.ALIGN_CENTRE_HORIZONTAL,
                                   size=(-1, self.height))
        endTimeTxt.Wrap(self.wrapLength)
        # self.endTimeCtrl = masked.TimeCtrl(endTimePanel, 4, size=(-1, self.ctrlHeight), displaySeconds=False, fmt24hr = True)
        # # self.endTimeCtrl.SetValue(wx.DateTime_Now().FormatTime())
        # self.endTimeCtrl.Bind(wx.EVT_KEY_DOWN, self.OnResetTime)
        self.endTimeCtrl = DropdownTime(False,
                                        parent=endTimePanel,
                                        id=4,
                                        size=(-1, self.ctrlHeight))
        endTimeSizer.Add(endTimeTxt, 1, wx.EXPAND)
        endTimeSizer.Add(self.endTimeCtrl, 1, wx.EXPAND)
        endTimeSizerH.Add(endTimeSizer, 1, wx.EXPAND)

        endTimePanel.SetSizer(endTimeSizerH)

        #Air Temperature Info
        airTempPanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        airTempPanel.SetBackgroundColour(self.BGColour)
        airTempSizer = wx.BoxSizer(wx.VERTICAL)
        airTempSizerH = wx.BoxSizer(wx.HORIZONTAL)

        airTempTxt = wx.StaticText(airTempPanel,
                                   5,
                                   label=self.airTempLbl,
                                   style=wx.ALIGN_CENTRE_HORIZONTAL,
                                   size=(-1, self.height))
        airTempTxt.Wrap(self.wrapLength)
        self.airTempCtrl = MyTextCtrl(airTempPanel,
                                      6,
                                      style=wx.TE_PROCESS_ENTER | wx.TE_CENTRE,
                                      size=(70, self.ctrlHeight))
        self.airTempCtrl.Bind(wx.EVT_TEXT, self.FloatNumberControl)
        self.airTempCtrl.Bind(wx.EVT_KILL_FOCUS, NumberControl.Round1)
        airTempSizer.Add(airTempTxt, 1, wx.EXPAND)
        airTempSizer.Add(self.airTempCtrl, 1, wx.EXPAND)
        airTempSizerH.Add(airTempSizer, 1, wx.EXPAND)

        airTempPanel.SetSizer(airTempSizerH)

        #Water Temperature Info
        waterTempPanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        waterTempPanel.SetBackgroundColour(self.BGColour)
        waterTempSizer = wx.BoxSizer(wx.VERTICAL)
        waterTempSizerH = wx.BoxSizer(wx.HORIZONTAL)

        waterTempTxt = wx.StaticText(waterTempPanel,
                                     7,
                                     label=self.waterTempLbl,
                                     style=wx.ALIGN_CENTRE_HORIZONTAL,
                                     size=(-1, self.height))
        waterTempTxt.Wrap(self.wrapLength)
        self.waterTempCtrl = MyTextCtrl(waterTempPanel,
                                        8,
                                        style=wx.TE_PROCESS_ENTER
                                        | wx.TE_CENTRE,
                                        size=(70, self.ctrlHeight))
        self.waterTempCtrl.Bind(wx.EVT_TEXT, self.FloatNumberControl)
        self.waterTempCtrl.Bind(wx.EVT_KILL_FOCUS, NumberControl.Round1)
        waterTempSizer.Add(waterTempTxt, 1, wx.EXPAND)
        waterTempSizer.Add(self.waterTempCtrl, 1, wx.EXPAND)
        waterTempSizerH.Add(waterTempSizer, 1, wx.EXPAND)

        waterTempPanel.SetSizer(waterTempSizerH)

        #Width Info
        widthPanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        widthPanel.SetBackgroundColour(self.BGColour)
        widthSizer = wx.BoxSizer(wx.VERTICAL)
        widthSizerH = wx.BoxSizer(wx.HORIZONTAL)

        widthTxt = wx.StaticText(widthPanel,
                                 9,
                                 label=self.widthLbl,
                                 style=wx.ALIGN_CENTRE_HORIZONTAL,
                                 size=(-1, self.height))
        widthTxt.Wrap(self.wrapLength)
        self.widthCtrl = MyTextCtrl(widthPanel,
                                    10,
                                    style=wx.TE_PROCESS_ENTER | wx.TE_CENTRE,
                                    size=(70, self.ctrlHeight))
        self.widthCtrl.Bind(wx.EVT_TEXT, self.FloatNumberControl)
        self.widthCtrl.Bind(wx.EVT_KILL_FOCUS, NumberControl.Sig3)
        widthSizer.Add(widthTxt, 1, wx.EXPAND)
        widthSizer.Add(self.widthCtrl, 1, wx.EXPAND)
        widthSizerH.Add(widthSizer, 1, wx.EXPAND)

        widthPanel.SetSizer(widthSizerH)

        #Area Info
        areaPanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        areaPanel.SetBackgroundColour(self.BGColour)
        areaSizer = wx.BoxSizer(wx.VERTICAL)
        areaSizerH = wx.BoxSizer(wx.HORIZONTAL)

        areaTxt = wx.StaticText(areaPanel,
                                11,
                                label=self.areaLbl,
                                style=wx.ALIGN_CENTRE_HORIZONTAL,
                                size=(-1, self.height))
        areaTxt.Wrap(self.wrapLength)
        self.areaCtrl = MyTextCtrl(areaPanel,
                                   12,
                                   style=wx.TE_PROCESS_ENTER | wx.TE_CENTRE,
                                   size=(70, self.ctrlHeight))
        self.areaCtrl.Bind(wx.EVT_TEXT, self.FloatNumberControl)
        self.areaCtrl.Bind(wx.EVT_KILL_FOCUS, NumberControl.Sig3)
        areaSizer.Add(areaTxt, 1, wx.EXPAND)
        areaSizer.Add(self.areaCtrl, 1, wx.EXPAND)
        areaSizerH.Add(areaSizer, 1, wx.EXPAND)

        areaPanel.SetSizer(areaSizerH)

        #Mean Velocity Info
        meanVelPanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        meanVelPanel.SetBackgroundColour(self.BGColour)
        meanVelSizer = wx.BoxSizer(wx.VERTICAL)
        meanVelSizerH = wx.BoxSizer(wx.HORIZONTAL)

        meanVelTxt = wx.StaticText(meanVelPanel,
                                   13,
                                   label=self.meanVelLbl,
                                   style=wx.ALIGN_CENTRE_HORIZONTAL,
                                   size=(-1, self.height))
        meanVelTxt.Wrap(self.wrapLength)
        self.meanVelCtrl = MyTextCtrl(meanVelPanel,
                                      14,
                                      style=wx.TE_PROCESS_ENTER | wx.TE_CENTRE,
                                      size=(85, self.ctrlHeight))
        self.meanVelCtrl.Bind(wx.EVT_TEXT, self.FloatNumberControl)
        self.meanVelCtrl.Bind(wx.EVT_KILL_FOCUS, self.OnMeanVel)
        meanVelSizer.Add(meanVelTxt, 1, wx.EXPAND)
        meanVelSizer.Add(self.meanVelCtrl, 1, wx.EXPAND)
        meanVelSizerH.Add(meanVelSizer, 1, wx.EXPAND)

        meanVelPanel.SetSizer(meanVelSizerH)

        #Mean Gauge Height Info
        mghPanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        mghPanel.SetBackgroundColour(self.BGColour)
        mghSizer = wx.BoxSizer(wx.VERTICAL)
        mghSizerH = wx.BoxSizer(wx.HORIZONTAL)

        cmghSizer = wx.BoxSizer(wx.HORIZONTAL)

        mghTxt = wx.StaticText(mghPanel,
                               15,
                               label=self.mghLbl,
                               style=wx.ALIGN_CENTRE_HORIZONTAL,
                               size=(-1, self.height / 2))
        self.correctMGHButton = wx.Button(mghPanel,
                                          size=(15, self.height / 2),
                                          label="!")
        self.correctMGHButton.SetForegroundColour('red')
        self.correctMGHButton.Bind(wx.EVT_BUTTON, self.OnCMGHBtn)

        self.mghCmbo = wx.ComboBox(mghPanel,
                                   choices=self.mghChoices,
                                   style=wx.CB_READONLY,
                                   size=(-1, self.height / 2))
        # set_trace()
        self.mghCmbo.Bind(wx.EVT_COMBOBOX, self.UpdateMGHCtrl)

        cmghSizer.Add(mghTxt, 1, wx.EXPAND)
        cmghSizer.Add(self.correctMGHButton, 0, wx.EXPAND)

        mghTxt.Wrap(self.wrapLength)

        self.mghCtrl = MyTextCtrl(mghPanel,
                                  16,
                                  style=wx.TE_READONLY | wx.TE_CENTRE,
                                  size=(-1, self.ctrlHeight))

        mghSizer.Add(cmghSizer, 3, wx.EXPAND)
        mghSizer.Add(self.mghCmbo, 4, wx.EXPAND)
        mghSizer.Add(self.mghCtrl, 5, wx.EXPAND)
        mghSizerH.Add(mghSizer, 1, wx.EXPAND)

        mghPanel.SetSizer(mghSizerH)

        #Discharge Info
        dischPanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        dischPanel.SetBackgroundColour(self.BGColour)
        dischSizer = wx.BoxSizer(wx.VERTICAL)
        dischSizer1 = wx.BoxSizer(wx.HORIZONTAL)
        dischSizerH = wx.BoxSizer(wx.HORIZONTAL)

        dischTxt = wx.StaticText(dischPanel,
                                 17,
                                 label=self.dischLbl,
                                 style=wx.ALIGN_CENTRE_HORIZONTAL,
                                 size=(-1, self.height))
        dischTxt.Wrap(self.wrapLength)
        self.dischCtrl = MyTextCtrl(dischPanel,
                                    18,
                                    style=wx.TE_PROCESS_ENTER | wx.TE_CENTRE,
                                    size=(70, self.ctrlHeight))
        self.dischCtrl.Bind(wx.EVT_TEXT, self.FloatNumberControl)
        self.dischCtrl.Bind(wx.EVT_TEXT, self.OnChangeUpdateMovingBoat)
        self.dischCtrl.Bind(wx.EVT_KILL_FOCUS, self.OnDischarge)
        self.dischCtrl.Bind(wx.EVT_KILL_FOCUS, self.OnUpdateHGQValues)
        # self.dischCombo = wx.ComboBox(dischPanel, choices=self.dischChoices, style=wx.CB_READONLY, size=(32, self.ctrlHeight))

        dischSizer.Add(dischTxt, 1, wx.EXPAND)
        dischSizer1.Add(self.dischCtrl, 1, wx.EXPAND)
        # dischSizer1.Add(self.dischCombo, 0, wx.EXPAND)
        dischSizer.Add(dischSizer1, 1, wx.EXPAND)
        dischSizerH.Add(dischSizer, 1, wx.EXPAND)

        dischPanel.SetSizer(dischSizerH)

        #Uncertainty Info
        uncertaintyPanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        uncertaintyPanel.SetBackgroundColour(self.BGColour)
        uncertaintySizer = wx.BoxSizer(wx.VERTICAL)
        uncertaintySizer1 = wx.BoxSizer(wx.HORIZONTAL)
        uncertaintySizerH = wx.BoxSizer(wx.HORIZONTAL)

        uncertaintyLabelSizerH = wx.BoxSizer(wx.HORIZONTAL)

        self.uncertaintyInfoBtn = wx.Button(uncertaintyPanel,
                                            size=(15, self.height / 2),
                                            label="!")
        self.uncertaintyInfoBtn.SetForegroundColour('red')
        self.uncertaintyInfoBtn.Bind(wx.EVT_BUTTON, self.OnUncertaintyInfoBtn)

        uncertaintyTxt = wx.StaticText(uncertaintyPanel,
                                       17,
                                       label=self.uncertaintyLbl,
                                       style=wx.ALIGN_CENTRE_HORIZONTAL,
                                       size=(-1, self.height))
        uncertaintyTxt.Wrap(self.wrapLength)
        self.uncertaintyCtrl = MyTextCtrl(uncertaintyPanel,
                                          18,
                                          style=wx.TE_PROCESS_ENTER
                                          | wx.TE_CENTRE,
                                          size=(70, self.ctrlHeight))
        self.uncertaintyCtrl.Bind(wx.EVT_TEXT, self.FloatNumberControl)
        # self.uncertaintyCtrl.Bind(wx.EVT_TEXT, self.OnChangeUpdateMovingBoat)
        self.uncertaintyCtrl.Bind(wx.EVT_KILL_FOCUS, self.OnDischarge)
        self.uncertaintyCtrl.Bind(wx.EVT_KILL_FOCUS, self.OnUpdateHGQValues)

        uncertaintyLabelSizerH.Add(uncertaintyTxt, 1, wx.EXPAND)
        uncertaintyLabelSizerH.Add(self.uncertaintyInfoBtn, 0, wx.EXPAND)

        uncertaintySizer.Add(uncertaintyLabelSizerH, 1, wx.EXPAND)
        uncertaintySizer1.Add(self.uncertaintyCtrl, 1, wx.EXPAND)
        uncertaintySizer.Add(uncertaintySizer1, 1, wx.EXPAND)

        uncertaintySizerH.Add(uncertaintySizer, 1, wx.EXPAND)

        uncertaintyPanel.SetSizer(uncertaintySizerH)

        #Mmt Mean Time Info
        mmtPanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        mmtPanel.SetBackgroundColour(self.BGColour)
        mmtLblSubPanel = wx.Panel(mmtPanel)
        mmtValSubPanel = wx.Panel(mmtPanel, style=wx.BORDER_SUNKEN)

        mmtSizerH = wx.BoxSizer(wx.HORIZONTAL)
        mmtLblSubSizerH = wx.BoxSizer(wx.HORIZONTAL)
        mmtValSubSizerH = wx.BoxSizer(wx.HORIZONTAL)

        mmtTxt = wx.StaticText(mmtLblSubPanel,
                               19,
                               label=self.mmtLbl,
                               style=wx.ALIGN_CENTRE_HORIZONTAL,
                               size=(-1, self.height))
        mmtTxt.Wrap(self.wrapLength)
        self.mmtValTxt = wx.StaticText(mmtValSubPanel,
                                       20,
                                       label='',
                                       style=wx.ALIGN_CENTRE_HORIZONTAL,
                                       size=(-1, self.ctrlHeight))

        mmtLblSubSizerH.Add(mmtTxt, 1, wx.EXPAND)
        mmtLblSubPanel.SetSizer(mmtLblSubSizerH)
        mmtValSubSizerH.Add(self.mmtValTxt, 1, wx.EXPAND)
        mmtValSubPanel.SetSizer(mmtValSubSizerH)

        mmtSizerH.Add(mmtLblSubPanel, 1, wx.EXPAND)
        mmtSizerH.Add(mmtValSubPanel, 1, wx.EXPAND)

        mmtPanel.SetSizer(mmtSizerH)

        #Calc Shift Base Curve Info
        shiftPanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        shiftPanel.SetBackgroundColour(self.BGColour)
        shiftSizerH = wx.BoxSizer(wx.HORIZONTAL)

        shiftTxt = wx.StaticText(shiftPanel,
                                 21,
                                 label=self.shiftLbl,
                                 style=wx.ALIGN_CENTRE_HORIZONTAL,
                                 size=(-1, self.height))
        shiftTxt.Wrap(self.wrapLength)
        self.shiftCtrl = MyTextCtrl(shiftPanel,
                                    22,
                                    style=wx.TE_PROCESS_ENTER | wx.TE_CENTRE,
                                    size=(70, self.ctrlHeight))
        self.shiftCtrl.Bind(wx.EVT_TEXT, self.FloatNumberControl)
        self.shiftCtrl.Bind(wx.EVT_TEXT, self.OnChangeUpdateMovingBoat)

        shiftSizerH.Add(shiftTxt, 1, wx.EXPAND)
        shiftSizerH.Add(self.shiftCtrl, 1, wx.EXPAND)

        shiftPanel.SetSizer(shiftSizerH)

        #Difference Base Curve Info
        diffPanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        diffPanel.SetBackgroundColour(self.BGColour)
        diffSizerH = wx.BoxSizer(wx.HORIZONTAL)

        diffTxt = wx.StaticText(diffPanel,
                                23,
                                label=self.diffLbl,
                                style=wx.ALIGN_CENTRE_HORIZONTAL,
                                size=(-1, self.height))
        diffTxt.Wrap(self.wrapLength)
        self.diffCtrl = MyTextCtrl(diffPanel,
                                   24,
                                   style=wx.TE_PROCESS_ENTER | wx.TE_CENTRE,
                                   size=(70, self.ctrlHeight))
        self.diffCtrl.Bind(wx.EVT_TEXT, self.FloatNumberControl)
        self.diffCtrl.Bind(wx.EVT_TEXT, self.OnChangeUpdateMovingBoat)

        diffSizerH.Add(diffTxt, 1, wx.EXPAND)
        diffSizerH.Add(self.diffCtrl, 1, wx.EXPAND)

        diffPanel.SetSizer(diffSizerH)

        #Curve Info
        curvePanel = wx.Panel(self, style=wx.SIMPLE_BORDER)
        curvePanel.SetBackgroundColour(self.BGColour)
        curveSizerG = wx.GridBagSizer(0, 0)

        curveTxt = wx.StaticText(curvePanel,
                                 25,
                                 label=self.curveLbl,
                                 style=wx.ALIGN_CENTRE_HORIZONTAL,
                                 size=(-1, self.height))
        curveTxt.Wrap(self.wrapLength)

        self.curveCtrl = wx.ComboBox(curvePanel,
                                     26,
                                     choices=self.curveList,
                                     style=wx.CB_DROPDOWN | wx.TE_PROCESS_ENTER
                                     | wx.TE_CENTRE,
                                     size=(120, self.ctrlHeight))
        self.curveCtrl.Bind(wx.EVT_TEXT, self.FloatNumberControl)
        self.curveCtrl.Bind(wx.EVT_TEXT, self.OnRCText)
        self.curveCtrl.Bind(wx.EVT_KILL_FOCUS, self.OnRCKillFocus)
        self.curveCtrl.Bind(wx.EVT_COMBOBOX, self.OnRCCombo)
        curveSizerG.Add(curveTxt, pos=(0, 0), span=(1, 1), flag=wx.EXPAND)
        curveSizerG.Add(self.curveCtrl,
                        pos=(0, 1),
                        span=(1, 2),
                        flag=wx.EXPAND)

        for i in range(2):
            curveSizerG.AddGrowableCol(i)
        for i in range(1):
            curveSizerG.AddGrowableRow(i)

        curvePanel.SetSizer(curveSizerG)

        #Control and Remarks
        controlConditionSizer = wx.BoxSizer(wx.HORIZONTAL)

        controlConditionPanel = wx.Panel(self,
                                         style=wx.SIMPLE_BORDER,
                                         size=(-1, self.height))
        controlConditionPanel.SetSizer(controlConditionSizer)

        controlTxt = wx.StaticText(controlConditionPanel,
                                   label=self.controlLbl,
                                   size=(80, self.height),
                                   style=wx.ALIGN_CENTRE_HORIZONTAL)
        controlTxt.SetForegroundColour("blue")
        controlTxt.SetBackgroundColour(self.BGColour)
        # controlTxt.SetBackgroundColour("gold")
        self.controlConditionCmbo = wx.ComboBox(controlConditionPanel,
                                                choices=self.contCondList,
                                                style=wx.CB_READONLY,
                                                size=(80, self.height))
        self.controlConditionCmbo.Bind(wx.EVT_MOUSEWHEEL, self.do_nothing)
        # self.picturedCkbox = wx.CheckBox(controlConditionPanel, label=self.picturedLbl)

        controlConditionSizer.Add(controlTxt, 1, wx.EXPAND)
        controlConditionSizer.Add(self.controlConditionCmbo, 1, wx.EXPAND)

        # #control condition remarks
        controlConditionRemarkSizer = wx.BoxSizer(wx.HORIZONTAL)
        controlConditionRemarkPanel = wx.Panel(self,
                                               style=wx.SIMPLE_BORDER,
                                               size=(-1, self.height * 1.2))
        controlConditionRemarkPanel.SetSizer(controlConditionRemarkSizer)

        controlConditionTxt = wx.StaticText(controlConditionRemarkPanel,
                                            label=self.controlConditionRemLbl,
                                            size=(200, self.height),
                                            style=wx.ALIGN_CENTRE_HORIZONTAL)
        self.controlConditionRemarksCtrl = wx.TextCtrl(
            controlConditionRemarkPanel,
            style=wx.TE_PROCESS_ENTER | wx.TE_MULTILINE | wx.TE_BESTWRAP,
            size=(-1, self.height * 1.2))
        controlConditionRemarkSizer.Add(controlConditionTxt, 0, wx.EXPAND)
        controlConditionRemarkSizer.Add(self.controlConditionRemarksCtrl, 1,
                                        wx.EXPAND)

        dischargeRemarkSizer = wx.BoxSizer(wx.HORIZONTAL)
        dischargeRemarkPanel = wx.Panel(self,
                                        style=wx.SIMPLE_BORDER,
                                        size=(-1, self.height * 1.2))
        dischargeRemarkPanel.SetSizer(dischargeRemarkSizer)

        self.dischTxt = wx.StaticText(dischargeRemarkPanel,
                                      label=self.dischRemarkLbl,
                                      style=wx.ALIGN_CENTRE_HORIZONTAL,
                                      size=(200, self.height))
        self.dischRemarksCtrl = wx.TextCtrl(dischargeRemarkPanel,
                                            style=wx.TE_PROCESS_ENTER
                                            | wx.TE_MULTILINE | wx.TE_BESTWRAP,
                                            size=(-1, self.height * 1.2))
        dischargeRemarkSizer.Add(self.dischTxt, 0)
        dischargeRemarkSizer.Add(self.dischRemarksCtrl, 1, wx.EXPAND)

        self.layoutSizer.Add(startTimePanel,
                             pos=(0, 0),
                             span=(2, 1),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(endTimePanel,
                             pos=(0, 1),
                             span=(2, 1),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(airTempPanel,
                             pos=(0, 2),
                             span=(2, 1),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(waterTempPanel,
                             pos=(0, 3),
                             span=(2, 1),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(widthPanel,
                             pos=(0, 4),
                             span=(2, 1),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(areaPanel,
                             pos=(0, 5),
                             span=(2, 1),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(meanVelPanel,
                             pos=(0, 6),
                             span=(2, 1),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(mghPanel, pos=(0, 7), span=(2, 1), flag=wx.EXPAND)
        self.layoutSizer.Add(dischPanel,
                             pos=(0, 8),
                             span=(2, 1),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(uncertaintyPanel,
                             pos=(0, 9),
                             span=(2, 1),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(mmtPanel, pos=(2, 0), span=(1, 2), flag=wx.EXPAND)
        self.layoutSizer.Add(shiftPanel,
                             pos=(2, 2),
                             span=(1, 2),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(diffPanel,
                             pos=(2, 4),
                             span=(1, 2),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(curvePanel,
                             pos=(2, 6),
                             span=(1, 4),
                             flag=wx.EXPAND)

        self.layoutSizer.Add(controlConditionPanel,
                             pos=(3, 0),
                             span=(1, 2),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(controlConditionRemarkPanel,
                             pos=(3, 2),
                             span=(1, 8),
                             flag=wx.EXPAND)
        self.layoutSizer.Add(dischargeRemarkPanel,
                             pos=(4, 0),
                             span=(1, 10),
                             flag=wx.EXPAND)

        self.startTimeCtrl.GetHourCtrl().Bind(wx.EVT_COMBOBOX,
                                              self.OnTimeChange)
        self.startTimeCtrl.GetMinuteCtrl().Bind(wx.EVT_COMBOBOX,
                                                self.OnTimeChange)
        self.startTimeCtrl.GetHourCtrl().Bind(wx.EVT_KEY_UP, self.OnTimeChange)
        self.startTimeCtrl.GetMinuteCtrl().Bind(wx.EVT_KEY_UP,
                                                self.OnTimeChange)
        self.startTimeCtrl.cBtn.Bind(wx.EVT_BUTTON, self.OnCBtn)
        # self.startTimeCtrl.GetHourCtrl().Bind(wx.EVT_TEXT, self.OnTimeChange)
        # self.startTimeCtrl.GetMinuteCtrl().Bind(wx.EVT_TEXT, self.OnTimeChange)
        self.endTimeCtrl.GetHourCtrl().Bind(wx.EVT_COMBOBOX, self.OnTimeChange)
        self.endTimeCtrl.GetMinuteCtrl().Bind(wx.EVT_COMBOBOX,
                                              self.OnTimeChange)
        self.endTimeCtrl.GetHourCtrl().Bind(wx.EVT_KEY_UP, self.OnTimeChange)
        self.endTimeCtrl.GetMinuteCtrl().Bind(wx.EVT_KEY_UP, self.OnTimeChange)
        self.endTimeCtrl.cBtn.Bind(wx.EVT_BUTTON, self.OnCBtn)
        # self.endTimeCtrl.GetHourCtrl().Bind(wx.EVT_TEXT, self.OnTimeChange)
        # self.endTimeCtrl.GetMinuteCtrl().Bind(wx.EVT_TEXT, self.OnTimeChange)

        for i in range(9):
            self.layoutSizer.AddGrowableCol(i)

        for i in range(3):
            self.layoutSizer.AddGrowableRow(i)

        self.SetSizerAndFit(self.layoutSizer)
Exemplo n.º 25
0
    def __init__(self):
        # Splash screen image will depend on currently language
        lang = False

        self.locale = wx.Locale(wx.LANGUAGE_DEFAULT)

        # Language information is available in session configuration
        # file. First we need to check if this file exist, if now, it
        # should be created
        create_session = False
        session = ses.Session()
        if not (session.ReadSession()):
            create_session = True

        install_lang = 0
        lang = session.GetLanguage()
        if lang:
            if (lang != "False"):
                _ = i18n.InstallLanguage(lang)
                install_lang = 1
            else:
                install_lang = 0
        else:
            install_lang = 0

        # If no language is set into session file, show dialog so
        # user can select language
        if install_lang == 0:
            dialog = lang_dlg.LanguageDialog()

            # FIXME: This works ok in linux2, darwin and win32,
            # except on win64, due to wxWidgets bug
            try:
                ok = (dialog.ShowModal() == wx.ID_OK)
            except wx._core.PyAssertionError:
                ok = True
            finally:
                if ok:
                    lang = dialog.GetSelectedLanguage()
                    session.SetLanguage(lang)
                    _ = i18n.InstallLanguage(lang)
                else:
                    homedir = self.homedir = os.path.expanduser('~')
                    invdir = os.path.join(homedir, ".invesalius")
                    shutil.rmtree(invdir)
                    sys.exit()

            dialog.Destroy()

        # Session file should be created... So we set the recent
        # choosen language
        if (create_session):
            session.CreateItens()
            session.SetLanguage(lang)
            session.WriteSessionFile()

        #  session.SaveConfigFileBackup()

           
        # Only after language was defined, splash screen will be
        # shown
        if lang:
            
            #import locale
            #try:
            #    locale.setlocale(locale.LC_ALL, '')
            #except locale.Error:
            #    pass
            
            
            # For pt_BR, splash_pt.png should be used
            if (lang.startswith('pt')):
                icon_file = "splash_pt.png"
            else:
                icon_file = "splash_" + lang + ".png"

            if hasattr(sys,"frozen") and (sys.frozen == "windows_exe"\
                                        or sys.frozen == "console_exe"):
                abs_file_path = os.path.abspath(".." + os.sep)
                path = abs_file_path
                path = os.path.join(path, 'icons', icon_file)
            
            else:

                path = os.path.join(".","icons", icon_file)
                if not os.path.exists(path):
                    path = os.path.join(".", "icons", "splash_en.png")
				
            bmp = wx.Image(path).ConvertToBitmap()

            try:
                style = wx.adv.SPLASH_TIMEOUT | wx.adv.SPLASH_CENTRE_ON_SCREEN
            except AttributeError:
                style = wx.SPLASH_TIMEOUT | wx.SPLASH_CENTRE_ON_SCREEN

            SplashScreen.__init__(self,
                                  bitmap=bmp,
                                  splashStyle=style,
                                  milliseconds=1500,
                                  id=-1,
                                  parent=None)
            self.Bind(wx.EVT_CLOSE, self.OnClose)
            wx.Yield()
            wx.CallLater(200, self.Startup)
Exemplo n.º 26
0
def main(argv):
    """
    Основная запускающая функция.
    @param argv: Список параметров коммандной строки.
    """
    # Разбираем аргументы командной строки
    try:
        options, args = getopt.getopt(argv, 'h?vdl', [
            'help', 'version', 'debug', 'log', 'scanner=', 'source=', 'mode=',
            'multi_scan', 'preview', 'page_size=', 'area=', 'scan_dir=',
            'file_name=', 'file_type=', 'ext_cmd=', 'pack_mode', 'pack_pages=',
            'glue', 'max_sheets='
        ])
    except getopt.error as msg:
        log.error(str(msg), bForcePrint=True)
        log.info(__doc__)
        sys.exit(2)

    # Инициализоция системы журналирования
    log.init(config)

    txt_version = '.'.join([str(ver) for ver in __version__])
    cmd_options = dict()
    for option, arg in options:
        if option in ('-h', '--help', '-?'):
            print(__doc__)
            sys.exit(0)
        elif option in ('-v', '--version'):
            print('icScanner version: %s' % txt_version)
            sys.exit(0)
        elif option in ('-d', '--debug'):
            config.set_glob_var('DEBUG_MODE', True)
        elif option in ('-l', '--log'):
            config.set_glob_var('LOG_MODE', True)
        elif option in ('--scanner', ):
            cmd_options['scanner'] = arg
        elif option in ('--source', ):
            cmd_options['scan_source'] = arg
        elif option in ('--mode', ):
            cmd_options['scan_mode'] = arg
        elif option in ('--multi_scan', ):
            cmd_options['is_multi_scan'] = True
        elif option in ('--preview', ):
            cmd_options['is_preview'] = True
        elif option in ('--page_size', ):
            if arg in ('A4', 'a4'):
                cmd_options['page_size'] = scan_manager.A4_PORTRAIT_PAGE_SIZE
            elif arg in ('A3', 'a3'):
                cmd_options['page_size'] = scan_manager.A3_PORTRAIT_PAGE_SIZE
            else:
                log.warning(u'Не обрабатываемый размер страницы <%s>' % arg)
        elif option in ('--area', ):
            try:
                area = tuple([float(x.strip()) for x in arg.split(',')])
                cmd_options['scan_area'] = area
            except:
                log.fatal(
                    u'Ошибка парсинга параметра области сканирования <%s>' %
                    arg)
        elif option in ('--scan_dir', ):
            cmd_options['scan_dir'] = arg
        elif option in ('--file_name', ):
            cmd_options['scan_filename'] = arg
        elif option in ('--file_type', ):
            cmd_options['scan_filetype'] = arg.lower()
        elif option in ('--depth', ):
            cmd_options['depth'] = int(arg)
        elif option in ('--ext_cmd', ):
            cmd_options['ext_scan_cmd'] = arg
        elif option in ('--pack_mode', ):
            cmd_options['pack_mode'] = True
        elif option in ('--pack_pages', ):
            cmd_options['pack_pages'] = arg
        elif option in ('--max_sheets', ):
            config.set_glob_var('DEFAULT_SCANNER_MAX_SHEETS', int(arg))
        else:
            log.warning(u'Не обрабатываемый параметр коммандной строки <%s>' %
                        option)

    # По умолчанию пакетный режим отключен+
    #                                     v
    if not cmd_options.get('pack_mode', False):
        # Внимание! Приложение создается для
        # управления диалоговыми окнами
        app = wx.PySimpleApp()
        # ВНИМАНИЕ! Выставить русскую локаль
        # Это необходимо для корректного отображения календарей,
        # форматов дат, времени, данных и т.п.
        locale = wx.Locale()
        locale.Init(wx.LANGUAGE_RUSSIAN)

        scanner_dlg.do_scan_dlg(options=cmd_options,
                                title=u'Сканирование. icScanner ' +
                                txt_version)
        app.MainLoop()
    else:
        # В пакетном режиме не используем диалоговое окно
        # Но в случае режима склеивания документа по частям диалоговые окна используются
        filenames = cmd_options.get('scan_filename', u'').split(';')
        pack_page_list = cmd_options.get('pack_pages', u'').split(';')
        n_pages = [
            int(pack_page.split('/')[0])
            if '/' in pack_page else int(pack_page)
            for pack_page in pack_page_list
        ]
        duplexes = [
            bool(int(pack_page.split('/')[1])) if '/' in pack_page else False
            for pack_page in pack_page_list
        ]
        scan_filenames = [(filename, n_pages[i] if i < len(n_pages) else 1,
                           duplexes[i] if i < len(duplexes) else False)
                          for i, filename in enumerate(filenames)]
        scan_admin = scanner_dlg.icScanAdministrator()
        # Установить дополнительные опции из коммандной строки
        scan_admin.setExtOptions(scan_dir=cmd_options['scan_dir'])
        scan_admin.runScanPack(*scan_filenames)
Exemplo n.º 27
0
    if wxlocale.GetCanonicalName()[:2] in [
            'ar', 'dv', 'fa', 'ha', 'he', 'ps', 'ur', 'yi'
    ]:
        wxlocale = wx.Locale(wx.LANGUAGE_DEFAULT)
    # wx.Locale on Py2.7/wx3.0 seems to delete the preferred encoding (utf-8)
    # Check if that happened and reinstate if needed.
    if locale_pkg.getpreferredencoding(do_setlocale=False) == '':
        locale_pkg.setlocale(locale_pkg.LC_ALL,
                             "{}.{}".format(codeFromWxId[languageID], encod))
    return wxlocale


# Get a dict of locale aliases from wx.Locale() -- same cross-platform
# (Win 7, Mac 10.9)
# this DOESN'T need the app to be instantiated
locale = wx.Locale()
aliases = {u'English (U.S.)': 'en_US'}
# set defaults because locale.GetLanguageInfo(0) can return None on some
# systems:
wxIdFromCode = {'en_US': wx.LANGUAGE_DEFAULT}  # int: 0 default, 2-229
# used in directory names e.g. ja_JP; never JPN ala Windows
codeFromWxId = {wx.LANGUAGE_DEFAULT: 'en_US'}
for i in range(230):
    info = locale.GetLanguageInfo(i)
    if info:
        # mix of forms: ja or ja_JP
        aliases[info.Description] = info.CanonicalName
        wxIdFromCode[info.CanonicalName] = i
        codeFromWxId[i] = info.CanonicalName

# read all known mappings cross-platform from a file:
Exemplo n.º 28
0
    def __init__(self, parent, pathToImage=None):

        # Use English dialog
        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)

        # Initialise the parent
        wx.Panel.__init__(self, parent)

        # Intitialise the matplotlib figure
        #self.figure = plt.figure(facecolor='gray',figsize = (9,8))
        self.figure = Figure(facecolor='gray', figsize=(9, 8))

        # Create an axes, turn off the labels and add them to the figure
        self.axes = plt.Axes(self.figure, [0, 0, 1, 1])
        self.axes.set_axis_off()
        self.figure.add_axes(self.axes)

        # Add the figure to the wxFigureCanvas
        self.canvas = FigureCanvas(self, -1, self.figure)

        # Add Button and Progress Bar
        self.openBtn = wx.Button(self,
                                 -1,
                                 "Open",
                                 pos=(680, 50),
                                 size=(70, 40))
        self.saveBtn = wx.Button(self,
                                 -1,
                                 "save",
                                 pos=(680, 150),
                                 size=(70, 40))
        self.cirBtn = wx.Button(self,
                                -1,
                                "circle",
                                pos=(680, 200),
                                size=(70, 40))
        self.rectBtn = wx.Button(self,
                                 -1,
                                 "rectangle",
                                 pos=(790, 200),
                                 size=(70, 40))
        self.lineBtn = wx.Button(self,
                                 -1,
                                 "line",
                                 pos=(790, 250),
                                 size=(70, 40))
        self.arrowlineBtn = wx.Button(self,
                                      -1,
                                      "arrowline",
                                      pos=(680, 250),
                                      size=(70, 40))
        #self.gauge=wx.Gauge(self,-1,100,(00,520),(640,50))

        # Attach button with function
        self.Bind(wx.EVT_BUTTON, self.load, self.openBtn)
        self.Bind(wx.EVT_BUTTON, self.save, self.saveBtn)
        self.Bind(wx.EVT_BUTTON, self.line, self.lineBtn)
        self.Bind(wx.EVT_BUTTON, self.rectangle, self.rectBtn)
        self.Bind(wx.EVT_BUTTON, self.arrow, self.arrowlineBtn)
        self.Bind(wx.EVT_BUTTON, self.circle, self.cirBtn)

        # Show dialog path
        self.pathText = wx.TextCtrl(
            self,
            -1,
            "",
            pos=(680, 100),
            size=(175, 30),
        )

        # Check box
        self.check = wx.CheckBox(self,
                                 -1,
                                 "Check",
                                 pos=(790, 50),
                                 size=(70, 20))
        self.check.Bind(wx.EVT_CHECKBOX, self.onCheck)

        #self.area_text.SetInsertionPoint(0)

        # Initialise the rectangle
        #self.rect = Rectangle((0,0), 0, 0, facecolor='None', edgecolor='red')
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        #self.axes.add_patch(self.rect)

        # The list of the picture(absolute path)
        self.fileList = []

        # Picture name
        self.picNameList = []

        # Picture index in list
        self.count = 0

        # Cut from the picture of the rectangle
        self.cut_img = None

        # Connect the mouse events to their relevant callbacks
        self.canvas.mpl_connect('button_press_event', self._onPress)
        self.canvas.mpl_connect('button_release_event', self._onRelease)
        self.canvas.mpl_connect('motion_notify_event', self._onMotion)

        # Lock to stop the motion event from behaving badly when the mouse isn't pressed
        self.pressed = False

        # If there is an initial image, display it on the figure
        if pathToImage is not None:
            self.setImage(pathToImage)
Exemplo n.º 29
0
    def export(self, wikiDocument, wordList, exportType, exportDest,
               compatFilenames, addOpt, progressHandler):
        """
        Run export operation.
        
        wikiDocument -- WikiDocument object
        wordList -- Sequence of wiki words to export
        exportType -- string tag to identify how to export
        exportDest -- Path to destination directory or file to export to
        compatFilenames -- Should the filenames be encoded to be lowest
                           level compatible
        addOpt -- additional options returned by getAddOpt()
        """
        self.wikiDocument = wikiDocument
        self.wordList = wordList
        self.exportDest = exportDest
        self.addOpt = addOpt
        self.exportFile = None
        self.rawExportFile = None
        self.firstSeparatorCallDone = False

        self.formatVer = min(addOpt[0], 1)
        self.writeWikiFuncPages = addOpt[1] and (self.formatVer > 0)
        self.writeSavedSearches = addOpt[2] and (self.formatVer > 0)
        self.writeVersionData = addOpt[3] and (self.formatVer > 0)

        try:
            for tryNumber in range(35):
                self.separator = u"-----%s-----" % createRandomString(25)
                try:
                    self.rawExportFile = open(pathEnc(self.exportDest), "w")

                    # Only UTF-8 mode currently
                    self.rawExportFile.write(BOM_UTF8)
                    self.exportFile = _SeparatorWatchUtf8Writer(
                        self.rawExportFile, self.separator, "replace")

                    self.wikiPageWriter = MultiPageTextWikiPageWriter(
                        self.wikiDocument, self.exportFile,
                        self.writeVersionData, self.formatVer)

                    # Identifier line with file format
                    self.exportFile.write(u"Multipage text format %i\n" %
                                          self.formatVer)
                    # Separator line
                    self.exportFile.write(u"Separator: %s\n" % self.separator)

                    # Write wiki-bound functional pages
                    if self.writeWikiFuncPages:
                        # Only wiki related functional pages
                        wikiFuncTags = [
                            ft for ft in DocPages.getFuncTags()
                            if ft.startswith("wiki/")
                        ]

                        for ft in wikiFuncTags:
                            self.exportFile.writeSeparator()
                            self.exportFile.write(u"funcpage/%s\n" % ft)
                            page = self.wikiDocument.getFuncPage(ft)
                            self.exportFile.write(page.getLiveText())

                    # Write saved searches
                    if self.writeSavedSearches:
                        # Wiki-wide searches
                        wikiData = self.wikiDocument.getWikiData()
                        unifNames = wikiData.getDataBlockUnifNamesStartingWith(
                            u"savedsearch/")

                        for un in unifNames:
                            self.exportFile.writeSeparator()
                            self.exportFile.write(un + u"\n")
                            datablock = wikiData.retrieveDataBlock(un)

                            self.exportFile.write(base64BlockEncode(datablock))

                        # Page searches
                        unifNames = wikiData.getDataBlockUnifNamesStartingWith(
                            u"savedpagesearch/")

                        for un in unifNames:
                            self.exportFile.writeSeparator()
                            self._writeHintedDatablock(un, False)

                    locale.setlocale(locale.LC_ALL, '')

                    wx.Locale(wx.LANGUAGE_DEFAULT)

                    # Write actual wiki words
                    for word in self.wordList:
                        self.wikiPageWriter.exportWikiWord(word)
                        self.exportFile.checkAndClearBuffer()
                    break

                except _SeparatorFoundException:
                    if self.exportFile is not None:
                        self.exportFile.flush()
                        self.exportFile = None

                    if self.rawExportFile is not None:
                        self.rawExportFile.close()
                        self.rawExportFile = None

                    continue
                except Exception, e:
                    traceback.print_exc()
                    raise ExportException(unicode(e))
            else:
Exemplo n.º 30
0
def _main_run():
    app = wx.GetApp()
    app.locale = wx.Locale(wx.LANGUAGE_DEFAULT)
    app.locale.AddCatalogLookupPathPrefix(SRC_PATH + "/pytigon_gui/locale")

    app.locale.AddCatalog("wx")
    app.locale.AddCatalog("pytigon")

    if app.embeded_browser:
        frame = browserframe.SchBrowserFrame(
            None,
            app.gui_style,
            wx.ID_ANY,
            app.title,
            wx.DefaultPosition,
            wx.Size(_APP_SIZE[0], _APP_SIZE[1]),
        )
    else:
        frame = appframe.SchAppFrame(
            app.gui_style,
            app.title,
            wx.DefaultPosition,
            wx.Size(_APP_SIZE[0], _APP_SIZE[1]),
            video=_VIDEO,
        )

    frame.CenterOnScreen()

    if not "tray" in app.gui_style:
        frame.Show()

    wx.Log.SetActiveTarget(wx.LogStderr())

    destroy_fun_tab = frame.destroy_fun_tab
    httpclient.set_http_error_func(http_error)

    def idle_fun():
        wx.GetApp().web_ctrl.OnIdle(None)

    httpclient.set_http_idle_func(idle_fun)

    # if app.task_manager:
    #    frame.idle_objects.append(app.task_manager)

    if _RPC:
        reactor.listenTCP(app.rpc, server.Site(app))

    if _WEBSOCKET:
        if ";" in _WEBSOCKET:
            websockets = _WEBSOCKET.split(";")
        else:
            websockets = [_WEBSOCKET]

        local = True if app.base_address.startswith("http://127.0.0.2") else False

        for websocket_id in websockets:
            create_websocket_client(app, websocket_id, local)

    if _INSPECTION == True:
        app.MainLoop()
    else:
        if "channels" in _PARAM or "rpc" in _PARAM or "websocket" in _PARAM:
            # loop = get_event_loop()
            LOOP.run_until_complete(app.MainLoop())
        else:
            app.MainLoop()

    # if app.task_manager:
    #    app.task_manager.wait_for_result()
    if app.server:
        app.server.stop()
    del app
    for pos in destroy_fun_tab:
        pos()