Ejemplo n.º 1
0
    def saveFile(self, event=None):
        '''
        If file being edited has a path, then overwrite with latest changes.
        If file was created from scratch and has no path, prompt JFileChooser
        to save in desired location.
        Also checks for project name, and if found, makes it default.
        '''
        atfText = self.atfAreaController.getAtfAreaText()
        if not self.currentFilename:
            fileChooser = JFileChooser(os.getcwd())
            status = fileChooser.showSaveDialog(self.view)
            if status == JFileChooser.APPROVE_OPTION:
                atfFile = fileChooser.getSelectedFile()
                filename = atfFile.getCanonicalPath()
                basename = atfFile.getName()
                self.currentFilename = filename
                self.view.setTitle(basename)
            else:
                return
        try:
            self.writeTextFile(self.currentFilename, atfText)
        except:
            self.logger.error("There was an error trying to save %s.",
                              self.currentFilename)
        else:
            self.logger.info("File %s successfully saved.",
                             self.currentFilename)

        # Find project and add to setting.yaml as default
        project = self.get_project()
        if project:
            if self.config['projects']['default'] != project:
                self.config['projects']['default'] = [project]
                save_yaml_config(self.config)
Ejemplo n.º 2
0
def MultiFileDialog(title):
    #hide/show debug prints
    verbose = 0
    # Choose image file(s) to open
    fc = JFileChooser()
    fc.setMultiSelectionEnabled(True)
    fc.setDialogTitle(title)

    sdir = OpenDialog.getDefaultDirectory()
    if sdir != None:
        fdir = File(sdir)
    if fdir != None:
        fc.setCurrentDirectory(fdir)

    returnVal = fc.showOpenDialog(IJ.getInstance())
    if returnVal != JFileChooser.APPROVE_OPTION:
        return
    files = fc.getSelectedFiles()

    paths = []
    for i in range(len(files)):
        paths.append(os.path.join(files[i].getParent(), files[i].getName()))

    if verbose > 0:
        for i in range(len(files)):
            path = os.path.join(files[i].getParent(), files[i].getName())
            print "Path: " + path

    return paths
Ejemplo n.º 3
0
 def getFilePath(self):
     chooseFile = JFileChooser()
     panel = JPanel()
     ret = chooseFile.showDialog(panel, "Choose output file (*.msc)")
     if ret == JFileChooser.APPROVE_OPTION: 
       file=chooseFile.getSelectedFile()
     return file 
Ejemplo n.º 4
0
    def save_pdf(self, event):
        from com.itextpdf.text.pdf import PdfWriter
        from com.itextpdf.text import Document

        fileChooser = JFileChooser()
        fileChooser.setSelectedFile(java.io.File('%s.pdf' % self.view.network.name))
        if fileChooser.showSaveDialog(self) == JFileChooser.APPROVE_OPTION:
            f = fileChooser.getSelectedFile()

            doc = Document()
            writer = PdfWriter.getInstance(doc, java.io.FileOutputStream(f))
            doc.open()
            cb = writer.getDirectContent()
            w = self.view.area.size.width
            h = self.view.area.size.height
            pw = 550
            ph = 800
            tp = cb.createTemplate(pw, ph)
            g2 = tp.createGraphicsShapes(pw, ph)
            at = java.awt.geom.AffineTransform()
            s = min(float(pw) / w, float(ph) / h)
            at.scale(s, s)
            g2.transform(at)
            self.view.area.pdftemplate = tp, s
            self.view.area.paint(g2)
            self.view.area.pdftemplate = None
            g2.dispose()

            cb.addTemplate(tp, 20, 0)
            doc.close()
Ejemplo n.º 5
0
 def add_file(self, evt):
     fc = JFileChooser()
     ret = fc.showOpenDialog(self.tab)
     if ret == JFileChooser.APPROVE_OPTION:
         with open(fc.getSelectedFile().getCanonicalPath()) as fd:
             for line in fd:
                 self.listModel.addElement(line)
def get_file_name():
    fc = JFileChooser()
    result = fc.showOpenDialog(None)
    if not result == JFileChooser.APPROVE_OPTION:
        return None
    file_name = fc.getSelectedFile()
    return file_name
Ejemplo n.º 7
0
    def openFile(self, event):
        '''
        1. Check if current file in text area has unsaved changes
            1.1 Prompt user for file saving
                1.1.1 Save file
        2. Display browser for user to choose file
        3. Load file in text area
        '''
        self.consoleController.addText("NammuController: Opening file...")

        self.handleUnsaved()

        fileChooser = JFileChooser()
        filter = FileNameExtensionFilter("ATF files", ["atf"])
        fileChooser.setFileFilter(filter)
        status = fileChooser.showDialog(self.view, "Choose file")

        if status == JFileChooser.APPROVE_OPTION:
            atfFile = fileChooser.getSelectedFile()
            filename = atfFile.getCanonicalPath()
            atfText = self.readTextFile(filename)
            self.currentFilename = atfFile.getCanonicalPath()
            self.atfAreaController.setAtfAreaText(atfText)

        #TODO: Else, prompt user to choose again before closing

        self.consoleController.addText(" OK\n")
Ejemplo n.º 8
0
def _show_directory_dialog():
    filechooser = JFileChooser("")
    filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
    selected = filechooser.showSaveDialog(None)
    if selected == JFileChooser.APPROVE_OPTION:
      file = filechooser.getSelectedFile()
      return file.getAbsolutePath()
Ejemplo n.º 9
0
    def __init__(self):
        self.descriptors = OrderedDict()

        self.chooser = JFileChooser()
        self.chooser.addChoosableFileFilter(PROTO_FILENAME_EXTENSION_FILTER)
        self.chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES)
        self.chooser.setMultiSelectionEnabled(True)
def searchFile2(event):
    label3.text = "Isi pesan terenkripsi"
    label4.text = "Isi pesan asli"
    myFileChooser = JFileChooser()
    rVal = int(myFileChooser.showOpenDialog(None))
    print rVal
    if (rVal == JFileChooser.APPROVE_OPTION):
        encryptedTextFile.text = myFileChooser.getSelectedFile().getName()
        encryptedTextPath.text = myFileChooser.getCurrentDirectory().toString()
        try:
            myPath = encryptedTextPath.text + "/" + encryptedTextFile.text
            fileReaderX = FileReader(myPath)
            bufferedReaderX = BufferedReader(fileReaderX)
            inputFile = ""
            textFieldReadable = bufferedReaderX.readLine()
            while (textFieldReadable != None):
                inputFile += textFieldReadable
                inputFile += "\n"
                textFieldReadable = bufferedReaderX.readLine()
            pesanAsli.text = inputFile

            import myGUI.saveToFile as convertThis

            return convertThis.convertBackToInt(inputFile)

        except (RuntimeError, TypeError, NameError):
            print "eror gan"
Ejemplo n.º 11
0
 def writeConfigDialog(self, e):
     """Open a file dialog to save configuration"""
     fileChooser = JFileChooser(os.getcwd())
     retval = fileChooser.showSaveDialog(None)
     if retval == JFileChooser.APPROVE_OPTION:
         f = fileChooser.getSelectedFile()
         self.writeConfig(f.getPath())
Ejemplo n.º 12
0
 def selectFile(self, event):
     print("Choose !!")
     chooseFile = JFileChooser()
     ret = chooseFile.showDialog(frm.panel, "Choose file")
     if ret == JFileChooser.APPROVE_OPTION:
         file = chooseFile.getSelectedFile()
         frm.jTextField4.setText(file.getCanonicalPath())
Ejemplo n.º 13
0
class FileManager(object):
    
    def __init__(self, pywin):
        self.fc = JFileChooser()
        self.fc.fileFilter = FileNameExtensionFilter("Python Files", ["py"])
        self.pywin = pywin
        self.load_path = None
        self.script_path = None

    @property
    def script_area(self):
        return self.pywin.script_pane.script_area
    
    def show_open_dialog(self, title):
        self.fc.dialogTitle = title
        res = self.fc.showOpenDialog(self.pywin.frame)
        if res == JFileChooser.APPROVE_OPTION:
            return self.fc.selectedFile
    
    def show_save_dialog(self, title):
        self.fc.dialogTitle = title
        res = self.fc.showSaveDialog(self.pywin.frame)
        if res == JFileChooser.APPROVE_OPTION:
            return self.fc.selectedFile
    
    def save_script(self):
        if self.script_path is None:
            return
        with codecs.open(self.script_path, "wb", "utf-8") as stream:
            stream.write(self.script_area.input)
    
    def open_script(self):
        f = self.show_open_dialog("Select script file to open")
        if f is None:
            return
        self.script_path = f.absolutePath
        with codecs.open(self.script_path, "rb", "utf-8") as stream:
            self.script_area.input = stream.read()
    
    def save_script_as(self):
        f = self.show_save_dialog("Select file to write script to")
        if f is None:
            return
        self.script_path = f.absolutePath
        self.save_script()
    
    def load_script(self):
        f = self.show_open_dialog("Select script file to load")
        if f is None:
            return
        self.load_path = f.absolutePath
        self.reload_script()
    
    def reload_script(self):
        print "*** Loading", self.load_path, "***"
        try:
            self.pywin.execfile(self.load_path)
        except Exception, e:
            self.pywin.outputpane.addtext(str(e) + '\n', 'error')
Ejemplo n.º 14
0
 def loadConfigDialog(self, e):
     """Open a file dialog to select configuration to load"""
     fileChooser = JFileChooser(os.getcwd())
     retval = fileChooser.showOpenDialog(None)
     if retval == JFileChooser.APPROVE_OPTION:
         f = fileChooser.getSelectedFile()
         log.info("Selected file: " + f.getPath())
         self.loadConfig(f.getPath())
Ejemplo n.º 15
0
 def onOpenFolder(self, event):
     chooseFile = JFileChooser()
     chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
     ret = chooseFile.showDialog(self, "Choose folder")
     if ret == JFileChooser.APPROVE_OPTION:
         self.faile= chooseFile.getSelectedFile()
         self.cbOutDir.addItem(self.faile.getPath())
         self.cbOutDir.selectedItem= self.faile.getPath()
Ejemplo n.º 16
0
 def showFC( self, event ) :
     fc = JFileChooser()
     result = fc.showOpenDialog( None )
     if result == JFileChooser.APPROVE_OPTION :
         message = 'result = "%s"' % fc.getSelectedFile()
     else :
         message = 'Request canceled by user'
     self.label.setText( message )
Ejemplo n.º 17
0
 def init():
     canvas = RayTracePanel(w, h, aa, threads)
     self.add(canvas)
     
     #Save FileChooser
     fcS = JFileChooser()
     fcS.addChoosableFileFilter(FileNameExtensionFilter('Windows Bitmap (*.bmp)', ['bmp']))
     fcS.addChoosableFileFilter(FileNameExtensionFilter('JPEG / JFIF (*.jpg)', ['jpg']))
     fcS.addChoosableFileFilter(FileNameExtensionFilter('Portable Network Graphics (*.png)', ['png']))
     def saveFile(event):
         '''Performed when the save button is pressed'''
         result = fcS.showSaveDialog(frame)
         if result == JFileChooser.APPROVE_OPTION:
             file = fcS.getSelectedFile()
             fname = file.getPath()
             ext = fcS.getFileFilter().getExtensions()[0]
             if not fname.endswith('.' + ext):
                 file = File(fname + '.' + ext)
             canvas.saveToFile(file, ext)
     
     #Open FileChooser
     fcO = JFileChooser()
     fcO.addChoosableFileFilter(FileNameExtensionFilter('RayTrace Scene File (*.rts)', ['rts']))
     def openFile(event):
         '''Performed when the open button is pressed'''
         result = fcO.showOpenDialog(frame)
         if result == JFileChooser.APPROVE_OPTION:
             fname = fcO.getSelectedFile().getPath()
             if fname.endswith('.rts'):
                 f = open(fname, 'rb')
                 newScene = SceneFactory().buildScene(f)
                 f.close()
                 Painter(canvas, newScene, openButton, saveButton, stopButton).start()
         
     def stop(event):
         '''Peformed when the stop button is pressed'''
         canvas.stopRendering()
         
     #Setup Menu
     menuBar = JMenuBar()
     menu = JMenu("File")
     menuBar.add(menu)
     openButton = JMenuItem("Open...", actionPerformed=openFile)
     openButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK))
     menu.add(openButton)
     saveButton = JMenuItem("Save as...", actionPerformed=saveFile)
     saveButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK))
     menu.add(saveButton)
     menu.addSeparator()
     stopButton = JMenuItem('Stop Render', actionPerformed=stop)
     stopButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));
     stopButton.setEnabled(False)
     menu.add(stopButton)
     menu.addSeparator()
     closeButton = JMenuItem('Close', actionPerformed=exit)
     closeButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, ActionEvent.ALT_MASK))
     menu.add(closeButton)
     self.setJMenuBar(menuBar)
Ejemplo n.º 18
0
    def actionPerformed(self, e):
        self.chooser = JFileChooser()
        self.option = self.chooser.showOpenDialog(self.frame)

        if (self.option == JFileChooser.APPROVE_OPTION):
            self.frame.statusbar.setText(
                "You chose " + self.chooser.getSelectedFile().getName())
        else:
            self.frame.statusbar.setText("You cancelled.")
Ejemplo n.º 19
0
 def onClick(self, e):
     chooseFile = JFileChooser()
     filter = FileNameExtensionFilter("c files", ["c"])
     chooseFile.addChoosableFileFilter(filter)
     ret = chooseFile.showDialog(self.panel, "Choose file")
     if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           
           print file
Ejemplo n.º 20
0
def loadPopNames():
    global frame, empiricalPanel
    fc = JFileChooser(dataPath)
    retVal = fc.showOpenDialog(frame)
    if retVal == JFileChooser.APPROVE_OPTION:
        file = fc.getSelectedFile()
        loadFilePopNames(file)
        updateAll()
        enablePanel(empiricalPanel)
Ejemplo n.º 21
0
def _imageFileChooser(element, imageValueFn):
	component = element.getRootElement().getComponent()
	fileChooser = JFileChooser()
	response = fileChooser.showDialog(component, 'Open')
	if response == JFileChooser.APPROVE_OPTION:
		sf = fileChooser.getSelectedFile()
		if sf is not None:
			return imageValueFn(sf)
	return None
Ejemplo n.º 22
0
 def actionPerformed(self, event):
     fileChooser = JFileChooser()
     if fileChooser.showOpenDialog(None) == JFileChooser.APPROVE_OPTION:
         self.frame.projects.addTab(
             fileChooser.selectedFile.name[:fileChooser.selectedFile.name.
                                           rfind(".")],
             panel.ProfelisPanel(
                 self.frame, fileChooser.selectedFile.
                 absolutePath[:fileChooser.selectedFile.absolutePath.
                              rfind(".")]))
Ejemplo n.º 23
0
Archivo: logme.py Proyecto: Yaeger/Burp
	def selectFile(self, event):
		'''
		Action handler to select a file to save to
		'''
		
		chooser = JFileChooser()
		retVal = chooser.showSaveDialog(None)

		#if reVal == JFileChooser.APPROVE_OPTION:
		self.saveFile = chooser.selectedFile.path
Ejemplo n.º 24
0
    def set_output_file(self, event=None):
        file_chooser = JFileChooser()
        choice = file_chooser.showSaveDialog(None)
        if choice == JFileChooser.APPROVE_OPTION:
            self.outputFileTextField.text = file_chooser.selectedFile.path
            self.output_file = open(file_chooser.selectedFile.path, 'a')
            self.script.stdout = self.output_file
            return True

        return False
Ejemplo n.º 25
0
 def openFileChooser(self, event):
     import sys
     theFilter = FileDialogFilter(
         ["jar", "zip"],
         jEdit.getProperty("jython.pathhandler.compressedfilter"))
     chooser = JFileChooser(len(sys.path) and sys.path[0] or ".", \
      fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES, dialogTitle =jEdit.getProperty("jython.pathhandler.addtitle"), \
      fileFilter = theFilter)
     if chooser.showOpenDialog(self) == JFileChooser.APPROVE_OPTION:
         self.pathField.text = chooser.selectedFile.path
Ejemplo n.º 26
0
	def actionPerformed(self, e):
	
		fc = JFileChooser()
		
		returnValue = fc.showSaveDialog(self.pi.mainWindow.frame)
		
		if returnValue == JFileChooser.APPROVE_OPTION:
			fileName = fc.selectedFile.absolutePath
			createIdcFile(fileName, self.module)
			MessageBox.showInformation(self.pi.mainWindow.frame, "Module information was successfully written to the selected IDC file. Please run the IDC file in IDA Pro now.")
Ejemplo n.º 27
0
def MultiFileDialog(title):
  #hide/show debug prints
  verbose = 0
  # Choose image file(s) to open
  fc = JFileChooser()
  fc.setMultiSelectionEnabled(True)
  fc.setDialogTitle(title)

  sdir = OpenDialog.getDefaultDirectory()
  if sdir!=None:
    fdir = File(sdir)
  if fdir!=None:
    fc.setCurrentDirectory(fdir)
  
  returnVal = fc.showOpenDialog(IJ.getInstance())
  if returnVal!=JFileChooser.APPROVE_OPTION:
    return
  files = fc.getSelectedFiles()

  paths = []
  for i in range(len(files)):
      paths.append(os.path.join(files[i].getParent(), files[i].getName()))
      
  if verbose > 0:
    for i in range(len(files)):
      path = os.path.join(files[i].getParent(), files[i].getName())
      print "Path: " + path
  
  return paths
Ejemplo n.º 28
0
def createFileChooserDialog(filters, filename, prefs, prefkey, multiselect):
    """
    Creates a file chooser dialog that remembers its last directory.

    """
    fileChooser = JFileChooser()

    # Add filters
    if not hasattr(filters, '__iter__'):
        filters = (filters, )
    if filters:
        for filter in filters:
            fileChooser.addChoosableFileFilter(filter)
        fileChooser.fileFilter = filters[0]

    # Enable/disable multiple file select
    fileChooser.setMultiSelectionEnabled(multiselect)

    # Restore the last directory
    if prefs and prefkey:
        defaultDirName = prefs.get(prefkey, None)
        if defaultDirName:
            defaultDirectory = File(defaultDirName)
            if defaultDirectory.exists():
                fileChooser.currentDirectory = defaultDirectory

    # Preset the file name
    if filename:
        fileChooser.selectedFile = File(fileChooser.currentDirectory, filename)

    return fileChooser
Ejemplo n.º 29
0
 def getFile(self,button):
     dlg = JFileChooser()
     result = dlg.showOpenDialog(None)
     if result == JFileChooser.APPROVE_OPTION:
         f = dlg.getSelectedFile()
         path = f.getPath()
         self.FileText.setText(path)
         try:
             self.getIPList(path)
         except:
             exit(0)
Ejemplo n.º 30
0
def openFolderDialog(dialogTitle):
    from javax.swing import JFileChooser
    chooser = JFileChooser()
    chooser.setMultiSelectionEnabled(True)
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
    chooser.setDialogTitle(dialogTitle)
    if chooser.showOpenDialog(None) == JFileChooser.APPROVE_OPTION:
        folderPathStrings = []
        for folderPath in chooser.getSelectedFiles():
            folderPathStrings.append(str(folderPath))
        return folderPathStrings
Ejemplo n.º 31
0
 def _onOpen(button, event):
     component = button.getElement().getRootElement().getComponent()
     fileChooser = JFileChooser()
     self._initFileChooser(fileChooser)
     response = fileChooser.showDialog(component, 'Open')
     if response == JFileChooser.APPROVE_OPTION:
         sf = fileChooser.getSelectedFile()
         if sf is not None:
             filename = sf.getPath()
             if filename is not None:
                 self._model.liveValue.setLiteralValue(filename)
def get_file_name():
    frame = JFrame("Filename")
    frame.setLocation(100, 100)
    frame.setSize(500, 400)
    frame.setLayout(None)
    fc = JFileChooser()
    result = fc.showOpenDialog(frame)
    if not result == JFileChooser.APPROVE_OPTION:
        return None
    file_name = fc.getSelectedFile()
    return file_name
Ejemplo n.º 33
0
 def getFile(self, button):
     dlg = JFileChooser()
     result = dlg.showOpenDialog(None)
     if result == JFileChooser.APPROVE_OPTION:
         f = dlg.getSelectedFile()
         path = f.getPath()
         self.FileText.setText(path)
         try:
             self.getIPList(path)
         except:
             exit(0)
Ejemplo n.º 34
0
	def get_image_file(self) :
		file_dialog = JFileChooser()
		#image files
		image_filter = FileNameExtensionFilter("Image Files", 
			["jpg","bmp","png","gif"])
		print image_filter.getExtensions()
		file_dialog.setFileFilter(image_filter)
		x = file_dialog.showOpenDialog(None)
		if x == JFileChooser.APPROVE_OPTION :
			return file_dialog.getSelectedFile()
		else :
			return None
    def onClick(self, e):

        chooseFile = JFileChooser()
        filter = FileNameExtensionFilter("SQLite", ["sqlite"])
        chooseFile.addChoosableFileFilter(filter)

        ret = chooseFile.showDialog(self.panel, "Select SQLite")

        if ret == JFileChooser.APPROVE_OPTION:
            file = chooseFile.getSelectedFile()
            text = self.readPath(file)
            self.area.setText(text)
Ejemplo n.º 36
0
 def showFC( self, event ) :
     fc = JFileChooser(
         RestrictedFileSystemView(
             File( r'C:\IBM\WebSphere' )
         )
     )
     result = fc.showOpenDialog( None )
     if result == JFileChooser.APPROVE_OPTION :
         message = 'result = "%s"' % fc.getSelectedFile()
     else :
         message = 'Request canceled by user'
     self.label.setText( message )
Ejemplo n.º 37
0
def mplab_chooseBootstrap(self):
    project_dir = ide.expandProjectMacros("${ProjectName}", "${ProjectDir}")
    pdl = len(project_dir)
    fileChooser = JFileChooser(project_dir)
    retval = fileChooser.showOpenDialog(None)
    if retval == JFileChooser.APPROVE_OPTION:
        f = fileChooser.getSelectedFile().getPath()
        if 0 == f.find(project_dir):
            f = "${ProjectDir}" + f[pdl:]
        bsOpt.binTxt.text = f
        msg.print("Selected bootstrap binary: %s\n" % f)
        settings.setString("boot.path", f)
Ejemplo n.º 38
0
 def _configFileDialogue(self):
     from javax.swing import JFileChooser
     from javax.swing.filechooser import FileNameExtensionFilter
     fileDialogue = JFileChooser(self.dssFilePath)
     filter = FileNameExtensionFilter("Configuration file (*.yml; *.yaml)",
                                      ["yaml", "yml"])
     fileDialogue.setFileFilter(filter)
     ret = fileDialogue.showOpenDialog(self.mainWindow)
     if ret == JFileChooser.APPROVE_OPTION:
         return fileDialogue.getSelectedFile().getAbsolutePath()
     else:
         raise CancelledError("Config file selection was cancelled.")
Ejemplo n.º 39
0
class GnitPickFileChooser(ActionListener):
  def __init__(self,frm):
    self.frame = frm

  def actionPerformed(self,e):
      self.chooser = JFileChooser()
      self.option = self.chooser.showOpenDialog(self.frame)
      
      if (self.option == JFileChooser.APPROVE_OPTION):
          self.frame.statusbar.setText("You chose " + self.chooser.getSelectedFile().getName())
      else:
          self.frame.statusbar.setText("You cancelled.")
Ejemplo n.º 40
0
    def approveSelection(self):
        if self._validator is not None:
            chosenFile = self.selectedFile
            chosenPath = chosenFile.path
            validatedPath = self._validator(chosenPath)
            if validatedPath is None or validatedPath is False:
                return
            elif validatedPath is True:
                pass
            elif validatedPath != chosenPath:
                self.selectedFile = File(validatedPath)

        JFileChooser.approveSelection(self)
Ejemplo n.º 41
0
    def approveSelection(self):
        if self._validator is not None:
            chosenFile = self.selectedFile
            chosenPath = chosenFile.path
            validatedPath = self._validator(chosenPath)
            if validatedPath is None or validatedPath is False:
                return
            elif validatedPath is True:
                pass
            elif validatedPath != chosenPath:
                self.selectedFile = File(validatedPath)

        JFileChooser.approveSelection(self)
Ejemplo n.º 42
0
class GnitPickFileChooser(ActionListener):
    def __init__(self, frm):
        self.frame = frm

    def actionPerformed(self, e):
        self.chooser = JFileChooser()
        self.option = self.chooser.showOpenDialog(self.frame)

        if (self.option == JFileChooser.APPROVE_OPTION):
            self.frame.statusbar.setText(
                "You chose " + self.chooser.getSelectedFile().getName())
        else:
            self.frame.statusbar.setText("You cancelled.")
Ejemplo n.º 43
0
def doOpen(event):
    global player
    global volume

    if not player == None:
        player.stop()

    chooser = JFileChooser()
    rc = chooser.showOpenDialog(None)
    if rc == JFileChooser.APPROVE_OPTION:
        soundFile = chooser.getSelectedFile()
        player = SoundPlayer(soundFile)
        volume = player.getVolume()
Ejemplo n.º 44
0
    def createDialogBoxForImportExport(self, dialogTitle, extensionFilter, buttonText):

        # create frame
        frameImportExportDialogBox = JFrame()

        # try to load the last used directory
        try:
            # load the directory for future imports/exports
            fileChooserDirectory = self._callbacks.loadExtensionSetting("fileChooserDirectory")

        # there is not a last used directory
        except:
            # set the last used directory to blank
            fileChooserDirectory = ""

        # create file chooser
        fileChooserImportExportDialogBox = JFileChooser(fileChooserDirectory)

        # set dialog title
        fileChooserImportExportDialogBox.setDialogTitle(dialogTitle)

        # create extension filter
        filterImportExportDialogBox = FileNameExtensionFilter(extensionFilter[0], extensionFilter[1])

        # set extension filter
        fileChooserImportExportDialogBox.setFileFilter(filterImportExportDialogBox)

        # show dialog box and get value
        valueFileChooserImportExportDialogBox = fileChooserImportExportDialogBox.showDialog(frameImportExportDialogBox, buttonText)

        # check if a file was not selected
        if valueFileChooserImportExportDialogBox != JFileChooser.APPROVE_OPTION:
        
            # return no path/file selected
            return False, "No Path/File"

        # get the directory
        fileChooserDirectory = fileChooserImportExportDialogBox.getCurrentDirectory()

        # store the directory for future imports/exports
        self._callbacks.saveExtensionSetting("fileChooserDirectory", str(fileChooserDirectory))

        # get absolute path of file
        fileChosenImportExportDialogBox = fileChooserImportExportDialogBox.getSelectedFile().getAbsolutePath()

        # split name and extension
        fileNameImportExportDialogBox, fileExtensionImportExportDialogBox = os.path.splitext(fileChosenImportExportDialogBox)

        # check if file does not have an extention
        if fileExtensionImportExportDialogBox == "":

            # add extension to file
            fileChosenImportExportDialogBox = fileChosenImportExportDialogBox + extensionFilter[2]

        # return dialog box value and path/file
        return True, fileChosenImportExportDialogBox
Ejemplo n.º 45
0
 def actionPerformed(self, event):
     option = event.getActionCommand()
     if option == 'Close':
         self.dispose()
     elif option == 'SCI':
         chooser = JFileChooser()
         returnVal = chooser.showSaveDialog(self)
         if returnVal == JFileChooser.APPROVE_OPTION:
             fileName = chooser.getSelectedFile().getPath()
             f = open(fileName, 'w')
             f.write("\t".join([
                 "Het", "Fst", "0.5(1-pval)quantile", "median",
                 "0.5(1+pval)quantile"
             ]) + "\n")
             for line in self.confLines:
                 f.write('\t'.join(map(lambda x: str(x), line)) + "\n")
             f.close()
     elif option == 'SLL':
         chooser = JFileChooser()
         returnVal = chooser.showSaveDialog(self)
         if returnVal == JFileChooser.APPROVE_OPTION:
             fileName = chooser.getSelectedFile().getPath()
             f = open(fileName, 'w')
             f.write("\t".join(
                 ["Locus", "Het", "Fst", "P(Simul Fst<sample Fst)"]) + "\n")
             for i in range(self.data.size()):
                 line = self.data.elementAt(i)
                 lineList = [str(line.elementAt(0))]
                 lineList.append(str(line.elementAt(1)))
                 lineList.append(str(line.elementAt(2)))
                 lineList.append(str(line.elementAt(3)))
                 f.write("\t".join(lineList) + "\n")
             f.close()
Ejemplo n.º 46
0
    def set_from_file(self, event):
        fileChooser = JFileChooser()
        if self.filename is not None:
            fileChooser.setSelectedFile(java.io.File(self.filename))

        if fileChooser.showOpenDialog(self) == JFileChooser.APPROVE_OPTION:
            self.filename = fileChooser.selectedFile.absolutePath

            #TODO: this doesn't for for nested FunctionInputs
            input = self.view.network.getNode(self.name)

            from nef.functions import Interpolator
            interp = Interpolator(self.filename)
            interp.load_into_function(input)
Ejemplo n.º 47
0
def createFileChooserDialog(filters, filename, prefs, prefkey, multiselect):
    """
    Creates a file chooser dialog that remembers its last directory.
    
    """
    fileChooser = JFileChooser()

    # Add filters
    if not hasattr(filters, '__iter__'):
        filters = (filters,)
    if filters:
        for filter in filters:
            fileChooser.addChoosableFileFilter(filter)
        fileChooser.fileFilter = filters[0]

    # Enable/disable multiple file select
    fileChooser.setMultiSelectionEnabled(multiselect)

    # Restore the last directory
    if prefs and prefkey:
        defaultDirName = prefs.get(prefkey, None)
        if defaultDirName:
            defaultDirectory = File(defaultDirName)
            if defaultDirectory.exists():
                fileChooser.currentDirectory = defaultDirectory

    # Preset the file name
    if filename:
        fileChooser.selectedFile = File(fileChooser.currentDirectory, filename)

    return fileChooser
Ejemplo n.º 48
0
    def Find_Plaso_File(self, e):

       chooseFile = JFileChooser()
       filter = FileNameExtensionFilter("All", ["*.*"])
       chooseFile.addChoosableFileFilter(filter)

       ret = chooseFile.showDialog(self.panel0, "Find Plaso Storage File")

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           Canonical_file = file.getCanonicalPath()
           #text = self.readPath(file)
           self.local_settings.setSetting('Plaso_Storage_File', Canonical_file)
           self.Plaso_Storage_File_TF.setText(Canonical_file)
    def onClick(self, e):

       chooseFile = JFileChooser()
       filter = FileNameExtensionFilter("SQLite", ["sqlite"])
       chooseFile.addChoosableFileFilter(filter)

       ret = chooseFile.showDialog(self.panel0, "Select SQLite")

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           Canonical_file = file.getCanonicalPath()
           #text = self.readPath(file)
           self.local_settings.setSetting('ExecFile', Canonical_file)
           self.Program_Executable_TF.setText(Canonical_file)
Ejemplo n.º 50
0
 def browse(self, event=None):
     '''
     Open new dialog for the user to select a path as default working dir.
     '''
     default_path = self.wd_field.getText()
     if not os.path.isdir(default_path):
         default_path = os.getcwd()
     fileChooser = JFileChooser(default_path)
     fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
     # Fixed showDialog bug using showOpenDialog instead. The former was
     # duplicating the last folder name in the path due to a Java bug in
     # OSX in the implementation of JFileChooser!
     status = fileChooser.showOpenDialog(self)
     if status == JFileChooser.APPROVE_OPTION:
         self.wd_field.setText(fileChooser.getSelectedFile().toString())
Ejemplo n.º 51
0
    def Find_Dir(self, e):

       chooseFile = JFileChooser()
       filter = FileNameExtensionFilter("All", ["*.*"])
       chooseFile.addChoosableFileFilter(filter)
       #chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)

       ret = chooseFile.showDialog(self.panel0, "Find Volatility Directory")

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           Canonical_file = file.getCanonicalPath()
           #text = self.readPath(file)
           self.local_settings.setSetting('Volatility_Directory', Canonical_file)
           self.Program_Executable_TF.setText(Canonical_file)
Ejemplo n.º 52
0
    def loadSimOut(self, event):
        chooseFile = JFileChooser()
        filtro = FileNameExtensionFilter("Output files (.h5)", ['h5'])
        chooseFile.addChoosableFileFilter(filtro)
        ret = chooseFile.showDialog(self.frame, "Choose simulation result")
        if ret == JFileChooser.APPROVE_OPTION:
            faile= chooseFile.getSelectedFile()
            self.cbfilesimOut.addItem(faile.getPath())
            self.cbfilesimOut.selectedItem(faile.getPath())

        h5pmu= PhasorMeasH5.PhasorMeasH5(faile)
        h5pmu.open_h5()
        h5pmu.load_h5('pwLine4', 'V')
        # result: 2 vectors per variable, work with pwLine4.n.vr, pwLine4.n.vi
        senyal= h5pmu.get_senyal()
        print senyal
Ejemplo n.º 53
0
 def __init__(self, configFileName=None, dssFilePath=None):
     """
     A tool is defined by providing a `yaml` configuration file 
     ``configFileName`` and a HEC-DSS database ``dssFilePath`` to operate on.
     If ``dssFilePath`` is not set, the active DSS-file in the HEC-DSSVue
     window will be used. If ``configFileName`` is not set, a file selection
     dialogue is displayed prompting for a configuration file.
     
     The attribute :attr:`.config` will be set containing the parsed yaml 
     config file.
     """
     
     if dssFilePath:
         self.dssFilePath = dssFilePath
         self.mainWindow = None
     else:
         from hec.dssgui import ListSelection
         self.mainWindow = ListSelection.getMainWindow()
         self.dssFilePath = self.mainWindow.getDSSFilename()
         if not configFileName:
             from javax.swing import JFileChooser
             from javax.swing.filechooser import FileNameExtensionFilter
             fileDialogue = JFileChooser(self.dssFilePath)
             filter = FileNameExtensionFilter("Configuration file (*.yml; *.yaml)", 
                                              ["yaml", "yml"])
             fileDialogue.setFileFilter(filter)
             ret = fileDialogue.showOpenDialog(self.mainWindow)
             if ret == JFileChooser.APPROVE_OPTION:
                 self.configFilePath = (fileDialogue.getSelectedFile().
                                        getAbsolutePath())
             else:
                 raise CancelledError("Config file selection was cancelled.") 
     
     if configFileName:
         self.configFilePath = path.join(path.dirname(self.dssFilePath), 
                                         configFileName)
     elif dssFilePath:
         raise ValueError("`configFileName` argument must be provided if `dssFilePath` is specified.")
     
     #: Message to be displayed in HEC-DSSVue after running the tool. This 
     #: attribute is typically set in the :meth:`main`.
     self.message = ""
     
     if self._toolIsValid():
         with codecs.open(self.configFilePath, encoding='utf-8') as configFile:
             self.config = yaml.load(configFile.read())
         self._configIsValid()
Ejemplo n.º 54
0
 def actionPerformed(self,e):
     self.chooser = JFileChooser()
     self.option = self.chooser.showOpenDialog(self.frame)
     
     if (self.option == JFileChooser.APPROVE_OPTION):
         self.frame.statusbar.setText("You chose " + self.chooser.getSelectedFile().getName())
     else:
         self.frame.statusbar.setText("You cancelled.")
Ejemplo n.º 55
0
    def approveSelection(self):
        filePath = self.getSelectedFile().getPath()
        fileName = String(self.getSelectedFile().getName())

        if fileName.matches('[_a-zA-Z0-9()~#.]+'):
            if os.path.exists(filePath):
                message = 'File "' + str(fileName) + ' exists. Overwrite?'
                result = JOptionPane.showConfirmDialog(self, message,
                                                       'Confirm Overwrite',
                                                       JOptionPane.YES_NO_OPTION)
                if result == JOptionPane.YES_OPTION:
                    JFileChooser.approveSelection(self)
            else:
                JFileChooser.approveSelection(self)
        else:
            message = 'The file name contains illegal characters. Please rename.'
            JOptionPane.showMessageDialog(self, message, 'Error', JOptionPane.ERROR_MESSAGE)
Ejemplo n.º 56
0
    def menuItemClicked(self, menuItemCaption, messageInfo):
        if menuItemCaption == 'Save PoC':

            if self.dir:
                fc = JFileChooser(self.dir)
            else:
                fc = JFileChooser()

            returnVal = fc.showSaveDialog(None)

            if returnVal == JFileChooser.APPROVE_OPTION:
                file = fc.getSelectedFile()

                try:
                    mode = 'w'
                    if file.exists():
                        res = JOptionPane.showConfirmDialog(None, 
                                "File exists. Append?")
                        mode = {
                                JOptionPane.YES_OPTION : 'a',
                                JOptionPane.NO_OPTION : 'w',
                                JOptionPane.CANCEL_OPTION : None,
                                }[res]

                    if not mode:
                        return
                    fp = open(str(file.getAbsolutePath()), mode)
                    for req_resp in messageInfo:
                        req = req_resp.getRequest()
                        resp = req_resp.getResponse()
                        fp.write(req.tostring())
                        fp.write('\r\n\r\n')
                        fp.write(resp.tostring())
                        fp.write('\r\n\r\n')
                    fp.close()
                except Exception, e:
                    JOptionPane.showMessageDialog(None, 
                            "Error during save: " + str(e), "Error",  
                            JOptionPane.ERROR_MESSAGE)
                    raise

                JOptionPane.showMessageDialog(None, 
                            "File was successfully saved", "Ok",  
                            JOptionPane.INFORMATION_MESSAGE)
                self.dir = fc.getCurrentDirectory()