Пример #1
0
    def OnCallees(self, event):
        if self.selected > -1:
            idx = self.getStatIdx()
            key = self.statKeyList[idx]
#            callDct = self.stats[key][4]

            self.calc_callees()
            if self.all_callees.has_key(key):
                callDct = self.all_callees[key]

                called = [`x[1]`+': '+x[0][2]+' | '+os.path.basename(os.path.splitext(x[0][0])[0])
                          for x in callDct.items()]
                 
                dlg = wx.SingleChoiceDialog(self.model.editor, _('Choose a function:'),
                  _('%s called...') % self.statKeyList[idx][2], called)
                try:
                    if dlg.ShowModal() == wx.ID_OK:
                        idx = called.index(dlg.GetStringSelection())
                        key = callDct.keys()[idx]

                        for i in range(self.GetItemCount()):
                            if self.statKeyList[self.GetItemData(i)] == key:
                                self.SetItemState(i,
                                  wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED,
                                  wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
                                self.EnsureVisible(i)
                finally:
                    dlg.Destroy()
Пример #2
0
    def addCollView(self, name, collInitMethod, create):
        comp, ctrl = self.objects[name][:2]
        collName = getCollName(collInitMethod, name)
        try:
            collCompClass = comp.subCompanions[collName]
        except KeyError:
            raise Exception, _('Sub-Companion not found for %s in %s')%(name, collInitMethod)
        collComp = collCompClass(name, self, comp, ctrl)
        if create:
            collComp.persistCollInit(collInitMethod, name, collName)

        collInit = self.model.objectCollections[collInitMethod]
        collComp.setConstrs(collInit.creators, collInit.initialisers,
          collInit.finalisers)

        # init DTCtrl
        for crt in collComp.textConstrLst:
            collComp.applyDesignTimeDefaults(crt.params, crt.method)
        collComp.initCollection()

        comp.collections[collName] = collComp

        collEditView = CollectionEdit.CollectionEditorView(self, self.inspector,
            self.model, collComp)
        collEditView.initialise()

        self.collEditors[(comp.name, collName)] = collEditView
Пример #3
0
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_MODULEFINDERDLG,
              name='ModuleFinderDlg', parent=prnt, pos=wx.Point(858, 575),
              size=wx.Size(317, 135),
              style=wx.RESIZE_BORDER | wx.DEFAULT_DIALOG_STYLE,
              title=_('Module finder for sys.path'))
        self.SetClientSize(wx.Size(309, 106))
        self.Center(wx.BOTH)

        self.staticText1 = wx.StaticText(id=wxID_MODULEFINDERDLGSTATICTEXT1,
              label=_('Module name:'), name='staticText1', parent=self,
              pos=wx.Point(10, 10), size=wx.Size(289, 16), style=0)

        self.txtModuleName = wx.TextCtrl(id=wxID_MODULEFINDERDLGTXTMODULENAME,
              name='txtModuleName', parent=self, pos=wx.Point(10, 36),
              size=wx.Size(289, 21), style=0, value='')

        self.okBtn = wx.Button(id=wx.ID_OK, label=_('OK'), name='okBtn',
              parent=self, pos=wx.Point(139, 67), size=wx.Size(75, 23),
              style=0)
        self.okBtn.SetDefault()

        self.cancelBtn = wx.Button(id=wx.ID_CANCEL, label=_('Cancel'),
              name='cancelBtn', parent=self, pos=wx.Point(224, 67),
              size=wx.Size(75, 23), style=0)

        self._init_sizers()
Пример #4
0
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_KEYDEFSDIALOG, name='KeyDefsDialog',
              parent=prnt, pos=wx.Point(430, 271), size=wx.Size(298, 184),
              style=wx.DEFAULT_DIALOG_STYLE, title=self.entryTitle)
        self.SetClientSize(wx.Size(290, 157))

        self.staticBox1 = wx.StaticBox(id=wxID_KEYDEFSDIALOGSTATICBOX1,
              label='Flags', name='staticBox1', parent=self, pos=wx.Point(8, 8),
              size=wx.Size(136, 96), style=0)

        self.ctrlFlagChb = wx.CheckBox(id=wxID_KEYDEFSDIALOGCTRLFLAGCHB,
              label='wx.ACCEL_CTRL', name='ctrlFlagChb', parent=self,
              pos=wx.Point(16, 24), size=wx.Size(120, 19), style=0)
        self.ctrlFlagChb.Bind(wx.EVT_CHECKBOX, self.OnUpdateShortcut,
              id=wxID_KEYDEFSDIALOGCTRLFLAGCHB)

        self.altFlagChb = wx.CheckBox(id=wxID_KEYDEFSDIALOGALTFLAGCHB,
              label='wx.ACCEL_ALT', name='altFlagChb', parent=self,
              pos=wx.Point(16, 48), size=wx.Size(120, 19), style=0)
        self.altFlagChb.Bind(wx.EVT_CHECKBOX, self.OnUpdateShortcut,
              id=wxID_KEYDEFSDIALOGALTFLAGCHB)

        self.shiftFlagChb = wx.CheckBox(id=wxID_KEYDEFSDIALOGSHIFTFLAGCHB,
              label='wx.ACCEL_SHIFT', name='shiftFlagChb', parent=self,
              pos=wx.Point(16, 72), size=wx.Size(120, 19), style=0)
        self.shiftFlagChb.Bind(wx.EVT_CHECKBOX, self.OnUpdateShortcut,
              id=wxID_KEYDEFSDIALOGSHIFTFLAGCHB)

        self.keyCodeCbb = wx.ComboBox(choices=self.preDefKeys,
              id=wxID_KEYDEFSDIALOGKEYCODECBB, name='keyCodeCbb', parent=self,
              pos=wx.Point(152, 32), size=wx.Size(125, 21), style=0, value='')
        self.keyCodeCbb.Bind(wx.EVT_COMBOBOX, self.OnUpdateShortcutKeyCodeCbb,
              id=wxID_KEYDEFSDIALOGKEYCODECBB)
        self.keyCodeCbb.Bind(wx.EVT_TEXT, self.OnUpdateShortcutKeyCodeCbb,
              id=wxID_KEYDEFSDIALOGKEYCODECBB)

        self.staticText1 = wx.StaticText(id=wxID_KEYDEFSDIALOGSTATICTEXT1,
              label=_('Key code:'), name='staticText1', parent=self,
              pos=wx.Point(152, 16), size=wx.Size(120, 13), style=0)

        self.staticText2 = wx.StaticText(id=wxID_KEYDEFSDIALOGSTATICTEXT2,
              label=_('Shortcut text:'), name='staticText2', parent=self,
              pos=wx.Point(152, 64), size=wx.Size(120, 13), style=0)

        self.shortcutTc = wx.TextCtrl(id=wxID_KEYDEFSDIALOGSHORTCUTTC,
              name='shortcutTc', parent=self, pos=wx.Point(152, 80),
              size=wx.Size(124, 21), style=0, value='')

        self.okBtn = wx.Button(id=wxID_KEYDEFSDIALOGOKBTN, label=_('OK'),
              name='okBtn', parent=self, pos=wx.Point(120, 120),
              size=wx.Size(75, 23), style=0)
        self.okBtn.Bind(wx.EVT_BUTTON, self.OnOkbtnButton,
              id=wxID_KEYDEFSDIALOGOKBTN)

        self.cancelBtn = wx.Button(id=wxID_KEYDEFSDIALOGCANCELBTN,
              label=_('Cancel'), name='cancelBtn', parent=self, pos=wx.Point(200,
              120), size=wx.Size(75, 23), style=0)
        self.cancelBtn.Bind(wx.EVT_BUTTON, self.OnCancelbtnButton,
              id=wxID_KEYDEFSDIALOGCANCELBTN)
Пример #5
0
    def saveAs(self, filename):
        # catch image type changes
        newExt = os.path.splitext(filename)[1].lower()
        oldExt = os.path.splitext(self.filename)[1].lower()
        updateViews = 0
        if newExt != oldExt:
            updateViews = 1
            import cStringIO

            bmp = wx.BitmapFromImage(wx.ImageFromStream(cStringIO.StringIO(self.data)))
            fn = tempfile.mktemp(newExt)
            try:
                bmp.SaveFile(fn, self.extTypeMap[newExt])
            except KeyError:
                raise Exception, _("%s image file types not supported") % newExt
            try:
                # convert data to new image format
                self.data = open(fn, "rb").read()
            finally:
                os.remove(fn)

        # Actually save the file
        PersistentModel.saveAs(self, filename)

        if updateViews:
            self.notify()
Пример #6
0
def matchbracket(text, findBracket, dir=None):
    if findBracket in containBegin or (dir is not None and dir == -1):
        dir = -1
        start = len(text)-1
        end = -1
        brktIdx = containBegin.index(findBracket)
    elif findBracket in containEnd or (dir is not None and dir == 1):
        dir = 1
        start = 0
        end = len(text)
        brktIdx = containEnd.index(findBracket)
    else:
        raise Exception, _('Unhandled bracket')

    # () {} []
    levels = [0, 0, 0]

    for cIdx in range(start, end, dir):
        c = text[cIdx]
        if c in containBegin:
            idx = containBegin.index(c)
            levels[idx] = levels[idx] + dir
        elif c in containEnd:
            idx = containEnd.index(c)
            levels[idx] = levels[idx] - dir

        if levels[brktIdx] < 0:
            return cIdx
    return -1
Пример #7
0
    def __init__(self, line=None, comp_name='', prop_setter='', params=None, prop_name=''):
        self.comp_name = comp_name
        self.prop_setter = prop_setter
        if params is None: self.params = []
        else:              self.params = params
        self.params = params
        self.prop_name = prop_name
        if line:
            self.m = is_prop.search(line)
            if self.m:
                self.checkContinued(line)
                self.params = safesplitfields(self.m.group('params'), ',')
                compsetter = self.m.group('name').split('.')

                if len(compsetter) < 1: raise Exception, _('Atleast 1 segment required, got: %r')%compsetter
                if len(compsetter) == 1:
                    self.comp_name = ''
                    self.prop_setter = compsetter[0]
                elif len(compsetter) == 2:
                    self.comp_name = compsetter[0]
                    self.prop_setter = compsetter[1]
                else: raise Exception, _('Too many attribute levels')
                
                if self.prop_setter == 'Bind':
                    self.m = None
Пример #8
0
    def OnJump(self, event):
        idx = len(self.stackView.stack)-1
        if idx < 0:
            wx.LogError(_('No stack available!'))
            return

        self.stackView.Select(idx)
        self.stackView.OnGotoSource()
        dlg = wx.TextEntryDialog(self, _('Enter line number to jump to:'),
              _('Debugger - Jump'), str(self.stackView.stack[idx]['lineno']))
        try:
            if dlg.ShowModal() != wx.ID_OK:
                return

            lineno = int(dlg.GetValue())
        finally:
            dlg.Destroy()

        #self.doDebugStep('set_step_jump', args=(lineno,))
        self.clearStepPos()
        self.invalidatePanes()
        self.updateSelectedPane(do_request=0)
        if not self.isRunning():
            self.runProcess()
        else:
            self.proceedAndRequestStatus('set_step_jump', None, (lineno,))
 def setStatus(self, mo):
     if mo:
         self.statusBar.SetStatusText(_('Match'), 1)
         self.sbImage.SetBitmap(self.statusImages[1])
     else:
         self.statusBar.SetStatusText(_('Failed to match'), 1)
         self.sbImage.SetBitmap(self.statusImages[0])
Пример #10
0
    def __init__(self, parent, model, actions = ()):
        ScrollingContainer.__init__(self, parent, wx.Size(self.defSize, self.defSize))
        EditorViews.EditorView.__init__(self, model,
          ((_('(Re)load diagram'), self.OnLoad, self.loadBmp, ''),
           (_('Save diagram'), self.OnSave, self.saveBmp, ''),
           (_('Print diagram to PostScript'), self.OnPrintToPS, '-', ''), 
           ('-', None, '-', ''),
           (_('Change size'), self.OnSetSize, '-', ''),
           )+actions)

        self.shapes = []
        self.canvas = PersistentShapeCanvas(self, self.shapes)
        self.canvas.SetSize(self.GetVirtualSize())

        self.canvas.Bind(wx.EVT_RIGHT_UP, self.OnRightClick)

        self.diagram = ogl.Diagram()
        self.canvas.SetDiagram(self.diagram)
        self.diagram.SetCanvas(self.canvas)

        self.shapeMenu = None

        self.size = self.defSize

        self._loaded = False

        self.active = True
Пример #11
0
    def clientFNToServerFN(self, filename):
        """Converts a filename on the client to a filename on the server.

        Currently just turns file URLs into paths.  If you want to be able to
        set breakpoints when running the client in a different environment
        from the server, you'll need to expand this.
        """
        # XXX should we .fncache this? Files changing names are undefined
        # XXX during the lifetime of the debugger

        from Explorers.Explorer import splitURI, getTransport
        from Explorers.ExplorerNodes import all_transports

        prot, category, filepath, filename = splitURI(filename)
        if prot == 'zope':
            node = getTransport(prot, category, filepath, all_transports)
            if node:
                props = node.properties
                return 'zopedebug://%s:%s/%s/%s'%(props['host'],
                      props['httpport'], filepath, node.metatype)
            else:
                raise Exception(_('No Zope connection for: %s')%filename)
        elif prot == 'zopedebug':
            raise Exception(_('"zopedebug" is a server filename protocol'))
        else:
        #if prot == 'file':
            if self.serverClientPaths:
                normFilepath = os.path.normcase(filepath)
                for serverPath, clientPath in self.serverClientPaths:
                    normClientPath = os.path.normcase(clientPath)
                    if normFilepath.startswith(normClientPath):
                        return serverPath+normFilepath[len(normClientPath):]
            return filepath
    def importInShell(self):
        modDir, modFile = os.path.split(self.assertLocalFile())
        modName = os.path.splitext(modFile)[0]
        if self.app:
            execDir = os.path.dirname(self.app.assertLocalFile())
            if execDir != modDir:
                p, m = os.path.split(relpath.relpath(execDir, self.assertLocalFile()))
                p = p.replace('/', '.')
                p = p.replace('\\', '.')
                pckName = p
                impExecStr = 'from %s import %s'%(pckName, modName)
            else:
                impExecStr = 'import %s'%modName

        else:
            execDir = modDir
            impExecStr = 'import %s'%modName

        shell = self.editor.shell
        if execDir not in sys.path:
            sys.path.append(execDir)
            shell.pushLine("print '## Appended to sys.path'")
        else:
            info = ''

        shell.pushLine(impExecStr, impExecStr)
        if shell.lastResult != 'stderr':
            return _('Import of %s successfull')%modName, 'Info'
        else:
            return _('Import of %s failed')%modName, 'Error'
Пример #13
0
    def loadSizes(self, filename):
        from Explorers.Explorer import openEx, TransportError
        t = openEx(filename)
        try:
            persProps = pickle.loads(t.load())
        except SyntaxError:
            if wx.MessageBox(_('%s is possibly corrupt (cannot be unpickled), delete it?'\
                  'Default layout will be used.')%filename, _('Corrupt file'), 
                  style = wx.YES_NO | wx.ICON_EXCLAMATION) == wx.YES:
                # XXX update to use transport !!
                if filename[:7] != 'file://':
                    wx.LogMessage(_('Sorry, only supported on the filesystem'))
                else:
                    os.remove(filename[7:])

            raise TransportError(_('Corrupt layout file'))

        unmatchedPcls = persProps.keys()
        matchedShapes = []

        for shape in self.shapes:
            if persProps.has_key(shape.unqPclName):
                unmatchedPcls.remove(shape.unqPclName)
            else:
                unmatchedPcls.append(shape.unqPclName)

        for shape in self.shapes:
            if persProps.has_key(shape.unqPclName):
                pos = persProps[shape.unqPclName]
                shape.setPos(pos)

        self.redraw()
    def reindent(self, updateModulePage=True):
        from ExternalLib import reindent
        self.refreshFromViews()
        eol = Utils.getEOLMode(self.data)
        file = SourcePseudoFile(self.getDataAsLines())
        ri = reindent.Reindenter(file, eol=eol)
        try:
            if ri.run():
                file.output = []
                ri.write(file)

                newData = ''.join(file.output)
                modified = self.data != newData
                self.modified = self.modified or modified

                if modified:
                    self.data = newData
                    if updateModulePage:
                        self.editor.updateModulePage(self)
                    self.update()
                    self.notify()

                    self.editor.statusBar.setHint(
                     _('Code reformatted (indents and or EOL characters fixed)'))
                    return True
        except Exception, error:
            self.editor.statusBar.setHint(
             _('Reindent failed - %s : %s') % (error.__class__, str(error)) , 'Error')
    def disassembleSource(self):
        import dis
        try:
            code = compile(self.data, self.filename, 'exec')
        except:
            oldOut = sys.stdout
            sys.stdout = Utils.PseudoFileOutStore()
            try:
                print _("''' Code does not compile\n\n    Disassembly of Traceback:\n'''")
                try:
                    dis.distb(sys.exc_info()[2])
                except:
                    print _("''' Could not disassemble traceback '''\n")
                return sys.stdout.read()
            finally:
                sys.stdout = oldOut

        oldOut = sys.stdout
        sys.stdout = Utils.PseudoFileOutStore()
        try:
            try:
                dis.disco(code)
            except:
                raise
            return sys.stdout.read()
        finally:
            sys.stdout = oldOut

        return 'Invisible code'
Пример #16
0
    def saveOrSaveAs(self, forceSaveAs=False):
        model = self.model
        editor = self.editor
        if forceSaveAs or not model.savedAs:
            oldName = model.filename
            if self.saveAs(oldName) and (oldName != model.filename):
                self.rename(oldName, model.filename)

                editor.statusBar.setHint(_('%s saved.')%\
                      os.path.basename(model.filename))
        else:
            from Explorers.ExplorerNodes import TransportModifiedSaveError
            try:
                model.save()
            except TransportModifiedSaveError, err:
                choice = wx.MessageBox(_('%s\nDo you want to overwrite these '
                  'changes (Yes), reload your file (No) or cancel this operation '
                  '(Cancel)?')%str(err), _('Overwrite newer file warning'),
                  wx.YES_NO | wx.CANCEL | wx.ICON_WARNING)
                if choice == wx.YES:
                    model.save(overwriteNewer=True)
                elif choice == wx.NO:
                    raise TransportModifiedSaveError('Reload')
                elif choice == wx.CANCEL:
                    raise TransportModifiedSaveError('Cancel')

            editor.updateModulePage(model)
            editor.updateTitle()

            editor.statusBar.setHint(_('%s saved.')%\
                  os.path.basename(model.filename))
    def cyclops(self, args='', execStart=None, execFinish=None):
        """ Run the saved application thru Cyclops """
        if self.savedAs:
            cwd = os.path.abspath(os.getcwd())
            filename = self.assertLocalFile()
            os.chdir(os.path.dirname(filename))
            page = ''
            try:
                name = os.path.basename(filename)
                report = tempfile.mktemp()

                # execute Cyclops in Python with module as parameter
                command = '"%s" "%s" "%s" "%s"'%(
                      Preferences.getPythonInterpreterPath(),
                      Utils.toPyPath('RunCyclops.py'), name, report)
                wx.Execute(command, True)

                # read report that Cyclops generated
                page = open(report, 'r').read()
                os.remove(report)
            finally:
                os.chdir(cwd)
                return page
        else:
            wx.LogWarning(_('Save before running Cyclops'))
            raise Exception, _('Not saved yet!')
    def _init_coll_lcInstallations_Columns(self, parent):
        # generated method, don't edit

        parent.InsertColumn(col=0, format=wx.LIST_FORMAT_LEFT,
              heading=_('Version'), width=60)
        parent.InsertColumn(col=1, format=wx.LIST_FORMAT_LEFT,
              heading=_('Install Path'), width=170)
Пример #19
0
    def OnConfigPyChecker(self, event):
        model = self.getModel()
        if model:
            home = os.environ.get('HOME')
            if home:
                appDir = home
                appConfig = home+'/.pycheckrc'
            else:
                filename = model.assertLocalFile()
                appDir = os.path.dirname(filename)
                appConfig = appDir+'/.pycheckrc'
            if not os.path.exists(appConfig):
                dlg = wx.MessageDialog(self.editor, _('The PyChecker configuration file '
                  'can not be found. Copy the default file here?'),
                  _('Config file not found'), wx.YES_NO | wx.ICON_QUESTION)
                try:
                    if dlg.ShowModal() == wx.ID_YES:
                        from pychecker import Config
                        open(appConfig, 'w').write(Config.outputRc(Config.Config()))
                    else:
                        return
                finally:
                    dlg.Destroy()

            from Explorers.PrefsExplorer import SourceBasedPrefColNode
            SourceBasedPrefColNode('PyChecker', ('*',), appConfig, -1, None).open(self.editor)
Пример #20
0
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self, id=wxID_PATHSPANEL, name='PathsPanel',
              parent=prnt, pos=wx.Point(316, 277), size=wx.Size(523, 274),
              style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(515, 247))

        self.staticBox1 = wx.StaticBox(id=wxID_PATHSPANELSTATICBOX1,
              label=_('Server to client filepath mappings'), name='staticBox1',
              parent=self, pos=wx.Point(0, 0), size=wx.Size(515, 247), style=0)

        self.grid = wx.grid.Grid(id=wxID_PATHSPANELGRID, name='grid',
              parent=self, pos=wx.Point(13, 25), size=wx.Size(489, 169),
              style=wx.SUNKEN_BORDER)
        self.grid.SetDefaultRowSize(20)
        self.grid.SetColLabelSize(20)
        self.grid.SetRowLabelSize(0)

        self.add_btn = wx.Button(id=wxID_PATHSPANELADD_BTN, label=_('Add'),
              name='add_btn', parent=self, pos=wx.Point(344, 210),
              size=wx.Size(75, 24), style=0)
        self.add_btn.Bind(wx.EVT_BUTTON, self.OnAdd_btnButton,
              id=wxID_PATHSPANELADD_BTN)

        self.remove_btn = wx.Button(id=wxID_PATHSPANELREMOVE_BTN,
              label=_('Remove'), name='remove_btn', parent=self, pos=wx.Point(427,
              210), size=wx.Size(75, 24), style=0)
        self.remove_btn.Bind(wx.EVT_BUTTON, self.OnRemove_btnButton,
              id=wxID_PATHSPANELREMOVE_BTN)

        self._init_sizers()
Пример #21
0
 def findInFiles(self):
     names = []
     pattern = self.findTxt.GetValue()
     bRecursive = self.chkRecursiveSearch.GetValue()
     file_filter = string.split(self.cmbFileFilter.GetValue(), ';')
     folder = [self.cmbFolder.GetValue()]
     self.engine.addFolder(folder[0])
     self.engine.addSuffix(self.cmbFileFilter.GetValue())
     dlg = wx.ProgressDialog(_("Building file list from directory '%s'") % (folder[0]),
                    _('Searching...'), 100, self.view,
                     wx.PD_CAN_ABORT | wx.PD_APP_MODAL | wx.PD_AUTO_HIDE)
     try:
         iterDirFiles = Search.listFiles(folder, file_filter, 1, bRecursive)
         iStep = 0
         for sFile in iterDirFiles:
             names.append(sFile)
             if iStep < 100 and not dlg.Update(iStep):
                 #self.view.model.editor.setStatus('Search aborted')
                 break
             iStep = iStep + 1
     finally:
         dlg.Destroy()
     self.engine.findAllInFiles(names, self.view, pattern )
     self.setComboBoxes('findInFiles')
     if self.engine.closeOnFound:
         self.EndModal(wx.ID_OK)
Пример #22
0
    def displayDiff(self, diffResult):
        if not self.diffPage:
            self.diffPage = wx.stc.StyledTextCtrl(self.notebook, -1,
                style=wx.SUNKEN_BORDER | wx.CLIP_CHILDREN)
            self.diffPage.SetMarginWidth(1, 0)
            self.diffPage.SetLexer(wx.stc.STC_LEX_DIFF)
            self.diffPage.StyleClearAll()
            # XXX Should be moved to StyleEditor
            fontPropStr = 'face:%s,size:%d'%(
                       Preferences.eoErrOutFont.GetFaceName(),
                       Preferences.eoErrOutFont.GetPointSize())
            for num, style in (
                  (wx.stc.STC_DIFF_DEFAULT,  fontPropStr),
                  (wx.stc.STC_DIFF_COMMENT,  fontPropStr+',back:#EEEEFF'),      # comment
                  (wx.stc.STC_DIFF_COMMAND,  fontPropStr+',fore:#FFFFCC,back:#000000,bold'), #diff
                  (wx.stc.STC_DIFF_HEADER,   fontPropStr+',back:#FFFFCC'),      #"--- ","+++ ",
                  (wx.stc.STC_DIFF_POSITION, fontPropStr+',back:#CCCCFF,bold'), #'@'
                  (wx.stc.STC_DIFF_DELETED,  fontPropStr+',back:#FFCCCC'),      #'-'
                  (wx.stc.STC_DIFF_ADDED,    fontPropStr+',back:#CCFFCC'),      #'+'
                 ):
                self.diffPage.StyleSetSpec(num, style)
            self.diffPage.SetText(diffResult)
            self.notebook.AddPage(text=_('Diffs'), select=not not diffResult,
                page=self.diffPage, imageId=self.diffImgIdx)
            self.menu.Enable(wxID_EO_CLOSEDIFF, True)
        else:
            self.diffPage.SetText(diffResult)
            if diffResult:
                pageIdx = self.findPage(_('Diffs'))
                if pageIdx != -1:
                    self.notebook.SetSelection(pageIdx)

        self.display()
Пример #23
0
    def OnMakeHTB(self, event):
        model = self.getModel()
        dlg = wx.SingleChoiceDialog(model.editor, _('Choose source files'),
              _('Make HTB'), [_('Files list'), _('Entire help book directory')])
        try:
            if dlg.ShowModal() != wx.ID_OK:
                return
            selected = dlg.GetSelection()
        finally:
            dlg.Destroy()

        modelFile = model.localFilename()
        zipfilename = os.path.splitext(modelFile)[0]+'.htb'

        docsDir = os.path.dirname(modelFile)
        if selected == 0:
            files = [os.path.join(docsDir, f) for f in model.config.files]
        elif selected == 1:
            files = []
            os.path.walk(docsDir, visitDir,
                         (files, [os.path.basename(zipfilename)]))

        wx.BeginBusyCursor()
        zf = zipfile.ZipFile(zipfilename, 'w', zipfile.ZIP_DEFLATED)
        try:
            for filename in files:
                zf.write(filename, filename[len(docsDir)+1:])
        finally:
            wx.EndBusyCursor()
            zf.close()

        wx.LogMessage(_('Written %s.')%zipfilename)
Пример #24
0
    def readComponents(self):
        """ Setup object collection dict by parsing all designer controlled methods """
        module = self.getModule()
        # Parse all _init_* methods
        self.objectCollections = {}
        if module.classes.has_key(self.main):
            main = module.classes[self.main]

            self.specialAttrs = self.readSpecialAttrs(module, main)
            self.customClasses = self.readCustomClasses(module, main)
            self.resources = self.readResources(module, main, 
                  specialAttrs=self.specialAttrs)

            for oc in self.identifyCollectionMethods():
                codeSpan = main.methods[oc]
                codeBody = module.source[codeSpan.start : codeSpan.end]

                self.objectCollections[oc] = self.readDesignerMethod(oc, codeBody)

                # XXX Hack: This should not be necessary !!
                for prop in self.objectCollections[oc].properties[:]:
                    if prop.asText() in ('self.%s()'%sourceconst.init_utils, 
                                         'self.%s()'%sourceconst.init_sizers):
                        self.objectCollections[oc].properties.remove(prop)

            # Set the model's constructor
            if self.objectCollections.has_key(sourceconst.init_ctrls):
                try:
                    self.mainConstr = \
                      self.objectCollections[sourceconst.init_ctrls].creators[0]
                except IndexError:
                    Exception, _('Inherited __init__ method missing')
        else:
            Exception, _('Main class "%s" not found. Please fix file header or class name.')%self.main
Пример #25
0
    def __init__(self, parent, debugger, is_local, name):
        DebuggerListCtrl.__init__(self, parent, wxID_NSVIEW)

        self.InsertColumn(0, _("Attribute"), wx.LIST_FORMAT_LEFT, 125)
        self.InsertColumn(1, _("Value"), wx.LIST_FORMAT_LEFT, 200)

        self.is_local = is_local

        self.menu = wx.Menu()

        idAs = wx.NewId()
        idA = wx.NewId()
        self.menu.Append(idAs, _("Add as watch"))
        self.menu.Append(idA, _("Add a %s watch") % name)
        self.Bind(wx.EVT_MENU, self.OnAddAsWatch, id=idAs)
        self.Bind(wx.EVT_MENU, self.OnAddAWatch, id=idA)
        outputId = wx.NewId()
        self.menu.Append(outputId, _("Write value to Output"))
        self.Bind(wx.EVT_MENU, self.OnValueToOutput, id=outputId)

        self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)

        self.pos = None

        self.setPopupMenu(self.menu)

        self.repr = Repr()
        self.repr.maxstring = 100
        self.repr.maxother = 100
        self.names = []

        self.debugger = debugger
Пример #26
0
    def OnSTCSettings(self, event):
        menu = wx.Menu()
        menu.Append(wxID_STC_WS, _('View Whitespace'), '', 1) #checkable
        menu.Check(wxID_STC_WS, self.GetViewWhiteSpace())
        menu.Append(wxID_STC_BUF, _('Buffered draw'), '', 1) #checkable
        menu.Check(wxID_STC_BUF, self.GetBufferedDraw())
        menu.Append(wxID_STC_IDNT, _('Use indentation guides'), '', 1) #checkable
        menu.Check(wxID_STC_IDNT, self.GetIndentationGuides())
        menu.Append(wxID_STC_EOL, _('View EOL symbols'), '', 1) #checkable
        menu.Check(wxID_STC_EOL, self.GetViewEOL())
        menu.AppendSeparator()

        eolModeMenu = wx.Menu()
        eolModeMenu.Append(wxID_STC_EOL_CRLF, 'CRLF', '', kind=wx.ITEM_RADIO)
        eolModeMenu.Check(wxID_STC_EOL_CRLF, self.GetEOLMode() == wx.stc.STC_EOL_CRLF)
        eolModeMenu.Append(wxID_STC_EOL_LF, 'LF', '', kind=wx.ITEM_RADIO)
        eolModeMenu.Check(wxID_STC_EOL_LF, self.GetEOLMode() == wx.stc.STC_EOL_LF)
        eolModeMenu.Append(wxID_STC_EOL_CR, 'CR', '', kind=wx.ITEM_RADIO)
        eolModeMenu.Check(wxID_STC_EOL_CR, self.GetEOLMode() == wx.stc.STC_EOL_CR)

        menu.AppendMenu(wxID_STC_EOL_MODE, _('EOL mode'), eolModeMenu)

        s = self.GetClientSize()

        self.PopupMenuXY(menu, s.x/2, s.y/2)
        menu.Destroy()
Пример #27
0
    def persistConstr(self, className, params):
        paramStrs = []
        for param in params.keys():
            paramStrs.append('%s = %s'%(param, params[param]))

        if not self.textConstr:
            xrcObjs = self.designer.getObjectsOfClass(wx.xrc.XmlResource)
            names = xrcObjs.keys()
            if names:
                dlg = wx.SingleChoiceDialog(self.designer, 
                      _('Select wx.xrc.XmlResource to LoadPanel from'),
                      'wx.xrc.XmlResource.LoadPanel', names)
                try:
                    if dlg.ShowModal() == wx.ID_OK:
                        xrcObj = dlg.GetStringSelection()
                        self.xmlResource = xrcObj.split('.')[1]
                    else:
                        raise Exception, 'Cancelled!'
                finally:
                    dlg.Destroy()
            else:
                raise Exception, _('No wx.xrc.XmlResource objects found')
        else:
            self.xmlResource = self.textConstr.factory[0]

        self.textConstr = methodparse.ConstructorParse(
            'self.%s = self.%s.LoadPanel(%s)'%(self.name, self.xmlResource,
            ', '.join(paramStrs)))

        self.designer.addCtrlToObjectCollection(self.textConstr)
Пример #28
0
    def OnAddFiles(self, event):
        helpBookDir = os.path.dirname(self.model.localFilename())
        dlg = wx.DirDialog(self)
        try:
            dlg.SetPath(helpBookDir)
            if dlg.ShowModal() != wx.ID_OK:
                return
            dir = dlg.GetPath()
        finally:
            dlg.Destroy()

        if not dir.startswith(helpBookDir):
            wx.LogError(self.helpBookDirMsg)
            return

        dlg = wx.TextEntryDialog(self, _('Enter wildcard'), _('Add Files'), '*.*')
        try:
            if dlg.ShowModal() != wx.ID_OK:
                return
            globStr = dlg.GetValue()
        finally:
            dlg.Destroy()

        files = glob.glob(os.path.join(dir, globStr))

        for filename in files:
            self.model.config.files.append(filename[len(helpBookDir)+1:])

        self.refreshCtrl()
        self.updateOtherViews()

        self.model.setModified()
        self.updateEditor()
Пример #29
0
    def __init__(self, parent, model):
        ListCtrlView.__init__(
            self,
            parent,
            model,
            wx.LC_REPORT,
            (
                (_("Open"), self.OnOpen, self.openBmp, ""),
                ("-", None, "", ""),
                (_("Add"), self.OnAdd, self.addModBmp, "Insert"),
                (_("Edit"), self.OnEdit, "-", ""),
                (_("Remove"), self.OnRemove, self.remModBmp, "Delete"),
                ("-", None, "", ""),
                (_("Find"), self.OnFind, self.findBmp, "Find"),
                ("-", None, "-", ""),
                (_("Make module main module"), self.OnMakeMain, "-", ""),
            ),
            0,
        )

        self.InsertColumn(0, _("Module"), width=150)
        self.InsertColumn(1, _("Type"), width=50)
        self.InsertColumn(2, _("Description"), width=150)
        self.InsertColumn(3, _("Relative path"), width=220)

        self.sortOnColumns = [0, 1, 3]

        self.SetImageList(model.editor.modelImageList, wx.IMAGE_LIST_SMALL)

        self.lastSearchPattern = ""
        self.active = True
        self.canExplore = True
        self.model = model
    def parse_response(self, f, sock=None):
        # read response from input file, and parse it
        # If there was no response, raise a special exception.
        got_data = 0

        p, u = self.getparser()

        while 1:
            if sock:
                response = sock.recv(1024)
            else:
                response = f.read(1024)
            if not response:
                break
            else:
                got_data = 1
            if self.verbose:
                print "body:", repr(response)
            p.feed(response)

        f.close()
        if not got_data:
            raise EmptyResponseError, _('Empty response from debugger process')

        p.close()
        return u.close()
Пример #31
0
    def OnOkbtnButton(self, event):
        hor = 0
        ver = 1
        self.choices = (self.radioBox1.GetStringSelection(),
                        self.radioBox2.GetStringSelection())

        selIdx = 0
        if len(self.selection):
            firstSel = self.selection[0]
            lastSel = self.selection[-1]
            firstSelPos = firstSel.position
            lastSelPos = lastSel.position
            selSize = len(self.selection)
        for sel in self.selection:
            domove = False
            newX, newY = sel.position.x, sel.position.y

            if self.choices[hor] == _('Left sides'):
                if sel != firstSel:
                    domove = True
                    newX = firstSelPos.x
            elif self.choices[hor] == _('Centers'):
                if sel != firstSel:
                    domove = True
                    newX = firstSelPos.x + firstSel.size.x / 2 - sel.size.x / 2
            elif self.choices[hor] == _('Right sides'):
                if sel != firstSel:
                    domove = True
                    newX = firstSelPos.x + firstSel.size.x - sel.size.x
            elif self.choices[hor] == _('Space equally'):
                if sel != firstSel and sel != lastSel:
                    domove = True
                    newX = (lastSelPos.x - firstSelPos.x) / (selSize-1) * selIdx \
                           + firstSelPos.x
#            elif self.choices[hor] == 'Center in window': pass # not implemented

            if self.choices[ver] == _('Tops'):
                if sel != firstSel:
                    domove = True
                    newY = firstSelPos.y
            elif self.choices[ver] == _('Centers'):
                if sel != firstSel:
                    domove = True
                    newY = firstSelPos.y + firstSel.size.y / 2 - sel.size.y / 2
            elif self.choices[ver] == _('Bottoms'):
                if sel != firstSel:
                    domove = True
                    newY = firstSelPos.y + firstSel.size.y - sel.size.y
            elif self.choices[ver] == _('Space equally'):
                if sel != firstSel and sel != lastSel:
                    domove = True
                    newY = (lastSelPos.y - firstSelPos.y) / (selSize-1) * selIdx \
                           + firstSelPos.y


#            elif self.choices[ver] == 'Center in window': pass

            if domove:
                sel.position = wx.Point(newX, newY)
                sel.dragging = True
                sel.moveRelease()
                sel.positionUpdate()

            selIdx = selIdx + 1

        self.EndModal(wx.OK)
Пример #32
0
class ProfileStatsView(ListCtrlView, CloseableViewMix):
    viewName = 'Profile stats'
    viewTitle = _('Profile stats')
    
    gotoLineBmp = 'Images/Editor/GotoLine.png'
    calleesBmp = 'Images/Editor/Callees.png'
    callersBmp = 'Images/Editor/Callers.png'
    saveAsBmp = 'Images/Editor/SaveAs.png'

    def __init__(self, parent, model):
        CloseableViewMix.__init__(self, _('stats'))
        ListCtrlView.__init__(self, parent, model, wx.LC_REPORT | wx.LC_SINGLE_SEL,
          ( (_('Goto line'), self.OnGoto, self.gotoLineBmp, ''),
            ('-', None, '', ''),
            (_('Callers (called this function)'), self.OnCallers, self.callersBmp, ''),
            (_('Callees (are called by this function)'), self.OnCallees, self.calleesBmp, ''),
            ('-', None, '', '') ) +
            self.closingActionItems +
          ( (_('Save stats'), self.OnSaveStats, self.saveAsBmp, ''),
            ), 0)

        self.InsertColumn(0, 'module')
        self.InsertColumn(1, 'line')
        self.InsertColumn(2, 'function')
        self.InsertColumn(3, 'ncalls')
        self.InsertColumn(4, 'tottime')
        self.InsertColumn(5, 'totpercall')
        self.InsertColumn(6, 'cumtime')
        self.InsertColumn(7, 'cumpercall')
        self.SetColumnWidth(0, 100)
        self.SetColumnWidth(1, 30)
        self.SetColumnWidth(2, 100)
        self.SetColumnWidth(3, 50)
        self.SetColumnWidth(4, 60)
        self.SetColumnWidth(5, 60)
        self.SetColumnWidth(6, 60)
        self.SetColumnWidth(7, 60)

        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick)

        self.sortAscend = False
        self.sortCol = 0
        self.all_callees = None

        self.active = True
        self.stats = None
        self.profDir = ''

    def sortCmp(self, item1, item2):
        res = 1
        if item1 < item2: res = -1
        elif item1 == item2: res = 0

        if not self.sortAscend:
            return res * -1
        else:
            return res

    def sortFunction(self, itemIdx1, itemIdx2):
        item1 = self.statKeyList[itemIdx1]
        item2 = self.statKeyList[itemIdx2]
        return self.sortCmp(item1, item2)

    def sortNCalls(self, itemIdx1, itemIdx2):
        item1 = self.stats[self.statKeyList[itemIdx1]][0]
        item2 = self.stats[self.statKeyList[itemIdx2]][0]
        return self.sortCmp(item1, item2)

    def sortTotTime(self, itemIdx1, itemIdx2):
        item1 = self.stats[self.statKeyList[itemIdx1]][2]
        item2 = self.stats[self.statKeyList[itemIdx2]][2]
        return self.sortCmp(item1, item2)

    def sortTotPerCall(self, itemIdx1, itemIdx2):
        key1 = self.statKeyList[itemIdx1]
        key2 = self.statKeyList[itemIdx2]
        ncalls1 = self.stats[key1][0]
        ncalls2 = self.stats[key2][0]
        if ncalls1 and ncalls2:
            item1 = self.stats[key1][2] / ncalls1
            item2 = self.stats[key2][2] / ncalls2
            return self.sortCmp(item1, item2)
        else:
            return 0

    def sortCumTime(self, itemIdx1, itemIdx2):
        item1 = self.stats[self.statKeyList[itemIdx1]][3]
        item2 = self.stats[self.statKeyList[itemIdx2]][3]
        return self.sortCmp(item1, item2)

    def sortCumPerCall(self, itemIdx1, itemIdx2):
        if self.stats[self.statKeyList[itemIdx1]][0] and \
          self.stats[self.statKeyList[itemIdx2]][0]:
            item1 = self.stats[self.statKeyList[itemIdx1]][3]/ \
              self.stats[self.statKeyList[itemIdx1]][0]
            item2 = self.stats[self.statKeyList[itemIdx2]][3]/ \
              self.stats[self.statKeyList[itemIdx2]][0]
            return self.sortCmp(item1, item2)
        else: return 0

    def calc_callees(self):
        """ from pstats """
        if self.all_callees: return
        self.all_callees = all_callees = {}
        for func in self.stats.keys():
            if not all_callees.has_key(func):
                all_callees[func] = {}
            cc, nc, tt, ct, callers = self.stats[func]
            for func2 in callers.keys():
                if not all_callees.has_key(func2):
                    all_callees[func2] = {}
                all_callees[func2][func] = callers[func2]
        return

    def refreshCtrl(self):
        ListCtrlView.refreshCtrl(self)
        if self.stats:
            self.statKeyList = self.stats.keys()
            self.statKeyList.sort()
            i = 0
            for filename, lineno, funcname in self.statKeyList:
                stats = self.stats[(filename, lineno, funcname)]
                i = self.addReportItems(i, (os.path.basename(filename), str(lineno),
                      funcname, '%d' % stats[0], '%f' % stats[2],
                      stats[0] and '%f' % (stats[2]/stats[0]) or '',
                      '%f' % stats[3],
                      stats[0] and '%f' % (stats[3]/stats[0]) or ''))
                self.SetItemData(i-1, i-1)
        self.pastelise()

    def getStatIdx(self):
        for i in range(self.GetItemCount()):
            if self.GetItemState(i, wx.LIST_STATE_SELECTED):
                return self.GetItemData(i)
        idx = self.GetItemData(i)
        return idx

    def OnGoto(self, event):
        if self.selected > -1:
            idx = self.getStatIdx()
            key = self.statKeyList[idx]
            if key[0] == '<string>':
                wx.LogMessage(_("Eval'd or exec'd code, no module."))
                return
            if os.path.isabs(key[0]):
                model, controller = self.model.editor.openOrGotoModule(key[0])
            else:
                model, controller = self.model.editor.openOrGotoModule(
                      os.path.join(self.profDir, key[0]))

            model.views['Source'].focus()
            model.views['Source'].SetFocus()
            model.views['Source'].gotoLine(key[1]-1)

    def OnCallers(self, event):
        if self.selected > -1:
            idx = self.getStatIdx()
            callDct = self.stats[self.statKeyList[idx]][4]

            called = [`x[1]`+': '+x[0][2]+' | '+os.path.basename(os.path.splitext(x[0][0])[0])
                      for x in callDct.items()]
            dlg = wx.SingleChoiceDialog(self.model.editor, _('Choose a function:'),
              _('%s was called by...') % self.statKeyList[idx][2], called)
            try:
                if dlg.ShowModal() == wx.ID_OK:
                    idx = called.index(dlg.GetStringSelection())
                    key = callDct.keys()[idx]

                    for i in range(self.GetItemCount()):
                        if self.statKeyList[self.GetItemData(i)] == key:
                            self.SetItemState(i,
                              wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED,
                              wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
                            self.EnsureVisible(i)
            finally:
                dlg.Destroy()
Пример #33
0
 def getTemplate(self, name):
     if self.conf.has_section(name):
         return self.conf.get(name, 'template')
     raise Exception, _('Code Template: %s not found') % name
Пример #34
0
    def _init_ctrls(self, prnt):
        wx.Frame.__init__(self,
                          size=wx.Size(330, 443),
                          id=wxID_ERRORSTACKMF,
                          title=_('Traceback and Output browser'),
                          parent=prnt,
                          name='ErrorStackMF',
                          style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_TOOL_WINDOW,
                          pos=wx.Point(464, 228))
        self._init_utils()
        self.Bind(wx.EVT_CLOSE, self.OnErrorstackmfClose)

        self.notebook = wx.Notebook(size=wx.Size(330, 418),
                                    id=wxID_ERRORSTACKMFNOTEBOOK,
                                    parent=self,
                                    name='notebook',
                                    style=self.notebookStyle,
                                    pos=wx.Point(0, 0))

        self.statusBar = wx.StatusBar(id=wxID_ERRORSTACKMFSTATUSBAR,
                                      parent=self,
                                      name='statusBar',
                                      style=0)
        self.SetStatusBar(self.statusBar)

        self.outputTC = wx.TextCtrl(size=wx.Size(326, 384),
                                    value='',
                                    pos=wx.Point(0, 0),
                                    parent=self.notebook,
                                    name='outputTC',
                                    style=wx.TE_MULTILINE | wx.TE_RICH,
                                    id=wxID_ERRORSTACKMFOUTPUTTC)

        self.errorTC = wx.TextCtrl(size=wx.Size(326, 384),
                                   value='',
                                   pos=wx.Point(0, 0),
                                   parent=self.notebook,
                                   name='errorTC',
                                   style=wx.TE_MULTILINE | wx.TE_RICH,
                                   id=wxID_ERRORSTACKMFERRORTC)
        self.errorTC.SetForegroundColour(wx.Colour(64, 0, 0))

        #--
        # Special case to fix GTK redraw problem
        if wx.Platform == '__WXGTK__':
            prxy, errorStackTC = Utils.wxProxyPanel(
                self.notebook,
                wx.TreeCtrl,
                size=wx.Size(312, 390),
                id=wxID_ERRORSTACKMFERRORSTACKTC,
                name='errorStackTC',
                style=wx.TR_HAS_BUTTONS | wx.SUNKEN_BORDER,
                pos=wx.Point(0, 0))
            self.errorStackTC = prxy
            self._init_coll_notebook_Pages(self.notebook)
            self.errorStackTC = errorStackTC
        else:
            self.errorStackTC = wx.TreeCtrl(size=wx.Size(312, 390),
                                            id=wxID_ERRORSTACKMFERRORSTACKTC,
                                            parent=self.notebook,
                                            name='errorStackTC',
                                            pos=wx.Point(4, 22),
                                            style=wx.TR_HAS_BUTTONS
                                            | wx.SUNKEN_BORDER)
            self._init_coll_notebook_Pages(self.notebook)
Пример #35
0
    def OnClearHistory(self, event):
        self.updateCtrls([], addToHistory=False)
        self.history = []
        self.historyIdx = None

        self.editor.setStatus(_('History cleared.'))
Пример #36
0
    def __init__(self, parent, editor):
        self.notebookStyle = 0
        self.tracebackImgIdx = 0
        self.tracebackText = _('Tracebacks')
        self.outputImgIdx = 1
        self.outputText = _('Output')
        self.errorsImgIdx = 2
        self.errorsText = _('Errors')

        self.processesPage = None
        self.processesImgIdx = 3
        self.processesText = _('Tasks')

        self.diffPage = None
        self.diffImgIdx = 4

        self.inputPage = None
        self.inputImgIdx = 5

        self.history = []
        self.historyIdx = None

        if Preferences.eoErrOutNotebookStyle == 'side':
            self.notebookStyle = wx.NB_LEFT
            self.tracebackText = '  '
            self.outputText = '  '
            self.errorsText = '  '

        if Preferences.eoErrOutNotebookStyle == 'text':
            self.tracebackImgIdx = self.outputImgIdx = self.errorsImgIdx = \
                  self.diffImgIdx = self.inputImgIdx = self.processesImgIdx = -1

        self._init_ctrls(parent)

        self._init_coll_statusBar_Fields(self.statusBar)

        self.outputTC.SetFont(Preferences.eoErrOutFont)
        self.errorTC.SetFont(Preferences.eoErrOutFont)
        self.errorTC.SetForegroundColour(wx.Colour(64, 0, 0))

        if Preferences.eoErrOutNotebookStyle == 'side':
            self.notebook.SetPadding(wx.Size(1, 5))

        if Preferences.eoErrOutNotebookStyle != 'text':
            for img in (
                    'Images/Shared/Traceback.png',
                    'Images/Shared/Info.png',
                    'Images/Shared/Error.png',
                    'Images/Shared/Processes.png',
                    'Images/CvsPics/Diff.png',
                    'Images/Shared/Input.png',
            ):
                self.images.Add(Preferences.IS.load(img))
            self.notebook.AssignImageList(self.images)

        self.SetIcon(Preferences.IS.load('Images/Icons/OutputError.ico'))

        self.editor = editor
        self.vetoEvents = False
        self.errorStackTC.Bind(wx.EVT_TREE_ITEM_ACTIVATED,
                               self.OnErrorstacktcTreeItemActivated,
                               id=wxID_ERRORSTACKMFERRORSTACKTC)
        self.errorStackTC.Bind(wx.EVT_TREE_SEL_CHANGED,
                               self.OnErrorstacktcTreeSelChanged,
                               id=wxID_ERRORSTACKMFERRORSTACKTC)
        #self.errorStackTC.Bind(wx.EVT_LEFT_DOWN, self.OnErrorstacktcLeftDown)

        #self.lastClick = (0, 0)

        self.menu = wx.Menu()
        self.Bind(wx.EVT_MENU, self.OnLoadHistory, id=wxID_EO_LOADHIST)
        self.menu.Append(wxID_EO_LOADHIST, _('Load history...'))
        self.Bind(wx.EVT_MENU, self.OnSaveHistory, id=wxID_EO_SAVEHIST)
        self.menu.Append(wxID_EO_SAVEHIST, _('Save history...'))
        self.Bind(wx.EVT_MENU, self.OnClearHistory, id=wxID_EO_CLRHIST)
        self.menu.Append(wxID_EO_CLRHIST, _('Clear history'))
        self.menu.AppendSeparator()
        self.Bind(wx.EVT_MENU, self.OnCloseDiff, id=wxID_EO_CLOSEDIFF)
        self.menu.Append(wxID_EO_CLOSEDIFF, _('Close diff page'))
        self.menu.Enable(wxID_EO_CLOSEDIFF, False)
        self.Bind(wx.EVT_MENU, self.OnCloseInput, id=wxID_EO_CLOSEINPT)
        self.menu.Append(wxID_EO_CLOSEINPT, _('Close input page'))
        self.menu.Enable(wxID_EO_CLOSEINPT, False)

        self.notebook.Bind(wx.EVT_RIGHT_UP, self.OnRightDown)

        self.processesMenu = wx.Menu()
        self.Bind(wx.EVT_MENU, self.OnKillProcess, id=wxID_EO_KILLPROC)
        self.processesMenu.Append(wxID_EO_KILLPROC, _('Kill process'))
        self.processesMenu.AppendSeparator()
        self.Bind(wx.EVT_MENU, self.OnCheckProcesses, id=wxID_EO_CHECKPROCS)
        self.processesMenu.Append(wxID_EO_CHECKPROCS, _('Check processes'))

        self.displayProcesses()
        self.processesPage.Bind(wx.EVT_RIGHT_DOWN, self.OnProcessesRightDown)

        self.winConfOption = 'errout'
        if Preferences.eoErrOutDockWindow == 'undocked':
            self.loadDims()
Пример #37
0
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self,
                           id=wxID_CONTROLALIGNMENTFRAME,
                           name='ControlAlignmentFrame',
                           parent=prnt,
                           pos=wx.Point(341, 140),
                           size=wx.Size(328, 219),
                           style=wx.DEFAULT_DIALOG_STYLE,
                           title='Alignment')
        self.SetClientSize(wx.Size(320, 192))

        self.panel1 = wx.Panel(id=wxID_CONTROLALIGNMENTFRAMEPANEL1,
                               name='panel1',
                               parent=self,
                               pos=wx.Point(0, 0),
                               size=wx.Size(320, 192),
                               style=wx.TAB_TRAVERSAL)

        self.radioBox1 = wx.RadioBox(choices=[
            _('No change'),
            _('Left sides'),
            _('Centers'),
            _('Right sides'),
            _('Space equally')
        ],
                                     id=wxID_CONTROLALIGNMENTFRAMERADIOBOX1,
                                     label=_('Horizontal'),
                                     majorDimension=1,
                                     name='radioBox1',
                                     parent=self.panel1,
                                     pos=wx.Point(8, 8),
                                     size=wx.Size(144, 144),
                                     style=wx.RA_SPECIFY_COLS)

        self.okBtn = wx.Button(id=wxID_CONTROLALIGNMENTFRAMEOKBTN,
                               label=_('OK'),
                               name='okBtn',
                               parent=self.panel1,
                               pos=wx.Point(160, 160),
                               size=wx.Size(72, 24),
                               style=0)
        self.okBtn.Bind(wx.EVT_BUTTON,
                        self.OnOkbtnButton,
                        id=wxID_CONTROLALIGNMENTFRAMEOKBTN)

        self.cancelBtn = wx.Button(id=wxID_CONTROLALIGNMENTFRAMECANCELBTN,
                                   label=_('Cancel'),
                                   name='cancelBtn',
                                   parent=self.panel1,
                                   pos=wx.Point(240, 160),
                                   size=wx.Size(72, 24),
                                   style=0)
        self.cancelBtn.Bind(wx.EVT_BUTTON,
                            self.OnCancelbtnButton,
                            id=wxID_CONTROLALIGNMENTFRAMECANCELBTN)

        self.radioBox2 = wx.RadioBox(choices=[
            _('No change'),
            _('Tops'),
            _('Centers'),
            _('Bottoms'),
            _('Space equally')
        ],
                                     id=wxID_CONTROLALIGNMENTFRAMERADIOBOX2,
                                     label=_('Vertical'),
                                     majorDimension=1,
                                     name='radioBox2',
                                     parent=self.panel1,
                                     pos=wx.Point(160, 8),
                                     size=wx.Size(152, 144),
                                     style=wx.RA_SPECIFY_COLS)
Пример #38
0
 def renameItem(self, name, newName):
     if self.entries.has_key(newName):
         raise Exception, _('Name exists')
     self.entries[newName] = newName
     del self.entries[name]
     self.updateConfig()
Пример #39
0
 def getTitle(self):
     return _('Find results for %s in %s') % (self.lastSearch,
                                              self.resourcepath)
Пример #40
0
 def __init__(self, parent, selection):
     self._init_ctrls(parent)
     self.choices = (_('No change'), _('No change'))
     self.selection = selection
     self.Centre(wx.BOTH)
Пример #41
0
 def actions(self, model):
     return Controllers.TextController.actions(
         self, model) + [(_('Compile to MO'), self.OnCompile, '-', '')]
Пример #42
0
def findFileExplorerNode(category, respath, transports):
    for tp in transports.entries:
        if tp.itemProtocol == 'file':
            return tp.getNodeFromPath(respath, forceFolder=False)
    raise ExplorerNodes.TransportError(
        _('FileSysCatNode not found in transports %s') % transports.entries)
Пример #43
0
class PyResourceImagesView(EditorViews.ListCtrlView):
    viewName = 'Images'
    viewTitle = _('Images')

    gotoLineBmp = 'Images/Editor/GotoLine.png'
    moveUpBmp = 'Images/Shared/up.png'
    moveDownBmp = 'Images/Shared/down.png'
    deleteBmp = 'Images/Shared/Delete.png'

    imageSize = (32, 32)

    onlyIcons = False

    def __init__(self,
                 parent,
                 model,
                 listStyle=wx.LC_ICON | wx.LC_ALIGN_TOP,
                 imgLstStyle=wx.IMAGE_LIST_NORMAL):
        EditorViews.ListCtrlView.__init__(
            self,
            parent,
            model,
            listStyle,
            ((_('Goto line'), self.OnGoto, self.gotoLineBmp, ''),
             #           ('Move up', self.OnMoveUp, self.moveUpBmp, ''),
             #           ('Move down', self.OnMoveDown, self.moveDownBmp, ''),
             #           ('Delete image', self.OnDeleteImage, self.deleteBmp, ''),
             ##           ('Add image', self.OnAddImage, '-', ''),
             #           ('Export image', self.OnExportImage, '-', ''),
             ),
            0)

        self.images = wx.ImageList(*self.imageSize)
        self.AssignImageList(self.images, imgLstStyle)

        self.imageSrcInfo = []
        self.functions = None
        self.cataloged = False
        self.eol = os.linesep

        self.active = True

    def refreshCtrl(self):
        EditorViews.ListCtrlView.refreshCtrl(self)

        self.functions = PyResourceModuleExec(self.model.data)
        self.imageSrcInfo = []
        self.images.RemoveAll()
        artProv = PyResourceArtProvider(self.functions)
        wx.ArtProvider.PushProvider(artProv)
        try:
            m = self.model.getModule()
            self.cataloged = ('catalog' in m.globals) and ('index'
                                                           in m.globals)
            self.eol = m.eol
            for f in m.function_order:
                if f.startswith('get') and f.endswith('Data'):
                    name = f[3:-4]
                    iconFunction = 'get%sIcon' % name in m.functions
                    if self.onlyIcons and not iconFunction:
                        continue
                    bmpFunctionStart = m.functions['get%sBitmap' % name].start
                    firstDataLine = m.source[m.functions['get%sData' %
                                                         name].start]
                    compressed = firstDataLine.strip().startswith(
                        'return zlib.decompress')
                    bmp = wx.ArtProvider.GetBitmap('get%sBitmap' % name,
                                                   size=self.imageSize)
                    idx = self.images.Add(bmp)
                    self.InsertImageStringItem(idx, name, idx)
                    self.imageSrcInfo.append(
                        (name, (m.functions[f].start, bmpFunctionStart),
                         compressed, iconFunction))
        finally:
            wx.ArtProvider.PopProvider()

    def OnGoto(self, event):
        if self.selected != -1:
            srcView = self.model.getSourceView()
            srcView.focus()
            lineNo = self.imageSrcInfo[self.selected][1][0]
            srcView.gotoLine(lineNo - 1)


##    def OnAddImage(self, event):
##        from Explorers.Explorer import openEx
##        fn = self.model.editor.openFileDlg(filter='*.*', curdir='.')
##        if fn.find('://') != -1:
##            fn = fn.split('://', 1)[1]
##        ConvertImgToPy

##        dlg =wx.DirDialog(self.model.editor)
##        try:
##            if dlg.ShowModal() != wx.ID_OK:
##                return
##            dir = dlg.GetPath()
##            res = []
##            os.path.walk(dir, visitor, res)
##        finally:
##            dlg.Destroy()
##
##def visitor(files, dirname, names):
##    for name in names:
##        filename = os.path.join(dirname, name)
##        if os.path.isfile(filename):
##            files.append(filename)

    def OnExportImage(self, event):
        if self.selected != -1:
            name = self.imageSrcInfo[self.selected][0]
            dlg = wx.FileDialog(self, 'Save image', '.', name + '.png',
                                ';'.join(['*%s' % e for e in extTypeMap]),
                                wx.SAVE)
            try:
                if dlg.ShowModal() == wx.ID_OK:
                    path = dlg.GetPath()
                    ext = os.path.splitext(path)[-1].lower()
                    if ext in extTypeMap:
                        func = self.functions.imageFunctions['get%sBitmap' %
                                                             name]()
                        func.SaveFile(path, extTypeMap[ext])
                    else:
                        wx.LogError(_('Unsupported image type: %s') % ext)
            finally:
                dlg.Destroy()

    def OnMoveUp(self, event):
        pass

    def OnMoveDown(self, event):
        pass

    def OnDeleteImage(self, event):
        pass
Пример #44
0
) = Utils.wxNewIds(13)

(
    wxID_FSFILTER,
    wxID_FSFILTERBOAMODULES,
    wxID_FSFILTERSTDMODULES,
    wxID_FSFILTERINTMODULES,
    wxID_FSFILTERALLMODULES,
) = Utils.wxNewIds(5)

filterDescrOrd = [
    'BoaFiles', 'StdFiles', 'BoaIntFiles', 'ImageFiles', 'AllFiles'
]

filterDescr = {
    'BoaFiles': (_('Boa files'), wxID_FSFILTERBOAMODULES),
    'StdFiles': (_('Standard files'), wxID_FSFILTERSTDMODULES),
    'BoaIntFiles': (_('Internal files'), wxID_FSFILTERINTMODULES),
    'ImageFiles': (_('Image files'), wxID_FSFILTERIMAGES),
    'AllFiles': (_('All files'), wxID_FSFILTERALLMODULES)
}


# XXX CVS and Zip support must also move to registering
class FileSysController(ExplorerNodes.Controller,
                        ExplorerNodes.ClipboardControllerMix):
    bookmarkBmp = 'Images/Shared/Bookmark.png'
    findBmp = 'Images/Shared/Find.png'
    inspectBmp = 'Images/Shared/Inspector.png'

    def __init__(self, editor, list, inspector, controllers):
class HelpBookFilesView(EditorViews.VirtualListCtrlView):
    viewName = 'Files'
    viewTitle = _('Files')

    addBmp = 'Images/Shared/NewItem.png'
    delBmp = 'Images/Shared/DeleteItem.png'

    def __init__(self, parent, model, provideActions=True):
        if provideActions:
            actions = (
                (_('Add file'), self.OnAddFile, self.addBmp, ''),
                (_('Add files'), self.OnAddFiles, '-', ''),
                (_('Remove file'), self.OnRemoveFile, self.delBmp, ''),
                (_('Open file'), self.OnOpenFile, '-', ''),
                ('-', None, '-', ''),
                (_('Normalise paths'), self.OnNormalisePaths, '-', ''),
            )
        else:
            actions = ()
        EditorViews.VirtualListCtrlView.__init__(self, parent, model,
                                                 wx.LC_REPORT, actions, -1)

        self.Bind(wx.EVT_LEFT_DOWN, self.OnFilesLeftDown)

        #self.sortOnColumns = [0, 1, 2]

        self.InsertColumn(0, _('Num'))
        self.InsertColumn(1, _('Name'))
        self.InsertColumn(2, _('Path'))
        self.SetColumnWidth(0, 30)
        self.SetColumnWidth(1, 150)
        self.SetColumnWidth(2, 300)

        if Preferences.hbShowDocumentTitles:
            self.InsertColumn(3, _('Title'))
            self.SetColumnWidth(3, 300)

        self.active = True

        self.resetCache()

        #self.Bind(wx.EVT_LIST_CACHE_HINT, self.OnCacheHint, id=self.GetId())

    def refreshCtrl(self):
        self.resetCache()
        self.SetItemCount(len(self.model.config.files))

    def OnGetItemText(self, item, col):
        f = self.model.config.files[item]
        if col == 0:
            return ` item `
        elif col == 1:
            return os.path.basename(f)
        elif col == 2:
            return f
        elif Preferences.hbShowDocumentTitles and col == 3:
            if not self.cached[item]:
                title = ''
                try:
                    if os.path.splitext(f)[1].lower() not in ('.htm', '.html'):
                        return ''
                    docsDir = os.path.dirname(self.model.filename)
                    try:
                        data = Explorer.openEx(os.path.join(docsDir, f)).load()
                    except ExplorerNodes.TransportError:
                        return ''
                    fmtr = formatter.NullFormatter(formatter.NullWriter())
                    try:
                        HtmlDocDetailParser(fmtr, breakOnTitle=True).feed(data)
                    except BreakOnTitle, title:
                        return str(title)
                    except:
                        return ''
                    else:
                        return ''
                finally:
                    self.cached[item] = title
Пример #46
0
 def __init__(self, model, view, actions):
     self.model = model
     self.view = view
     actions.extend(((_('Wrap selection with _()'),
                      self.OnI18NWrapSelection, '-', 'I18NWrap'), ))
def createContentsDlg(parent, title, htmlTitle, location, anchors):
    return HelpBookItemDlg(parent, _('Help Book - Contents'), title,
                           _('Title'), htmlTitle, location, _('Location'),
                           anchors)
class HelpBookContentsTreeView(wx.TreeCtrl, EditorViews.EditorView):
    viewName = 'Contents'
    viewTitle = _('Contents')

    def __init__(self, parent, model, parentView=None):
        wx.TreeCtrl.__init__(self,
                             parent,
                             -1,
                             style=wx.TR_HAS_BUTTONS | wx.SUNKEN_BORDER
                             | wx.TR_DEFAULT_STYLE)
        EditorViews.EditorView.__init__(self, model, (), -1)
        self.parentView = parentView
        #(('Edit entry', self.OnEditEntry, '-', ''),)

        self.SetDropTarget(HelpBookContentsDropTarget(self))

        self.helpImgLst = wx.ImageList(16, 16)
        for artId in (wx.ART_HELP_BOOK, wx.ART_HELP_FOLDER, wx.ART_HELP_PAGE):
            bmp = wx.ArtProvider_GetBitmap(artId, wx.ART_TOOLBAR, (16, 16))
            self.helpImgLst.Add(bmp)
        self.AssignImageList(self.helpImgLst)

        self.Bind(wx.EVT_TREE_ITEM_EXPANDING,
                  self.OnTreeExpand,
                  id=self.GetId())
        self.Bind(wx.EVT_TREE_SEL_CHANGED,
                  self.OnTreeSelChanged,
                  id=self.GetId())

        self.active = True

    def refreshCtrl(self):
        self.DeleteAllItems()
        title = self.model.config.options['Title']
        rootItem = self.AddRoot(title,
                                0,
                                data=wx.TreeItemData(
                                    (title, None, self.model.contents)))

        self.SetItemHasChildren(rootItem, True)
        self.Expand(rootItem)

    def recurseAddItems(self, items, treeItem):
        # XXX no longer used, build entire tree recursively
        for name, value, children in items:
            item = self.AppendItem(treeItem, name, children and 1 or 2, -1,
                                   wx.TreeItemData((value, items, children)))
            if children:
                self.recurseAddItems(children, item)
                self.SetItemHasChildren(item, True)

    def addTreeItems(self, items, treeItem):
        self.DeleteChildren(treeItem)
        for name, value, children in items:
            item = self.AppendItem(treeItem, name, children and 1 or 2, -1,
                                   wx.TreeItemData((value, items, children)))
            if children:
                self.SetItemHasChildren(item, True)

    def OnRightClick(self, event):
        if self.parentView:
            menu = self.parentView.generateMenu()
            event.GetEventObject().PopupMenuXY(menu, event.GetX(),
                                               event.GetY())
            menu.Destroy()

    def OnTreeExpand(self, event):
        item = event.GetItem()
        self.addTreeItems(self.GetPyData(item)[-1], item)

    def OnTreeSelChanged(self, event):
        item = event.GetItem()
        if item.Ok():
            location = self.GetPyData(item)[0]
            self.model.editor.setStatus(location)

    def OnEditEntry(self, event):
        tree = self
        item = tree.GetSelection()
        name = tree.GetItemText(item)
        value, items, children = tree.GetPyData(item)

        if item == tree.GetRootItem():
            options = self.model.config.options
            dlg = HelpBookItemDlg(self.model.editor,
                                  _('Help Book - Contents properties'),
                                  options['Title'], _('Title'),
                                  '', options['Default topic'],
                                  _('Default topic'), [])
            try:
                if dlg.ShowModal() != wx.ID_OK:
                    return

                title, defTopic = dlg.GetResult()
            finally:
                dlg.Destroy()

            if options['Title'] != title or options[
                    'Default topic'] != defTopic:
                self.model.setModified('config')
                self.updateEditor()

                options['Title'] = title
                options['Default topic'] = defTopic

                tree.SetItemData(item,
                                 wx.TreeItemData((title, defTopic, children)))
                tree.SetItemText(item, title)

            # XXX mark hhp modified
            return

        docsDir = os.path.dirname(self.model.filename)
        title, page = doContentsDlg(name, value, docsDir)

        if (title, page) == (None, None):
            return

        if (name, value, children) != (title, page, children):
            idx = items.index((name, value, children))
            items[idx] = (title, page, children)

            self.model.setModified('contents')
            self.updateEditor()

            tree.SetItemData(item, wx.TreeItemData((page, items, children)))
            tree.SetItemText(item, title)

    def OnDeleteEntry(self, event):
        item = self.GetSelection()

        if item == self.GetRootItem():
            wx.LogError(_('Cannot delete root node.'))
            return

        name = self.GetItemText(item)
        value, items, children = self.GetPyData(item)

        idx = items.index((name, value, children))

        if wx.MessageBox(
                _('Delete %s') % name, _('Delete node and children'),
                wx.ICON_WARNING | wx.YES_NO) == wx.YES:
            del items[idx]
            self.model.modified = True
            self.updateEditor()

            self.Collapse(item)
            self.Delete(item)
    def doStartDrag(self):
        sel = self.GetSelections()
        if sel:
            filenames = [self.model.config.files[idx] for idx in sel]
            filelist = wx.CustomDataObject(wx.CustomDataFormat('FileList'))
            filelist.SetData( ` filenames `)
            #tdo =wx.TextDataObject(filename)
            ds = wx.DropSource(self)
            ds.SetData(filelist)
            ds.DoDragDrop(wx.Drag_DefaultMove)

    def OnFilesLeftDown(self, event):
        event.Skip()
        wx.CallAfter(self.doStartDrag)

    helpBookDirMsg = _('Help documents must be in the same directory as the help '\
                     'book, or a sub-directory. Not allowed outside the tree.')

    def OnAddFile(self, event):
        if not self.model.savedAs:
            wx.LogError(
                _('Please save the help book before adding files\n') +
                self.helpBookDirMsg)
            return

        filename = self.model.editor.openFileDlg()
        if filename:
            helpProjDir = os.path.dirname(self.model.filename)
            if not filename.startswith(helpProjDir):
                wx.LogError(self.helpBookDirMsg)
                return
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self,
                           id=wxID_HELPBOOKITEMDLG,
                           name='HelpBookItemDlg',
                           parent=prnt,
                           pos=wx.Point(452, 359),
                           size=wx.Size(446, 136),
                           style=wx.DEFAULT_DIALOG_STYLE,
                           title=self.caption)
        self.SetClientSize(wx.Size(438, 109))

        self.staticText1 = wx.StaticText(id=wxID_HELPBOOKITEMDLGSTATICTEXT1,
                                         label=self.nameLabel,
                                         name='staticText1',
                                         parent=self,
                                         pos=wx.Point(8, 16),
                                         size=wx.Size(56, 13),
                                         style=0)

        self.txtTitle = wx.TextCtrl(id=wxID_HELPBOOKITEMDLGTXTTITLE,
                                    name='txtTitle',
                                    parent=self,
                                    pos=wx.Point(72, 8),
                                    size=wx.Size(232, 21),
                                    style=0,
                                    value=self.name)

        self.staticText2 = wx.StaticText(id=wxID_HELPBOOKITEMDLGSTATICTEXT2,
                                         label=self.valueLabel,
                                         name='staticText2',
                                         parent=self,
                                         pos=wx.Point(8, 48),
                                         size=wx.Size(64, 13),
                                         style=0)

        self.txtPage = wx.TextCtrl(id=wxID_HELPBOOKITEMDLGTXTPAGE,
                                   name='txtPage',
                                   parent=self,
                                   pos=wx.Point(72, 40),
                                   size=wx.Size(232, 21),
                                   style=0,
                                   value=self.value)

        self.cbbAnchors = wx.ComboBox(choices=self.valueAnchors,
                                      id=wxID_HELPBOOKITEMDLGCBBANCHORS,
                                      name='cbbAnchors',
                                      parent=self,
                                      pos=wx.Point(304, 40),
                                      size=wx.Size(125, 21),
                                      style=0,
                                      value=self.valueAnchorsValue)

        self.btnReadTitle = wx.Button(id=wxID_HELPBOOKITEMDLGBTNREADTITLE,
                                      label=_('Title from HTML'),
                                      name='btnReadTitle',
                                      parent=self,
                                      pos=wx.Point(304, 8),
                                      size=wx.Size(123, 23),
                                      style=0)
        self.btnReadTitle.Bind(wx.EVT_BUTTON,
                               self.OnBtnreadtitleButton,
                               id=wxID_HELPBOOKITEMDLGBTNREADTITLE)

        self.button2 = wx.Button(id=wx.ID_OK,
                                 label=_('OK'),
                                 name='button2',
                                 parent=self,
                                 pos=wx.Point(272, 72),
                                 size=wx.Size(75, 23),
                                 style=0)

        self.button3 = wx.Button(id=wx.ID_CANCEL,
                                 label=_('Cancel'),
                                 name='button3',
                                 parent=self,
                                 pos=wx.Point(353, 72),
                                 size=wx.Size(75, 23),
                                 style=0)
Пример #51
0
 def assertFilename(self, filename):
     """ Utility function to strip and assert the protocol from the uri """
     from Explorers.Explorer import splitURI
     prot, cat, res, uri = splitURI(filename)
     assert self.protocol == prot, _('Illegal protocol change')
     return res
def createIndexDlg(parent, keyword, location, anchors):
    return HelpBookItemDlg(parent, _('Help Book - Index'), keyword,
                           _('Keyword(s)'), '', location, _('Location'),
                           anchors)
Пример #53
0
class AppView(ListCtrlView, FindResultsAdderMixin):
    viewName = 'Application'
    viewTitle = _('Application')

    openBmp = 'Images/Editor/OpenFromApp.png'
    addModBmp = 'Images/Editor/AddToApp.png'
    remModBmp = 'Images/Editor/RemoveFromApp.png'
    findBmp = 'Images/Shared/Find.png'

    def __init__(self, parent, model):
        ListCtrlView.__init__(self, parent, model, wx.LC_REPORT, (
            (_('Open'), self.OnOpen, self.openBmp, ''),
            ('-', None, '', ''),
            (_('Add'), self.OnAdd, self.addModBmp, 'Insert'),
            (_('Edit'), self.OnEdit, '-', ''),
            (_('Remove'), self.OnRemove, self.remModBmp, 'Delete'),
            ('-', None, '', ''),
            (_('Find'), self.OnFind, self.findBmp, 'Find'),
            ('-', None, '-', ''),
            (_('Make module main module'), self.OnMakeMain, '-', ''),
        ), 0)

        self.InsertColumn(0, _('Module'), width=150)
        self.InsertColumn(1, _('Type'), width=50)
        self.InsertColumn(2, _('Description'), width=150)
        self.InsertColumn(3, _('Relative path'), width=220)

        self.sortOnColumns = [0, 1, 3]

        self.SetImageList(model.editor.modelImageList, wx.IMAGE_LIST_SMALL)

        self.lastSearchPattern = ''
        self.active = True
        self.canExplore = True
        self.model = model


#        EVT_LIST_BEGIN_DRAG(self, self.GetId(), self.OnDrag)

#    def OnDrag(self, event):
#        print 'drag', event.GetString()
#        print 'drag', dir(event.__class__.__bases__[0])

    def explore(self):
        modSort = self.model.modules.keys()
        modSort.sort()
        return modSort

    def refreshCtrl(self):
        ListCtrlView.refreshCtrl(self)
        i = 0
        modSort = self.model.modules.keys()
        modSort.sort()
        for mod in modSort:
            # XXX Show a broken icon as default
            imgIdx = -1
            modTpe = 'Unknown'
            if self.model.moduleModels.has_key(mod):
                imgIdx = self.model.moduleModels[mod].imgIdx
                modTpe = self.model.moduleModels[mod].modelIdentifier
            else:
                self.model.idModel(mod)
                if self.model.moduleModels.has_key(mod):
                    imgIdx = self.model.moduleModels[mod].imgIdx
                    modTpe = self.model.moduleModels[mod].modelIdentifier

            appMod = self.model.modules[mod]

            if appMod[0]:
                modTpe = '*%s*' % modTpe

            i = self.addReportItems(i, (mod, modTpe, appMod[1], appMod[2]),
                                    imgIdx)

        self.pastelise()

    def OnOpen(self, event):
        if self.selected >= 0:
            # XXX maybe this should be done in the browsing framework
            self.model.openModule(self.GetItemText(self.selected))
            self.model.prevSwitch = self

    def OnAdd(self, event):
        self.model.viewAddModule()

    def OnEdit(self, event):
        name = self.GetItemText(self.selected)
        dlg = wx.TextEntryDialog(self, _('Set the description of the module'),
                                 _('Edit item'), self.model.modules[name][1])
        try:
            if dlg.ShowModal() == wx.ID_OK:
                answer = dlg.GetValue()
                self.model.editModule(name, name, self.model.modules[name][0],
                                      answer)
                self.model.update()
                self.model.notify()
        finally:
            dlg.Destroy()

    def OnRemove(self, event):
        if self.selected >= 0:
            if not self.model.modules[self.GetItemText(self.selected)][0]:
                self.model.removeModule(self.GetItemText(self.selected))
            else:
                wx.MessageBox(
                    _('Cannot remove the main frame of an application'),
                    _('Module remove error'))

    def OnImports(self, events):
        wx.BeginBusyCursor()
        try:
            self.model.showImportsView()
        finally:
            wx.EndBusyCursor()

        if self.model.views.has_key('Imports'):
            self.model.views['Imports'].focus()
        self.model.update()
        self.model.notify()

    def OnOpenAll(self, event):
        modules = self.model.modules.keys()
        modules.sort()
        for mod in modules:
            try:
                self.model.editor.openOrGotoModule(\
                  self.model.modules[mod][2])
            except:
                pass

    def OnFind(self, event):
        import FindReplaceDlg
        FindReplaceDlg.find(self, self.model.editor.finder, self)

    def OnMakeMain(self, event):
        if self.selected >= 0:
            self.model.changeMainFrameModule(self.GetItemText(self.selected))
Пример #54
0
class BookmarksCatNode(CategoryNode):
    """ Stores folderish references to any transport protocol """
    #protocol = 'config.bookmark'
    defName = _('Bookmark')
    defaultStruct = Preferences.explorerFileSysRootDefault[1]
    refTree = True

    def __init__(self,
                 clipboards,
                 config,
                 parent,
                 catTransports,
                 tree=None,
                 name=_('Bookmarks'),
                 confSpec=('explorer', 'bookmarks')):
        CategoryNode.__init__(self, name, confSpec, None, config, parent)
        self.catTransports = catTransports
        self.tree = tree
        self.treeitem = None
        self.clipboards = clipboards
        self.imgIdx = EditorHelper.imgFolderBookmark

    def cleanup(self):
        self.catTransports = None
        self.tree = None
        self.clipboards = None

    def createChildNode(self, name, value):
        if type(value) == type({}):
            return SubBookmarksCatNode(self, name, value)
        else:
            from Explorers.Explorer import splitURI, getTransport, TransportError
            prot, cat, res, uri = splitURI(value)
            try:
                node = getTransport(prot, cat, res, self.catTransports)
            except TransportError:
                # XXX should return broken link items
                #print 'transport not found %s %s %s' %(prot, cat, res)
                return None
            if node.isFolderish():
                if prot == 'file':
                    node.imgIdx = EditorHelper.imgFSDrive
                elif prot == 'zope':
                    node.imgIdx = EditorHelper.imgZopeConnection
                else:
                    node.imgIdx = EditorHelper.imgNetDrive

            node.treename = name
            return node

    def getDefault(self):
        return self.config.get(self.resourcepath[0], 'defaultbookmark')

    def add(self, respath):
        respath = str(respath)
        if respath[-1] in ('/', '\\'):
            name = os.path.splitext(os.path.basename(respath[:-1]))[0]
        else:
            name = os.path.splitext(os.path.basename(respath))[0]
        if self.entries.has_key(name):
            name = Utils.getValidName(self.entries.keys(), name)
        self.entries[name] = respath
        self.updateConfig()

        self.refreshTree()

    def refreshTree(self):
        return
        # XXX if under bookmarks when adding bookmarks, tree is rebuilt and
        # XXX position in tree is lost
        # XXX At least update list when Bookmarks node is selected.

        #if self.tree and self.treeitem and self.treeitem.IsOk():
        #    if self.tree.IsExpanded(self.treeitem):
        #        self.tree.CollapseAndReset(self.treeitem)
        #        self.tree.Expand(self.treeitem)

    def createCatCompanion(self, catNode):
        return BookmarkCategoryStringCompanion(catNode.treename, self)

    def copyCatFrom(self, node):
        name = Utils.getValidName(self.entries.keys(), node.name
                                  or node.treename)
        self.entries[name] = node.resourcepath
        self.updateConfig()
Пример #55
0
class AppFindResults(ListCtrlView, CloseableViewMix):
    viewName = 'Application Find Results'
    viewTitle = _('Application Find Results')

    gotoLineBmp = 'Images/Editor/GotoLine.png'

    def __init__(self, parent, model):
        CloseableViewMix.__init__(self, _('find results'))
        ListCtrlView.__init__(self, parent, model, wx.LC_REPORT, (
            (_('Goto match'), self.OnGoto, self.gotoLineBmp, ''),
            (_('Rerun query'), self.OnRerun, '-', ''),
        ) + self.closingActionItems, 0)

        self.InsertColumn(0, _('Module'), width=100)
        self.InsertColumn(1, _('Line no'), wx.LIST_FORMAT_CENTRE, 40)
        self.InsertColumn(2, _('Col'), wx.LIST_FORMAT_CENTRE, 40)
        self.InsertColumn(3, _('Text'), width=550)

        self.results = {}
        self.listResultIdxs = []
        self.tabName = 'Results'
        self.findPattern = ''
        self.active = True
        self.model = model

    def refreshCtrl(self):
        ListCtrlView.refreshCtrl(self)
        i = 0
        self.listResultIdxs = []
        for mod in self.results.keys():
            for result in self.results[mod]:
                self.listResultIdxs.append((mod, result))
                i = self.addReportItems(i,
                                        (os.path.basename(mod), ` result[0]
                                         `, ` result[1] `, result[2].strip()))

        self.model.editor.statusBar.setHint(
            _('%d matches of "%s".') % (i, self.findPattern))

        self.pastelise()

    def OnGoto(self, event):
        if self.selected >= 0:
            modName = self.listResultIdxs[self.selected][0]
            model, cntrl = self.model.openModule(modName)
            srcView = model.views['Source']
            srcView.focus()
            foundInfo = self.listResultIdxs[self.selected][1]
            srcView.lastSearchPattern = self.findPattern
            srcView.lastSearchResults = self.results[modName]
            try:
                srcView.lastMatchPosition = self.results[modName].index(
                    foundInfo)
            except:
                srcView.lastMatchPosition = 0
                #print 'foundInfo not found'

            srcView.selectSection(foundInfo[0], foundInfo[1], self.findPattern)

    def OnRerun(self, event):
        self.rerun(None)
Пример #56
0
import wx

import Plugins
from Utils import _

try:
    import wx.lib.flatnotebook
except ImportError:
    raise Plugins.SkipPluginSilently, _(
        'Module %s not found') % 'wx.lib.flatnotebook'

from Companions.ContainerCompanions import BookCtrlDTC
from Companions.EventCollections import *

EventCategories['FlatNotebookEvent'] = \
 ('wx.lib.flatnotebook.EVT_FLATNOTEBOOK_PAGE_CHANGED',
    'wx.lib.flatnotebook.EVT_FLATNOTEBOOK_PAGE_CHANGING',
    'wx.lib.flatnotebook.EVT_FLATNOTEBOOK_PAGE_CLOSING',
    'wx.lib.flatnotebook.EVT_FLATNOTEBOOK_PAGE_CLOSED',
    'wx.lib.flatnotebook.EVT_FLATNOTEBOOK_PAGE_CONTEXT_MENU')

commandCategories.append('FlatNotebookEvent')


class FlatNotebookDTC(BookCtrlDTC):
    bookCtrlName = 'wx.lib.flatnotebook.FlatNotebook'

    def __init__(self, name, designer, parent, ctrlClass):
        BookCtrlDTC.__init__(self, name, designer, parent, ctrlClass)
        self.windowStyles = \
            ['wx.lib.flatnotebook.FNB_VC71',
Пример #57
0
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self,
                           id=wxID_PROCESSPROGRESSDLG,
                           name='ProcessProgressDlg',
                           parent=prnt,
                           pos=wx.Point(313, 215),
                           size=wx.Size(428, 363),
                           style=wx.RESIZE_BORDER | wx.DEFAULT_DIALOG_STYLE,
                           title=self.dlg_caption)
        self.SetAutoLayout(True)
        self.SetClientSize(wx.Size(420, 336))
        self.Bind(wx.EVT_CLOSE, self.OnProcessprogressdlgClose)

        self.cancelBtn = wx.Button(id=wxID_PROCESSPROGRESSDLGCANCELBTN,
                                   label=_('Cancel'),
                                   name='cancelBtn',
                                   parent=self,
                                   pos=wx.Point(332, 304),
                                   size=wx.Size(80, 24),
                                   style=0)
        self.cancelBtn.SetConstraints(
            LayoutAnchors(self.cancelBtn, False, False, True, True))
        self.cancelBtn.Bind(wx.EVT_BUTTON,
                            self.OnCancelbtnButton,
                            id=wxID_PROCESSPROGRESSDLGCANCELBTN)

        self.cmdStxt = wx.StaticText(id=wxID_PROCESSPROGRESSDLGCMDSTXT,
                                     label='staticText1',
                                     name='cmdStxt',
                                     parent=self,
                                     pos=wx.Point(8, 8),
                                     size=wx.Size(404, 64),
                                     style=wx.ST_NO_AUTORESIZE)
        self.cmdStxt.SetConstraints(
            LayoutAnchors(self.cmdStxt, True, True, True, False))

        self.splitterWindow = wx.SplitterWindow(
            id=wxID_PROCESSPROGRESSDLGSPLITTERWINDOW,
            name='splitterWindow',
            parent=self,
            pos=wx.Point(8, 80),
            size=wx.Size(360, 192),
            style=self.splitterStyle)
        self.splitterWindow.SetConstraints(
            LayoutAnchors(self.splitterWindow, True, True, True, True))

        self.errorTctrl = wx.TextCtrl(id=wxID_PROCESSPROGRESSDLGERRORTCTRL,
                                      name='errorTctrl',
                                      parent=self.splitterWindow,
                                      pos=wx.Point(0, 0),
                                      size=wx.Size(360, 80),
                                      style=wx.TE_MULTILINE | wx.TE_RICH,
                                      value='')
        self.errorTctrl.SetForegroundColour(wx.Colour(128, 0, 0))

        self.outputTctrl = wx.TextCtrl(id=wxID_PROCESSPROGRESSDLGOUTPUTTCTRL,
                                       name='outputTctrl',
                                       parent=self.splitterWindow,
                                       pos=wx.Point(0, 87),
                                       size=wx.Size(360, 105),
                                       style=wx.TE_MULTILINE | wx.TE_RICH,
                                       value='')
        self.splitterWindow.SplitHorizontally(self.errorTctrl,
                                              self.outputTctrl, 80)

        self.statusStxt = wx.StaticText(id=wxID_PROCESSPROGRESSDLGSTATUSSTXT,
                                        label='staticText1',
                                        name='statusStxt',
                                        parent=self,
                                        pos=wx.Point(8, 288),
                                        size=wx.Size(292, 16),
                                        style=0)
        self.statusStxt.SetConstraints(
            LayoutAnchors(self.statusStxt, True, False, True, True))

        self.statusGge = wx.Gauge(id=wxID_PROCESSPROGRESSDLGSTATUSGGE,
                                  name='statusGge',
                                  parent=self,
                                  pos=wx.Point(8, 312),
                                  range=100,
                                  size=wx.Size(208, 16),
                                  style=wx.GA_HORIZONTAL)
        self.statusGge.SetConstraints(
            LayoutAnchors(self.statusGge, True, False, True, True))

        self.killBtn = wx.Button(id=wxID_PROCESSPROGRESSDLGKILLBTN,
                                 label=_('Kill'),
                                 name='killBtn',
                                 parent=self,
                                 pos=wx.Point(242, 304),
                                 size=wx.Size(81, 24),
                                 style=0)
        self.killBtn.SetConstraints(
            LayoutAnchors(self.killBtn, False, False, True, True))
        self.killBtn.Enable(False)
        self.killBtn.Bind(wx.EVT_BUTTON,
                          self.OnKillbtnButton,
                          id=wxID_PROCESSPROGRESSDLGKILLBTN)
Пример #58
0
class AppToDoView(ListCtrlView):
    viewName = 'Application Todo'
    viewTitle = _('Application Todo')

    gotoLineBmp = 'Images/Editor/GotoLine.png'

    def __init__(self, parent, model):
        ListCtrlView.__init__(
            self, parent, model, wx.LC_REPORT,
            ((_('Goto file'), self.OnGoto, self.gotoLineBmp, ''), ), 0)

        self.sortOnColumns = [0, 1]

        self.InsertColumn(0, _('Name'))
        self.InsertColumn(1, _('#Todos'))
        self.InsertColumn(2, _('Filepath'))
        self.SetColumnWidth(0, 75)
        self.SetColumnWidth(1, 25)
        self.SetColumnWidth(2, 350)

        self.todos = []
        self.active = True

    def refreshCtrl(self):
        ListCtrlView.refreshCtrl(self)

        todos = []
        prog = 0
        from Models.PythonEditorModels import ModuleModel
        absModPaths = self.model.absModulesPaths()
        progStep = 100.0 / len(absModPaths)
        for module in absModPaths:
            #module = 'file://'+absModPath
            self.model.editor.statusBar.progress.SetValue(int(prog * progStep))
            prog += 1
            self.model.editor.setStatus(_('Parsing %s...') % module)
            #module = self.modules[moduleName]
            #filename = self.normaliseModuleRelativeToApp(module[2])
            if module[:7] != 'file://':
                print _(
                    '%s skipped, only local files supported for Imports View')
                continue
            else:
                fn = module[7:]
            try:
                f = open(fn)
            except IOError:
                print _("couldn't load %s") % module
                continue
            else:
                data = f.read()
                f.close()
                name = os.path.splitext(os.path.basename(module))[0]
                model = ModuleModel(data, name, self.model.editor, 1)

                m = model.getModule()
                if m.todos:
                    todos.append((name, len(m.todos), module))

        self.model.editor.statusBar.progress.SetValue(0)
        self.model.editor.setStatus(_('Finished parsing'))

        i = 0
        for name, numTodos, path in todos:
            self.addReportItems(i, (name, numTodos, path))
            i += 1

        self.pastelise()

        self.todos = todos

    def OnGoto(self, event):
        if self.selected >= 0:
            name, numTodos, path = self.todos[self.selected]
            mod, ctrlr = self.model.editor.openOrGotoModule(path)
            if mod.views.has_key('Todo'):
                view = mod.views['Todo']
            else:
                view = mod.editor.addNewView(ToDoView.viewName, ToDoView)
            view.refreshCtrl()
            view.focus()
Пример #59
0
 def actions(self, model):
     return BaseEditorController.actions(self, model) + \
            [(_('Close'), self.OnClose, self.closeBmp, 'Close')]
Пример #60
0
class AppCompareView(ListCtrlView, CloseableViewMix):
    viewName = 'App. Compare'
    viewTitle = _('App. Compare')

    gotoLineBmp = 'Images/Editor/GotoLine.png'

    def __init__(self, parent, model):
        CloseableViewMix.__init__(self, _('compare results'))
        ListCtrlView.__init__(self, parent, model, wx.LC_REPORT,
          ( ('Do diff', self.OnGoto, self.gotoLineBmp, ''), ) +\
           self.closingActionItems, 0)

        self.InsertColumn(0, _('Module'), width=100)
        self.InsertColumn(1, _('Differs from'), width=450)
        self.InsertColumn(2, _('Result'), width=75)

        self.results = {}
        self.listResultIdxs = []
        self.tabName = 'App. Compare'
        self.active = True
        self.model = model
        self.compareTo = ''

    def refreshCtrl(self):
        ListCtrlView.refreshCtrl(self)

        from Models.PythonEditorModels import BaseAppModel
        otherApp = BaseAppModel('', self.compareTo, '', self.model.editor,
                                True, {})

        from Explorers.Explorer import openEx
        otherApp.transport = openEx(self.compareTo)

        otherApp.load()
        otherApp.readModules()

        filename, otherFilename = self.model.assertLocalFile(
        ), otherApp.assertLocalFile()

        i = 0
        # Compare apps
        if not cmp(filename, otherFilename):
            i = self.addReportItems(i, (os.path.splitext(
                os.path.basename(filename))[0], otherFilename, _('changed')))

        # Find changed modules and modules not occuring in other module
        for module in self.model.modules.keys():
            if otherApp.modules.has_key(module):
                otherFile = otherApp.assertLocalFile(
                    otherApp.moduleFilename(module))
                filename = self.model.assertLocalFile(
                    self.model.moduleFilename(module))
                try:
                    if not cmp(filename, otherFile):
                        i = self.addReportItems(
                            i, (module, otherFile, _('changed')))
                except OSError:
                    pass
            else:
                i = self.addReportItems(i, (module, '', _('deleted')))

        # Find modules only occuring in other module
        for module in otherApp.modules.keys():
            if not self.model.modules.has_key(module):
                #otherFile = otherApp.moduleFilename(module)
                i = self.addReportItems(i, (module, '', _('added')))

        self.pastelise()

    def OnGoto(self, event):
        if self.selected >= 0:
            module = self.GetItemText(self.selected)
            model, controller = self.model.openModule(module)
            otherModule = self.GetItem(self.selected, 1).GetText()
            if otherModule:
                controller.OnDiffModules(filename=otherModule)