Пример #1
0
    def readDesignerMethod(self, meth, codeBody):
        """ Create a new ObjectCollection by parsing the given method body """
        from Views import ObjCollection
        import methodparse
        # Collection method
        if ObjCollection.isInitCollMeth(meth):
            ctrlName = methodparse.ctrlNameFromMeth(meth)
            try:
                res = Utils.split_seq(codeBody, '', string.strip)
                inits, body, fins = res[:3]
            except ValueError:
                raise Exception, _(
                    'Collection body %s not in init, body, fin form') % meth

            allInitialisers, unmatched = methodparse.parseMixedBody(\
             [methodparse.EventParse, methodparse.CollectionItemInitParse],body)

            creators = allInitialisers.get(methodparse.CollectionItemInitParse,
                                           [])
            collectionInits = []
            properties = []
            events = allInitialisers.get(methodparse.EventParse, [])

            methodparse.decorateParseItems(creators + events, ctrlName,
                                           self.main)
        # Normal method
        else:
            inits = []
            fins = []

            allInitialisers, unmatched = methodparse.parseMixedBody(\
              [methodparse.ConstructorParse, methodparse.EventParse,
               methodparse.CollectionInitParse, methodparse.PropertyParse],
               codeBody)

            creators = allInitialisers.get(methodparse.ConstructorParse, [])
            collectionInits = allInitialisers.get(
                methodparse.CollectionInitParse, [])
            properties = allInitialisers.get(methodparse.PropertyParse, [])
            events = allInitialisers.get(methodparse.EventParse, [])

        newObjColl = ObjCollection.ObjectCollection()
        newObjColl.setup(creators, properties, events, collectionInits, inits,
                         fins)

        if unmatched:
            wx.LogWarning(_('The following lines were not used by the Designer '\
                            'and will be lost:\n'))
            for line in unmatched:
                wx.LogWarning(line)
            wx.LogWarning(_('\nThere were unprocessed lines in the source code of '\
                            'method: %s\nIf this was unexpected, it is advised '\
                            'that you cancel this Designer session and correct '\
                            'the problem before continuing.')%meth)

        return newObjColl
Пример #2
0
 def writeCollectionItems(self, output, stripFrmId=''):
     CollectionIddDTC.writeCollectionItems(self, output, stripFrmId)
     warn = 0
     for constr in self.textConstrLst:
         if constr.params.has_key('control') and constr.params['control'] == 'None':
             wx.LogWarning(_("Invalid None control for toolbar %s's AddControl")%(
                   self.parentCompanion.name))
             warn = 1
     if warn:
         wx.LogWarning(_('Control may not be None or the generated source will '
                         'be invalid outside the Designer.'))
Пример #3
0
 def on_btn_airmon_check(self, event):
     if self.iface is not None:
         if self.iface.modo == 'monitor':
             wx.LogDebug(self.iface.optimize())
             if self.iface.is_optimized:
                 wx.LogDebug(
                     "El modo monitor esta funcionando correctamente")
         else:
             wx.LogWarning(
                 "Debes activar el modo monitor antes de usar esta opcion")
     else:
         wx.LogWarning("Primero debes seleccionar una interfaz")
Пример #4
0
 def writeCollectionItems(self, output, stripFrmId=''):
     CollectionDTC.writeCollectionItems(self, output, stripFrmId)
     warn = 0
     for constr in self.textConstrLst:
         if constr.params['page'] == 'None':
             wx.LogWarning('No control for %s, page %s'%(
                   self.parentCompanion.name, constr.params['text']))
             warn = 1
     if warn:
         wx.LogWarning(_('The red-dashed area of a %s page must contain\n'\
         'a control or the generated source will be invalid outside the '\
         'Designer')% self.parentCompanion.bookCtrlName)
Пример #5
0
 def writeCollectionItems(self, output, stripFrmId=''):
     CollectionDTC.writeCollectionItems(self, output, stripFrmId)
     warn = 0
     for constr in self.textConstrLst:
         if constr.params[0] == 'None':
             wx.LogWarning(
                 _('No control/sizer for sizer item of %s') %
                 (self.parentCompanion.name))
             warn = 1
     if warn:
         wx.LogWarning(
             _('None values are only valid in the Designer.\n'
               'The generated source will be invalid outside the '
               'Designer and should be fixed before executing.'))
Пример #6
0
    def InitLanguage(self):
        langsAvail = {
            "System default": self.sysLng,
            "English": wx.LANGUAGE_ENGLISH,
            "French": wx.LANGUAGE_FRENCH,
            "German": wx.LANGUAGE_GERMAN,
            "Italian": wx.LANGUAGE_ITALIAN,
        }

        sel = wx.GetSingleChoice("Please choose language:", "Language",
                                 list(langsAvail.keys()))
        if sel == "":
            sel = "System default"

        lang = langsAvail[sel]
        # We don't have to do anything if the selected language is english
        # As the strings of this app have been written in this lang
        if lang == wx.LANGUAGE_ENGLISH:
            return

        wx.Locale.AddCatalogLookupPathPrefix("../langs")
        self.locale = wx.Locale()
        if not self.locale.Init(lang):
            wx.LogWarning("This language is not supported by the system.")
        if not self.locale.AddCatalog("internat"):
            wx.LogError(
                "Couldn't find/load the 'internat' catalog for locale '" +
                self.locale.GetCanonicalName() + "'.")
Пример #7
0
    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!')
Пример #8
0
 def debug(self, params=None, cont_if_running=0, cont_always=0,
           temp_breakpoint=None):
     app = self.findAppInModules(params)
     if app:
         app.debug(params, cont_if_running, cont_always, temp_breakpoint)
     else:
         wx.LogWarning('No Application module found in modules list to link to')
Пример #9
0
 def run(self, args='', execStart=None, execFinish=None):
     app = self.findAppInModules(args)
     if app:
         app.run(args, execStart, execFinish)
     else:
         wx.LogWarning(
             'No Application module found in modules list to link to')
Пример #10
0
 def on_btn_airmon_toggle(self, event):
     if self.combo_iface.Selection > 0:
         wx.LogDebug(self.iface.airmon_toggle())
         self.update_ifaces()
     else:
         wx.LogWarning(
             "Debes seleccionar una tarjeta antes de usar esta opcion")
Пример #11
0
 def on_btn_run_reaver(self, event):
     if self.parent.iface_name is None:
         wx.LogWarning("Debes seleccionar una interfaz de red")
     else:
         cmd = self.get_command()
         self.reaver.set_comando(cmd)
         self.reaver.start()
         self.read_logfile()
Пример #12
0
 def on_btn_new_reaver_config(self, event):
     nombre = wx.GetTextFromUser("Introduce un nombre: ", "Crear nueva configuración", parent=self)
     if nombre != "":
         nuevo, created = ReaverConfig.get_or_create(name=nombre)
         if created:
             nuevo.save()
             self.load_reaver_configs()
         else:
             wx.LogWarning("Ya existe un perfil con este nombre")
 def _getValidFilename(self, filename):
     protsplit = filename.split('://')
     if len(protsplit) > 1:
         if protsplit[0] != 'file' or len(protsplit) > 2:
             wx.LogWarning(
                 _('%s not searched, only local files allowed') % filename)
             return ''
         return protsplit[1]
     return filename
Пример #14
0
 def deleteItems(self, names):
     for name in names:
         try:
             del self.entries[name]
         except KeyError:
             wx.LogWarning(
                 _('Could not find %s in %s for deletion') %
                 (name, self.entries.keys()))
     self.updateConfig()
Пример #15
0
 def on_btn_select_iface(self, event):
     if self.iface is not None:
         if self.iface.modo == 'monitor':
             if self.iface.is_optimized:
                 self.iface_name = self.iface.name
                 self.SetStatusText(self.iface_name, 1)
                 self.SetStatusWidths([-1, 100])
                 wx.LogDebug(self.iface.ifconfig_up())
             else:
                 txt = "La interfaz no esta optimizada, usa el boton 'Optimizar interfaz'."
                 wx.LogStatus(txt)
                 txt += "\nEl boton 'optimizar' desactivará servicios de red usados por el sistema. "
                 wx.LogWarning(txt)
         else:
             wx.LogWarning(
                 "Activa el modo monitor antes de usar esta opcion")
     else:
         wx.LogWarning("Primero debes seleccionar una interfaz")
Пример #16
0
def importTransport(moduleName):
    try:
        __import__(moduleName, globals())
    except ImportError, error:
        if Preferences.pluginErrorHandling == 'raise':
            raise
        wx.LogWarning(_('%s not installed: %s') % (moduleName, str(error)))
        ExplorerNodes.failedModules[moduleName] = str(error)
        return True
Пример #17
0
 def on_btn_saveas_reaver_config(self, event):
     nombre = wx.GetTextFromUser("Introduce un nombre: ", "Guardar como...", parent=self)
     if nombre != "":
         nuevo, created = ReaverConfig.get_or_create(name=nombre)
         if created:
             nuevo.update_info(self._get_opciones)
             nuevo.save()
             self.load_reaver_configs()
         else:
             wx.LogWarning("Ya existe un perfil con este nombre")
Пример #18
0
 def on_btn_scan(self, event):
     self.lista_redes.DeleteAllItems()
     if self.iface_name is not None:
         timeout = self.spin_timeout.GetValue()
         channel = self.combo_canal.GetSelection()
         self.wash.configure(self.iface_name, timeout, channel)
         if not self.wash.is_alive:
             self.wash.start()
     else:
         wx.LogWarning("No hay ninguna interfaz configurada")
Пример #19
0
def ConvertImgToPy(imgPath, editor):
    funcName = fileNameToFunctionName(
        os.path.basename(os.path.splitext(imgPath)[0]))
    pyResPath, ok = editor.saveAsDlg(funcName + '_img.py')
    if ok:
        if pyResPath.find('://') != -1:
            pyResPath = pyResPath.split('://', 1)[1]

        # snip script usage, leave only options
        docs = img2py.__doc__[img2py.__doc__.find('Options:') + 11:]

        cmdLine = zopt + '-n %s' % (funcName)
        if os.path.exists(pyResPath):
            cmdLine = '-a ' + cmdLine

        dlg = wx.TextEntryDialog(
            editor,
            _('Options:\n\n%s\n\nEdit options string:') % docs, 'img2py',
            cmdLine)
        try:
            if dlg.ShowModal() != wx.ID_OK:
                return
            cmdLine = dlg.GetValue().strip()
        finally:
            dlg.Destroy()

        opts = cmdLine.split()
        opts.extend([imgPath, pyResPath])

        tmp = sys.argv[0]
        sys.argv[0] = 'Boa Constructor'
        try:
            img2py.main(opts)
        finally:
            sys.argv[0] = tmp

        import sourceconst
        header = (sourceconst.defSig % {
            'modelIdent': 'PyImgResource',
            'main': ''
        }).strip()
        if os.path.exists(pyResPath):
            src = open(pyResPath, 'r').readlines()
            if not (src and src[0].startswith(header)):
                src.insert(0, header + '\n')
                src.insert(1, '\n')
                open(pyResPath, 'w').writelines(src)

            m, c = editor.openOrGotoModule(pyResPath)
            c.OnReload(None)
        else:
            wx.LogWarning(
                _('Resource module not found. img2py failed to create the module'
                  ))
Пример #20
0
    def IsValidSelectedItem(self):
        # check for selected item
        if self.GetSelectedItemCount() == 0 or self.GetSelectedItemCount() > 1:
            wx.LogWarning("Select only one bookmark!")
            return False

        itemindex = self.GetFirstSelected()
        # check and ignore default text
        if self.GetItemText(itemindex, col=1) == self.defaultColumnText:
            return False
        return True
Пример #21
0
    def importExplorers(self, conf):
        """ Import names defined in the config files to register them """
        installTransports = ['Explorers.PrefsExplorer', 'Explorers.EditorExplorer'] +\
              eval(conf.get('explorer', 'installedtransports'), {})

        warned = False
        for moduleName in installTransports:
            warned = warned | importTransport(moduleName)
        if warned:
            wx.LogWarning(_('One or more transports could not be loaded, if the problem '
                         'is not rectifiable,\nconsider removing the transport under '
                         'Preferences->Plug-ins->Transports. Click "Details"'))
Пример #22
0
    def edit_node_dialog(self):
        """display the edit node dialog"""
        my_node_index = self.m_listctrl.GetFirstSelected()
        if my_node_index == -1:
            wx.LogWarning("Nothing selected, select à node first!")
            return False

        my_node = self.m_nodes[my_node_index]
        assert(my_node)

        myDlg = GKUINodeEditDialog(self.m_parent_frame, my_node)
        if myDlg.ShowModal() == wx.ID_SAVE:
            self.reload_list()
Пример #23
0
def logWarning_DEPRECATED(msg):
    """DEPRECATED.  Rather use devide_app.logWarning().
    """

    # create nice formatted string with tracebacks and all
    ei = sys.exc_info()
    #dmsg = \
    #     string.join(traceback.format_exception(ei[0],
    #                                            ei[1],
    #                                            ei[2]))

    dmsgs = traceback.format_exception(ei[0], ei[1], ei[2])

    # we can't disable the timestamp yet
    # wxLog_SetTimestamp()
    # set the detail message
    for dmsg in dmsgs:
        wx.LogWarning(dmsg)
    # then the most recent
    wx.LogWarning(msg)
    # and flush... the last message will be the actual error
    # message, what we did before will add to it to become the
    # detail message
    wx.Log_FlushActive()
Пример #24
0
    def reload_path(self):
        """clear the list ctrl and parse the node paths"""
        for path in self.m_node_paths:
            if os.path.exists(path) is False:
                wx.LogError("{} didn't exist!".format(path))
            else:
                for myfile in os.listdir(path):
                    if myfile.endswith(".gkn"):  # node files
                        node = GKNode()
                        if node.load_from_file(myfile) is False:
                            wx.LogWarning("Error loading: {}".format(myfile))
                        else:
                            self.add_node_to_list(node)

                # reload the node list
                self.reload_list()
Пример #25
0
    def refreshCtrl(self):
        self.pos = self.GetCurrentPos()
        selection = self.GetSelection()
        prevVsblLn = self.GetFirstVisibleLine()
        self._blockUpdate = True
        try:
            newData = self.getModelData()
            curData = Utils.stringFromControl(self.GetText())
            if newData != curData:
                resetUndo = not self.CanUndo() and not curData
                ro = self.GetReadOnly()
                self.SetReadOnly(False)
                self.SetText(Utils.stringToControl(newData))
                self.SetReadOnly(ro)
                if resetUndo:
                    self.EmptyUndoBuffer()
            self.GotoPos(self.pos)
            curVsblLn = self.GetFirstVisibleLine()
            self.LineScroll(0, prevVsblLn - curVsblLn)
            # XXX not preserving selection
            self.SetSelection(*selection)
        finally:
            self._blockUpdate = False

        if self.eol is None:
            self.eol = Utils.getEOLMode(newData, self.defaultEOL)

            self.SetEOLMode({
                '\r\n': wx.stc.STC_EOL_CRLF,
                '\r': wx.stc.STC_EOL_CR,
                '\n': wx.stc.STC_EOL_LF
            }[self.eol])

        if not self.eolsChecked:
            if Utils.checkMixedEOLs(newData):
                wx.LogWarning(_('Mixed EOLs detected in %s, please use '
                             'Edit->Convert... to fix this problem.')\
                             %os.path.basename(self.model.filename))
            self.eolsChecked = True

        self.SetSavePoint()
        self.nonUserModification = False
        self.updatePageName()

        self.updateFromAttrs()
Пример #26
0
    def adjustBreakpoints(self, linesAdded, modType, evtPos):
        line = self.LineFromPosition(evtPos)  #event.GetPosition())

        endline = self.GetLineCount()
        if self.breaks.hasBreakpoint(min(line, endline), max(line, endline)):

            changed = self.breaks.adjustBreakpoints(line, linesAdded)
            debugger = self.model.editor.debugger
            if debugger:
                # XXX also check that module has been imported
                # XXX this should apply; with or without breakpoint
                if debugger.running and \
                      not modType & wx.stc.STC_PERFORMED_UNDO:
                    wx.LogWarning(
                        _('Adding or removing lines from the '
                          'debugger will cause the source and the '
                          'debugger to be out of sync.'
                          '\nPlease undo this action.'))

                debugger.adjustBreakpoints(self.model.filename, line,
                                           linesAdded)
            else:
                # bdb must still be updated
                import bdb

                bpList = bdb.Breakpoint.bplist
                filename = self.model.filename  #canonic form, same as url form I think
                setBreaks = []

                # store reference and remove from (fn, ln) refed dict.
                for bpFile, bpLine in bpList.keys():
                    if bpFile == filename and bpLine > line:
                        setBreaks.append(bpList[bpFile, bpLine])
                        del bpList[bpFile, bpLine]

                # put old break at new place and renumber
                for brks in setBreaks:
                    for brk in brks:
                        brk.line = brk.line + linesAdded
                        # merge in moved breaks
                        if bpList.has_key((filename, brk.line)):
                            bpList[filename, brk.line].append(brk)
                        else:
                            bplist[filename, brk.line] = [brk]
Пример #27
0
    def OnSelectSizer(self, event):
        # XXX maybe move hasSizer/isSizer logic to WindowDTC ?
        inspector = self.group.inspector
        companion = self.group.selCompn
        designer = companion.designer
        if self.hasSizer:
            if designer.sizersView:
                s = companion.GetSizer(None)
                for objInfo in designer.sizersView.objects.values():
                    if objInfo[1] == s:
                        compn = objInfo[0]
                        designer.sizersView.focus()
                        inspector.selectObject(compn)
                        designer.sizersView.selectCtrls([compn.name])
                        return

        elif self.inSizer:
            openCollEditorForSizerItem(inspector, companion)
            designer.Raise()
        else:
            wx.LogWarning('Not part of a sizer')
Пример #28
0
    def setComp(self, event):
        self.flt.comp = []
        compStr = self.compTextCtrl.GetValue()

        if len(compStr) != 0:
            try:
                toks = compStr.replace(' ', '').split(',')

                for tok in toks:
                    if '-' in tok:
                        low, high = (int(c) for c in tok.split('-'))
                        comp = range(low, high + 1)
                    else:
                        comp = [int(tok, )]

                    self.flt.comp += comp

            except Exception as e:
                self.flt.comp = []
                wx.LogWarning('Invalid component config: %s.' % str(compStr))

        self.flt.updateFilteredTrain()
        self.updateTrace()
Пример #29
0
def logwarn(msg):
    if is_cli:
        logger.warn(msg)
    else:
        wx.LogWarning(msg)
Пример #30
0
 def warn(self, msg):
     if self.cli:
         self.logger.warn(msg)
     else:
         wx.LogWarning(msg)