Exemple #1
0
def chooseFile():
    global frame, dataPath
    global systemPanel, chartPanel
    global isTemporal
    fc = JFileChooser(dataPath)
    retVal = fc.showOpenDialog(frame)
    if retVal != JFileChooser.APPROVE_OPTION:
        return
    fname = fc.getSelectedFile().getAbsolutePath()
    dataPath = os.sep.join(fname.split(os.sep)[:-1])
    if isTemporal:
        info(frame, "We need a file with information about the temporal point of each sample")
        tfc = JFileChooser(dataPath)
        tRetVal = tfc.showOpenDialog(frame)
        if retVal != JFileChooser.APPROVE_OPTION:
            return
        tname = tfc.getSelectedFile().getAbsolutePath()
    systemPanel.enableChartFun = False
    chartPanel.resetData()
    loadGenePop(fname)
    if isTemporal:
        if not loadTemporal(tname):
            return
    updateAll()
    enablePanel(empiricalPanel)
Exemple #2
0
def check_directory(path):

    if (os.path.lexists(path)):
        contents = os.listdir(path)

        if (contents.count("install-birch") == 0):
            print_console("The selected directory " + path +
                          " does NOT contain a BIRCH installation!")
            message = "The selected path does NOT contain a BIRCH installation.\nPlease select the base directory of the installation that you wish to update,\nOr click \"no\" to cancel update."
            reload = JOptionPane.showConfirmDialog(None, message, "Input",
                                                   JOptionPane.YES_NO_OPTION)

            if (reload == JOptionPane.NO_OPTION):
                print_console("User aborted install.")
                commonlib.shutdown()

            fc = JFileChooser()
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
            fc.showOpenDialog(None)
            path = fc.getSelectedFile().getPath()

            check_directory(path)

        else:
            ARGS.install_dir = path
            print_console("The selected directory " + path +
                          " contains a BIRCH installation, it will be updated")
Exemple #3
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;
Exemple #4
0
    def actionPerformed(self, event):
        """Delete the last row"""

        # Generate a save dialog
        dialog = JFileChooser(Prefs.get("roiGroup.importDir", ""))
        dialog.setSelectedFile(File("roiGroups.txt"))
        dialog.setFileFilter(FileNameExtensionFilter("Text file", ["txt"]))
        output = dialog.showOpenDialog(
            self.groupTable)  # could be None argument too

        if output in [JFileChooser.CANCEL_OPTION, JFileChooser.ERROR_OPTION]:
            return
        selectedFile = dialog.getSelectedFile()
        directory = selectedFile.getParent()
        Prefs.set("roiGroup.importDir", directory)
        if not selectedFile.isFile(): return
        filePath = selectedFile.getPath()

        # Read comma-separated group from file
        with open(filePath, "r") as textFile:
            stringGroup = textFile.readline().rstrip()

        # Update table with content of file
        tableModel = self.groupTable.tableModel
        tableModel.setGroupColumn(stringGroup)
Exemple #5
0
 def openFile(self, fileext, filedesc, fileparm):
     myFilePath = ''
     chooseFile = JFileChooser()
     myFilter = FileNameExtensionFilter(filedesc, [fileext])
     chooseFile.setFileFilter(myFilter)
     ret = chooseFile.showOpenDialog(self.tab)
     if ret == JFileChooser.APPROVE_OPTION:
         file = chooseFile.getSelectedFile()
         myFilePath = str(file.getCanonicalPath()).lower()
         if not myFilePath.endswith(fileext):
             myFilePath += '.' + fileext
         okWrite = JOptionPane.YES_OPTION
         if os.path.isfile(myFilePath):
             okWrite = JOptionPane.showConfirmDialog(
                 self.tab, 'File already exists. Ok to over-write?', '',
                 JOptionPane.YES_NO_OPTION)
             if okWrite == JOptionPane.NO_OPTION:
                 return
         j = True
         while j:
             try:
                 f = open(myFilePath, mode=fileparm)
                 j = False
             except IOError:
                 okWrite = JOptionPane.showConfirmDialog(
                     self.tab, 'File cannot be opened. Correct and retry?',
                     '', JOptionPane.YES_NO_OPTION)
                 if okWrite == JOptionPane.NO_OPTION:
                     return None, False
         return f, True
Exemple #6
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)
Exemple #7
0
def openFolderDialog(dialogTitle):
    from javax.swing import JFileChooser
    chooser = JFileChooser()
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
    chooser.setDialogTitle(dialogTitle)
    if chooser.showOpenDialog(None) == JFileChooser.APPROVE_OPTION:
        return str(chooser.getSelectedFile())
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
Exemple #9
0
    def actionPerformed(self, e):
        file_chooser = JFileChooser()
        is_load_file = str(e.getActionCommand()) == "load"
        is_save_file = str(e.getActionCommand()) == "save"

        if is_load_file:
            file_chooser.setDialogTitle("Load JSON File")
            file_chooser.setDialogType(JFileChooser.OPEN_DIALOG)
            open_dialog = file_chooser.showOpenDialog(self.file_button)
            is_approve = open_dialog == JFileChooser.APPROVE_OPTION

            if is_approve:
                load_file = file_chooser.getSelectedFile()
                file_name = str(load_file)
                self.load_data(file_name)
            else:
                print("JSON file load cancelled")

        if is_save_file:
            file_chooser.setDialogTitle("Save JSON File")
            file_chooser.setDialogType(JFileChooser.SAVE_DIALOG)
            save_dialog = file_chooser.showSaveDialog(self.file_button)
            is_approve = save_dialog == JFileChooser.APPROVE_OPTION

            if is_approve:
                save_file = str(file_chooser.getSelectedFile())
                self.save_data(save_file)
            else:
                print("JSON file save cancelled")
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"
Exemple #11
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
Exemple #12
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
Exemple #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')
Exemple #14
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 )
Exemple #15
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())
Exemple #16
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)
 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
Exemple #18
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(".")]))
Exemple #19
0
 def readFromTheFile(self,event):
     choseFile = JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
     choseFile.setDialogTitle('Select The File Which Will Be Pasted')
     choseFile.setFileSelectionMode(JFileChooser.FILES_ONLY)
     returnValue = choseFile.showOpenDialog(None);
     if(returnValue == JFileChooser.APPROVE_OPTION):
         selectedFile = choseFile.getSelectedFile()
         file=open(selectedFile.getAbsolutePath(),"r")
         editedRequest = self._request[:self._position[0]]+str(file.read())+self._request[self._position[1]:]
         self._message[0].setRequest(self._helpers.bytesToString(editedRequest))
Exemple #20
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)
Exemple #21
0
    def fileButtonClick(self, callbacks):
        fileTypeList = ["csv", "txt", "json"]
        txtFilter = FileNameExtensionFilter("txt", fileTypeList)
        fileChooser = JFileChooser()
        fileChooser.addChoosableFileFilter(txtFilter)
        result = fileChooser.showOpenDialog(self._splitpane)

        if result == JFileChooser.APPROVE_OPTION:
            f = fileChooser.getSelectedFile()
            fileName = f.getPath()
            self.populateTableModel(f)
Exemple #22
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
Exemple #23
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)
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
 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.")
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.")
Exemple #27
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
Exemple #28
0
 def actionPerformed(self, actionEvent):
     chooser = JFileChooser()
     #chooser.setCurrentDirectory(".")
     chooser.setDialogTitle("Choose file")
     chooser.setFileSelectionMode(JFileChooser.FILES_ONLY)
     chooser.setAcceptAllFileFilterUsed(False)
     if chooser.showOpenDialog(self) == JFileChooser.APPROVE_OPTION:
         print chooser.getCurrentDirectory()
         print chooser.getSelectedFile()
         self.field.setText(str(chooser.getSelectedFile()))
     else:
         print "No file selected"
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)
 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 )
Exemple #31
0
    def fileButtonClick(self, e):

        fileTypeList = ["war", "ear", "zip"]
        warFilter = FileNameExtensionFilter("war", fileTypeList)
        fileChooser = JFileChooser()
        fileChooser.addChoosableFileFilter(warFilter)
        result = fileChooser.showOpenDialog(self._splitpane)

        if result == JFileChooser.APPROVE_OPTION:
            f = fileChooser.getSelectedFile()
            fileName = f.getPath()
            self.populateJTable(f)
Exemple #32
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.")
Exemple #33
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()
Exemple #34
0
    def _filepicker(self):
        """
        Run the filepicker and return if approved

        :return: boolean, true if approved
        """
        fileChooser = JFileChooser()
        fileChooser.setCurrentDirectory(File(System.getProperty("user.home")))
        result = fileChooser.showOpenDialog(self.this)
        isApproveOption = result == JFileChooser.APPROVE_OPTION
        if isApproveOption:
            selectedFile = fileChooser.getSelectedFile()
            self._omnibar.setText(selectedFile.getAbsolutePath())
        return isApproveOption
Exemple #35
0
 def loadPayloadButtonAction(self, event):
     fileChooser = JFileChooser()
     fileChooser.dialogTitle = 'Choose Payload List'
     fileChooser.fileSelectionMode = JFileChooser.FILES_ONLY
     if (fileChooser.showOpenDialog(
             self.mainPanel) == JFileChooser.APPROVE_OPTION):
         file = fileChooser.getSelectedFile()
         with open(file.getAbsolutePath(), 'r') as reader:
             for line in reader.readlines():
                 self.extender.PayloadList.append(line.strip('\n'))
         self.listPayloads.setListData(self.extender.PayloadList)
         self.showMessage('{} payloads loaded'.format(
             len(self.extender.PayloadList)))
         self.writePayloadsListFile()
 def showFC(self, event):
     Type = 'Open,Save,Custom'.split(',')
     Answer = 'Error,Approve,Cancel'.split(',')
     fc = JFileChooser()
     fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
     result = fc.showOpenDialog(None)
     if result == JFileChooser.APPROVE_OPTION:
         message = 'result = "%s"' % fc.getSelectedFile()
         self.directory = fc.getSelectedFile()
         print(self.directory)
         print(type(self.directory))
     else:
         message = 'Request canceled by user'
     self.label.setText(message)
Exemple #37
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)
Exemple #38
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())
Exemple #39
0
def check_directory(path):

	if (os.path.lexists(path)):
		contents=os.listdir(path)
		
		if (contents.count("install-birch")==0):
			print_console("The selected directory "+path+" does NOT contain a BIRCH installation!")
			message="The selected path does NOT contain a BIRCH installation.\nPlease select the base directory of the installation that you wish to update,\nOr click \"no\" to cancel update."
			reload = JOptionPane.showConfirmDialog(None,message, "Input",JOptionPane.YES_NO_OPTION);
		
			if (reload==JOptionPane.NO_OPTION):
				print_console("User aborted install.")
				commonlib.shutdown()
			
			fc = JFileChooser();
			fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			fc.showOpenDialog(None);
			path = fc.getSelectedFile().getPath();
			
			check_directory(path)
			
		else:
			ARGS.install_dir=path
			print_console("The selected directory "+path+" contains a BIRCH installation, it will be updated")
def openGVL():
    from javax.swing import JFileChooser
    GUIUtil=PluginServices.getPluginServices("com.iver.cit.gvsig.cad").getClassLoader().loadClass("com.iver.cit.gvsig.gui.GUIUtil")
    chooser = JFileChooser()
    chooser.setFileFilter(GUIUtil().createFileFilter("GVL Legend File",["gvl"]))
    from java.util.prefs import Preferences
    lastPath = Preferences.userRoot().node("gvsig.foldering").get("DataFolder", "null")
    chooser.setCurrentDirectory(File(lastPath))
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY)
    returnVal = chooser.showOpenDialog(None)
    if returnVal == chooser.APPROVE_OPTION:
        gvlPath = chooser.getSelectedFile().getPath()
    elif returnVal == chooser.CANCEL_OPTION:
        JOptionPane.showMessageDialog(None, "You have to open a .gvl file. Retry!","Batch Legend",JOptionPane.WARNING_MESSAGE)
        gvlPath = ""
    return gvlPath
Exemple #41
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()
Exemple #42
0
    def generate_board(self, event):

        chooser = JFileChooser()
        status = chooser.showOpenDialog(self.frame)
        if status != JFileChooser.APPROVE_OPTION:
            return

        imageFile = chooser.getSelectedFile()

        self.puzzle = SimplePyzzle(float(int(self.combo_box.getSelectedItem())))
        self.draw_board()
        self.load_images(imageFile, self.puzzle.level())
        self.canvas.set_puzzle(self.puzzle)
        width = self.images_dict[0].getWidth()
        height = self.images_dict[0].getHeight()
        size = Dimension(width * self.puzzle.level(), height * self.puzzle.level())
        self.frame.setPreferredSize(size)
        self.frame.setSize(size)
Exemple #43
0
    def saveas(self, e):
        c = None
        if "lastdir" in self.settings.keys():
            c = JFileChooser(self.settings["lastdir"])
        else:
            c = JFileChooser()

        r = c.showOpenDialog(self.frame)

        if r == JFileChooser.APPROVE_OPTION:
            f = c.getSelectedFile()
            self.f = f
            s = f.getAbsolutePath()

            self.settings["lastdir"] = f.getParent()
            self.settings.save()

            o = FileOutputStream(s)
            self.text.setoutput(o)
Exemple #44
0
    def opencopy(self, e):
        c = None
        if "lastcopy" in self.settings.keys():
            c = JFileChooser(self.settings["lastcopy"])
        else:
            c = JFileChooser()

        r = c.showOpenDialog(self.frame)

        if r == JFileChooser.APPROVE_OPTION:
            f = c.getSelectedFile()
            self.f = f
            s = f.getAbsolutePath()

            self.settings["lastcopy"] = f.getParent()
            self.settings.save()

            #            i = FileInputStream(s)
            self.text.setcopy(s)
Exemple #45
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
Exemple #46
0
   def onClick(self, e):

       print outputTextField.getText()
       chooseFile = JFileChooser()
       filter = ExampleFileFilter()
       filter.addExtension("txt")
       filter.setDescription("txt HL7 input files")
       chooseFile.setFileFilter(filter)
       

       ##ret = chooseFile.showDialog(self.panel, "Choose file")
       ret = chooseFile.showOpenDialog(self.panel)

       if ret == JFileChooser.APPROVE_OPTION:
           file = chooseFile.getSelectedFile()
           text = self.readFile(file)
           self.area.append(text)
           outputFile = outputTextField.getText()
           p1 = HL7RepClass.ParseORUClass(file.getCanonicalPath(), outputFile)
           p1.parseORU()
           print "\noutfile = ", outputFile
Exemple #47
0
    def opendialog(self, e):
        c = None
        if "lastdir" in self.settings.keys():
            c = JFileChooser(self.settings["lastdir"])
        else:
            c = JFileChooser()

        r = c.showOpenDialog(self.frame)

        if r == JFileChooser.APPROVE_OPTION:
            f = c.getSelectedFile()
            self.f = f
            s = f.getAbsolutePath()

            self.settings["lastdir"] = f.getParent()
            self.settings.save()

            i = FileInputStream(s)
            self.text.setinput(i)
            self.frame.pack()
            self.frame.setSize(800, 500)
Exemple #48
0
 def go(self, fileTypes=None, default=None, directoryAllowed=False):
     fileChooser = JFileChooser()
     if self.title:
         fileChooser.setDialogTitle(self.title)
     if default:
         fileChooser.setSelectedFile(java.io.File(default))
     fileChooser.setCurrentDirectory(java.io.File("."))
     if fileTypes:
         for extension, description in fileTypes:
            fileChooser.addChoosableFileFilter(FileFilterForExtension(extension, description))            
     if self.loadOrSave == "load":
         result = fileChooser.showOpenDialog(self.parent)
     else:
         result = fileChooser.showSaveDialog(self.parent)
     if (result == JFileChooser.APPROVE_OPTION):
         fileResult = None
         fileAndMaybeDir = fileChooser.getSelectedFile().getAbsoluteFile()
         if directoryAllowed or not fileAndMaybeDir.isDirectory():
             fileResult = str(fileAndMaybeDir)
         return fileResult
     else:
         return None
Exemple #49
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.")
 def loadConfigClicked(self, ev):
     openFile = JFileChooser();
     openFile.showOpenDialog(None);
     self._configFile = openFile.getSelectedFile()
Exemple #51
0
 def actionPerformed(self, event):
   fileChooser = JFileChooser()
   fileChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
   if fileChooser.showOpenDialog(None) == JFileChooser.APPROVE_OPTION:
     self.field.text = fileChooser.selectedFile.absolutePath
def FileChooser(JFrame):
    chooseFile = JFileChooser()
    chooseFile.showOpenDialog(JFrame)
    return chooseFile.selectedFile
 def choose_file(self, event):
     chooseFile = JFileChooser()
     chooseFile.showOpenDialog(None)
     chosenFile = chooseFile.getSelectedFile()
     return str(chosenFile)
def FolderChooser(JFrame):
    chooseFolder = JFileChooser()
    chooseFolder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
    chooseFolder.showOpenDialog(JFrame)
    return chooseFolder.selectedFile
class JythonGui(object):
    def __init__(self, instructionsURI=""):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger("sasi_gridder_gui")
        self.logger.addHandler(logging.StreamHandler())

        def log_fn(msg):
            self.log_msg(msg)

        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame("SASI Gridder", defaultCloseOperation=WindowConstants.EXIT_ON_CLOSE)
        self.frame.size = (650, 600)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1

        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">' "<U>open instructions</U></FONT><HTML>"),
            actionPerformed=self.browseInstructions,
        )
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT)
        instructionsButton.setBorderPainted(False)
        instructionsButton.setOpaque(False)
        instructionsButton.setBackground(Color.WHITE)
        instructionsButton.setToolTipText(self.instructionsURI)
        self.top_panel.add(instructionsButton)

        # Select input elements.
        self.top_panel.add(getStageLabel("Select an input data folder:"))
        self.top_panel.add(JButton("Select input...", actionPerformed=self.openInputChooser))

        # Select output elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # Run elements.
        self.top_panel.add(getStageLabel("Run SASI Gridder: (this might take a hwile"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASIGridder)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10, 10, 10, 10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
        self.outputChooser = JFileChooser()
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY
        defaultOutputFile = os.path.join(System.getProperty("user.home"), "gridded_efforts.csv")
        self.outputChooser.setSelectedFile(File(defaultOutputFile))

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True

    def browseInstructions(self, event):
        """ Open a browser to the instructions page. """
        browseURI(self.instructionsURI)
        return

    def log_msg(self, msg):
        self.log.append(msg + "\n")
        self.log.setCaretPosition(self.log.getDocument().getLength())

    def openInputChooser(self, event):
        ret = self.inputChooser.showOpenDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_input_file = self.inputChooser.selectedFile
            self.log_msg("Selected '%s' as input." % self.selected_input_file.path)

    def openOutputChooser(self, event):
        ret = self.outputChooser.showSaveDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_output_file = self.outputChooser.selectedFile
            self.log_msg("Selected '%s' as output." % self.selected_output_file.path)

    def runSASIGridder(self, event):
        try:
            self.validateParameters()
        except Exception as e:
            self.log_msg("ERROR: '%s'" % e)

        # Run task in a separate thread, so that log
        # messages will be shown as task progresses.
        def run_task():

            self.progressBar.setValue(0)
            self.progressBar.setIndeterminate(True)

            try:
                input_dir = self.selected_input_file.path
                output_path = self.selected_output_file.path

                grid_path = os.path.join(input_dir, "grid", "grid.shp")

                stat_areas_path = os.path.join(input_dir, "stat_areas", "stat_areas.shp")

                raw_efforts_path = os.path.join(input_dir, "raw_efforts.csv")

                gear_mappings_path = os.path.join(input_dir, "gear_mappings.csv")

                gear_mappings = {}
                with open(gear_mappings_path, "rb") as f:
                    r = csv.DictReader(f)
                    for mapping in r:
                        gear_mappings[mapping["trip_type"]] = mapping["gear_code"]

                task = SASIGridderTask(
                    grid_path=grid_path,
                    raw_efforts_path=raw_efforts_path,
                    stat_areas_path=stat_areas_path,
                    output_path=output_path,
                    logger=self.logger,
                    gear_mappings=gear_mappings,
                    effort_limit=None,
                )
                task.call()
            except Exception as e:
                self.logger.exception("Could not complete task")

            self.progressBar.setIndeterminate(False)
            self.progressBar.setValue(100)

        Thread(target=run_task).start()

    def validateParameters(self):
        return True
class JythonGui(ItemListener):
    def __init__(self, instructionsURI=''):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger('sasi_runner_gui')
        self.logger.addHandler(logging.StreamHandler())
        def log_fn(msg):
            self.log_msg(msg)
        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame(
            "SASI Runner",
            defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE,
        )
        self.frame.size = (650, 600,)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1
        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">'
             '<U>open instructions</U></FONT><HTML>'),
            actionPerformed=self.browseInstructions)
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT);
        instructionsButton.setBorderPainted(False);
        instructionsButton.setOpaque(False);
        instructionsButton.setBackground(Color.WHITE);
        instructionsButton.setToolTipText(self.instructionsURI);
        self.top_panel.add(instructionsButton)

        # 'Select input' elements.
        self.top_panel.add(getStageLabel(
            "Select a SASI .zip file or data folder:"))
        self.top_panel.add(
            JButton("Select input...", actionPerformed=self.openInputChooser))

        # 'Select output' elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(
            JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # 'Set result fields' elements.
        result_fields = [
            {'id': 'gear_id', 'label': 'Gear', 'selected': True, 
             'enabled': False}, 
            {'id': 'substrate_id', 'label': 'Substrate', 'selected': True}, 
            {'id': 'energy_id', 'label': 'Energy', 'selected': False},
            {'id': 'feature_id', 'label': 'Feature', 'selected': False}, 
            {'id': 'feature_category_id', 'label': 'Feature Category', 
             'selected': False}
        ]
        self.selected_result_fields = {}
        resolutionLabelPanel = JPanel(GridLayout(0,1))
        resolutionLabelPanel.add(getStageLabel("Set result resolution:"))
        resolutionLabelPanel.add(
            JLabel(("<html><i>This sets the specificity with which<br>"
                    "results will be grouped. Note that enabling<br>"
                    "more fields can *greatly* increase resulting<br>"
                    "output sizes and run times.</i>")))
        #self.top_panel.add(getStageLabel("Set result resolution:"))
        self.top_panel.add(resolutionLabelPanel)
        checkPanel = JPanel(GridLayout(0, 1))
        self.top_panel.add(checkPanel) 
        self.resultFieldCheckBoxes = {}
        for result_field in result_fields:
            self.selected_result_fields.setdefault(
                result_field['id'], result_field['selected'])
            checkBox = JCheckBox(
                result_field['label'], result_field['selected'])
            checkBox.setEnabled(result_field.get('enabled', True))
            checkBox.addItemListener(self)
            checkPanel.add(checkBox)
            self.resultFieldCheckBoxes[checkBox] = result_field

        # 'Run' elements.
        self.top_panel.add(getStageLabel("Run SASI: (this might take a while)"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASI)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(
            self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10,10,10,10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.logScrollBar = self.logScrollPane.getVerticalScrollBar()
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES

        self.outputChooser = JFileChooser()
        defaultOutputFile = os.path.join(System.getProperty("user.home"),
                                         "sasi_project.zip")

        self.outputChooser.setSelectedFile(File(defaultOutputFile));
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True

    def browseInstructions(self, event):
        """ Open a browser to the instructions page. """
        browseURI(self.instructionsURI)

    def itemStateChanged(self, event):
        """ Listen for checkbox changes. """
        checkBox = event.getItemSelectable()
        is_selected = (event.getStateChange() == ItemEvent.SELECTED)
        result_field = self.resultFieldCheckBoxes[checkBox]
        self.selected_result_fields[result_field['id']] = is_selected

    def log_msg(self, msg):
        """ Print message to log and scroll to bottom. """
        self.log.append(msg + "\n")
        self.log.setCaretPosition(self.log.getDocument().getLength())

    def openInputChooser(self, event):
        ret = self.inputChooser.showOpenDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_input_file = self.inputChooser.selectedFile
            self.log_msg("Selected '%s' as input." % self.selected_input_file.path)

    def openOutputChooser(self, event):
        ret = self.outputChooser.showSaveDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            selectedPath = self.outputChooser.selectedFile.path
            if not selectedPath.endswith('.zip'):
                zipPath = selectedPath + '.zip'
                self.outputChooser.setSelectedFile(File(zipPath))
            self.selected_output_file = self.outputChooser.selectedFile
            self.log_msg(
                "Selected '%s' as output." % self.selected_output_file.path)

    def runSASI(self, event):
        try:
            self.validateParameters()
        except Exception as e:
            self.log_msg("ERROR: '%s'" % e)

        # Run task in a separate thread, so that log
        # messages will be shown as task progresses.
        def run_task():
            self.tmp_dir = tempfile.mkdtemp(prefix="sasi_runner.")
            self.db_file = os.path.join(self.tmp_dir, "sasi_runner.db")

            self.progressBar.setValue(0)
            self.progressBar.setIndeterminate(True)

            def get_connection():
                engine = create_engine('h2+zxjdbc:////%s' % self.db_file)
                con = engine.connect()
                return con

            try:
                # Set result fields.
                result_fields = []
                for field_id, is_selected in self.selected_result_fields.items():
                    if is_selected: result_fields.append(field_id)

                task = RunSasiTask(
                    input_path=self.selected_input_file.path,
                    output_file=self.selected_output_file.path,
                    logger=self.logger,
                    get_connection=get_connection,
                    config={
                        'result_fields': result_fields,
                        'run_model': {
                            'run': {
                                'batch_size': 'auto',
                            }
                        },
                        'output': {
                            'batch_size': 'auto',
                        },
                    }
                )
                task.call()
            except Exception as e:
                self.logger.exception("Could not complete task")

            self.progressBar.setIndeterminate(False)
            self.progressBar.setValue(100)

            try:
                shutil.rmtree(self.tmp_dir)
            except:
                pass

        Thread(target=run_task).start()

    def validateParameters(self):
        return True
Exemple #57
0
import jmri
import java
import com.csvreader
from javax.swing import JFileChooser, JOptionPane
from javax.swing.filechooser import FileNameExtensionFilter

dialogTitle = "Class Keys Report"
print "   {}".format(dialogTitle)
keyList = []

# Select a Java program or package directory to be analyzed.
fc = JFileChooser(FileUtil.getProgramPath())
fc.setDialogTitle(dialogTitle)
fc.setFileFilter(FileNameExtensionFilter("Java Program", ["java"]));
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES)
ret = fc.showOpenDialog(None)
if ret == JFileChooser.APPROVE_OPTION:
    selectedItem = fc.getSelectedFile().toString()
else:
    print 'No file selected, bye'
    quit()

# RegEx patterns.  Capture the first word after the start of the match string.
# The first one looks for a word within double quotes.
# The second one looks for a plain word.
# A word contains a-z, A-Z, 0-9 or underscore characters.
reStrKey = re.compile('\W*"(\w+)"\W*[,)]')
reVarKey = re.compile('\W*(\w+)\W')

##
# Determine class for a variable key.
from javax.swing import JFileChooser, JOptionPane,
chooser = JFileChooser()
option = chooser.showOpenDialog(getMainFrame())
if option == JFileChooser.APPROVE_OPTION:
    file = chooser.getSelectedFile()
    if not file.isDirectory():
        file = file.getParentFile()
    folderName = file.getName()
    #need to sort out get movie name by its folder name
    #movieName = folderName.replace('.', '')
    if movieName != None:
        movieNames = searchMovieByName(movieName)
        if movieNames == 0:
            return
        movieName = movieNames[0]
        if movieNames.length() > 1:
            comboBox = JComboBox(movieNames)
            option = JOptionPane.showOptionDialog(frame, comboBox, "Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
            if option == JOptionPane.OK_OPTION:
                movieName = comboBox.getSelectedItem()
        addMovie(movieName);