Beispiel #1
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
Beispiel #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
Beispiel #3
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
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
Beispiel #5
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
Beispiel #6
0
def multiple_file_location_chooser(default_directory):
	"""choose input data location with potential for being split over multiple files"""
	chooser = JFileChooser(default_directory);
	chooser.setDialogTitle("Choose one or more tiff files representing the data...");
	ext_filter = FileNameExtensionFilter("*.tif", ["tif", "tiff"]);
	chooser.setFileFilter(ext_filter);
	chooser.setMultiSelectionEnabled(True);
	chooser.showOpenDialog(None);
	file_paths = [f.toString() for f in chooser.getSelectedFiles()];
	if file_paths is None or len(file_paths)==0:
		raise IOError('no input file chosen');
	return file_paths;
Beispiel #7
0
def FolderDialog(title, folder):
  fc = JFileChooser()
  fc.setMultiSelectionEnabled(False)
  fc.setDialogTitle(title)
  fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
  fc.setAcceptAllFileFilterUsed(False);
  if folder ==None:
    sdir = OpenDialog.getDefaultDirectory()
  else:
    sdir = folder
  if sdir!=None:
    fdir = File(sdir)
  if fdir!=None:
    fc.setCurrentDirectory(fdir)
  returnVal = fc.showOpenDialog(IJ.getInstance())
  if returnVal!=JFileChooser.APPROVE_OPTION:
    return
  folder = fc.getSelectedFile();
  path = os.path.join(folder.getParent(), folder.getName())
  return path
Beispiel #8
0
    def actionPerformed(self, actionEvent):
        global yara_rules
        global yara_path

        if actionEvent.getSource() is self.menuItem:
            yara_path = self._yara_exe_txtField.getText()
            yara_rules = self._yara_rules_files
            t = Thread(self)
            t.start()
        elif actionEvent.getSource() is self._yara_clear_button:
            # Delete the LogEntry objects from the log
            row = self._log.size()
            self._lock.acquire()
            self._log.clear()

            # Update the Table
            self.fireTableRowsDeleted(0, row)

            # Clear data regarding any selected LogEntry objects from the request / response viewers
            self._requestViewer.setMessage([], True)
            self._responseViewer.setMessage([], False)
            self._currentlyDisplayedItem = None
            self._lock.release()
        elif actionEvent.getSource() is self._yara_rules_select_files_button:
            fileChooser = JFileChooser()
            yarFilter = FileNameExtensionFilter("Yara Rules", ["yar"])
            fileChooser.addChoosableFileFilter(yarFilter)
            fileChooser.setFileFilter(yarFilter)
            fileChooser.setMultiSelectionEnabled(True)
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY)
            ret = fileChooser.showOpenDialog(None)
            if ret == JFileChooser.APPROVE_OPTION:
                self._yara_rules_files.clear()
                for file in fileChooser.getSelectedFiles():
                    self._yara_rules_files.add(file.getPath())
                self._yara_rules_fileList.setListData(self._yara_rules_files)
        else:
            stdout.println("Unknown Event Received.")
Beispiel #9
0
class BurpExtender(IBurpExtender, IMessageEditorTabFactory, ITab, IExtensionStateListener):
    EXTENSION_NAME = "Protobuf Editor"

    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 registerExtenderCallbacks(self, callbacks):
        self.callbacks = callbacks
        self.helpers = callbacks.getHelpers()

        self.enabled = False

        try:
            process = subprocess.Popen(['protoc', '--version'],
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            output, error = process.communicate()
            self.enabled = output.startswith('libprotoc')

            if error:
                raise RuntimeError(error)

        except (OSError, RuntimeError) as error:
            self.callbacks.getStderr().write(
                    "Error calling protoc: %s\n" % (error.message, ))

        if not self.enabled:
            return

        rules = []
        saved_rules = callbacks.loadExtensionSetting('rules')

        if saved_rules:
            rules = json.loads(base64.b64decode(saved_rules))

            # For checkboxes to be rendered in a table model, the
            # type has to be java.lang.Boolean, not a Python bool.

            for rule in rules:
                rule[-1] = Boolean(rule[-1])

        self.table = ParameterProcessingRulesTable(self, *rules)

        callbacks.setExtensionName(self.EXTENSION_NAME)
        callbacks.registerExtensionStateListener(self)
        callbacks.registerMessageEditorTabFactory(self)
        callbacks.addSuiteTab(self)
        return

    def createNewInstance(self, controller, editable):
        return ProtobufEditorTab(self, controller, editable)

    def getTabCaption(self):
        return self.EXTENSION_NAME

    def getUiComponent(self):
        return self.table

    def extensionUnloaded(self):
        if not self.table.rules:
            return

        rules = self.table.rules

        # The default JSONENcoder cannot dump a java.lang.Boolean type,
        # so convert it to a Python bool. (We'll have to change it back
        # when loading the rules again.

        for rule in rules:
            rule[-1] = bool(rule[-1])

        self.callbacks.saveExtensionSetting(
                'rules', base64.b64encode(json.dumps(rules)))
        return
all.add( JLabel("Min") )
all.add( minField )
all.add( JLabel("Max") )
all.add(maxField )
all.add( JLabel("Score :") )
all.add(scoreField)
frame = JFrame("CCM scoring")
frame.getContentPane().add(JScrollPane(all))
frame.pack()
frame.addWindowListener( Closing() )
scoreField.requestFocusInWindow()

# Get the grid files
chooser = JFileChooser()
chooser.setDialogTitle("Choose plate grids")
chooser.setMultiSelectionEnabled(True)
chooser.setCurrentDirectory( File(os.path.expanduser("~")))
chooser.showOpenDialog(JPanel())

# This is a hack to get a file path from the
# sun.awt.shell.DefaultShellFolder object returned by the chooser
fp = [str(i) for i in chooser.getSelectedFiles()]

if len(fp) != 0:
    gd = GenericDialog("Name your output file")
    gd.addStringField("Score file name", "scores.csv")
    gd.showDialog()
    if not gd.wasCanceled():
        scoreFile = gd.getNextString()
        scoreFile = os.path.join( os.path.split(fp[0])[0], scoreFile)
        cropDir = os.path.splitext( scoreFile)[0] + "_cropped"
Beispiel #11
0
    def actionPerformed(self, event):
        """Called when a button is pressed."""
        if event.getActionCommand() == "new-type":
            type_name = JOptionPane.showInputDialog("Enter new name")

            # Error out if already defined
            if type_name in blackboxprotobuf.known_messages:
                JOptionPane.showMessageDialog(
                    self._type_def_tab._component,
                    "Message type %s already exists" % type_name)
                return

            typedef_editor.TypeEditorWindow(
                self._type_def_tab._burp_callbacks, {},
                self.create_save_callback(type_name)).show()

        elif event.getActionCommand() == "edit-type":
            list_component = self._type_def_tab._type_list_component
            # Check if something is selected
            if list_component.isSelectionEmpty():
                return

            type_name = list_component.getSelectedValue()
            typedef_editor.TypeEditorWindow(
                self._type_def_tab._burp_callbacks,
                blackboxprotobuf.known_messages[type_name],
                self.create_save_callback(type_name)).show()

        elif event.getActionCommand() == "delete-type":
            list_component = self._type_def_tab._type_list_component
            # Check if something is selected
            if list_component.isSelectionEmpty():
                return

            type_name = list_component.getSelectedValue()
            #TODO Confirm delete?
            del blackboxprotobuf.known_messages[type_name]
            self._type_def_tab.updateList()

        elif event.getActionCommand() == 'save-types':
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("JSON Type Definition", ["json"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showSaveDialog(
                self._type_def_tab.getUiComponent())
            if action == JFileChooser.CANCEL_OPTION or action == JFileChooser.ERROR_OPTION:
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            ext = os.path.splitext(file_name)[1]
            if ext == '':
                #No extension, add .json
                file_name += '.json'

            with open(file_name, 'w+') as selected_file:
                json.dump(blackboxprotobuf.known_messages,
                          selected_file,
                          indent=4,
                          sort_keys=True)

        elif event.getActionCommand() == 'load-types':
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("JSON Type Definition", ["json"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showOpenDialog(
                self._type_def_tab.getUiComponent())
            if action == JFileChooser.CANCEL_OPTION or action == JFileChooser.ERROR_OPTION:
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            types = {}
            with open(file_name, 'r') as selected_file:
                types = json.load(selected_file)
            for key, value in types.items():
                blackboxprotobuf.known_messages[key] = value
            self._type_def_tab.updateList()
    def actionPerformed(self, event):
        """Called when a button is pressed."""
        if event.getActionCommand() == "new-type":
            self._typedef_tab.add_typedef()

        elif event.getActionCommand() == "edit-type":
            self._typedef_tab.edit_typedef()

        elif event.getActionCommand() == "rename-type":
            list_component = self._typedef_tab._type_list_component
            # Check if something is selected
            if list_component.isSelectionEmpty():
                return

            # Get's only the first value
            previous_type_name = list_component.getSelectedValue()
            new_type_name = JOptionPane.showInputDialog(
                "Enter new name for %s:" % previous_type_name)
            if new_type_name in default_config.known_types:
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    'Message type "%s" already exists' % new_type_name,
                )
                return
            if previous_type_name not in default_config.known_types:
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    'Message type "%s" does not exist' % previous_type_name,
                )
                return
            if not NAME_REGEX.match(new_type_name):
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    'Message type name "%s" is not valid.' % new_type_name,
                )
                return
            typedef = default_config.known_types[previous_type_name]
            default_config.known_types[new_type_name] = typedef
            del default_config.known_types[previous_type_name]
            # TODO should manage this centrally somewhere
            self._typedef_tab._extension.refresh_message_model()
            for key, typename in self._typedef_tab._extension.saved_types.items(
            ):
                if typename == previous_type_name:
                    self._typedef_tab._extension.saved_types[
                        key] = new_type_name

        elif event.getActionCommand() == "delete-type":
            list_component = self._typedef_tab._type_list_component
            # Check if something is selected
            if list_component.isSelectionEmpty():
                return

            type_names = list_component.getSelectedValuesList()
            # TODO Confirm delete?
            for type_name in type_names:
                del default_config.known_types[type_name]
            self._typedef_tab._extension.refresh_message_model()

        elif event.getActionCommand() == "save-types":
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("JSON Type Definition", ["json"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showSaveDialog(self._typedef_tab.getUiComponent())
            if (action == JFileChooser.CANCEL_OPTION
                    or action == JFileChooser.ERROR_OPTION):
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            ext = os.path.splitext(file_name)[1]
            if ext == "":
                # No extension, add .json
                file_name += ".json"

            with open(file_name, "w+") as selected_file:
                json.dump(
                    default_config.known_types,
                    selected_file,
                    indent=4,
                    sort_keys=True,
                )

        elif event.getActionCommand() == "load-types":
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("JSON Type Definition", ["json"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showOpenDialog(self._typedef_tab.getUiComponent())
            if (action == JFileChooser.CANCEL_OPTION
                    or action == JFileChooser.ERROR_OPTION):
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            types = {}
            with open(file_name, "r") as selected_file:
                types = json.load(selected_file)
            for key, value in types.items():
                # check to make sure we don't nuke existing messages
                if key in default_config.known_types:
                    overwrite = (JOptionPane.showConfirmDialog(
                        self._typedef_tab._component,
                        "Message %s already saved. Overwrite?" % key,
                    ) == 0)
                    if not overwrite:
                        continue
                default_config.known_types[key] = value
            self._typedef_tab._extension.refresh_message_model()
        elif event.getActionCommand() == "export-proto":
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("Protobuf Type Definition", ["proto"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showSaveDialog(self._typedef_tab.getUiComponent())
            if (action == JFileChooser.CANCEL_OPTION
                    or action == JFileChooser.ERROR_OPTION):
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            ext = os.path.splitext(file_name)[1]
            if ext == "":
                # No extension, add .proto
                file_name += ".proto"

            if os.path.exists(file_name):
                # 0 is the YES option
                overwrite = (JOptionPane.showConfirmDialog(
                    self._typedef_tab._component,
                    "File %s already exists. Overwrite?" % file_name,
                ) == 0)
                if not overwrite:
                    return
                print("overwriting file: %s" % file_name)
            try:
                blackboxprotobuf.export_protofile(default_config.known_types,
                                                  file_name)
            except Exception as exc:
                self._typedef_tab._burp_callbacks.printError(
                    traceback.format_exc())
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    "Error saving .proto file: " + str(exc),
                )

        elif event.getActionCommand() == "import-proto":
            chooser = JFileChooser()
            chooser.setFileFilter(
                FileNameExtensionFilter("Protobuf Type Definition", ["proto"]))
            chooser.setMultiSelectionEnabled(False)

            action = chooser.showOpenDialog(self._typedef_tab.getUiComponent())
            if (action == JFileChooser.CANCEL_OPTION
                    or action == JFileChooser.ERROR_OPTION):
                return

            file_name = chooser.getSelectedFile().getCanonicalPath()
            if not os.path.exists(file_name):
                self._typedef_tab._burp_callbacks.printError(
                    "Attempted to import %s, but the file does not exist." %
                    file_name)
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    "File %s does not exist to import." + str(exc),
                )
                return
            try:
                new_typedefs = blackboxprotobuf.import_protofile(
                    file_name, save_to_known=False)
                for key, value in new_typedefs.items():
                    # check to make sure we don't nuke existing messages
                    if key in default_config.known_types:
                        overwrite = (JOptionPane.showConfirmDialog(
                            self._typedef_tab._component,
                            "Message %s already saved. Overwrite?" % key,
                        ) == 0)
                        if not overwrite:
                            continue
                    else:
                        self._typedef_tab._extension.known_message_model.addElement(
                            key)
                    default_config.known_types[key] = value
            except Exception as exc:
                self._typedef_tab._burp_callbacks.printError(
                    traceback.format_exc())
                JOptionPane.showMessageDialog(
                    self._typedef_tab._component,
                    "Error loading .proto file: " + str(exc),
                )