コード例 #1
0
    def filemenu_open_config_handler(self, event):
        """Load configuration info from file."""
        default_path = common.config_manager.get_scenarios_path()
        default_file = os.path.join('config.ini')

        config_path = wx.FileSelector(
            flags=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST,
            wildcard='config files (*.ini)|*.ini|all files (*.*)|*.*',
            default_path=default_path,
            default_filename=default_file)

        wx.BeginBusyCursor()
        common.config_manager.set_config_file(config_path)
        common.config_manager.initialize_logging()

        # If the config file specifies a scenario, load it.
        scenario_path = common.config_manager.get_scenario_path()
        if scenario_path is not None:
            self.load_scenario(scenario_path)

        wx.EndBusyCursor()
コード例 #2
0
ファイル: fixstarsdlg.py プロジェクト: kshravi86/Morinus
	def fill(self, names):
		wx.WindowDisabler()

		self.initchecking = True
		wx.BeginBusyCursor()
		self.load()
		self.Populate()

		nset = set()
		items = self.fixstardata.iteritems()
		for k, v in items:
			for nomname in names.iterkeys():
				if v[1] == nomname and nomname not in nset:
					if len(nset) >= FixStarListCtrl.MAX_SEL_NUM:
						break

					self.CheckItem(k-1)
					nset.add(nomname)

		wx.EndBusyCursor()
		self.initchecking = False
コード例 #3
0
ファイル: mainui_ctrl.py プロジェクト: AndrDm/nditoolbox-labs
 def on_display_log(self, evt):
     """Handles request to display application log"""
     try:
         wx.BeginBusyCursor()
         log_path = pathfinder.log_path()
         default_log_contents = ['Log is currently empty.']
         log_contents = []
         if os.path.exists(log_path):
             with open(log_path, "r") as fidin:
                 log_contents = fidin.readlines()
         if len(log_contents) is 0:
             log_contents = default_log_contents
         text_display_dlg = dlg.TextDisplayDialog(
             parent=self.view,
             text=log_contents,
             title='NDIToolbox Log - {0}'.format(log_path),
             wrap=False,
             style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
         text_display_dlg.Show()
     finally:
         wx.EndBusyCursor()
コード例 #4
0
 def EvtRadioBox(self, event):
     realmId = event.GetInt()
     self.logger.debug('EvtRadioBox:     entry id : {}'.format(realmId))
     self.logger.debug('EvtRadioBox: selectedRealm: {}'.format(
         self.realms[realmId]))
     self.logger.debug('EvtRadioBox: currentRealm : {}'.format(
         self.currentRealm))
     if self.currentRealmId != realmId:
         try:
             self.currentRealm = self.realms[realmId]
             self.currentRealmId = realmId
             wx.BeginBusyCursor()
             self.updateDataPanel()
             wx.EndBusyCursor()
         except:
             stacktrace = traceback.format_exception(
                 sys.exc_info()[0],
                 sys.exc_info()[1],
                 sys.exc_info()[2])
             self.logger.debug(
                 'Failure in EvtRadioBox: {}'.format(stacktrace))
コード例 #5
0
    def doAutoDetect(self, event):
        wx.BeginBusyCursor()
        self.shutdown()
        impinjHost = AutoDetect(ImpinjInboundPort, self.autoDetectCallback)
        wx.EndBusyCursor()

        if impinjHost:
            self.useStaticAddress.SetValue(True)
            self.useHostName.SetValue(False)

            self.impinjHost.SetValue(impinjHost)
            self.doReset()
            self.writeOptions()
            wx.Bell()
        else:
            dlg = wx.MessageDialog(
                self,
                'Auto Detect Failed.\nCheck that reader has power and is connected to the router.',
                'Auto Detect Failed', wx.OK | wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
コード例 #6
0
 def OnSearch(self, event=None):
     value = self.filter.GetValue()
     if not value:
         self.resultList.initResultsActive()
         self.resultList.OnUpdateColumns()
         self.resultList.PopulateList()
         self.resultList.SendSizeEvent()
         return
     wx.BeginBusyCursor()
     newId = 1
     self.resultList.resultsActive.clear()
     for prevId, data in self.resultList.results.items():
         for entry in data:
             if re.search(str(value), str(entry), re.I):
                 self.resultList.resultsActive[newId] = data[:]
                 newId += 1
                 break
     self.resultList.OnUpdateColumns()
     self.resultList.PopulateList()
     self.resultList.SendSizeEvent()
     wx.EndBusyCursor()
コード例 #7
0
    def OnPickDir(self, event):

        wx.BeginBusyCursor()
        self.Freeze()
        path = event.GetPath()

        try:
            self.ulc.PopulateList(path)
        except OSError:
            self.log.write("You dont have permission to access folder: %s" %
                           path)
            wx.EndBusyCursor()
            self.Thaw()
            return

        self.Layout()
        self.SendSizeEvent()
        self.Thaw()

        self.ulc.DoLayout()
        wx.EndBusyCursor()
コード例 #8
0
    def _populate_with_data(self):
        pat = gmPerson.gmCurrentPatient()
        if not pat.connected:
            return True

        wx.BeginBusyCursor()
        try:
            self.__tl_file = gmTimelineExporter.create_timeline_file(
                patient=pat)
            self._PNL_timeline.open_timeline(self.__tl_file)
        except Exception:  # more specifically: TimelineIOError
            _log.exception('cannot load EMR from timeline XML')
            self._PNL_timeline.clear_timeline()
            self.__tl_file = gmTimelineExporter.create_fake_timeline_file(
                patient=pat)
            self._PNL_timeline.open_timeline(self.__tl_file)
            return True
        finally:
            wx.EndBusyCursor()

        return True
コード例 #9
0
 def CalcFPPS(self):
     """generate set of f' & f" curves for selected elements
        does constant delta-lambda/lambda steps over defined range
     """
     FPPS = []
     if self.Elems:
         wx.BeginBusyCursor()
         try:
             for Elem in self.Elems:
                 Els = Elem[0]
                 Els = Els = Els.ljust(2).lower().capitalize()
                 Wmin = self.Wmin
                 Wmax = self.Wmax
                 Z = Elem[1]
                 if Z > 78: Wmin = 0.16        #heavy element high energy failure of Cromer-Liberman
                 if Z > 94: Wmax = 2.67        #heavy element low energy failure of Cromer-Liberman
                 lWmin = math.log(Wmin)
                 N = int(round(math.log(Wmax/Wmin)/self.Wres))    #number of constant delta-lam/lam steps
                 I = range(N+1)
                 Ws = []
                 for i in I: Ws.append(math.exp(i*self.Wres+lWmin))
                 fps = []
                 fpps = []
                 Es = []
                 for W in Ws:
                     E = self.Kev/W
                     DE = E*self.Eres                         #smear by defined source resolution
                     res1 = G2elem.FPcalc(Elem[3],E+DE)
                     res2 = G2elem.FPcalc(Elem[3],E-DE)
                     fps.append((res1[0]+res2[0])/2.0)
                     fpps.append((res1[1]+res2[1])/2.0)
                     Es.append(E)
                 if self.ifWave:
                     Fpps = (Els,Ws,fps,fpps)
                 else:
                     Fpps = (Els,Es,fps,fpps)
                 FPPS.append(Fpps)
         finally:
             wx.EndBusyCursor()
     self.FPPS = FPPS
コード例 #10
0
    def run(self):
        """Filter all the given tiers."""

        wx.BeginBusyCursor()
        # Create a progress bar
        progress = ProcessProgressDialog(self.parent, self.parent._prefsIO,
                                         "Filtering progress...")
        progress.set_header("Filter system")
        progress.update(0, "")
        total = self.file_manager.GetSize()

        for i in range(self.file_manager.GetSize()):
            # obj is a TrsList instance
            obj = self.file_manager.GetObject(i)
            trs = obj.GetTranscription()

            # find the Y-tier
            y_tier = None
            if self.y_tier_name is not None:
                y_tier = trs.find(self.y_tier_name)

            for tier in trs:
                # tier is selected to be filtered
                if obj.IsSelected(tier.get_name()):
                    progress.set_header(self.file_manager.GetFilename(i))
                    progress.set_text(tier.get_name())

                    # so, we do the job!
                    new_tier = self.run_on_tier(tier, y_tier)
                    if new_tier is not None:
                        # add the new tier both in Transcription and in the list
                        obj.AddTier(new_tier)

                    progress.set_fraction(float((i + 1)) / float(total))

        # Indicate completed!
        progress.update(1, "Completed.\n")
        progress.set_header("")
        progress.close()
        wx.EndBusyCursor()
コード例 #11
0
def launch_process(function, callback=None, *args, **kwargs):
    resultchannel = multiprocessing.Queue()
    stuff = (function, resultchannel, args, kwargs)
    subproc = multiprocessing.Process(target=sub_runner, args=stuff)
    try:
        wx.BeginBusyCursor()
        subproc.start()

        while subproc.is_alive():
            wx.Yield()
            sleep(0.1)

        subproc.join()
        results = resultchannel.get(block=False)

        if isinstance(results, Exception):
            raise results
        elif callable(callback):
            return callback(results)
        elif hasattr(callback, 'Enable'):
            callback.Enable(True)
            return
        elif not callback:
            return results
        else:
            raise Exception, "Invalid callback."
    except Exception as err:
        messdog = wx.MessageDialog(
            None, ('An error occured:\n%s\n'
                   'Please consider '
                   'submitting a bug report '
                   'on the Multiplierz Github page.' % repr(err)),
            'Error',
            style=wx.OK)
        messdog.ShowModal()
        messdog.Destroy()
        #raise err
        return err
    finally:
        wx.EndBusyCursor()
コード例 #12
0
ファイル: sampling_frame.py プロジェクト: pesekon2/grass
    def writeArea(self, coords, rasterName):
        polyfile = tempfile.NamedTemporaryFile(delete=False)
        polyfile.write("AREA\n")
        for coor in coords:
            east, north = coor
            point = " %s %s\n" % (east, north)
            polyfile.write(point)

        catbuf = "=%d a\n" % self.catId
        polyfile.write(catbuf)
        self.catId = self.catId + 1

        polyfile.close()
        region_settings = grass.parse_command('g.region', flags='p',
                                              delimiter=':')
        pname = polyfile.name.split('/')[-1]
        tmpraster = "rast_" + pname
        tmpvector = "vect_" + pname
        wx.BeginBusyCursor()
        wx.GetApp().Yield()
        RunCommand('r.in.poly', input=polyfile.name, output=tmpraster,
                   rows=region_settings['rows'], overwrite=True)

        RunCommand('r.to.vect', input=tmpraster, output=tmpvector,
                   type='area', overwrite=True)

        RunCommand('v.to.rast', input=tmpvector, output=rasterName,
                   value=1, use='val')
        wx.EndBusyCursor()
        grass.use_temp_region()
        grass.run_command('g.region', vector=tmpvector)
        region = grass.region()

        marea = MaskedArea(region, rasterName)

        RunCommand('g.remove', flags='f', type='raster', name=tmpraster)
        RunCommand('g.remove', flags='f', type='vector', name=tmpvector)

        os.unlink(polyfile.name)
        return marea
コード例 #13
0
def class_select(inspector_win, class_name):
    try:
        wx.BeginBusyCursor()
        # Temporary object for get the commands, must be deleted!!
        inspector = pynebula.new(
                            "nobjinspector",
                            "/editor/inspector"
                            )
    
        # I can call the init function multipletimes to get the 
        # commands for all classes I want
        if class_name == "All":
            for name in inspector_win.object.getclasses():
                inspector.initcmdsclass( str(name) )
        else:
            inspector.initcmdsclass( str(class_name) )
            doc_string = "Class %s not found in xml database.\n"\
                                "Doc and custom controls deactivated" % class_name
            inspector_win.doc_text.SetLabel(doc_string)
            inspector_win.Layout()

        # Add the commands to the combox list
        num_cmds = inspector.getcmdscount()
        inspector_win.cmds_protos = list()
        inspector_win.get_dict = dict()
        for index in xrange(num_cmds):            
            inspector_win.cmds.Append(
                inspector.getcmdname(index) 
                )
            if re.compile("get.*").match( inspector.getcmdname(index) ):
                inspector_win.get_dict[inspector.getcmdname(index)] = \
                                                inspector.getcmdprotoname(index)

        # Delete the inspector
        pynebula.delete("/editor/inspector")
    
        inspector_win.cmds.SetValue("Choose command")
        inspector_win.btn_exec.Disable()
    finally:
        wx.EndBusyCursor()
コード例 #14
0
ファイル: setup.py プロジェクト: lvu/Phoenix
    def ResetClock(self):
        clock = self.GetParent()

        wx.BeginBusyCursor()

        clock.SetClockStyle(styles.DEFAULT_CLOCK_STYLE)
        clock.SetTickStyle(styles.TICKS_POLY, styles.HOUR)
        clock.SetTickStyle(styles.TICKS_CIRCLE, styles.MINUTE)

        clock.SetTickFont(wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT))

        clock.SetHandBorderWidth(0)
        clock.SetTickBorderWidth(0)
        clock.SetFaceBorderWidth(0)

        clock.SetHandSize(7, styles.HOUR)
        clock.SetHandSize(5, styles.MINUTE)
        clock.SetHandSize(1, styles.SECOND)

        clock.SetTickSize(25, styles.HOUR)
        clock.SetTickSize(5, styles.MINUTE)

        clock.SetTickOffset(0)

        clock.SetWindowStyle(wx.NO_BORDER)

        sw = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW)
        clock.SetShadowColour(sw)

        no_color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DFACE)
        clock.SetFaceFillColour(no_color)
        clock.SetFaceBorderColour(no_color)
        clock.SetBackgroundColour(no_color)

        fg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
        clock.SetForegroundColour(fg)

        self.UpdateControls()

        wx.EndBusyCursor()
コード例 #15
0
ファイル: wxgui.py プロジェクト: larygwil/fontypython
    def do_pog_zip(self, e):
        """
        The button in the choose_zipdir_panel was clicked.
        """
        czd = self.choose_zipdir_panel
        todir = czd.get_path()
        emsg = ""
        printer = czd.printout
        if todir:
            wx.BeginBusyCursor()
            for p in self.panelTargetPogChooser.list_of_target_pogs_selected:
                ipog = fontcontrol.Pog(p)
                (bugs, fail, emsgs) = ipog.zip(todir)

                if fail:
                    printer(
                        _("I could not create the zip for {}").format(ipog))
                    printer(emsgs[0])
                    printer("")
                else:
                    printer(
                        _("Zipped as \"{}.fonts.zip\" in the \"{}\" directory."
                          ).format(p, todir))
                    printer("")
                    if bugs:
                        printer(_("Some bugs happened:"))
                        for m in emsgs:
                            printer(m)
                        printer("")
            wx.EndBusyCursor()

            if bugs:
                printer(
                    _("Some fonts were skipped, try purging the Pog(s) involved."
                      ))
                ps.pub(print_to_status_bar, _("Something went wrong."))
            else:
                printer(_("Zip file(s) have been created."))
                ps.pub(print_to_status_bar,
                       _("Zip file(s) have been created."))
コード例 #16
0
    def OnButton_testParButton(self, event):
        '''Tests the entered parameters when the `Test parameters` button is pressed'''
        if args.debug: print('main_gui.OnButton_testParButton')
        self.status_bar.SetStatusText("Testing parameters...", 0)

        #Prep the parameters
        variables = self.update_variables()
        self.checkBox_fixed_ROI.Enable(False)

        ## Set up figure for plots
        self.figure.clear()
        self.axes = [
            self.figure.add_subplot(231),
            self.figure.add_subplot(232),
            self.figure.add_subplot(233),
            self.figure.add_subplot(234),
            self.figure.add_subplot(235),
            self.figure.add_subplot(236)
        ]

        ## Busy cursor while the main function runs
        wx.BeginBusyCursor()
        try:
            variables = variables + ['debug=' + str(args.debug)]
            self.detector.parameter_testing(variables, self.axes)
        finally:
            wx.EndBusyCursor()

        ## Renders plots in the GUI
        self.figure.tight_layout()
        self.figure.canvas.draw()

        # Enable buttons and print statements once parameter testing is complete
        self.button_reload_video.Enable(True)
        self.button_store_parameters.Enable(True)
        if args.debug: print('Parameter testing complete')
        self.status_bar.SetStatusText(
            "Refine detector parameters by reloading the video, or finish optimization by pressing 'Save configuration'",
            0)
        return
コード例 #17
0
	def updateData(self):
		wx.BeginBusyCursor()

		savedHeadersActive = self.headersActive[:]
		#self.logger.debug(' =======> updateData 0: {}'.format(self.headersActive))
		#self.logger.debug(' =======> updateData 1: {}'.format(savedHeadersActive))
		self.getResults()
		## Reset the active headers and the resultAttrs (positions)
		self.headersActive = savedHeadersActive
		self.resultAttrs = list(range(0,len(self.headers)))
		for x in reversed(range(0, len(self.headers))):
			headerName = self.headers[x]
			if headerName not in self.headersActive:
				self.resultAttrs.pop(x)
		#self.logger.debug(' =======> updateData 2: {}'.format(self.headersActive))
		self.resultsActive.clear()
		for prevId,data in self.results.items():
			self.resultsActive[prevId] = data[:]
		self.OnUpdateColumns()
		self.PopulateList()
		self.Layout()
		wx.EndBusyCursor()
コード例 #18
0
ファイル: gis_set.py プロジェクト: snakeice/grass
    def ImportFile(self, filePath):
        """Tries to import file as vector or raster.

        If successfull sets default region from imported map.
        """
        RunCommand('db.connect', flags='c')
        mapName = os.path.splitext(os.path.basename(filePath))[0]
        vectors = RunCommand('v.in.ogr', input=filePath, flags='l', read=True)

        wx.BeginBusyCursor()
        wx.GetApp().Yield()
        if vectors:
            # vector detected
            returncode, error = RunCommand('v.in.ogr',
                                           input=filePath,
                                           output=mapName,
                                           flags='e',
                                           getErrorMsg=True)
        else:
            returncode, error = RunCommand('r.in.gdal',
                                           input=filePath,
                                           output=mapName,
                                           flags='e',
                                           getErrorMsg=True)
        wx.EndBusyCursor()

        if returncode != 0:
            GError(parent=self,
                   message=_("Import of <%(name)s> failed.\n"
                             "Reason: %(msg)s") % ({
                                 'name': filePath,
                                 'msg': error
                             }))
        else:
            GMessage(message=_(
                "Data file <%(name)s> imported successfully. "
                "The location's default region was set from this imported map."
            ) % {'name': filePath},
                     parent=self)
コード例 #19
0
	def updateDataPanel(self):
		try:
			wx.BeginBusyCursor()
			self.logger.debug('updateDataPanel: starting')
			self.thisPanel.Freeze()

			## Replace the jobListPanel pane on the right
			self.jobBox.Detach(self.jobListPanel)
			self.jobListPanel.Destroy()
			self.jobListPanel = ResultListCtrlPanel(self.thisPanel, self.logger,
													self.api, self.jobDetails,
													self.jobView, self.orderedHeaders)
			self.jobBox.Add(self.jobListPanel, 1, wx.EXPAND|wx.TOP, 6)
			self.jobBox.Layout()
			self.thisPanel.SetSizer(self.mainBox)
			self.thisPanel.Thaw()
			self.thisPanel.Show()
			self.thisPanel.SendSizeEvent()
		except:
			stacktrace = traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])
			self.logger.debug('Failure in updateDataPanel: {}'.format(stacktrace))
		wx.EndBusyCursor()
コード例 #20
0
 def AddSearchResultsToListView(self, DocPaths, totalResults=0):
     wx.BeginBusyCursor()
     
     self.listSearchResults.ClearAll()
     self.AddListColumnHeadings()
     self.IconDict = {}
     totalFiles = 0
     self.il = wx.ImageList(16, 16)
     self.listSearchResults.AssignImageList(self.il, wx.IMAGE_LIST_SMALL)
     for doc in DocPaths:
         fileName = PlatformMethods.Decode(doc)
         iconFound = False
         if not (fileName.rfind('.') == -1):
             fileExtension = fileName[fileName.rfind('.'):]
             fileType = wx.TheMimeTypesManager.GetFileTypeFromExtension(fileExtension)
             if fileType:
                 #fullFileName = os.path.join(self.dirPath, data[0])
                 #try:
                 info = fileType.GetIconInfo()
                 if info:
                     icon, file, idx = info
                     #print icon
                     if icon.Ok():
                         #iconInfo[totalFiles] = icon
                         #bmp = wx.Image(opj('bitmaps/image.bmp'), wx.BITMAP_TYPE_BMP).ConvertToBitmap()
                         icon.SetSize(wx.Size(16, 16))
                         self.IconDict[totalFiles] = self.il.AddIcon(icon)
                         iconFound = True
                     
         if not iconFound:
             icon = images.getNoFile16Icon()
             self.IconDict[totalFiles] = self.il.AddIcon(icon)
             
         self.listSearchResults.InsertImageStringItem(sys.maxint, fileName, self.IconDict[totalFiles])
         totalFiles += 1
     
     self.lblSearchResults.SetLabel("Search Results for word: " + self.searchDocuments.GetValue() + " (" + str(totalResults) + ")")
     self.SetCursor(wx.STANDARD_CURSOR)
     wx.EndBusyCursor()
コード例 #21
0
    def MiseAJour(self, projet, fenDoc):
        if isinstance(self.pdf, wx.StaticText):
            #        if get_min_adobe_version() == None:
            print "Problème version Adobe"
            return
#        if hasattr(self, 'dosstemp') and get_min_adobe_version() == None:
#            shutil.rmtree(self.dosstemp)
        self.dosstemp = tempfile.mkdtemp()
        fichertemp = os.path.join(self.dosstemp, "pdfdoss.pdf")

        wx.BeginBusyCursor()
        Ok = genererDossierValidation(fichertemp, projet, fenDoc)
        if Ok:
            if not self.chargerFichierPDF(fichertemp):
                wx.EndBusyCursor()
                return
#            try:
#                self.pdf.LoadFile(fichertemp)
#            except:
#                print "ERREUR PDF"
#                wx.EndBusyCursor()
#                return

        if True:  #get_min_adobe_version() != None:
            try:
                shutil.rmtree(self.dosstemp)
            except:
                time.sleep(.5)
                try:
                    shutil.rmtree(self.dosstemp)
                except:
                    pass

        wx.EndBusyCursor()
        if not Ok:
            self.pdf = wx.StaticText(
                self, -1,
                u"Un des textes descriptifs du projet est trop grand !")
            self.sizer.Add(self.pdf, proportion=1, flag=wx.EXPAND)
コード例 #22
0
ファイル: render2.py プロジェクト: lucadelu/grass-addons
    def AddMapLayer(self, mlayer, render=False, pos=-1):
        wx.BeginBusyCursor()
        # opacity must be <0;1>
        if mlayer.opacity < 0:
            opacity = 0
        elif mlayer.opacity > 1:
            opacity = 1

        # add maplayer to the list of layers
        if pos > -1:
            self.layers.insert(pos, mlayer)
        else:
            self.layers.append(mlayer)

        Debug.msg(3, "Map.AddLayer(): layer=%s" % mlayer.name)
        if render:
            if not mlayer.Render():
                raise GException(_("Unable to render map layer <%s>.") % mlayer.name)

        wx.EndBusyCursor()

        return mlayer
コード例 #23
0
    def FormatMode(self, mode):
        wx.BeginBusyCursor()
        wx.Yield()
        if mode == "Mac":
            self.SetEOLMode(wx.stc.STC_EOL_CR)
            text = self.GetText()
            text = EpyGlob.FormatMacReTarget.sub('\r', text)
            self.SetText(text)
            self.OnModified(None)
        elif mode == "Unix":
            self.SetEOLMode(wx.stc.STC_EOL_LF)
            text = self.GetText()
            text = EpyGlob.FormatUnixReTarget.sub('\n', text)
            self.SetText(text)
        elif mode == 'Win':
            self.SetEOLMode(wx.stc.STC_EOL_CRLF)
            text = self.GetText()
            text = EpyGlob.FormatWinReTarget.sub('\r\n', text)
            self.SetText(text)

        self.OnModified(None)
        wx.EndBusyCursor()
コード例 #24
0
    def OnItemSelected(self, e):
        filename = self.GetFilePath()
        if not filename:
            return
        wx.BeginBusyCursor()

        try:
            try:
                image = core.load_image(filename)
            except Exception as e:
                gui_util.message(
                    "Loading image %s failed. \n\nThe error was:\n%s" %
                    (filename, str(e)))
                return
        finally:
            wx.EndBusyCursor()
        width, height = self.image_display.id.GetSize()
        scale = max(
            float(width) / float(image.width),
            (float(height) / float(image.height)))
        self.image_display.id.set_image(image, weak=0)
        self.image_display.id.scale(scale)
コード例 #25
0
    def UpdateSearch(self):
        dmin = self.datmin.GetValue()
        ctb.DATSEARCH1 = dmin
        dmax = self.datmax.GetValue()
        ctb.DATSEARCH2 = dmax
        filter = "reg.id_caus=%d" % self.cauid
        par = []
        if dmin:
            filter += " AND reg.datreg>=%s"
            par.append(dmin)
        if dmax:
            filter += " AND reg.datreg<=%s"
            par.append(dmax)
        try:
            wx.BeginBusyCursor()
            try:
                cmd = \
"""   SELECT reg.id, reg.datreg, riv.codice, reg.numiva, """\
"""          pdc.descriz, reg.numdoc, reg.datdoc, """\
"""          SUM(row.imponib), SUM(row.imposta) """\
"""     FROM ((%s AS reg JOIN %s AS cau ON reg.id_caus=cau.id) """\
"""LEFT JOIN contab_b AS row ON row.id_reg=reg.id) """\
"""LEFT JOIN pdc AS pdc ON row.id_pdcpa=pdc.id """\
"""     JOIN regiva AS riv ON reg.id_regiva=riv.id """\
"""    WHERE %s """\
""" GROUP BY reg.id, reg.datreg, riv.codice, reg.numiva, """\
"""          pdc.descriz, reg.numdoc, reg.datdoc """\
""" ORDER BY reg.datreg, reg.numiva """\
 % (bt.TABNAME_CONTAB_H, bt.TABNAME_CFGCONTAB, filter)
                db_curs = Env.adb.db.__database__._dbCon.cursor()
                db_curs.execute(cmd, par)
                rs = db_curs.fetchall()
                db_curs.close()
                self.gridsrc.ChangeData(rs)

            except MySQLdb.Error, e:
                MsgDialogDbError(self, e)
        finally:
            wx.EndBusyCursor()
コード例 #26
0
 def OnCallDoc(self, event):
     assert isinstance(self, dbglib.DbGrid)
     row = event.GetRow()
     dbdoc = self.dbdoc
     if 0 <= row < dbdoc.RowsCount():
         dbdoc.MoveRow(row)
         if magazz.CheckPermUte(dbdoc.id_tipdoc, 'leggi'):
             wx.BeginBusyCursor()
             try:
                 Dialog = magazz.GetDataentryDialogClass()
                 dlg = Dialog(aw.awu.GetParentFrame(self))
                 dlg.SetOneDocOnly(dbdoc.id)
                 dlg.CenterOnScreen()
             finally:
                 wx.EndBusyCursor()
             r = dlg.ShowModal()
             if r in (magazz.DOC_MODIFIED, magazz.DOC_DELETED):
                 self.UpdateGrid()
                 if r == magazz.DOC_MODIFIED:
                     wx.CallAfter(lambda: self.SelectRow(row))
             dlg.Destroy()
     event.Skip()
コード例 #27
0
    def Remplissage(self):
        """ Remplissage du contrôle """
        wx.BeginBusyCursor()
        self.Freeze()

        self.ClearAll()
        if self.mode == "local":
            self.listeFichiers = self.GetListeFichiersLocal()
        else:
            self.listeFichiers = self.GetListeFichiersReseau()

        self.InsertColumn(0, "Column 1")
        self.InsertColumn(1, "Column 2")

        for dictFichier in self.listeFichiers:
            index = self.InsertStringItem(six.MAXSIZE, "")

            klass = FirstColumnRenderer(self,
                                        titre=dictFichier["titre"],
                                        image=dictFichier["image"],
                                        description=dictFichier["description"])
            self.SetItemCustomRenderer(index, 0, klass)

            if self.details == True and self.mode != "reseau":
                self.SetStringItem(index, 1, "")
                klass = SecondColumnRenderer(
                    self,
                    dateModif=dictFichier["dateModif"],
                    taille=dictFichier["taille"])
                self.SetItemCustomRenderer(index, 1, klass)

            self.SetItemPyData(index, dictFichier)

        self.SetColumnWidth(0, ULC.ULC_AUTOSIZE_FILL)
        self.SetColumnWidth(1, wx.LIST_AUTOSIZE)

        self.Thaw()
        self.SendSizeEvent()
        wx.EndBusyCursor()
コード例 #28
0
def adaptiveConstrastStretch(image, localAreaSize):
    """This function performs the adaptive contrast stretching using the
    Pizer method. (see Majid Rabbani notes) It operates only on monochrome
    images."""

    image = image.convert("L")

    sizeX, sizeY = image.size
    if localAreaSize >= sizeX or localAreaSize >= sizeY:
        return linearConstrastStretch(image)
    else:
        wx.BeginBusyCursor()  # start hour-glass cursor
        mono1 = image.copy()
        ngp = getGridSize(localAreaSize, sizeX, sizeY)  # number of grid points in x and y
        gp = getGridPointLocations(ngp, sizeX, sizeY, localAreaSize) # grid point locations
        minmax = obtainMinMax(mono1, gp, ngp, localAreaSize) # set of min-max at each gridpoint
        ngpx = ngp[0]
        ngpy = ngp[1]

        for y in range(0, ngpy-1):
            for x in range(0, ngpx-1):
                upperleft = gp[y*ngpx+x]
                lowerright = gp[(y + 1)*ngpx+(x + 1)]

                gridArea = getAreaBetweenGridpoints(mono1, upperleft, lowerright)
                locmm = get4PtMinMax(minmax, x, y, ngp)
                gridArea = contrastStretchLocArea(gridArea, locmm)

                # copies gridArea to proper part of aoi
                gsX, gsY = gridArea.size
                sizeX, sizeY = mono1.size
                if upperleft[0]+gsX > sizeX:
                    upperleft[0] = sizeX - gsX
                if upperleft[1]+gsY > sizeY:
                    upperleft[1] = sizeY - gsY
                image.paste(gridArea, (upperleft[0], upperleft[1], upperleft[0]+gsX, upperleft[1]+gsY))

        wx.EndBusyCursor()  # end hour-glass cursor
        return image
コード例 #29
0
ファイル: clipboard.py プロジェクト: rdhyee/wxGlade
def _paste(parent, index, clipboard_data, rebuild_tree=True):
    "parse XML and insert widget"
    option, span, flag, border, xml_unicode = clipboard2widget( clipboard_data )
    if not xml_unicode: return None
    import xml_parse
    try:
        wx.BeginBusyCursor()
        # widget representation is still unicode, but parser need UTF8
        xml_utf8 = xml_unicode.encode('utf8')
        parser = xml_parse.ClipboardXmlWidgetBuilder(parent, index, option, span, flag, border)
        with parent and parent.frozen() or misc.dummy_contextmanager():
            parser.parse_string(xml_utf8)
            if parent and hasattr(parent, "on_child_pasted"):
                parent.on_child_pasted()  # trigger e.g. re-sizing of the children
        freeze = parser._object_counter>80  # for more objects, we freeze the Tree during re-build
        if rebuild_tree: misc.rebuild_tree( parser.top_obj, freeze=freeze )
        return parser.top_obj  # Widget hierarchy pasted.
    except xml_parse.XmlParsingError:
        if config.debugging: raise
        return None
    finally:
        wx.EndBusyCursor()
コード例 #30
0
ファイル: main.py プロジェクト: nagyistoce/devide
    def set_progress(self, progress, message, noTime=False):
        self._main_frame.set_progress(int(round(progress)), message)

        # we also output an informative message to standard out
        # in cases where DeVIDE is very busy, this is quite
        # handy.
        print "%s: %.2f" % (message, progress)

        # activate the busy cursor (we're a bit more lenient
        # on its epsilon)
        if abs(progress - 100.0) > 1:
            if not wx.IsBusy():
                wx.BeginBusyCursor()

            # or switch it off
        else:
            if wx.IsBusy():
                wx.EndBusyCursor()

            # let's also show the completion message in the
            # message log...
            self.log_info(message)

        # bring this window to the top if the user wants it
        #if self._main_frame.progressRaiseCheckBox.GetValue():
        #    self._main_frame.Raise()

        # we want wx to update its UI, but it shouldn't accept any
        # user input, else things can get really crazy. -
        # we do keep interaction for the main window enabled,
        # but we disable all menus.
        menuCount = self._main_frame.GetMenuBar().GetMenuCount()
        for menuPos in range(menuCount):
            self._main_frame.GetMenuBar().EnableTop(menuPos, False)

        wx.SafeYield(win=self._main_frame)

        for menuPos in range(menuCount):
            self._main_frame.GetMenuBar().EnableTop(menuPos, True)