コード例 #1
0
ファイル: profiler.py プロジェクト: wangdyna/wxPython
    def Load(self, path):
        """Load the profiles data set with data from the given file
        @param path: path to file to load data from
        @note: The files data must have been written with a pickler

        """
        if os.path.exists(path):
            try:
                fhandle = open(path, 'rb')
                val = cPickle.load(fhandle)
                fhandle.close()
            except (IOError, SystemError, OSError,
                    cPickle.UnpicklingError, EOFError), msg:
                dev_tool.DEBUGP("[profile][err] %s" % str(msg))
            else:
                if isinstance(val, dict):
                    self.update(val)
                    self.Set('MYPROFILE', path)
                    dev_tool.DEBUGP("[profile][info] Loaded %s" % path)
コード例 #2
0
ファイル: ed_print.py プロジェクト: CrownBonded/editra
    def OnPrintPage(self, page):
        """Scales and Renders the page to a DC and prints it
        @param page: page number to print

        """
        line_height = self.stc.TextHeight(0)

        # Calculate sizes
        dc = self.GetDC()
        dw, dh = dc.GetSizeTuple()

        margin_w = self.margin * dw
        margin_h = self.margin * dh
        #         text_area_w = dw - margin_w * 2
        text_area_h = dh - margin_h * 2

        scale = float(text_area_h) / (line_height * self.lines_pp)
        dc.SetUserScale(scale, scale)

        # Render the title and page numbers
        font = self.stc.GetDefaultFont()
        if font.GetPointSize() < 12:
            font.SetPointSize(12)
        dc.SetFont(font)

        if self.title:
            title_w, title_h = dc.GetTextExtent(self.title)
            dc.DrawText(self.title, int(dw / scale / 2 - title_w / 2),
                        int(margin_h / scale - title_h * 3))

        # Page Number
        page_lbl = _("Page: %d") % page
        pg_lbl_w, pg_lbl_h = dc.GetTextExtent(page_lbl)
        dc.DrawText(page_lbl, int(dw / scale / 2 - pg_lbl_w / 2),
                    int((text_area_h + margin_h) / scale + pg_lbl_h * 2))

        # Render the STC window into a DC for printing
        start_pos = self.stc.PositionFromLine((page - 1) * self.lines_pp)
        end_pos = self.stc.GetLineEndPosition(page * self.lines_pp - 1)
        max_w = (dw / scale) - margin_w
        self.stc.SetPrintColourMode(self.colour)
        end_point = self.stc.FormatRange(True, start_pos, end_pos, dc, dc,
                                        wx.Rect(int(margin_w/scale),
                                                int(margin_h/scale),
                                                max_w,
                                                int(text_area_h/scale)+1),
                                        wx.Rect(0, (page - 1) * \
                                                self.lines_pp * \
                                                line_height, max_w,
                                                line_height * self.lines_pp))

        if end_point < end_pos:
            dev_tool.DEBUGP("[printout][err] Rendering Error, page %s" % page)
        return True
コード例 #3
0
ファイル: util.py プロジェクト: wangdyna/wxPython
def GetFileWriter(file_name, enc='utf-8'):
    """Returns a file stream writer object for reading the
    supplied file name. It returns a file writer in the supplied
    encoding if the host system supports it other wise it will return
    an ascii reader. The default will try and return a utf-8 reader.
    If there is an error in creating the file reader the function
    will return a negative number.
    @param file_name: path of file to get writer for
    @keyword enc: encoding to write text to file with

    """
    try:
        file_h = open(file_name, "wb")
    except IOError:
        dev_tool.DEBUGP("[file_writer][err] Failed to open file %s" % file_name)
        return -1
    try:
        writer = codecs.getwriter(enc)(file_h)
    except (LookupError, IndexError, ValueError):
        dev_tool.DEBUGP('[file_writer][err] Failed to get %s Writer' % enc)
        writer = file_h
    return writer
コード例 #4
0
def Main():
    """Configures and Runs an instance of Editra
    @summary: Parses command line options, loads the user profile, creates
              an instance of Editra and starts the main loop.

    """
    try:
        opts, args = getopt.getopt(sys.argv[1:], "dhv",
                                   ['debug', 'help', 'version'])
    except getopt.GetoptError, msg:
        dev_tool.DEBUGP("[main][err] %s" % str(msg))
        opts = list()
        args = list()
コード例 #5
0
ファイル: util.py プロジェクト: wangdyna/wxPython
def GetFileReader(file_name, enc='utf-8'):
    """Returns a file stream reader object for reading the
    supplied file name. It returns a file reader using the encoding
    (enc) which defaults to utf-8. If lookup of the reader fails on
    the host system it will return an ascii reader.
    If there is an error in creating the file reader the function
    will return a negative number.
    @param file_name: name of file to get a reader for
    @keyword enc: encoding to use for reading the file
    @return file reader, or int if error.

    """
    try:
        file_h = file(file_name, "rb")
    except (IOError, OSError):
        dev_tool.DEBUGP("[file_reader] Failed to open file %s" % file_name)
        return -1

    try:
        reader = codecs.getreader(enc)(file_h)
    except (LookupError, IndexError, ValueError):
        dev_tool.DEBUGP('[file_reader] Failed to get %s Reader' % enc)
        reader = file_h
    return reader
コード例 #6
0
    def Write(self, path):
        """Write the dataset of this profile as a pickle
        @param path: path to where to write the pickle
        @return: True on success / False on failure

        """
        try:
            self.Set('MYPROFILE', path)
            fhandle = open(path, 'wb')
            cPickle.dump(self.copy(), fhandle, cPickle.HIGHEST_PROTOCOL)
            fhandle.close()
            UpdateProfileLoader()
        except (IOError, cPickle.PickleError), msg:
            dev_tool.DEBUGP("[profile][err] %s" % str(msg))
            return False
コード例 #7
0
def InitConfig():
    """Initializes the configuration data
    @postcondition: all configuration data is set

    """
    ed_glob.CONFIG['PROFILE_DIR'] = util.ResolvConfigDir("profiles")
    import profiler
    profile_updated = False
    if util.HasConfigDir():
        if profiler.ProfileIsCurrent():
            profiler.Profile().Load(profiler.GetProfileStr())
        else:
            dev_tool.DEBUGP("[main_info] Updating Profile to current version")
            pstr = profiler.GetProfileStr()
            # upgrade earlier profiles to current
            if len(pstr) > 3 and pstr[-2:] == "pp":
                pstr = pstr + u'b'
            profiler.Profile().LoadDefaults()
            if wx.Platform == '__WXGTK__':
                Profile_Set('ICONS', 'Default')
            profiler.Profile().Write(pstr)  # Write out defaults
            profiler.Profile().Load(pstr)  # Test reload profile
            # When upgrading from an older version make sure all
            # config directories are available.
            for cfg in ["cache", "styles", "plugins", "profiles"]:
                if not util.HasConfigDir(cfg):
                    util.MakeConfigDir(cfg)
            profile_updated = True
    else:
        util.CreateConfigDir()
    if 'DEBUG' in Profile_Get('MODE'):
        ed_glob.DEBUG = True
    ed_glob.CONFIG['CONFIG_DIR'] = util.ResolvConfigDir("")
    ed_glob.CONFIG['PIXMAPS_DIR'] = util.ResolvConfigDir("pixmaps")
    ed_glob.CONFIG['SYSPIX_DIR'] = util.ResolvConfigDir("pixmaps", True)
    ed_glob.CONFIG['PLUGIN_DIR'] = util.ResolvConfigDir("plugins")
    ed_glob.CONFIG['THEME_DIR'] = util.ResolvConfigDir(os.path.join("pixmaps", \
                                                                    "theme"))
    ed_glob.CONFIG['LANG_DIR'] = util.ResolvConfigDir("locale", True)
    ed_glob.CONFIG['STYLES_DIR'] = util.ResolvConfigDir("styles")
    ed_glob.CONFIG['SYS_PLUGIN_DIR'] = util.ResolvConfigDir("plugins", True)
    ed_glob.CONFIG['SYS_STYLES_DIR'] = util.ResolvConfigDir("styles", True)
    ed_glob.CONFIG['TEST_DIR'] = util.ResolvConfigDir("tests", True)
    if not util.HasConfigDir("cache"):
        util.MakeConfigDir("cache")
    ed_glob.CONFIG['CACHE_DIR'] = util.ResolvConfigDir("cache")
    return profile_updated
コード例 #8
0
ファイル: profiler.py プロジェクト: wangdyna/wxPython
        """
        if os.path.exists(path):
            try:
                fhandle = open(path, 'rb')
                val = cPickle.load(fhandle)
                fhandle.close()
            except (IOError, SystemError, OSError,
                    cPickle.UnpicklingError, EOFError), msg:
                dev_tool.DEBUGP("[profile][err] %s" % str(msg))
            else:
                if isinstance(val, dict):
                    self.update(val)
                    self.Set('MYPROFILE', path)
                    dev_tool.DEBUGP("[profile][info] Loaded %s" % path)
        else:
            dev_tool.DEBUGP("[profile][err] %s does not exist" % path)
            dev_tool.DEBUGP("[profile][info] Loading defaults")
            self.LoadDefaults()
            self.Set('MYPROFILE', path)
            return False

        # Update profile to any keys that are missing
        for key in _DEFAULTS:
            if key not in self:
                self.Set(key, _DEFAULTS[key])
        return True

    def LoadDefaults(self):
        """Loads the default values into the profile
        @return: None
コード例 #9
0
def Main():
    """Configures and Runs an instance of Editra
    @summary: Parses command line options, loads the user profile, creates
              an instance of Editra and starts the main loop.

    """
    opts, args = ProcessCommandLine()

    # We are ready to run so fire up the config and launch the app
    profile_updated = InitConfig()

    # Put extern subpackage on path so that bundled external dependancies
    # can be found if needed.
    if not hasattr(sys, 'frozen'):
        epath = os.path.join(os.path.dirname(__file__), 'extern')
        if os.path.exists(epath):
            sys.path.append(epath)

    # Create Application
    dev_tool.DEBUGP("[main][app] Initializing application...")
    editra_app = Editra(False)

    # Print ipc server authentication info
    if '--auth' in opts:
        opts.remove('--auth')
        print "port=%d,key=%s" % (ed_ipc.EDPORT,
                                  profiler.Profile_Get('SESSION_KEY'))

    # Check if this is the only instance, if its not exit since
    # any of the opening commands have already been passed to the
    # master instance
    if not editra_app.IsOnlyInstance():
        dev_tool.DEBUGP("[main][info] Second instance exiting...")
        editra_app.Destroy()
        os._exit(0)

    if profile_updated:
        # Make sure window iniliazes to default position
        profiler.Profile_Del('WPOS')
        wx.MessageBox(_("Your profile has been updated to the latest "
                        "version") + u"\n" + \
                      _("Please check the preferences dialog to check "
                        "your preferences"),
                      _("Profile Updated"))

    # Splash a warning if version is not a final version
    if profiler.Profile_Get('APPSPLASH'):
        import edimage
        splash_img = edimage.splashwarn.GetBitmap()
        splash = wx.SplashScreen(splash_img, wx.SPLASH_CENTRE_ON_PARENT | \
                                 wx.SPLASH_NO_TIMEOUT, 0, None, wx.ID_ANY)
        splash.Show()

    if profiler.Profile_Get('SET_WSIZE'):
        wsize = profiler.Profile_Get('WSIZE')
    else:
        wsize = (700, 450)
    frame = ed_main.MainWindow(None, wx.ID_ANY, wsize, ed_glob.PROG_NAME)
    frame.Maximize(profiler.Profile_Get('MAXIMIZED'))
    editra_app.RegisterWindow(repr(frame), frame, True)
    editra_app.SetTopWindow(frame)
    frame.Show(True)

    # Load Session Data
    # But not if there are command line args for files to open
    if profiler.Profile_Get('SAVE_SESSION', 'bool', False) and not len(args):
        frame.GetNotebook().LoadSessionFiles()

    # Unlike wxMac/wxGTK Windows doesn't post an activate event when a window
    # is first shown, so do it manually to make sure all event handlers get
    # pushed.
    if wx.Platform == '__WXMSW__':
        wx.PostEvent(frame, wx.ActivateEvent(wx.wxEVT_ACTIVATE, True))

    if 'splash' in locals():
        splash.Destroy()

    # Do update check, only check if its been more than a day since the last
    # check
    if profiler.Profile_Get('CHECKUPDATE', default=True):
        uthread = updater.UpdateThread(editra_app, ID_UPDATE_CHECK)
        uthread.start()

    for arg in args:
        try:
            arg = os.path.abspath(arg)
            fname = ed_txt.DecodeString(arg, sys.getfilesystemencoding())
            frame.DoOpen(ed_glob.ID_COMMAND_LINE_OPEN, fname)
        except IndexError:
            dev_tool.DEBUGP("[main][err] IndexError on commandline args")

    # 3. Start Applications Main Loop
    dev_tool.DEBUGP("[main][info] Starting MainLoop...")
    editra_app.MainLoop()
    dev_tool.DEBUGP("[main][info] MainLoop finished exiting application")
    os._exit(0)
コード例 #10
0
def InitConfig():
    """Initializes the configuration data
    @postcondition: all configuration data is set

    """
    ed_glob.CONFIG['PROFILE_DIR'] = util.ResolvConfigDir("profiles")
    profile_updated = False
    if util.HasConfigDir():
        if profiler.ProfileIsCurrent():
            profiler.Profile().Load(profiler.GetProfileStr())
        else:
            dev_tool.DEBUGP(
                "[InitConfig][info] Updating Profile to current version")

            # Load and update profile
            pstr = profiler.GetProfileStr()
            profiler.Profile().Load(pstr)
            profiler.Profile().Update()

            #---- Temporary Profile Adaptions ----#

            # GUI_DEBUG mode removed in 0.2.5
            mode = profiler.Profile_Get('MODE')
            if mode == 'GUI_DEBUG':
                profiler.Profile_Set('MODE', 'DEBUG')

            profiler.Profile_Del('LASTCHECK')
            #---- End Temporary Profile Adaptions ----#

            # Write out updated profile
            profiler.Profile().Write(pstr)

            # When upgrading from an older version make sure all
            # config directories are available.
            for cfg in ["cache", "styles", "plugins", "profiles"]:
                if not util.HasConfigDir(cfg):
                    util.MakeConfigDir(cfg)

            profile_updated = True
    else:
        # Fresh install
        util.CreateConfigDir()

        # Set default eol for windows
        if wx.Platform == '__WXMSW__':
            profiler.Profile_Set('EOL', 'Windows (\\r\\n)')

    # Set debug mode
    if 'DEBUG' in profiler.Profile_Get('MODE'):
        ed_glob.DEBUG = True

    # Resolve resource locations
    ed_glob.CONFIG['CONFIG_DIR'] = util.ResolvConfigDir("")
    ed_glob.CONFIG['SYSPIX_DIR'] = util.ResolvConfigDir("pixmaps", True)
    ed_glob.CONFIG['PLUGIN_DIR'] = util.ResolvConfigDir("plugins")
    ed_glob.CONFIG['THEME_DIR'] = util.ResolvConfigDir(
        os.path.join("pixmaps", "theme"))
    ed_glob.CONFIG['LANG_DIR'] = util.ResolvConfigDir("locale", True)
    ed_glob.CONFIG['STYLES_DIR'] = util.ResolvConfigDir("styles")
    ed_glob.CONFIG['SYS_PLUGIN_DIR'] = util.ResolvConfigDir("plugins", True)
    ed_glob.CONFIG['SYS_STYLES_DIR'] = util.ResolvConfigDir("styles", True)
    ed_glob.CONFIG['TEST_DIR'] = util.ResolvConfigDir(
        os.path.join("tests", "syntax"), True)
    if not util.HasConfigDir("cache"):
        util.MakeConfigDir("cache")
    ed_glob.CONFIG['CACHE_DIR'] = util.ResolvConfigDir("cache")

    return profile_updated
コード例 #11
0
            ) % ed_glob.VERSION
            os._exit(0)

        if True in [x[0] in ['-v', '--version'] for x in opts]:
            print "%s - v%s - Developers Editor" % (ed_glob.PROG_NAME, \
                                                    ed_glob.VERSION)
            os._exit(0)

        if True in [x[0] in ['-d', '--debug'] for x in opts]:
            ed_glob.DEBUG = True

    # We are ready to run so fire up the config and launch the app
    profile_updated = InitConfig()

    # Create Application
    dev_tool.DEBUGP("[main][info] Initializing Application...")
    editra_app = Editra(False)

    if profile_updated:
        # Make sure window iniliazes to default position
        profiler.Profile_Del('WPOS')
        wx.MessageBox(_("Your profile has been updated to the latest "
                        "version") + u"\n" + \
                      _("Please check the preferences dialog to reset "
                        "your preferences"),
                      _("Profile Updated"))

    # Splash a warning if version is not a final version
    if profiler.Profile_Get('APPSPLASH') and int(ed_glob.VERSION[0]) < 1:
        import edimage
        splash_img = edimage.splashwarn.GetBitmap()
コード例 #12
0
def InitConfig():
    """Initializes the configuration data
    @postcondition: all configuration data is set

    """
    # Look for a profile directory on the system level. If this directory exists
    # Use it instead of the user one. This will allow for running Editra from
    # a portable drive or for system administrators to enforce settings on a
    # system installed version.
    config_base = util.ResolvConfigDir(u'.Editra', True)
    if os.path.exists(config_base):
        ed_glob.CONFIG['CONFIG_BASE'] = config_base
        ed_glob.CONFIG['PROFILE_DIR'] = os.path.join(config_base, u"profiles")
        ed_glob.CONFIG['PROFILE_DIR'] += os.sep
    else:
        ed_glob.CONFIG['PROFILE_DIR'] = util.ResolvConfigDir("profiles")

    # Check for if config directory exists and if profile is from the current
    # running version of Editra.
    profile_updated = False
    if util.HasConfigDir() and os.path.exists(ed_glob.CONFIG['PROFILE_DIR']):
        if profiler.ProfileIsCurrent():
            profiler.Profile().Load(profiler.GetProfileStr())
        else:
            dev_tool.DEBUGP(
                "[InitConfig][info] Updating Profile to current version")

            # Load and update profile
            pstr = profiler.GetProfileStr()
            profiler.Profile().Load(pstr)
            profiler.Profile().Update()

            #---- Temporary Profile Adaptions ----#

            # GUI_DEBUG mode removed in 0.2.5
            mode = profiler.Profile_Get('MODE')
            if mode == 'GUI_DEBUG':
                profiler.Profile_Set('MODE', 'DEBUG')

            # This key has been removed so clean it from old profiles
            profiler.Profile_Del('LASTCHECK')

            # Print modes don't use strings anymore
            if isinstance(profiler.Profile_Get('PRINT_MODE'), basestring):
                profiler.Profile_Set('PRINT_MODE', ed_glob.PRINT_BLACK_WHITE)
            #---- End Temporary Profile Adaptions ----#

            # Write out updated profile
            profiler.Profile().Write(pstr)

            # When upgrading from an older version make sure all
            # config directories are available.
            for cfg in ["cache", "styles", "plugins", "profiles"]:
                if not util.HasConfigDir(cfg):
                    util.MakeConfigDir(cfg)

            profile_updated = True
    else:
        # Fresh install
        util.CreateConfigDir()

        # Set default eol for windows
        if wx.Platform == '__WXMSW__':
            profiler.Profile_Set('EOL', 'Windows (\\r\\n)')

    # Set debug mode
    if 'DEBUG' in profiler.Profile_Get('MODE'):
        ed_glob.DEBUG = True

    # Resolve resource locations
    ed_glob.CONFIG['CONFIG_DIR'] = util.ResolvConfigDir("")
    ed_glob.CONFIG['SYSPIX_DIR'] = util.ResolvConfigDir("pixmaps", True)
    ed_glob.CONFIG['PLUGIN_DIR'] = util.ResolvConfigDir("plugins")
    ed_glob.CONFIG['THEME_DIR'] = util.ResolvConfigDir(
        os.path.join("pixmaps", "theme"))
    ed_glob.CONFIG['LANG_DIR'] = util.ResolvConfigDir("locale", True)
    ed_glob.CONFIG['STYLES_DIR'] = util.ResolvConfigDir("styles")
    ed_glob.CONFIG['SYS_PLUGIN_DIR'] = util.ResolvConfigDir("plugins", True)
    ed_glob.CONFIG['SYS_STYLES_DIR'] = util.ResolvConfigDir("styles", True)
    ed_glob.CONFIG['TEST_DIR'] = util.ResolvConfigDir(
        os.path.join("tests", "syntax"), True)
    if not util.HasConfigDir("cache"):
        util.MakeConfigDir("cache")
    ed_glob.CONFIG['CACHE_DIR'] = util.ResolvConfigDir("cache")

    return profile_updated
コード例 #13
0
def InitConfig():
    """Initializes the configuration data
    @postcondition: all configuration data is set

    """
    # Look for a profile directory on the system level. If this directory exists
    # Use it instead of the user one. This will allow for running Editra from
    # a portable drive or for system administrators to enforce settings on a
    # system installed version.
    config_base = util.ResolvConfigDir(u'.Editra', True)
    if os.path.exists(config_base):
        ed_glob.CONFIG['CONFIG_BASE'] = config_base
        ed_glob.CONFIG['PROFILE_DIR'] = os.path.join(config_base, u"profiles")
        ed_glob.CONFIG['PROFILE_DIR'] += os.sep
    else:
        config_base = wx.StandardPaths.Get().GetUserDataDir()
        ed_glob.CONFIG['PROFILE_DIR'] = util.ResolvConfigDir("profiles")

    # Check for if config directory exists and if profile is from the current
    # running version of Editra.
    profile_updated = False
    if util.HasConfigDir() and os.path.exists(ed_glob.CONFIG['PROFILE_DIR']):
        if profiler.ProfileIsCurrent():
            profiler.Profile().Load(profiler.GetProfileStr())
        else:
            dev_tool.DEBUGP(
                "[InitConfig][info] Updating Profile to current version")

            # Load and update profile
            pstr = profiler.GetProfileStr()
            profiler.Profile().Load(pstr)
            profiler.Profile().Update()

            #---- Temporary Profile Adaptions ----#

            # GUI_DEBUG mode removed in 0.2.5
            mode = profiler.Profile_Get('MODE')
            if mode == 'GUI_DEBUG':
                profiler.Profile_Set('MODE', 'DEBUG')

            # This key has been removed so clean it from old profiles
            profiler.Profile_Del('LASTCHECK')

            # Print modes don't use strings anymore
            if isinstance(profiler.Profile_Get('PRINT_MODE'), basestring):
                profiler.Profile_Set('PRINT_MODE', ed_glob.PRINT_BLACK_WHITE)

            # Simplifications to eol mode persistance (0.4.0)
            TranslateEOLMode()

            #---- End Temporary Profile Adaptions ----#

            # Write out updated profile
            profiler.Profile().Write(pstr)

            # When upgrading from an older version make sure all
            # config directories are available.
            for cfg in ["cache", "styles", "plugins", "profiles"]:
                if not util.HasConfigDir(cfg):
                    util.MakeConfigDir(cfg)

            profile_updated = True
    else:
        # Fresh install
        util.CreateConfigDir()

        # Check and upgrade installs from old location
        success = True
        try:
            success = UpgradeOldInstall()
        except Exception, msg:
            dev_tool.DEBUGP("[InitConfig][err] %s" % msg)
            success = False

        if not success:
            old_cdir = u"%s%s.%s%s" % (wx.GetHomeDir(), os.sep,
                                       ed_glob.PROG_NAME, os.sep)
            msg = (
                "Failed to upgrade your old installation\n"
                "To retain your old settings you may need to copy some files:\n"
                "\nFrom: %s\n\nTo: %s") % (old_cdir, config_base)
            wx.MessageBox(msg, "Upgrade Failed", style=wx.ICON_WARNING | wx.OK)

        # Set default eol for windows
        if wx.Platform == '__WXMSW__':
            profiler.Profile_Set('EOL', 'CRLF')
            profiler.Profile_Set('ICONSZ', (16, 16))