Example #1
0
    def on_start_btn(self, event):
        if self.file_fname.GetValue() == '':
            self.log_text.AppendText(
                f'{datetime.now()}\tPlease select a file to process first\n')
            return

        if self.base_checkbox.GetValue() and self.base_fname.GetValue() == '':
            self.log_text.AppendText(
                f'{datetime.now()}\tPlease select a basestation file first\n')
            return

        # BASE STATION DATA
        self.base_filename = self.base_fname.GetValue()
        self.log_text.AppendText(
            f'{datetime.now()}:\tBase station file: {self.base_filename}\n')
        base = prep_functions.Base(self.base_filename,
                                   utc=int(config['Base']['utc_offset']))
        base_data = base.read_file()

        # MAG DATA
        self.filename = self.file_fname.GetValue()
        sensor = self.sensor_radio_box.GetStringSelection()

        if sensor == 'MagArrow':
            self.log_text.AppendText(
                f'{datetime.now()}:\tStarting to process MagArrow file: {self.filename}\n'
            )

            ma = prep_functions.MagArrow(filename=self.filename,
                                         base=base_data)

            # check file and if all readings are valid
            try:
                if ma.check_mag() != 0:
                    ma.valid = False
            except IOError:
                self.log_text.AppendText(
                    'Wrong file. Please check filepath.\n')
                return

            # deal with file if some readings are invalid
            if not ma.valid:
                msg = 'Invalid readings in MagArrow file. Do you want to continue?'
                warn_dlg = wx.MessageBox(message=msg,
                                         caption="Warning",
                                         style=wx.YES_NO)

                if warn_dlg == wx.YES:
                    ma.valid = True
                else:
                    return

            # start processing file
            ma.start_after_check()

            # SAVE DATA
            self.log_text.AppendText(
                f'{datetime.now()}:\tData processing finished\n')
            # get path
            dlg = wx.FileDialog(self,
                                message='Save MagArrow file',
                                defaultDir="",
                                defaultFile="",
                                wildcard="csv files (*.csv)|*.csv",
                                style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
            if dlg.ShowModal() == wx.ID_OK:
                self.filename_newfile = dlg.GetPath()
            else:
                self.log_text.AppendText(
                    f'{datetime.now()}:\tUser stopped saving data.\n')
            # save
            if ma.save_data(new_file=self.filename_newfile):
                self.log_text.AppendText(
                    f'{datetime.now()}:\tData saved as {self.filename_newfile}\n\n'
                )
            else:
                self.log_text.AppendText(
                    f'{datetime.now()}:\tCan not save data. Check filepath\n')

        elif sensor == 'MagDrone':
            try:
                with open(self.filename) as f:
                    file_header = f.readline()
            except IOError:
                self.log_text.AppendText(
                    'Wrong file. Please check filepath.\n')
                return

            self.log_text.AppendText(
                f'{datetime.now()}:\tStarting to process MagDrone file: {self.filename} '
                f'with header: {file_header}')
            md = prep_functions.MagDrone(filename=self.filename,
                                         base=base_data)

            # SAVE DATA
            self.log_text.AppendText(
                f'{datetime.now()}:\tFinished processing MagDrone file. Save file..\n'
            )

            # get path
            dlg = wx.FileDialog(self,
                                message='Save MagDrone file',
                                defaultDir="",
                                defaultFile="",
                                wildcard="csv files (*.csv)|*.csv",
                                style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
            if dlg.ShowModal() == wx.ID_OK:
                self.filename_newfile = dlg.GetPath()
            else:
                self.log_text.AppendText(
                    f'{datetime.now()}:\tUser stopped saving data.\n')
                return

            # save
            if md.save_data(new_file=self.filename_newfile):
                self.log_text.AppendText(
                    f'{datetime.now()}:\tData saved as {self.filename_newfile}\n\n'
                )
            else:
                self.log_text.AppendText(
                    f'{datetime.now()}:\tSomething wrong with path to new file.\n'
                )

        # FLIGHTLOG MERGE
        if self.flightlog_radio_box.GetStringSelection() == 'Yes':
            self.flightlog_merge()
 def __on_open(self, _event):
     dlg = wx.FileDialog(self, "Open a scan", self.directory, '',
                         File.get_type_filters(File.Types.SAVE), wx.OPEN)
     if dlg.ShowModal() == wx.ID_OK:
         self.__open(dlg.GetDirectory(), dlg.GetFilename())
     dlg.Destroy()
Example #3
0
 def onLoadFile(self, e):
     self.openFileDialog = wx.FileDialog(self, "Open", "", "", "*",
                                         wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
     self.openFileDialog.ShowModal()
     print self.openFileDialog.GetPath()
     self.openFileDialog.Destroy()
Example #4
0
def save_figure(self, evt=None):
    """
        A substitude function for save in:
        matplotlib.backends.backend_wx.NavigationToolbar2Wx
        We want to be able to give parameters such as dirname and filename.
    """
    try:
        parent = self.canvas.HACK_parent
        fig = self.canvas.HACK_fig
        Page = self.canvas.HACK_Page
        add = self.canvas.HACK_append
        dirname = parent.dirname
        filename = self.canvas.get_window_title().replace(" ",
                                                          "_").lower() + add
        formats = fig.canvas.get_supported_filetypes()
    except:
        dirname = "."
        filename = ""
        formats = self.canvas.get_supported_filetypes()
        parent = self
    fieltypestring = ""
    keys = formats.keys()
    keys.sort()
    for key in keys:
        fieltypestring += formats[key] + "(*." + key + ")|*." + key + "|"
    # remove last |
    fieltypestring = fieltypestring[:-1]
    dlg = wx.FileDialog(parent, "Save figure", dirname, filename,
                        fieltypestring, wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
    # png is default
    dlg.SetFilterIndex(keys.index("png"))
    # user cannot do anything until he clicks "OK"
    if dlg.ShowModal() == wx.ID_OK:
        wildcard = keys[dlg.GetFilterIndex()]
        filename = dlg.GetPath()
        if not filename.endswith(wildcard):
            filename += "." + wildcard
        dirname = dlg.GetDirectory()
        #savename = os.path.join(dirname, filename)
        savename = filename
        try:
            self.canvas.figure.savefig(savename)
        except:  # RuntimeError:
            # The file does not seem to be what it seems to be.
            info = sys.exc_info()
            errstr = "Could not latex output:\n"
            errstr += str(filename) + "\n\n"
            errstr += str(info[0]) + "\n"
            errstr += str(info[1]) + "\n"
            for tb_item in traceback.format_tb(info[2]):
                errstr += tb_item
            wx.MessageDialog(parent,
                             errstr,
                             "Error",
                             style=wx.ICON_ERROR | wx.OK | wx.STAY_ON_TOP)
    else:
        dirname = dlg.GetDirectory()
    try:
        parent.dirname = dirname
    except:
        pass
Example #5
0
 def OpenFiles(self, filenames=[], select=True, index=-1):
     if not len(filenames):
         dialog = wx.FileDialog(self,
                                defaultDir=os.path.dirname(
                                    self.GetEditor().filename),
                                wildcard=self.filetypes,
                                style=wx.FD_OPEN | wx.FD_MULTIPLE)
         if dialog.ShowModal() == wx.ID_OK:
             filenames = dialog.GetPaths()
         dialog.Destroy()
         if not len(filenames):
             return
     if len(filenames) > 15:
         proceed = wx.MessageBox(
             _("Opening too many files at once can use an excessive amount of system resources.\nAre you sure that you want to continue?"
               ), "Write++", wx.ICON_WARNING | wx.YES_NO | wx.NO_DEFAULT)
         if proceed != wx.YES:
             return
     if pywin32:
         for i in range(len(filenames)):
             if os.path.splitext(
                     filenames[i]
             )[1] == ".lnk":  # Don't open a shortcut, but the file it points to
                 shortcut = pythoncom.CoCreateInstance(
                     shell.CLSID_ShellLink, None,
                     pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
                 shortcut.QueryInterface(pythoncom.IID_IPersistFile).Load(
                     filenames[i])
                 filenames[i] = shortcut.GetPath(shell.SLGP_UNCPRIORITY)[0]
     filenames = self.CheckOpenFiles(filenames)
     for filename in filenames:
         if os.path.isfile(filename):
             if self.notebook.GetPageCount(
             ) == 1 and not self.HasSavedOrChanged():
                 self.GetEditor(0).OnInit(filename)
             else:
                 page = notebook.SplitterWindow(self, filename)
                 editor = page.editors[0]
                 title = os.path.split(filename)[1]
                 if editor.changes:
                     title = "*%s" % title
                 if index == -1:
                     self.notebook.AddPage(page, title, select,
                                           editor.image)
                     self.notebook.SetRenamable(
                         self.notebook.GetPageCount() - 1, True)
                 else:
                     self.notebook.InsertPage(index, page, title, select,
                                              editor.image)
                     self.notebook.SetRenamable(index, True)
                     index += 1
             self.menubar.recent.AddFile(filename)
         elif os.path.isdir(filename):
             filenames2 = []
             for path, dirs, files in os.walk(filename, False):
                 filenames2 += [
                     os.path.join(path, filename2) for filename2 in files
                 ]
             self.OpenFiles(filenames2, select, index)
         else:
             create = wx.MessageBox(
                 _("'%s' does not exist.\nWould you like to create it?") %
                 filename, "Write++",
                 wx.ICON_QUESTION | wx.YES_NO | wx.NO_DEFAULT)
             if create == wx.YES:
                 open(filename, 'w').close()
                 self.OpenFile(filename, select, index)
             elif filename in self._app.settings["RecentFiles"]:
                 self.menubar.recent.RemoveFile(filename)
Example #6
0
    def __init__(self, parent, mode):
        wx.Frame.__init__(self, parent, -1, "Ballot File Editor")

        warnings.showwarning = self.catchWarnings

        self.MakeMenu()
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
        self.logfName = ""

        fn = os.path.join(getHome(), "Icons", "blt.ico")
        icon = wx.Icon(fn, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

        # Edit a new ballot file
        if mode == "new":

            # Create an empty ballots class instance
            self.b = Ballots()

            # Get the candidate names from the user
            dlg = CandidatesDialog(parent, self.b)
            dlg.Center()
            if dlg.ShowModal() != wx.ID_OK:
                dlg.Destroy()
                self.Destroy()
                return
            dlg.Destroy()

        # Edit an existing ballot file
        elif mode == "old":
            dlg = wx.FileDialog(self,
                                "Edit Ballot File",
                                style=wx.OPEN | wx.CHANGE_DIR)
            if dlg.ShowModal() != wx.ID_OK:
                dlg.Destroy()
                self.Destroy()
                return
            fName = dlg.GetPath()
            dlg.Destroy()

            # Open the file
            try:
                self.b = Ballots()
                self.b.loadUnknown(fName)
            except RuntimeError as msg:
                wx.MessageBox(str(msg), "Error", wx.OK | wx.ICON_ERROR)
                self.Destroy()
                return

        else:
            assert (0)

        # Set the window title to include the filename
        fn = self.b.getFileName()
        if fn is not None:
            title = "%s - Ballot File Editor" % os.path.basename(fn)
        else:
            title = "%s - Ballot File Editor" % "New File"
        self.SetTitle(title)

        # Create a notebook with an editing page and a log page
        nb = wx.Notebook(self, -1)

        self.panel = BallotsPanel(nb, self.b)
        nb.AddPage(self.panel, "Ballots")

        self.logN = 1  # counter for display purposes
        self.log = wx.TextCtrl(nb, -1,
                               style=wx.TE_MULTILINE|wx.TE_READONLY|\
                               wx.TE_WORDWRAP|wx.FIXED)
        self.log.SetMaxLength(0)
        nb.AddPage(self.log, "Log")

        # Initialize
        if mode == "new":
            self.panel.NeedToSaveBallots = True
            self.Log("Created a new ballot file.")
        elif mode == "old":
            self.panel.NeedToSaveBallots = False
            self.Log("Loaded %d ballots from file %s." %\
                     (self.b.numBallots, os.path.basename(self.b.getFileName())))
        else:
            assert (0)

        # Set up the sizer
        sizer = wx.BoxSizer()
        sizer.Add(nb, 1, wx.EXPAND, 0)
        self.SetSizer(sizer)
        sizer.Fit(self)
        sizer.SetSizeHints(self)
Example #7
0
    def OnCalibrateAstigmatism(self, event):
        #TODO - move all non-GUI logic for this out of this file?
        from PYME.recipes.measurement import FitPoints
        from PYME.IO.FileUtils import nameUtils
        import matplotlib.pyplot as plt
        import matplotlib.cm
        import mpld3
        import warnings
        if warnings.filters[0] == ('always', None, DeprecationWarning, None,
                                   0):
            #mpld3 has messed with warnings - undo
            warnings.filters.pop(0)

        import json
        from PYME.Analysis.PSFEst import extractImages
        import wx
        from PYME.Analysis.points.astigmatism import astigTools

        # query user for type of calibration
        # NB - GPU fit is not enabled here because it exits on number of iterations, which is not necessarily convergence for very bright beads!
        ftypes = ['BeadConvolvedAstigGaussFit',
                  'AstigGaussFitFR']  # , 'AstigGaussGPUFitFR']
        fitType_dlg = wx.SingleChoiceDialog(self.dsviewer,
                                            'Fit-type selection',
                                            'Fit-type selection', ftypes)
        fitType_dlg.ShowModal()
        fitMod = ftypes[fitType_dlg.GetSelection()]

        if (fitMod == 'BeadConvolvedAstigGaussFit') and (
                'Bead.Diameter' not in self.image.mdh.keys()):
            beadDiam_dlg = wx.NumberEntryDialog(None, 'Bead diameter in nm',
                                                'diameter [nm]',
                                                'diameter [nm]', 100, 1, 9e9)
            beadDiam_dlg.ShowModal()
            beadDiam = float(beadDiam_dlg.GetValue())
            # store this in metadata
            self.image.mdh['Analysis.Bead.Diameter'] = beadDiam

        ps = self.image.pixelSize

        obj_positions = {}

        obj_positions['x'] = ps * self.image.data.shape[0] * 0.5 * np.ones(
            self.image.data.shape[2])
        obj_positions['y'] = ps * self.image.data.shape[1] * 0.5 * np.ones(
            self.image.data.shape[2])
        obj_positions['t'] = np.arange(self.image.data.shape[2])
        z = np.arange(
            self.image.data.shape[2]) * self.image.mdh['voxelsize.z'] * 1.e3
        obj_positions['z'] = z - z.mean()

        ptFitter = FitPoints()
        ptFitter.trait_set(roiHalfSize=11)
        ptFitter.trait_set(fitModule=fitMod)

        namespace = {'input': self.image, 'objPositions': obj_positions}

        results = []

        for chanNum in range(self.image.data.shape[3]):
            # get z centers
            dx, dy, dz = extractImages.getIntCenter(self.image.data[:, :, :,
                                                                    chanNum])

            ptFitter.trait_set(channel=chanNum)
            ptFitter.execute(namespace)

            res = namespace['fitResults']

            dsigma = abs(res['fitResults_sigmax']) - abs(
                res['fitResults_sigmay'])
            valid = ((res['fitError_sigmax'] > 0) *
                     (res['fitError_sigmax'] < 50) *
                     (res['fitError_sigmay'] < 50) *
                     (res['fitResults_A'] > 0) > 0)

            results.append({
                'sigmax':
                abs(res['fitResults_sigmax'][valid]).tolist(),
                'error_sigmax':
                abs(res['fitError_sigmax'][valid]).tolist(),
                'sigmay':
                abs(res['fitResults_sigmay'][valid]).tolist(),
                'error_sigmay':
                abs(res['fitError_sigmay'][valid]).tolist(),
                'dsigma':
                dsigma[valid].tolist(),
                'z':
                obj_positions['z'][valid].tolist(),
                'zCenter':
                obj_positions['z'][int(dz)]
            })

        #generate new tab to show results
        use_web_view = False
        if not '_astig_view' in dir(self):
            try:
                self._astig_view = wx.html2.WebView.New(self.dsviewer)
                self.dsviewer.AddPage(self._astig_view, True,
                                      'Astigmatic calibration')

            except NotImplementedError:
                use_web_view = False

        # find reasonable z range for each channel, inject 'zRange' into the results. FIXME - injection is bad
        results = astigTools.find_and_add_zRange(results)

        #do plotting
        plt.ioff()
        f = plt.figure(figsize=(10, 4))

        colors = iter(
            matplotlib.cm.Dark2(np.linspace(0, 1,
                                            2 * self.image.data.shape[3])))
        plt.subplot(121)
        for i, res in enumerate(results):
            nextColor1 = next(colors)
            nextColor2 = next(colors)
            lbz = np.absolute(res['z'] - res['zRange'][0]).argmin()
            ubz = np.absolute(res['z'] - res['zRange'][1]).argmin()
            plt.plot(res['z'], res['sigmax'], ':',
                     c=nextColor1)  # , label='x - %d' % i)
            plt.plot(res['z'], res['sigmay'], ':',
                     c=nextColor2)  # , label='y - %d' % i)
            plt.plot(res['z'][lbz:ubz],
                     res['sigmax'][lbz:ubz],
                     label='x - %d' % i,
                     c=nextColor1)
            plt.plot(res['z'][lbz:ubz],
                     res['sigmay'][lbz:ubz],
                     label='y - %d' % i,
                     c=nextColor2)

        #plt.ylim(-200, 400)
        plt.grid()
        plt.xlabel('z position [nm]')
        plt.ylabel('Sigma [nm]')
        plt.legend()

        plt.subplot(122)
        colors = iter(
            matplotlib.cm.Dark2(np.linspace(0, 1, self.image.data.shape[3])))
        for i, res in enumerate(results):
            nextColor = next(colors)
            lbz = np.absolute(res['z'] - res['zRange'][0]).argmin()
            ubz = np.absolute(res['z'] - res['zRange'][1]).argmin()
            plt.plot(res['z'], res['dsigma'], ':', lw=2,
                     c=nextColor)  # , label='Chan %d' % i)
            plt.plot(res['z'][lbz:ubz],
                     res['dsigma'][lbz:ubz],
                     lw=2,
                     label='Chan %d' % i,
                     c=nextColor)
        plt.grid()
        plt.xlabel('z position [nm]')
        plt.ylabel('Sigma x - Sigma y [nm]')
        plt.legend()

        plt.tight_layout()

        plt.ion()
        #dat = {'z' : objPositions['z'][valid].tolist(), 'sigmax' : res['fitResults_sigmax'][valid].tolist(),
        #                   'sigmay' : res['fitResults_sigmay'][valid].tolist(), 'dsigma' : dsigma[valid].tolist()}

        if use_web_view:
            fig = mpld3.fig_to_html(f)
            data = json.dumps(results)

            template = env.get_template('astigCal.html')
            html = template.render(astigplot=fig, data=data)
            #print html
            self._astig_view.SetPage(html, '')
        else:
            plt.show()

        fdialog = wx.FileDialog(
            None,
            'Save Astigmatism Calibration as ...',
            wildcard='Astigmatism Map (*.am)|*.am',
            style=wx.FD_SAVE,
            defaultDir=nameUtils.genShiftFieldDirectoryPath(
            ))  #, defaultFile=defFile)
        succ = fdialog.ShowModal()
        if (succ == wx.ID_OK):
            fpath = fdialog.GetPath()

            fid = open(fpath, 'w', encoding='utf8')
            json.dump(results, fid, indent=4, sort_keys=True)
            fid.close()
            if use_web_view:  # save the html too
                import os
                fpath = os.path.splitext(fpath)[0] + '.html'
                with open(fpath, 'wb') as fid:
                    fid.write(html.encode('utf-8'))

        return results
Example #8
0
#==============================================================================
# start the wx application
app = None
app = wx.App()
#==============================================================================
# Show a FileSelect dialog to choose a file for display
#==============================================================================

# Wildcard: offer all supported filetypes for display
wild = "supported files|*.pdf;*.xps;*.oxps;*.epub;*.cbz"

#==============================================================================
# define the file selection dialog
#==============================================================================
dlg = wx.FileDialog(None, message = "Choose a file to display",
                    defaultDir = os.path.expanduser("~"),
                    defaultFile = "",
                    wildcard = wild, style=wx.OPEN|wx.CHANGE_DIR)

#==============================================================================
# now display and ask for return code in one go
#==============================================================================
# We got a file only when one was selected and OK pressed
if dlg.ShowModal() == wx.ID_OK:
    # This returns a Python list of selected files (we only have one though)
    filename = dlg.GetPaths()[0]
else:
    filename = None

# destroy this dialog
dlg.Destroy()
    def onAddEvidence(self, event):
        global caseDetails
        try:
            caseDetails
        except NameError:
            #if caseDetails not defined
            print("Case not opened")
        else:
            #if caseDetails is defined
            #creates a filedialog that only allow user to select .pcap files
            openFileDialog = wx.FileDialog(self, "Open", "", "", "*.pcap",
                                           wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

            openFileDialog.ShowModal()
            global caseDir, caseDbPath

            #get path of selected dd file
            evidencePath = openFileDialog.GetPath()

            #find the window corresponding to the File tab so that we can access it
            pageCount = self.auiNotebook.GetPageCount()
            found = False
            print("Page count: ", pageCount)

            #must initialize the page count on top so i can use here to match the text
            for i in range(0, pageCount):  #0 to pageCount - 1
                text = self.auiNotebook.GetPageText(i)
                print("Page ", i, ": ", text, ";")
                if text == "Credentials":
                    window = self.auiNotebook.GetPage(i)
                    found = True
                    break  #from for-loop

            if False == found:
                print("ERROR: Credentials tab window not found!")
                #can't continue with this function
                return

            username = os.path.splitext(os.path.basename(evidencePath))
            print("Username: "******"\n")

            password = (os.stat(evidencePath)).st_size
            print("Username: "******"\n")

            login = (os.stat(evidencePath)).st_size
            print("Valid Login: "******"\n")

            timestamp = datetime.datetime.fromtimestamp(ts).strftime(
                '%Y-%m-%d %H:%M:%S')
            print("Login Timestamp: ", timestamp)
            print("\n")

            #rb is for opening non-text files
            f = open(evidencePath, 'rb')
            pcap = dpkt.pcap.Reader(f)

            for ts, buf in pcap:
                eth = dpkt.ethernet.Ethernet(buf)

                if eth.type == dpkt.ethernet.ETH_TYPE_IP:
                    ip_hdr = eth.data
                    ip = eth.ip
                    tcp = ip.data

                    #--------------------------#
                    #   Server to Web Client   #
                    #--------------------------#
                    src_ip_addr_bin = ip_hdr.src
                    src_host_str = socket.inet_ntoa(src_ip_addr_bin)

                    if ip_hdr.p == dpkt.ip.IP_PROTO_TCP:
                        #if the source port is 80 or 443 then looking at Response message
                        #from the server to the web client.
                        try:
                            http = dpkt.http.Response(tcp.data)
                            content_length = http.headers[
                                'content-length'] if 'content-length' in http.headers else ""
                            size = str(content_length)
                            #print("Content length: ", size)
                            protocol = protocol + (
                                http.headers['transfer-encoding']
                                if 'transfer-encoding' in http.headers else "")

                        except Exception:
                            print("Exception in Response direction")

                    else:
                        print("Protocol is not TCP")

                    #--------------------------#
                    #   Web Client to Server   #
                    #--------------------------#
                    dst_ip_addr_bin = ip_hdr.dst
                    dst_host_str = socket.inet_ntoa(dst_ip_addr_bin)

                    if ip_hdr.p == dpkt.ip.IP_PROTO_TCP:
                        #if the desitnation port is 80 or 443 then we're looking at a Request message
                        #from the web client to the server
                        try:
                            http = dpkt.http.Request(tcp.data)

                            host = http.headers[
                                'host'] if 'host' in http.headers else None
                            dst_host_str = dst_host_str + " [" + str(
                                host) + "]"

                            uri = http.uri
                            evidencePath = str(uri)
                            fileName = os.path.basename(evidencePath)
                            ext = os.path.splitext(fileName)[1][1:]

                            user_agent = http.headers[
                                'user-agent'] if 'user-agent' in http.headers else None
                            src_host_str = src_host_str + " [" + str(
                                user_agent) + "]"

                            protocol = protocol + (
                                http.headers['transfer-encoding']
                                if 'transfer-encoding' in http.headers else "")

                            if fileName != "":
                                httpFileTransferCount = httpFileTransferCount + 1

                        except Exception:
                            print("Exception in Request direction")

                    else:
                        print("Protocol is not TCP")

                    #------------------------#
                    #   Output to database   #
                    #------------------------#
                    #only show packets relating with file transfers (via port 80 or port 443)
                    sequence = [
                        src_host_str, dst_host_str, username, password, login,
                        timestamp
                    ]
                    pcapCredentialsTab.TabPanel.addCredentialsDetails(
                        window, sequence)

                else:
                    print("Unsupported packet type. Values not extracted.")

            print("\nPCAP extraction finished.\n")

            #close PCAP file
            openFileDialog.Destroy()
Example #10
0
    def on1DXRD(self,event=None):

        read, save, plot = False, False, False
        if self.calfile is not None and self.plt_img is not None:
            myDlg = Calc1DPopup(self,self.plt_img)
            if myDlg.ShowModal() == wx.ID_OK:
                read = True
                save = myDlg.ch_save.GetValue()
                plot = myDlg.ch_plot.GetValue()
                unts = myDlg.save_choice.GetSelection()
                wdgs = myDlg.wedges.GetValue()
                if int(myDlg.xstep.GetValue()) < 1:
                    attrs = {'steps':5001}
                else:
                    attrs = {'steps':int(myDlg.xstep.GetValue())}
                unit = '2th' if unts == 1 else 'q'
                attrs.update({'unit':unit,'verbose':True})
            myDlg.Destroy()
        else:
            print('Data and calibration files must be available for this function.')
            return

        if read:
            if save:
                wildcards = '1D XRD file (*.xy)|*.xy|All files (*.*)|*.*'
                dlg = wx.FileDialog(self, 'Save file as...',
                                   defaultDir=os.getcwd(),
                                   wildcard=wildcards,
                                   style=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
                if dlg.ShowModal() == wx.ID_OK:
                    filename = dlg.GetPath().replace('\\', '/')
                    if not filename.endswith('.xy'):
                        filename = '%s.xy' % filename
                    attrs.update({'file':filename})

                dlg.Destroy()
            data1D = integrate_xrd(self.plt_img,self.calfile,**attrs)
            if wdgs > 1:
                xrdq_wdg,xrd1d_wdg,lmts_wdg = [],[],[]
                wdg_sz = 360./int(wdgs)
                for iwdg in range(wdgs):
                    wdg_lmts = np.array([iwdg*wdg_sz, (iwdg+1)*wdg_sz]) - 180
                    attrs.update({'wedge_limits':wdg_lmts})

                    if save:
                        wedgename = '%s_%i_to_%ideg.xy' % (filename.split('.xy')[0],
                                                           (wdg_lmts[0]+180),
                                                           (wdg_lmts[1]+180))
                        attrs.update({'file':wedgename})
                    q,counts = integrate_xrd(self.plt_img,self.calfile,**attrs)
                    xrdq_wdg  += [q]
                    xrd1d_wdg += [counts]
                    lmts_wdg  += [wdg_lmts]


            if plot:
                if self.xrddisplay1D is None:
                    self.xrddisplay1D = diFFit1DFrame()

                kwargs = {}
                wvlngth = read_lambda(self.calfile)
                kwargs.update({'wavelength':wvlngth,'energy':E_from_lambda(wvlngth)})
                kwargs.update({'label':self.open_image[self.ch_img.GetSelection()].label})
                data1dxrd = xrd1d(**kwargs)
                data1dxrd.xrd_from_2d(data1D,attrs['unit'])

                try:
                    self.xrddisplay1D.xrd1Dviewer.add1Ddata(data1dxrd)
                except PyDeadObjectError:
                    self.xrddisplay1D = diFFit1DFrame()
                    self.xrddisplay1D.xrd1Dviewer.add1Ddata(data1dxrd)

                if wdgs > 1:
                    for lmts,q,cnts in zip(lmts_wdg,xrdq_wdg,xrd1d_wdg):
                        label = '%s (%i to %i deg)' % (self.open_image[self.ch_img.GetSelection()].label,
                                                        (lmts[0]+180), (lmts[1]+180))
                        kwargs.update({'label':label})
                        data1dxrd = xrd1d(**kwargs)
                        data1dxrd.xrd_from_2d([q,cnts],'q')
                        self.xrddisplay1D.xrd1Dviewer.add1Ddata(data1dxrd)
                self.xrddisplay1D.Show()
 def OnBoutonExporter(self, event):
     # Récupération de la langue
     dictLangue = self.ctrl_langues.GetCode()
     if dictLangue == None :
         dlg = wx.MessageDialog(self, _(u"Vous devez sélectionner une langue dans la liste !"), _(u"Erreur"), wx.OK | wx.ICON_EXCLAMATION)
         dlg.ShowModal()
         dlg.Destroy()
         return
     
     nom = dictLangue["nom"]
     textesLangue = dictLangue["textes"]
     
     # Demande à l'utilisateur le nom de fichier et le répertoire de destination
     nom_fichier = u"Textes_originaux.txt"
     wildcard = u"Fichier Texte (*.txt)|*.xml| Tous les fichiers (*.*)|*.*"
     sp = wx.StandardPaths.Get()
     cheminDefaut = sp.GetDocumentsDir()
     dlg = wx.FileDialog(
         None, message = _(u"Veuillez sélectionner le répertoire de destination et le nom du fichier"), defaultDir=cheminDefaut, 
         defaultFile = nom_fichier, 
         wildcard = wildcard, 
         style = wx.SAVE
         )
     dlg.SetFilterIndex(0)
     if dlg.ShowModal() == wx.ID_OK:
         cheminFichier = dlg.GetPath()
         dlg.Destroy()
     else:
         dlg.Destroy()
         return
     
     # Le fichier de destination existe déjà :
     if os.path.isfile(cheminFichier) == True :
         dlg = wx.MessageDialog(None, _(u"Un fichier portant ce nom existe déjà. \n\nVoulez-vous le remplacer ?"), "Attention !", wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION)
         if dlg.ShowModal() == wx.ID_NO :
             return False
             dlg.Destroy()
         else:
             dlg.Destroy()
     
     # Lecture du fichier dat
     fichier = shelve.open(Chemins.GetStaticPath("DatabasesTextes.dat"), "r")
     listeTextes = []
     for texte, listeFichiers in fichier.iteritems() :
         listeTextes.append(texte)
     fichier.close()
     listeTextes.sort() 
     
     # Enregistrement du fichier texte
     fichier = open(cheminFichier, "w")
     nbreTextes = 0
     for texte in listeTextes :
         if self.check_nontraduits.GetValue() == False or (self.check_nontraduits.GetValue() == True and texte not in textesLangue) :
             fichier.write(texte + "\n")
             nbreTextes += 1
     fichier.close() 
     
     # Confirmation fin
     dlg = wx.MessageDialog(self, _(u"Le fichier a été généré avec succès (%d textes) !") % nbreTextes, _(u"Génération"), wx.OK | wx.ICON_INFORMATION)
     dlg.ShowModal()
     dlg.Destroy()
Example #12
0
def ExportTexte(listview=None, grid=None, titre=u"", listeColonnes=None, listeValeurs=None, autoriseSelections=True):
    """ Export de la liste au format texte """
    if (listview != None and len(listview.donnees) == 0) or (grid != None and (grid.GetNumberRows() == 0 or grid.GetNumberCols() == 0)):
        dlg = wx.MessageDialog(None, _(u"Il n'y a aucune donnée dans la liste !"), "Erreur", wx.OK | wx.ICON_ERROR)
        dlg.ShowModal()
        dlg.Destroy()
        return

    # Récupération des valeurs
    if listview != None and listeColonnes == None and listeValeurs == None :
        listeColonnes, listeValeurs = GetValeursListview(listview, format="texte")
        
    if grid != None and listeColonnes == None and listeValeurs == None :
        autoriseSelections = False
        listeColonnes, listeValeurs = GetValeursGrid(grid)

    # Selection des lignes
    if autoriseSelections == True :
        dlg = DLG_Selection_liste.Dialog(None, listeColonnes, listeValeurs, type="exportTexte")
        if dlg.ShowModal() == wx.ID_OK:
            listeSelections = dlg.GetSelections()
            dlg.Destroy()
        else:
            dlg.Destroy()
            return False
    
    # Demande à l'utilisateur le nom de fichier et le répertoire de destination
    nomFichier = "ExportTexte_%s.txt" % datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    wildcard = "Fichier texte (*.txt)|*.txt|" \
                    "All files (*.*)|*.*"
    sp = wx.StandardPaths.Get()
    cheminDefaut = sp.GetDocumentsDir()
    dlg = wx.FileDialog(
        None, message = _(u"Veuillez sélectionner le répertoire de destination et le nom du fichier"), defaultDir=cheminDefaut, 
        defaultFile = nomFichier, 
        wildcard = wildcard, 
        style = wx.SAVE
        )
    dlg.SetFilterIndex(0)
    if dlg.ShowModal() == wx.ID_OK:
        cheminFichier = dlg.GetPath()
        dlg.Destroy()
    else:
        dlg.Destroy()
        return
    
    # Le fichier de destination existe déjà :
    if os.path.isfile(cheminFichier) == True :
        dlg = wx.MessageDialog(None, _(u"Un fichier portant ce nom existe déjà. \n\nVoulez-vous le remplacer ?"), "Attention !", wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION)
        if dlg.ShowModal() == wx.ID_NO :
            dlg.Destroy()
            return False
        else:
            dlg.Destroy()

    # Création du fichier texte
    texte = ""
    separateur = ";"
    for labelCol, alignement, largeur, code in listeColonnes :
        try :
            if "CheckState" in unicode(code) :
                code = "Coche"
        except :
            pass
        texte += labelCol + separateur
    texte = texte[:-1] + "\n"

    for valeurs in listeValeurs :
        if autoriseSelections == False or valeurs[0] == "" or int(valeurs[0]) in listeSelections :
            for valeur in valeurs :
                if valeur == None :
                    valeur = u""
                texte += u"%s%s" % (valeur, separateur)
            texte = texte[:-1] + "\n"
    
    # Elimination du dernier saut à la ligne
    texte = texte[:-1]

    # Création du fichier texte
    f = open(cheminFichier, "w")
    f.write(texte.encode("utf8"))
    f.close()
    
    # Confirmation de création du fichier et demande d'ouverture directe dans Excel
    txtMessage = _(u"Le fichier Texte a été créé avec succès. Souhaitez-vous l'ouvrir dès maintenant ?")
    dlgConfirm = wx.MessageDialog(None, txtMessage, _(u"Confirmation"), wx.YES_NO|wx.NO_DEFAULT|wx.ICON_QUESTION)
    reponse = dlgConfirm.ShowModal()
    dlgConfirm.Destroy()
    if reponse == wx.ID_NO:
        return
    else:
        FonctionsPerso.LanceFichierExterne(cheminFichier)
Example #13
0
def ExportExcel(listview=None, grid=None, titre=_(u"Liste"), listeColonnes=None, listeValeurs=None, autoriseSelections=True):
    """ Export de la liste au format Excel """
    # Plus de sélection pour éviter les bugs !!!!
    autoriseSelections = False 
    
    # Vérifie si données bien présentes
    if (listview != None and len(listview.donnees) == 0) or (grid != None and (grid.GetNumberRows() == 0 or grid.GetNumberCols() == 0)):
        dlg = wx.MessageDialog(None, _(u"Il n'y a aucune donnée dans la liste !"), "Erreur", wx.OK | wx.ICON_ERROR)
        dlg.ShowModal()
        dlg.Destroy()
        return
        
    # Récupération des valeurs
    if listview != None and listeColonnes == None and listeValeurs == None :
        listeColonnes, listeValeurs = GetValeursListview(listview, format="original")
        
    if grid != None and listeColonnes == None and listeValeurs == None :
        autoriseSelections = False
        listeColonnes, listeValeurs = GetValeursGrid(grid)
    
    # Selection des lignes
    if autoriseSelections == True :
        dlg = DLG_Selection_liste.Dialog(None, listeColonnes, listeValeurs, type="exportExcel")
        if dlg.ShowModal() == wx.ID_OK:
            listeSelections = dlg.GetSelections()
            dlg.Destroy()
        else:
            dlg.Destroy()
            return False

    # Choix Action
    dlg = DLG_Choix_action(None)
    reponse = dlg.ShowModal()
    dlg.Destroy()
    if reponse == 100 :
        mode = "enregistrer"
    elif reponse == 200 :
        mode = "email"
    else :
        return

    # Définit le nom et le chemin du fichier
    nomFichier = "ExportExcel_%s.xls" % datetime.datetime.now().strftime("%Y%m%d%H%M%S")

    # Mode Enregistrer
    if mode == "enregistrer" :

        # Demande à l'utilisateur le nom de fichier et le répertoire de destination
        wildcard = "Fichier Excel (*.xls)|*.xls|" \
                        "All files (*.*)|*.*"
        sp = wx.StandardPaths.Get()
        cheminDefaut = sp.GetDocumentsDir()
        dlg = wx.FileDialog(
            None, message = _(u"Veuillez sélectionner le répertoire de destination et le nom du fichier"), defaultDir=cheminDefaut,
            defaultFile = nomFichier,
            wildcard = wildcard,
            style = wx.SAVE
            )
        dlg.SetFilterIndex(0)
        if dlg.ShowModal() == wx.ID_OK:
            cheminFichier = dlg.GetPath()
            dlg.Destroy()
        else:
            dlg.Destroy()
            return

        # Le fichier de destination existe déjà :
        if os.path.isfile(cheminFichier) == True :
            dlg = wx.MessageDialog(None, _(u"Un fichier portant ce nom existe déjà. \n\nVoulez-vous le remplacer ?"), "Attention !", wx.YES_NO | wx.NO_DEFAULT | wx.ICON_EXCLAMATION)
            if dlg.ShowModal() == wx.ID_NO :
                return False
                dlg.Destroy()
            else:
                dlg.Destroy()

    # Mode Envoyer par Email
    if mode == "email" :
        cheminFichier = UTILS_Fichiers.GetRepTemp(fichier=nomFichier)


    # Export
    import pyExcelerator
    # Création d'un classeur
    wb = pyExcelerator.Workbook()
    # Création d'une feuille
    ws1 = wb.add_sheet(titre)
    # Remplissage de la feuille

    al = pyExcelerator.Alignment()
    al.horz = pyExcelerator.Alignment.HORZ_LEFT
    al.vert = pyExcelerator.Alignment.VERT_CENTER
    
    ar = pyExcelerator.Alignment()
    ar.horz = pyExcelerator.Alignment.HORZ_RIGHT
    ar.vert = pyExcelerator.Alignment.VERT_CENTER

    styleEuros = pyExcelerator.XFStyle()
    styleEuros.num_format_str = '"$"#,##0.00_);("$"#,##'
    styleEuros.alignment = ar

    styleDate = pyExcelerator.XFStyle()
    styleDate.num_format_str = 'DD/MM/YYYY'
    styleDate.alignment = ar

    styleHeure = pyExcelerator.XFStyle()
    styleHeure.num_format_str = "[hh]:mm"
    styleHeure.alignment = ar

    # Création des labels de colonnes
    x = 0
    y = 0
    for labelCol, alignement, largeur, nomChamp in listeColonnes :
        try :
            if "CheckState" in unicode(nomChamp) :
                nomChamp = "Coche"
        except :
            pass
        ws1.write(x, y, labelCol)
        ws1.col(y).width = largeur*42
        y += 1

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

    # Création des lignes
    def RechercheFormatFromChaine(valeur):
        """ Recherche le type de la chaîne """
        if valeur.endswith(SYMBOLE) :
            # Si c'est un montant en euros
            try :
                if valeur.startswith("- ") :
                    valeur = valeur.replace("- ", "-")
                if valeur.startswith("+ ") :
                    valeur = valeur.replace("+ ", "")
                nbre = float(valeur[:-1]) 
                return (nbre, styleEuros)
            except :
                pass
                
        # Si c'est un nombre
        try :
            if valeur.startswith("- ") :
                valeur = valeur.replace("- ", "-")
            nbre = float(valeur)
            return (nbre, None)
        except :
            pass
        
        # Si c'est une date
        try :
            if len(valeur) == 10 :
                if valeur[2] == "/" and valeur[5] == "/" :
                    return (valeur, styleDate)
        except :
            pass

        if type(valeur) == datetime.timedelta :
            return (valeur, styleHeure)

        # Si c'est une heure
        try :
            if len(valeur) > 3 :
                if ":" in valeur :
                    separateur = ":"
                elif "h" in valeur :
                    separateur = "h"
                else :
                    separateur = None
                if separateur != None :
                    heures, minutes = valeur.split(separateur)
                    valeur = datetime.timedelta(minutes= int(heures)*60 + int(minutes))
                    # valeur = datetime.time(hour=int(valeur.split(separateur)[0]), minute=int(valeur.split(separateur)[1]))
                    return (valeur, styleHeure)
        except :
            pass

        return unicode(valeur), None

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

    def RechercheFormat(valeur):
        """ Recherche le type de la donnée """
        if type(valeur) == decimal.Decimal :
            valeur = float(valeur)
            return (valeur, styleEuros)
                
        if type(valeur) == float :
            return (valeur, None)
                
        if type(valeur) == int :
            return (valeur, None)
        
        if type(valeur) == datetime.date :
            valeur = UTILS_Dates.DateDDEnFr(valeur)
            return (valeur, styleDate)

        if type(valeur) == datetime.timedelta :
            return (valeur, styleHeure)

        try :
            if len(valeur) > 3 :
                if ":" in valeur :
                    separateur = ":"
                elif "h" in valeur :
                    separateur = "h"
                else :
                    separateur = None
                if separateur != None :
                    donnees = valeur.split(separateur)
                    if len(donnees) == 2 :
                        heures, minutes = donnees
                    if len(donnees) == 3 :
                        heures, minutes, secondes = donnees
                    valeur = datetime.timedelta(minutes= int(heures)*60 + int(minutes))
                    # valeur = datetime.time(hour=int(valeur.split(separateur)[0]), minute=int(valeur.split(separateur)[1]))
                    return (valeur, styleHeure)
        except :
            pass

        if type(valeur) in (str, unicode) :
            if len(valeur) == 10 :
                if valeur[2] == "/" and valeur[5] == "/" : return (valeur, styleDate)
                if valeur[4] == "-" and valeur[7] == "-" : return (UTILS_Dates.DateEngFr(valeur), styleDate)
                
        return unicode(valeur), None

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

    x = 1
    y = 0
    for valeurs in listeValeurs :
        if autoriseSelections == False or int(valeurs[0]) in listeSelections :
            for valeur in valeurs :
                if valeur == None :
                    valeur = u""
                    
                # Recherche s'il y a un format de nombre ou de montant
                if listview != None :
                    valeur, format = RechercheFormat(valeur) #RechercheFormatFromChaine(valeur)
                else :
                    valeur, format = RechercheFormatFromChaine(valeur)
                        
                # Enregistre la valeur
                if format != None :
                    ws1.write(x, y, valeur, format)
                else:
                    ws1.write(x, y, valeur)

                y += 1
            x += 1
            y = 0
            
    # Finalisation du fichier xls
    try :
        wb.save(cheminFichier)
    except :
        dlg = wx.MessageDialog(None, _(u"Il est impossible d'enregistrer le fichier Excel. Veuillez vérifier que ce fichier n'est pas déjà ouvert en arrière-plan."), "Erreur", wx.OK | wx.ICON_ERROR)
        dlg.ShowModal()
        dlg.Destroy()
        return

    # Confirmation de création du fichier et demande d'ouverture directe dans Excel
    if mode == "enregistrer" :
        txtMessage = _(u"Le fichier Excel a été créé avec succès. Souhaitez-vous l'ouvrir dès maintenant ?")
        dlgConfirm = wx.MessageDialog(None, txtMessage, _(u"Confirmation"), wx.YES_NO|wx.NO_DEFAULT|wx.ICON_QUESTION)
        reponse = dlgConfirm.ShowModal()
        dlgConfirm.Destroy()
        if reponse == wx.ID_NO:
            return
        else:
            FonctionsPerso.LanceFichierExterne(cheminFichier)

    # Envoyer par Email
    if mode == "email" :
        import DLG_Mailer
        dlg = DLG_Mailer.Dialog(None)
        dlg.ChargerModeleDefaut()
        dlg.SetPiecesJointes([cheminFichier,])
        dlg.ShowModal()
        dlg.Destroy()
#######################################################################
#os.chdir("D:\\staging\\")

#ff_1 = tkinter.filedialog.askopenfilename()

#############################################################################
# wx was introduced here for better operation
app = wx.App()

frame = wx.Frame(None, -1, 'win.py')
frame.SetSize(0, 0, 200, 50)
SrcDir = "D:\\staging\\"
# Create open file dialog

openFileDialog = wx.FileDialog(frame, "Open", SrcDir, "",
                               "Zip files (*.ZIP)|*.zip",
                               wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

#openFileDialog.SetDirectory("C:\\opt\\staging")
openFileDialog.ShowModal()
ff_1 = openFileDialog.GetPath()
print(ff_1)
openFileDialog.Destroy()
#################################################################################

print(ff_1)
# changed "/" to "\\" , this is DOS style
if ((ff_1.split(':')[0].upper() != "D")
        or (ff_1.split('\\')[1].lower() != "staging")):
    print(ff_1.split(':')[0].upper())
    print(ff_1.split('/')[1].lower())
Example #15
0
    def LoadGerberFile(self, evt):
        dlg = wx.FileDialog(self, "Open Gerber file", "", "",
                            "Gerber Files (*.gbl;*.gtl;*.gbr;*.cmp)|*.gbl;*.gtl;*.gbr;*.cmp|All Files (*.*)|*",
                            wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

        if dlg.ShowModal() == wx.ID_CANCEL:
            self.SetStatusText("Load Gerber file cancelled by user", 0)
            return
        filename = dlg.GetPath()
        dlg.Destroy()

        self.SetStatusText("Loading Gerber: " + filename + "...", 0)

        [data, tracks] = load_file(filename)
        self.data = data

        xmin = 1E99
        xmax = -1E99
        ymin = 1E99
        ymax = -1E99

        sum1 = 0
        sumReg = 0
        sumBound = 0
        sumTracks = 0
        sumPads = 0

        cbounds = pyclipper.Pyclipper()
        boundarys = []
        pcb_edges = []

        layers = list(data.layers)
        for gl in layers:
            if gl.type == GerberLayer.TYPE_PCBEDGE:
                data.layers.remove(gl)
                pcb_edges.extend(gl.points)
                for segment in gl.points:
                    sum1 += len(segment)
                    for vertex in segment:
                        x = vertex[0]
                        y = vertex[1]
                        if x < xmin: xmin = x
                        if x > xmax: xmax = x
                        if y < ymin: ymin = y
                        if y > ymax: ymax = y
                continue
            if gl.type == GerberLayer.TYPE_REGION:
                sumReg += len(gl.points)
                # regions.extend(gl.points)
                continue
            if gl.type == GerberLayer.TYPE_TRACK:
                sumTracks += len(gl.points)
                continue
            if gl.type == GerberLayer.TYPE_PAD:
                sumPads += len(gl.points)
                continue
            if gl.type == GerberLayer.TYPE_BOUNDARY:
                # if gl.isDark:
                #     # boundarys.extend(gl.points)
                #     # if len(boundarys) == 0:
                #         boundarys.extend(gl.points)
                #     # else:
                #     #     cbounds.AddPaths(boundarys, pyclipper.PT_SUBJECT)
                #     #     cbounds.AddPaths(gl.points, pyclipper.PT_SUBJECT)
                #     #     boundarys = cbounds.Execute(pyclipper.CT_UNION, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)
                #     #     cbounds.Clear()
                # else:
                #     cbounds.AddPaths(boundarys, pyclipper.PT_SUBJECT)
                #     cbounds.AddPaths(gl.points, pyclipper.PT_CLIP)
                #     boundarys = cbounds.Execute(pyclipper.CT_DIFFERENCE, pyclipper.PFT_EVENODD, pyclipper.PFT_EVENODD)
                #     cbounds.Clear()
                if gl.isDark:
                    boundarys.extend(gl.points)
                else:
                    cbounds.AddPaths(boundarys, pyclipper.PT_SUBJECT)
                    cbounds.AddPaths(gl.points, pyclipper.PT_CLIP)
                    boundarys = cbounds.Execute(pyclipper.CT_DIFFERENCE, pyclipper.PFT_NONZERO, pyclipper.PFT_NONZERO)
                    cbounds.Clear()
                sumBound += len(gl.points)
                for segment in gl.points:
                    sum1 += len(segment)
                    for vertex in segment:
                        x = vertex[0]
                        y = vertex[1]
                        if x < xmin: xmin = x
                        if x > xmax: xmax = x
                        if y < ymin: ymin = y
                        if y > ymax: ymax = y
                continue
            if gl.type == GerberLayer.TYPE_MERGEDCOPPER:
                data.layers.remove(gl)
                continue

        print "   fraction = ",self.data.fraction
        print "   found", sumBound, "polygons,", sum1, "vertices"
        print "   found", sumReg, "pours"
        print "   found", sumTracks, "tracks"
        print "   found", sumPads, "pads"
        print "   found", len(pcb_edges), "edge segments"
        print "   xmin: %0.3g " % xmin, "xmax: %0.3g " % xmax, "dx: %0.3g " % (xmax - xmin)
        print "   ymin: %0.3g " % ymin, "ymax: %0.3g " % ymax, "dy: %0.3g " % (ymax - ymin)

        data.xmin2 = xmin
        data.xmax2 = xmax
        data.ymin2 = ymin
        data.ymax2 = ymax

        if len(pcb_edges) == 0:
            outer_offset = (1 if data.units == 0 else 0.03937) * 10**data.fraction  # 1 mm
            # outer_offset = 0.01 * 10**data.fraction
            xmin -= outer_offset
            ymin -= outer_offset
            xmax += outer_offset
            ymax += outer_offset
            pcb_edge = [[xmax, ymax], [xmax, ymin], [xmin, ymin], [xmin, ymax], [xmax, ymax]]
            pcb_edges.append(pcb_edge)

        self.pcb_edges = pcb_edges
        self.boundarys = boundarys = pyclipper.SimplifyPolygons(boundarys, pyclipper.PFT_NONZERO)
        # boundarys = GerberReader3.replace_holes_with_seams(boundarys)
        GerberReader3.closeOffPolys(boundarys)

        data.layers.append(GerberLayer(True, "PCB Edge", pcb_edges, True, False, "blue", GerberLayer.TYPE_PCBEDGE))
        data.layers.append(GerberLayer(True, "Merged Copper", boundarys, False, color="brown", type=GerberLayer.TYPE_MERGEDCOPPER))

        # PCB bounds
        data.xmin = xmin
        data.xmax = xmax
        data.ymin = ymin
        data.ymax = ymax

        # View bounds
        # Includes the origin
        if xmin > 0: xmin = 0
        if xmax < 0: xmax = 0
        if ymin > 0: ymin = 0
        if ymax < 0: ymax = 0

        # Add margin
        ww = (xmax - xmin)*0.1
        hh = (ymax - ymin)*0.1
        xmin -= ww
        xmax += ww
        ymin -= hh
        ymax += hh

        self.contours = []
        self.layersPanel.loadLayersPanel(data, self.NotifyDataChange)
        self.canvas.loadData2(self.data, xmin, xmax, ymin, ymax)
        self.SetStatusText("Load Gerber file completed successfully", 0)
        self.origincombo.SetSelection(0)
        self.nativeLabel.SetLabelText("(File unit: %s, Dec. places: %0d)" % ("mm" if data.units == 0 else "in", data.fraction))
Example #16
0
 def on_save_plot(self, event):
   fileChoices = "PNG (*.png)|*.png"
   dlg = wx.FileDialog(self,message="Save risk scatter",defaultDir=os.getcwd(),defaultFile="scatter.png",wildcard=fileChoices,style=wx.SAVE)
   if dlg.ShowModal() == wx.ID_OK:
     path = dlg.GetPath()
     self.canvas.print_figure(path, dpi=self.dpi)
Example #17
0
    def LoadEdgeFile(self, evt):
        if self.data is None:
            dlg = wx.MessageDialog(self, "You must load a Gerber file first", "Error", wx.OK | wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()
            return

        dlg = wx.FileDialog(self, "Open edge file", "", "",
                            "Gerber Files (*.gml;*.gbl;*.gtl;*.gbr;*.cmp)|*.gml;*.gbl;*.gtl;*.gbr;*.cmp|All Files (*.*)|*",
                            wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

        if dlg.ShowModal() == wx.ID_CANCEL:
            self.SetStatusText("Load edge file cancelled by user", 0)
            return
        filename = dlg.GetPath()
        dlg.Destroy()

        self.SetStatusText("Loading edge: " + filename + "...", 0)

        [data, edges] = load_file(filename)
        brdoutline = []
        brdseg = -1

        while len(edges) > 0:
            brdoutline.append([])
            brdseg += 1
            brdoutline[brdseg].extend(edges[0])
            edges.remove(edges[0])
            startpnt = brdoutline[brdseg][0]
            endpnt = brdoutline[brdseg][len(brdoutline[brdseg]) - 1]

            while (abs(startpnt[0] - endpnt[0]) > 10) | (abs(startpnt[1] - endpnt[1]) > 10):
                found = False
                for seg in edges:
                    if abs(seg[0][0] - endpnt[0]) < 10:
                        if abs(seg[0][1] - endpnt[1]) < 10:
                            brdoutline[brdseg].extend(seg)
                            edges.remove(seg)
                            endpnt = brdoutline[brdseg][len(brdoutline[brdseg]) - 1]
                            found = True
                            break
                    if abs(seg[len(seg) - 1][0] - endpnt[0]) < 10:
                        if abs(seg[len(seg) - 1][1] - endpnt[1]) < 10:
                            edges.remove(seg)
                            seg = seg[::-1]
                            brdoutline[brdseg].extend(seg)
                            endpnt = brdoutline[brdseg][len(brdoutline[brdseg]) - 1]
                            found = True
                            break
                if not found:
                    dlg = wx.MessageDialog(self, "Edge outline cannot contain any gaps.\n"
                                                 "No changes were made.", "Load edge file failed",
                                           wx.OK | wx.ICON_ERROR)
                    dlg.ShowModal()
                    dlg.Destroy()
                    self.SetStatusText("Load edge failed", 0)
                    return

        xmin = 1E99
        xmax = -1E99
        ymin = 1E99
        ymax = -1E99
        if data.units == self.data.units:
            for poly in brdoutline:
                for (x, y) in poly:
                    if x < xmin: xmin = x
                    if x > xmax: xmax = x
                    if y < ymin: ymin = y
                    if y > ymax: ymax = y
        else:
            # finx bounds and convert units of data at same time
            conv = 25.4 if data.units == 1 else 1/25.4
            print " Unit conversion of edge file data"
            for poly in brdoutline:
                for pt in poly:
                    x = pt[0] = int(pt[0] * conv)
                    y = pt[1] = int(pt[1] * conv)
                    if x < xmin: xmin = x
                    if x > xmax: xmax = x
                    if y < ymin: ymin = y
                    if y > ymax: ymax = y

        # Check if PCB fits inside edge. We're lazy so we just use box bounds (should really use
        # polygon bounds checking).
        eps = 10
        if self.data.xmin2 + eps < xmin or self.data.xmax2 - eps > xmax or \
                self.data.ymin2 + eps < ymin or self.data.ymax2 - eps > ymax:
            print self.data.xmin, xmin
            print self.data.ymin, ymin
            print self.data.xmax, xmax
            print self.data.ymax, ymax
            dlg = wx.MessageDialog(self, "The loaded edge does not fully contain the PCB board.\n"
                                         "Do you still wish to proceed using this edge file?",
                                   "PCB board extends past edge boundary", wx.YES | wx.NO | wx.ICON_WARNING)
            ans = dlg.ShowModal()
            dlg.Destroy()
            if ans != wx.ID_YES:
                self.SetStatusText("Load edge file cancelled by user", 0)
                return

        self.data.xmin = xmin
        self.data.xmax = xmax
        self.data.ymin = ymin
        self.data.ymax = ymax

        # View bounds
        # Includes the origin
        if xmin > 0: xmin = 0
        if xmax < 0: xmax = 0
        if ymin > 0: ymin = 0
        if ymax < 0: ymax = 0

        # Add margin
        ww = (xmax - xmin)*0.1
        hh = (ymax - ymin)*0.1
        xmin -= ww
        xmax += ww
        ymin -= hh
        ymax += hh

        pcb_edges = brdoutline
        pcb_edges = pyclipper.CleanPolygons(pcb_edges)
        for poly in pcb_edges:
            poly.append(poly[0])  # close off polygons

        # Remove existing edge
        layers = list(self.data.layers)
        for gl in layers:
            if gl.type == GerberLayer.TYPE_PCBEDGE: self.data.layers.remove(gl)

        # Add edge data to existing data
        self.data.layers.insert(-1, GerberLayer(True, "PCB Edge", pcb_edges, True, False, "blue", GerberLayer.TYPE_PCBEDGE))
        self.pcb_edges = pcb_edges

        self.canvas.toolpaths = []
        self.canvas.loadData2(self.data, xmin, xmax, ymin, ymax)
        self.layersPanel.loadLayersPanel(self.data, self.NotifyDataChange)
        self.SetStatusText("Load edge file completed successfully", 0)
Example #18
0
        return


#==============================================================================
# main program
#------------------------------------------------------------------------------
# Show a standard FileSelect dialog to choose a file
#==============================================================================
# Wildcard: only offer PDF files
wild = "*.pdf"

#==============================================================================
# define the file selection dialog
#==============================================================================
dlg = wx.FileDialog(None,
                    message="Choose a file to display",
                    wildcard=wild,
                    style=wx.FD_OPEN | wx.FD_CHANGE_DIR)

# We got a file only when one was selected and OK pressed
if dlg.ShowModal() == wx.ID_OK:
    filename = dlg.GetPath()
else:
    filename = None

# destroy this dialog
dlg.Destroy()

# only continue if we have a filename
if filename:
    # create the dialog
    dlg = PDFdisplay(None, filename)
Example #19
0
def onLoadFile(td,
               message="Select File",
               modename='addon_pathmode',
               pathname='addon_path',
               extname='addon_ext',
               wildcard='Any|*',
               ask_org_copy=True,
               file=None,
               reject_loc=None):
    '''
    onLoadFile ask user an file to read.
    copy it to its own directory as filename.
    also another copy is made as filename + '.org'
    for future record

    if ask_org_copy = False: it automatically copy original for
    read only data and make a duplicate file for edit. It is only
    useful when the file size is small
    '''
    if td.getvar("original file") is not None:
        dir = os.path.dirname(td.getvar("original file"))
    else:
        dir = '.'
    if not os.path.exists(dir):
        dir = ''

    if file is None:
        open_dlg = wx.FileDialog(None,
                                 message=message,
                                 defaultDir=dir,
                                 style=wx.FD_OPEN,
                                 wildcard=wildcard)
        if open_dlg.ShowModal() != wx.ID_OK:
            open_dlg.Destroy()
            return False
        file = open_dlg.GetPath()
        open_dlg.Destroy()

    if reject_loc is not None:
        rmode, rpath = td.fullpath2path(td, file)
        if rmode in reject_loc:
            m = 'Improper import source location'
            ret = dialog.message(None, message=m, title='Import error')
            return

    try:
        # this may fail if owndir does not exist
        #print(os.path.dirname(file), td.owndir())
        samefile = os.path.samefile(os.path.dirname(file), td.owndir())
        # print(samefile)
    except BaseException:
        samefile = False
    if ask_org_copy and not samefile:
        from ifigure.widgets.dlg_fileimportmode import DlgFileimportmode
        copy_file, pathmodes, ret = DlgFileimportmode(td, ask_copyorg=True)
        '''
        choices = ["auto", "abs", "home", "proj"]
        if td.get_extfolderpath() is not None:
            choices.append(td.get_extfolderpath())
        list6 = [[None,  [True, ['auto']], 127,
                 [{'text':'copy file to project'},
                  {'elp':[['Select path mode', 'auto', 4,
                           {"style":wx.CB_READONLY,
                            "choices": choices}],]}], ],
                 [None, False, 3,
                 {"text":"copy original to project as a separate file"}], ]
        value = DialogEditList(list6, modal = True,
                     style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER,
                     tip = None,
                     parent=None,)

        if not value[0]: return
        ret = value[1][1]
        copy_file = value[1][0][0]
        pathmodes = value[1][0][1]
        if str(pathmodes[0]) == 'auto':
           pathmodes = ['proj', 'home', 'abs']
        '''
    else:
        ret = True
        copy_file = True

    for name, child in td.get_children():
        child.destroy()
    if not td.has_owndir():
        td.mk_owndir()
    od = td.owndir()

    if ret:
        new_ofile = os.path.join(od, os.path.basename(file) + '.org')
        shutil.copyfile(file, new_ofile)
        td.setvar('ofile_pathmode', 'owndir')
        td.setvar('ofile_path', os.path.basename(new_ofile))
        if not 'ofile_path' in td._items:
            td._items.append('ofile_path')
#         td._items.append('ofile_path')
    else:
        new_ofile = file
        td.setvar('ofile_pathmode', 'abs')
        td.setvar('ofile_path', file)
        if 'ofile_path' in td._items:
            td.remove_ownitem(items=['ofile_path'])
            td._items.remove('ofile_path')

    # nl_file is the file to be edited
    if copy_file:
        nl_file = os.path.join(od, os.path.basename(file))
        print(nl_file)
        try:
            # this may fail if owndir does not exist
            if os.path.exists(nl_file):
                samefile = os.path.samefile(file, nl_file)
            else:
                samefile = True
        except BaseException:
            import traceback
            traceback.print_exc()
            samefile = False
        if not samefile:
            print("not the same file")
            #td.remove_ownitem(items=[pathname])
            sss = nl_file.split('.')
            nl_file = '.'.join(sss[:-1]) + '1.' + sss[-1]
        shutil.copyfile(file, nl_file)
        td.set_path_pathmode(nl_file, modename, pathname, extname)
    else:
        td.remove_ownitem(items=[pathname])
        td.set_path_pathmode(file,
                             modename,
                             pathname,
                             extname,
                             checklist=pathmodes)
    return True
    def run_as_data_tool(self):
        from cellprofiler.gui.editobjectsdlg import EditObjectsDialog
        import wx
        from wx.lib.filebrowsebutton import FileBrowseButton
        from cellprofiler.modules.namesandtypes import ObjectsImageProvider
        from bioformats import load_image

        with wx.Dialog(None) as dlg:
            dlg.Title = "Choose files for editing"
            dlg.Sizer = wx.BoxSizer(wx.VERTICAL)
            box = wx.StaticBox(dlg, -1, "Choose or create new objects file")
            sub_sizer = wx.StaticBoxSizer(box, wx.HORIZONTAL)
            dlg.Sizer.Add(sub_sizer, 0, wx.EXPAND | wx.ALL, 5)
            new_or_existing_rb = wx.RadioBox(dlg,
                                             style=wx.RA_VERTICAL,
                                             choices=("New", "Existing"))
            sub_sizer.Add(new_or_existing_rb, 0, wx.EXPAND)
            objects_file_fbb = FileBrowseButton(
                dlg,
                size=(300, -1),
                fileMask=
                "Objects file (*.tif, *.tiff, *.png, *.bmp, *.jpg)|*.tif;*.tiff;*.png;*.bmp;*.jpg",
                dialogTitle="Select objects file",
                labelText="Objects file:")
            objects_file_fbb.Enable(False)
            sub_sizer.AddSpacer(5)
            sub_sizer.Add(objects_file_fbb, 0, wx.ALIGN_TOP | wx.ALIGN_RIGHT)

            def on_radiobox(event):
                objects_file_fbb.Enable(new_or_existing_rb.GetSelection() == 1)

            new_or_existing_rb.Bind(wx.EVT_RADIOBOX, on_radiobox)

            image_file_fbb = FileBrowseButton(
                dlg,
                size=(300, -1),
                fileMask=
                "Objects file (*.tif, *.tiff, *.png, *.bmp, *.jpg)|*.tif;*.tiff;*.png;*.bmp;*.jpg",
                dialogTitle="Select guide image file",
                labelText="Guide image:")
            dlg.Sizer.Add(image_file_fbb, 0, wx.EXPAND | wx.ALL, 5)

            allow_overlap_checkbox = wx.CheckBox(dlg, -1,
                                                 "Allow objects to overlap")
            allow_overlap_checkbox.Value = True
            dlg.Sizer.Add(allow_overlap_checkbox, 0, wx.EXPAND | wx.ALL, 5)

            buttons = wx.StdDialogButtonSizer()
            dlg.Sizer.Add(buttons, 0,
                          wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL,
                          5)
            buttons.Add(wx.Button(dlg, wx.ID_OK))
            buttons.Add(wx.Button(dlg, wx.ID_CANCEL))
            buttons.Realize()
            dlg.Fit()
            result = dlg.ShowModal()
            if result != wx.ID_OK:
                return
            self.allow_overlap.value = allow_overlap_checkbox.Value
            fullname = objects_file_fbb.GetValue()
            guidename = image_file_fbb.GetValue()

        if new_or_existing_rb.GetSelection() == 1:
            provider = ObjectsImageProvider("InputObjects",
                                            pathname2url(fullname), None, None)
            image = provider.provide_image(None)
            pixel_data = image.pixel_data
            shape = pixel_data.shape[:2]
            labels = [pixel_data[:, :, i] for i in range(pixel_data.shape[2])]
        else:
            labels = None
        #
        # Load the guide image
        #
        guide_image = load_image(guidename)
        if np.min(guide_image) != np.max(guide_image):
            guide_image = ((guide_image - np.min(guide_image)) /
                           (np.max(guide_image) - np.min(guide_image)))
        if labels is None:
            shape = guide_image.shape[:2]
            labels = [np.zeros(shape, int)]
        with EditObjectsDialog(guide_image, labels, self.allow_overlap,
                               self.object_name.value) as dialog_box:
            result = dialog_box.ShowModal()
            if result != wx.OK:
                return
            labels = dialog_box.labels
        n_frames = len(labels)
        with wx.FileDialog(None,
                           style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as dlg:

            dlg.Path = fullname
            dlg.Wildcard = ("Object image file (*.tif,*.tiff)|*.tif;*.tiff|"
                            "Ilastik project file (*.ilp)|*.ilp")
            result = dlg.ShowModal()
            fullname = dlg.Path
            if result == wx.ID_OK:
                if fullname.endswith(".ilp"):
                    self.save_into_ilp(fullname, labels, guidename)
                else:
                    from bioformats.formatwriter import write_image
                    from bioformats.omexml import PT_UINT16
                    if os.path.exists(fullname):
                        os.unlink(fullname)
                    for i, l in enumerate(labels):
                        write_image(fullname,
                                    l,
                                    PT_UINT16,
                                    t=i,
                                    size_t=len(labels))
Example #21
0
    def __init__(self):
        displaySize = wx.DisplaySize()
        no_resize = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.RESIZE_BOX
                                               | wx.MAXIMIZE_BOX)
        wx.Frame.__init__(self,
                          None,
                          title="FlashGen",
                          size=(displaySize[0], displaySize[1] / 12 * 11),
                          style=no_resize)
        ico = wx.Icon('images/icons/FlashGen.ico', wx.BITMAP_TYPE_ICO)
        self.SetIcon(ico)

        # create the file dialog to get a file path from the user
        wildcard = "Text File (*.txt)|*.txt"
        dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "",
                               wildcard, wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            path = dialog.GetPath()
        else:
            sys.exit("No text file selected")
        dialog.Destroy()

        # create formatting for window
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.splitter = wx.SplitterWindow(self)

        noteCardJSON = getNotes(path)

        self.splitter.cards = Cards(noteCardJSON)
        self.splitter.rightP = RightPanel(self.splitter, self)
        self.splitter.leftP = LeftPanel(self.splitter, self)

        # split the window for the separate panels
        self.splitter.SplitVertically(self.splitter.leftP,
                                      self.splitter.rightP)
        self.splitter.SetMinimumPaneSize(250)
        self.sizer.Add(self.splitter, 1, wx.EXPAND)
        self.SetSizer(self.sizer)

        # create the menu bar at the top of the GUI
        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        helpMenu = wx.Menu()

        # create open option in file menu with image and hotkey
        qmi = wx.MenuItem(fileMenu, wx.ID_OPEN, '&Open\tCtrl+O')
        qmi.SetBitmap(wx.Bitmap('images/icons/open.png'))
        fileMenu.AppendItem(qmi)
        self.Bind(wx.EVT_MENU, self.OnOpen, id=wx.ID_OPEN)
        # create quit option in file menu with image and hotkey
        qmi = wx.MenuItem(fileMenu, wx.ID_EXIT, '&Quit\tCtrl+Q')
        qmi.SetBitmap(wx.Bitmap('images/icons/exit.png'))
        fileMenu.AppendItem(qmi)
        self.Bind(wx.EVT_MENU, self.OnQuit, id=wx.ID_EXIT)
        # create about option in help menu with image
        qmi = wx.MenuItem(helpMenu, wx.ID_ABOUT, '&About')
        qmi.SetBitmap(wx.Bitmap('images/icons/about.png'))
        helpMenu.AppendItem(qmi)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)
        # create help option in help menu with image and hotkey
        qmi = wx.MenuItem(helpMenu, wx.ID_HELP, '&Help\tCtrl+H')
        qmi.SetBitmap(wx.Bitmap('images/icons/help.png'))
        helpMenu.AppendItem(qmi)
        self.Bind(wx.EVT_MENU, self.OnHelp, id=wx.ID_HELP)

        menubar.Append(fileMenu, '&File')
        menubar.Append(helpMenu, '&Help')
        self.SetMenuBar(menubar)
Example #22
0
def openCeciliaFile(parent, openfile=None, builtin=False):
    if not openfile:
        wildcard = "Cecilia file (*.%s)|*.%s" % (FILE_EXTENSION,
                                                 FILE_EXTENSION)
        defaultPath = getVar("openFilePath", unicode=True)
        openDialog = wx.FileDialog(parent,
                                   message='Choose a Cecilia file to open...',
                                   defaultDir=defaultPath,
                                   wildcard=wildcard,
                                   style=wx.FD_OPEN)
        if openDialog.ShowModal() == wx.ID_OK:
            cecFilePath = openDialog.GetPath()
            setVar("openFilePath", (os.path.split(cecFilePath)[0]))
        else:
            cecFilePath = None
        openDialog.Destroy()

        if cecFilePath is None:
            return
    else:
        cecFilePath = openfile

    if getVar("audioServer").isAudioServerRunning():
        stopCeciliaSound()

    snds = []
    if getVar("rememberedSound") and getVar("interfaceWidgets") and getVar(
            "userInputs"):
        names = [d['name'] for d in getVar("interfaceWidgets")]
        keys = getVar("userInputs").keys()
        sortlist = list(zip([names.index(k) for k in keys], keys))
        sortlist.sort()
        index, keys = list(zip(*sortlist))
        for key in keys:
            if getVar("userInputs")[key]['path'] != '':
                snds.append(getVar("userInputs")[key]['path'])

    if not closeCeciliaFile(parent):
        return

    getVar("mainFrame").Hide()

    setVar("isModified", False)

    if not getVar("audioServer").openCecFile(cecFilePath):
        return

    setVar("builtinModule", builtin)
    setVar("currentCeciliaFile", cecFilePath)
    setVar("lastCeciliaFile", cecFilePath)

    if getVar("mainFrame") is not None:
        getVar("mainFrame").newRecent(cecFilePath)

    saveCompileBackupFile(cecFilePath)

    if getVar("interface"):
        for i, cfilein in enumerate(getControlPanel().getCfileinList()):
            if i >= len(snds):
                break
            cfilein.onLoadFile(snds[i])

    savePresetToDict("init")

    if "last save" in getVar("presets"):
        setVar("presetToLoad", "last save")

    getVar("mainFrame").updateTitle()

    wx.CallAfter(getVar("interface").Raise)
Example #23
0
def ShowAcquisitionFileDialog(parent, filename):
    """
    parent (wxFrame): parent window
    filename (string): full filename to propose by default
    Note: updates the acquisition configuration if the user did pick a new file
    return (string or None): the new filename (or the None if the user cancelled)
    """
    conf = get_acqui_conf()

    # Find the available formats (and corresponding extensions)
    formats_to_ext = dataio.get_available_formats()

    # current filename
    path, base = os.path.split(filename)

    # Note: When setting 'defaultFile' when creating the file dialog, the
    #   first filter will automatically be added to the name. Since it
    #   cannot be changed by selecting a different file type, this is big
    #   nono. Also, extensions with multiple periods ('.') are not correctly
    #   handled. The solution is to use the SetFilename method instead.
    wildcards, formats = formats_to_wildcards(formats_to_ext)
    dialog = wx.FileDialog(parent,
                           message="Choose a filename and destination",
                           defaultDir=path,
                           defaultFile="",
                           style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
                           wildcard=wildcards)

    # Select the last format used
    prev_fmt = conf.last_format
    try:
        idx = formats.index(conf.last_format)
    except ValueError:
        idx = 0
    dialog.SetFilterIndex(idx)

    # Strip the extension, so that if the user changes the file format,
    # it will not have 2 extensions in a row.
    if base.endswith(conf.last_extension):
        base = base[:-len(conf.last_extension)]
    dialog.SetFilename(base)

    # Show the dialog and check whether is was accepted or cancelled
    if dialog.ShowModal() != wx.ID_OK:
        return None

    # New location and name have been selected...
    # Store the path
    path = dialog.GetDirectory()
    conf.last_path = path

    # Store the format
    fmt = formats[dialog.GetFilterIndex()]
    conf.last_format = fmt

    # Check the filename has a good extension, or add the default one
    fn = dialog.GetFilename()
    ext = None
    for extension in formats_to_ext[fmt]:
        if fn.endswith(extension) and len(extension) > len(ext or ""):
            ext = extension

    if ext is None:
        if fmt == prev_fmt and conf.last_extension in formats_to_ext[fmt]:
            # if the format is the same (and extension is compatible): keep
            # the extension. This avoid changing the extension if it's not
            # the default one.
            ext = conf.last_extension
        else:
            ext = formats_to_ext[fmt][0]  # default extension
        fn += ext

    conf.last_extension = ext

    return os.path.join(path, fn)
Example #24
0
 def on_save(self, event):
     '''called on save button'''
     dlg = wx.FileDialog(None, self.settings.get_title(), '', "", '*.*',
                         wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
     if dlg.ShowModal() == wx.ID_OK:
         self.settings.save(dlg.GetPath())
Example #25
0
            cut_to(nx, ny, nz)

    f.close()


# clear the volume
setrect(0, 0, 0, 1024, 1024, 256, -1)
repaint()

# make a default block 50mm x 50mm x 10mm
global voxels_per_mm
vwidth = 600
mwidth = 50
voxels_per_mm = vwidth / mwidth
x0 = 512 - 300
y0 = 512 - 300
z0 = 256 - 10 * voxels_per_mm
x1 = 512 + 300
y1 = 512 + 300
z1 = 256
setrect(x0, y0, z0, x1, y1, z1, 0)
repaint()

# ask the user to choose an nc file
app = wx.App()
fd = wx.FileDialog(None, "Open NC File", "", "", "Tap Files (*.tap)|*.tap")
result = fd.ShowModal()

if result == wx.ID_OK:
    read_nc_file(fd.GetPath())
Example #26
0
	def OnLoadFile(self, event):
		dlg = wx.FileDialog(self, wildcard = '*.htm*', style=wx.FD_OPEN)
		if dlg.ShowModal():
			path = dlg.GetPath()
			self.html.LoadPage(path)
		dlg.Destroy()
Example #27
0
 def OnUpsButton(self, event):
     dialog = wx.FileDialog(self, "Select a file", 'C:\\')
     modal = dialog.ShowModal()
     if modal == wx.ID_OK:
         self.upstextctrl.SetValue(dialog.GetPath())
Example #28
0
    def _on_merge_vault(self, dummy):
        wildcard = "|".join((_("Vault") + " (*.psafe3)", "*.psafe3", _("All files") + " (*.*)", "*.*"))
        dialog = wx.FileDialog(self, message = _("Open Vault..."), defaultFile = self.vault_file_name, wildcard = wildcard, style = wx.FD_OPEN)
        if dialog.ShowModal() != wx.ID_OK:
            return
        filename = dialog.GetPath()
        dialog.Destroy()

        dial = wx.PasswordEntryDialog(self,
                                _("Password"),
                                _("Open Vault...")
                                )
        retval = dial.ShowModal()
        password = dial.Value.encode('latin1', 'replace')
        dial.Destroy()
        if retval != wx.ID_OK:
            return

        merge_vault = None
        try:
            merge_vault = Vault(password, filename=filename)
        except Vault.BadPasswordError:
            dial = wx.MessageDialog(self,
                                    _('The given password does not match the Vault'),
                                    _('Bad Password'),
                                    wx.OK | wx.ICON_ERROR
                                    )
            dial.ShowModal()
            dial.Destroy()
            return
        except Vault.VaultVersionError:
            dial = wx.MessageDialog(self,
                                    _('This is not a PasswordSafe V3 Vault'),
                                    _('Bad Vault'),
                                    wx.OK | wx.ICON_ERROR
                                    )
            dial.ShowModal()
            dial.Destroy()
            return
        except Vault.VaultFormatError:
            dial = wx.MessageDialog(self,
                                    _('Vault integrity check failed'),
                                    _('Bad Vault'),
                                    wx.OK | wx.ICON_ERROR
                                    )
            dial.ShowModal()
            dial.Destroy()
            return

        oldrecord_newrecord_reason_pairs = []  # list of (oldrecord, newrecord, reason) tuples to merge
        for record in merge_vault.records:
            # check if corresponding record exists in current Vault
            my_record = None
            for record2 in self.vault.records:
                if record2.is_corresponding(record):
                    my_record = record2
                    break

            # record is new
            if not my_record:
                oldrecord_newrecord_reason_pairs.append((None, record, _("new")))
                continue

            # record is more recent
            if record.is_newer_than(my_record):
                oldrecord_newrecord_reason_pairs.append((my_record, record, _('updates "%s"') % my_record.title))
                continue

        dial = MergeFrame(self, oldrecord_newrecord_reason_pairs)
        retval = dial.ShowModal()
        oldrecord_newrecord_reason_pairs = dial.get_checked_items()
        dial.Destroy()
        if retval != wx.ID_OK:
            return

        for (oldrecord, newrecord, reason) in oldrecord_newrecord_reason_pairs:
            if oldrecord:
                oldrecord.merge(newrecord)
            else:
                self.vault.records.append(newrecord)
        self.mark_modified()
Example #29
0
    def browseDir(self, event):
        """
        Show the File Dialog and ask the user to select the video file
        """

        self.statusbar.SetStatusText(
            "Looking for a video to start extraction..")
        dlg = wx.FileDialog(self, "SELECT A VIDEO", os.getcwd(), "", "*.*",
                            wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.video_source_original = dlg.GetPath()
            self.video_source = str(Path(self.video_source_original).resolve())

            self.load.Enable(False)
        else:
            pass
            dlg.Destroy()
            self.Close(True)
        dlg.Destroy()
        selectedvideo = Path(self.video_source)

        self.statusbar.SetStatusText("Working on video: {}".format(
            os.path.split(str(selectedvideo))[-1]))

        if str(selectedvideo.stem) in self.video_names:
            self.grab.Enable(True)
            self.vid = cv2.VideoCapture(self.video_source)
            self.videoPath = os.path.dirname(self.video_source)
            self.filename = Path(self.video_source).name
            self.numberFrames = int(self.vid.get(cv2.CAP_PROP_FRAME_COUNT))
            # Checks if the video is corrupt.
            if not self.vid.isOpened():
                msg = wx.MessageBox(
                    "Invalid Video file!Do you want to retry?",
                    "Error!",
                    wx.YES_NO | wx.ICON_WARNING,
                )
                if msg == 2:
                    self.load.Enable(True)
                    MainFrame.browseDir(self, event)
                else:
                    self.Destroy()
            self.slider.Bind(wx.EVT_SLIDER, self.OnSliderScroll)
            self.update()

            cropMsg = wx.MessageBox(
                "Do you want to crop the frames?",
                "Want to crop?",
                wx.YES_NO | wx.ICON_INFORMATION,
            )
            if cropMsg == 2:
                self.cropping = True
                self.grab.SetLabel("Set cropping parameters")
                self.grab.Bind(wx.EVT_BUTTON, self.is_crop_ok)
                self.widget_panel.Layout()
                self.basefolder = "data-" + self.Task + "/"
                MainFrame.CheckCropping(self)
            else:
                self.cropping = False
                self.slider.Show()
                self.start_frames_sizer.ShowItems(show=True)
                self.end_frames_sizer.ShowItems(show=True)
                self.widget_panel.Layout()
                self.slider.SetMax(self.numberFrames - 1)
                self.startFrame.SetMax(self.numberFrames - 1)
                self.endFrame.SetMax(self.numberFrames - 1)

        else:
            wx.MessageBox(
                "Video file is not in config file. Use add function to add this video in the config file and retry!",
                "Error!",
                wx.OK | wx.ICON_WARNING,
            )
            self.Close(True)
Example #30
0
    def flightlog_merge(self):
        """
        merge data from mag sensor with GPS locations and timestamps from UAS
        designed for DJI .DAT files. need to convert .DAT files to csv using DatCon
        (https://datfile.net/DatCon/intro.html)
        """
        self.log_text.AppendText(
            f'{datetime.now()}\tStarting flightlog merge\n')

        # read flightlog. take only data from sensors that are available. settings read from .ini file
        gps = np.array([
            config.getboolean('flightlog', 'GPS1_working'),
            config.getboolean('flightlog', 'GPS2_working'),
            config.getboolean('flightlog', 'GPS3_working')
        ])
        sensors_working = np.where(gps == True)[0]

        if len(sensors_working) == 3:  # take all GNSS sensors
            fl_columns = [
                'offsetTime',
                f'IMU_ATTI({sensors_working[0]}):barometer:Smooth[meters]',
                'GPS(0):Time', 'GPS(1):Time', 'GPS(2):Time',
                'GPS(0):Lat[degrees]', 'GPS(1):Lat[degrees]',
                'GPS(2):Lat[degrees]', 'GPS(0):Long[degrees]',
                'GPS(1):Long[degrees]', 'GPS(2):Long[degrees]',
                'IMU_ATTI(0):Latitude[degrees [-180;180]]',
                'IMU_ATTI(1):Latitude[degrees [-180;180]]',
                'IMU_ATTI(2):Latitude[degrees [-180;180]]',
                'IMU_ATTI(0):Longitude[degrees [-180;180]]',
                'IMU_ATTI(1):Longitude[degrees [-180;180]]',
                'IMU_ATTI(2):Longitude[degrees [-180;180]]'
            ]  # all columns needed from flightlog data

        elif len(sensors_working) == 2:  # take only 2 GNSS sensors
            fl_columns = [
                'offsetTime',
                f'IMU_ATTI({sensors_working[0]}):barometer:Smooth[meters]',
                f'GPS({sensors_working[0]}):Time',
                f'GPS({sensors_working[1]}):Time',
                f'GPS({sensors_working[0]}):Lat[degrees]',
                f'GPS({sensors_working[1]}):Lat[degrees]',
                f'GPS({sensors_working[0]}):Long[degrees]',
                f'GPS({sensors_working[1]}):Long[degrees]',
                f'IMU_ATTI({sensors_working[0]}):Latitude[degrees [-180;180]]',
                f'IMU_ATTI({sensors_working[0]}):Longitude[degrees [-180;180]]',
                f'IMU_ATTI({sensors_working[1]}):Latitude[degrees [-180;180]]',
                f'IMU_ATTI({sensors_working[1]}):Longitude[degrees [-180;180]]'
            ]

        else:  # take only 1 GNSS sensor
            fl_columns = [
                'offsetTime',
                f'IMU_ATTI({sensors_working[0]}):barometer:Smooth[meters]',
                f'GPS({sensors_working[0]}):Time',
                f'GPS({sensors_working[0]}):Lat[degrees]',
                f'GPS({sensors_working[0]}):Long[degrees]',
                f'IMU_ATTI({sensors_working[0]}):Latitude[degrees [-180;180]]',
                f'IMU_ATTI({sensors_working[0]}):Longitude[degrees [-180;180]]'
            ]

        self.flightlog_filename = self.flightlog_file.GetValue()

        fl_data = pd.read_csv(self.flightlog_filename, usecols=fl_columns)
        # remove 1st row if flightlog converter added NaN to beginning
        if np.isnan(fl_data[f'GPS({sensors_working[0]}):Time'][0]):
            fl_data = fl_data.drop(0)
            fl_data = fl_data.reset_index(drop=True)
        self.log_text.AppendText(f'{datetime.now()}\tFlightlog data loaded\n')

        # create avg gps
        fl_data = fmf.avg_gps_timing(fl_data,
                                     sensors_available=sensors_working)

        self.log_text.AppendText(
            f'{datetime.now()}\tFlightlog data processed\n')

        # read mag data
        mag_data = pd.read_csv(self.filename_newfile)

        self.log_text.AppendText(f'{datetime.now()}\tMag data loaded\n')

        # set timestamps
        mag_data = fmf.set_timestamp_mag(mag_data)
        fl_data = fmf.set_timestamp_flightlog(fl_data, mag_data)

        # down-sample to 100 Hz
        if self.sensor_radio_box.GetStringSelection() == 'MagArrow':
            mag_dec = fmf.decimate_magarrow(mag_data, 10,
                                            '1L')  # get down to 100 Hz
            crs = int(config['MA']['crs_epsg'])
        elif self.sensor_radio_box.GetStringSelection() == 'MagDrone':
            mag_dec = fmf.decimate_magdrone(mag_data, 2,
                                            '5L')  # get down to 100 Hz
            crs = int(config['MD']['crs_epsg'])
        else:
            return

        # create new dataframe with merged data
        new_df = fmf.merge(fl_data, mag_dec, round_per='10L')

        # average locations of the GPS sensors
        new_df = fmf.avg_gps_loc(new_df, sensors=sensors_working)

        new_df = new_df.interpolate(method='linear', axis=0)

        # correct time format
        new_df = fmf.correct_time_format(new_df)

        # project coordinates
        new_df = fmf.project_coordinates(
            new_df, crs, int(config['general']['proj_crs_epsg']))
        self.log_text.AppendText(
            f'{datetime.now()}:\tFlightlog coordinates projected to '
            f'{config["general"]["proj_crs"]}.\n')

        # no need to save all data from FL. take only columns specified in fl_cols
        fl_cols = np.array([
            'GPS(Fuse):Lat[degrees]', 'GPS(Fuse):Long[degrees]',
            'GPS(Fuse):Time',
            f'IMU_ATTI({sensors_working[0]}):barometer:Smooth[meters]',
            'X_flightlog_m', 'Y_flightlog_m'
        ])
        cols = np.concatenate((mag_data.columns.values, fl_cols), axis=None)
        new_df = new_df[cols]

        self.log_text.AppendText(f'{datetime.now()}\tData merged\n')

        new_df_nparray = new_df.to_numpy()

        # get correct save format
        sensor = self.sensor_radio_box.GetStringSelection()
        if sensor == 'MagArrow':
            fl_format = config['MA'][
                'save_col_format'] + ',%.8f,%.8f,%s,%.3f,%.3f,%.3f'
        elif sensor == 'MagDrone':
            fl_format = config['MD'][
                'save_col_format'] + ',%.8f,%.8f,%s,%.3f,%.3f,%.3f'
        else:
            self.log_text.AppendText(
                f'{datetime.now()}:\tWrong sensor selection.')
            return

        # save data
        with wx.FileDialog(self,
                           message='Save merged data to file',
                           defaultDir="",
                           defaultFile="",
                           wildcard="csv files (*.csv)|*.csv",
                           style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as dlg:
            if dlg.ShowModal() == wx.ID_CANCEL:
                self.log_text.AppendText(
                    f'{datetime.now()}\tUser stopped flightlog merge\n')
                return

            merged_path = dlg.GetPath()
            # new_df.to_csv(merged_path, index=False)
            np.savetxt(fname=merged_path,
                       X=new_df_nparray,
                       fmt=fl_format,
                       delimiter=',',
                       newline='\n',
                       header=','.join([i for i in list(new_df.columns)]))

            self.log_text.AppendText(
                f'{datetime.now()}\tMerged data saved to {merged_path}\n\n')