private CustomVfsUiPanel getPanelFromFileUri(String fileUri) {
   if (customUIPanels != null) {
     for (CustomVfsUiPanel panel : customUIPanels) {
       if (fileUri.startsWith(panel.getVfsScheme())) {
         return panel;
       }
     }
   }
   return null;
 }
 public FileObject resolveFile(String fileUri, FileSystemOptions opts) throws FileSystemException {
   // try to match up a CustomVfsUiPanel with the scheme from the fileUri
   CustomVfsUiPanel panel = getPanelFromFileUri(fileUri);
   if (panel != null) {
     if (opts == null) {
       return panel.resolveFile(fileUri);
     } else {
       return panel.resolveFile(fileUri, opts);
     }
   }
   return null;
 }
  public void populateCustomUIPanel(Shell dialog) {
    ArrayList<String> customNames = new ArrayList<String>();
    for (int i = 0; i < customUIPanels.size(); i++) {
      CustomVfsUiPanel panel = customUIPanels.get(i);
      if (panel.getVfsScheme().equalsIgnoreCase("file")
          || schemeRestrictions == null
          || isRestrictedTo(panel.getVfsScheme())) {
        if (panel.getVfsScheme().equalsIgnoreCase("file") && !showFileScheme) {
          continue;
        }
        customNames.add(panel.getVfsSchemeDisplayText());
      }
    }

    customUIPicker.setItems(customNames.toArray(new String[] {}));
    hideCustomPanelChildren();

    // hide entire panel if no customizations
    if (customNames.size() == 0) {
      customUIPanel.setParent(fakeShell);
    } else {
      if (customNames.size() == 1 && "file".equals(customNames.get(0))) {
        customUIPanel.setParent(fakeShell);
      } else {
        String initialSchemeDisplayText = initialScheme;
        for (int i = 0; i < customUIPanels.size(); i++) {
          if (customUIPanels.get(i).getVfsScheme().equalsIgnoreCase(initialScheme)) {
            initialSchemeDisplayText = customUIPanels.get(i).getVfsSchemeDisplayText();
            break;
          }
        }
        for (int i = 0; i < customUIPicker.getItemCount(); i++) {
          if (customUIPicker.getItem(i).equalsIgnoreCase(initialSchemeDisplayText)) {
            customUIPicker.select(i);
            customUIPicker.notifyListeners(SWT.Selection, null);
          }
        }
      }
    }
  }
 public void resolveVfsBrowser() {
   FileObject newRoot = null;
   try {
     //      newRoot =
     // rootFile.getFileSystem().getFileSystemManager().resolveFile(getSelectedFile().getName().getURI());
     if (currentPanel != null) {
       newRoot = currentPanel.resolveFile(getSelectedFile().getName().getURI());
     }
   } catch (FileSystemException e) {
     displayMessageBox(SWT.OK, Messages.getString("VfsFileChooserDialog.error"), e.getMessage());
   }
   // if (newRoot != null && !newRoot.equals(vfsBrowser.getRootFileObject())) {
   if (newRoot != null) {
     vfsBrowser.resetVfsRoot(newRoot);
   }
 }
 public void promptForNewVfsRoot() {
   boolean done = false;
   String defaultText = vfsBrowser.rootFileObject.getName().getURI();
   String text = defaultText;
   while (!done) {
     if (text == null) {
       text = defaultText;
     }
     File fileRoots[] = File.listRoots();
     String roots[] = new String[fileRoots.length];
     for (int i = 0; i < roots.length; i++) {
       try {
         roots[i] = fileRoots[i].toURI().toURL().toExternalForm();
       } catch (MalformedURLException e) {
         e.printStackTrace();
       }
     }
     ComboBoxInputDialog textDialog =
         new ComboBoxInputDialog(
             Messages.getString("VfsFileChooserDialog.enterNewVFSRoot"),
             text,
             roots,
             650,
             100); //$NON-NLS-1$
     text = textDialog.open();
     if (text != null && !"".equals(text)) { // $NON-NLS-1$
       try {
         vfsBrowser.resetVfsRoot(currentPanel.resolveFile(text));
         done = true;
       } catch (FileSystemException e) {
         MessageBox errorDialog = new MessageBox(vfsBrowser.getDisplay().getActiveShell(), SWT.OK);
         errorDialog.setText(Messages.getString("VfsFileChooserDialog.error")); // $NON-NLS-1$
         errorDialog.setMessage(e.getMessage());
         errorDialog.open();
       }
     } else {
       done = true;
     }
   }
 }
  public void updateParentFileCombo(FileObject selectedItem) {
    try {
      List<FileObject> parentChain = new ArrayList<FileObject>();
      // are we a directory?
      try {
        if (selectedItem.getType() == FileType.FOLDER && selectedItem.getType().hasChildren()) {
          // we have real children....
          parentChain.add(selectedItem);
        }
      } catch (Exception e) {
        // we are not a folder
      }
      FileObject parentFileObject;
      parentFileObject = selectedItem.getParent();
      while (parentFileObject != null) {
        parentChain.add(parentFileObject);
        parentFileObject = parentFileObject.getParent();
      }

      File roots[] = File.listRoots();
      if (currentPanel != null) {
        for (int i = 0; i < roots.length; i++) {
          parentChain.add(currentPanel.resolveFile(roots[i].getAbsolutePath()));
        }
      }

      String items[] = new String[parentChain.size()];
      int idx = 0;
      for (int i = parentChain.size() - 1; i >= 0; i--) {
        items[idx++] = ((FileObject) parentChain.get(i)).getName().getURI();
      }

      openFileCombo.setItems(items);
      openFileCombo.select(items.length - 1);
    } catch (Exception e) {
      e.printStackTrace();
      // then let's not update the GUI
    }
  }
 private void selectCustomUI() {
   hideCustomPanelChildren();
   String desiredScheme = customUIPicker.getText();
   for (CustomVfsUiPanel panel : customUIPanels) {
     if (desiredScheme.equals(panel.getVfsSchemeDisplayText())) {
       panel.setParent(customUIPanel);
       panel.activate();
       currentPanel = panel;
     }
   }
   if (currentPanel == null) {
     currentPanel = customUIPanels.get(0);
     currentPanel.setParent(customUIPanel);
     currentPanel.activate();
   }
   customUIPanel.pack();
   dialog.layout();
 }
  public void widgetSelected(SelectionEvent se) {
    if (se.widget == openFileCombo) {
      // String filePath = parentFoldersCombo.getItem(parentFoldersCombo.getSelectionIndex());
      // vfsBrowser.selectTreeItemByName(filePath, true);

      try {
        // resolve the selected folder (without displaying access/secret keys in plain text)
        //        FileObject newRoot =
        // rootFile.getFileSystem().getFileSystemManager().resolveFile(folderURL.getFolderURL(openFileCombo.getText()));
        FileObject newRoot = currentPanel.resolveFile(getSelectedFile().getName().getURI());
        vfsBrowser.resetVfsRoot(newRoot);
      } catch (FileSystemException e) {
      }

    } else if (se.widget == okButton) {
      okPressed();
    } else if (se.widget == folderUpButton) {
      try {
        FileObject newRoot = vfsBrowser.getSelectedFileObject().getParent();
        if (newRoot != null) {
          vfsBrowser.resetVfsRoot(newRoot);
          vfsBrowser.setSelectedFileObject(newRoot);
          // make sure access/secret keys not displayed in plain text
          //          String str = folderURL.setFolderURL(newRoot.getName().getURI());
          openFileCombo.setText(newRoot.getName().getURI());
        }
      } catch (Exception e) {
        // top of root
      }
    } else if (se.widget == newFolderButton) {
      promptForNewFolder();
    } else if (se.widget == deleteFileButton) {
      MessageBox messageDialog =
          new MessageBox(se.widget.getDisplay().getActiveShell(), SWT.YES | SWT.NO);
      messageDialog.setText(Messages.getString("VfsFileChooserDialog.confirm")); // $NON-NLS-1$
      messageDialog.setMessage(
          Messages.getString("VfsFileChooserDialog.deleteFile")); // $NON-NLS-1$
      int status = messageDialog.open();
      if (status == SWT.YES) {
        try {
          vfsBrowser.deleteSelectedItem();
        } catch (FileSystemException e) {
          MessageBox errorDialog = new MessageBox(se.widget.getDisplay().getActiveShell(), SWT.OK);
          errorDialog.setText(Messages.getString("VfsFileChooserDialog.error")); // $NON-NLS-1$
          errorDialog.setMessage(e.getMessage());
          errorDialog.open();
        }
      }
      // } else if (se.widget == changeRootButton) {
      // promptForNewVfsRoot();
    } else if (se.widget == fileFilterCombo) {

      Runnable r =
          new Runnable() {
            public void run() {
              String filter = fileFilters[fileFilterCombo.getSelectionIndex()];
              vfsBrowser.setFilter(filter);
              try {
                vfsBrowser.applyFilter();
              } catch (FileSystemException e) {
                MessageBox mb = new MessageBox(newFolderButton.getShell(), SWT.OK);
                mb.setText(
                    Messages.getString("VfsFileChooserDialog.errorApplyFilter")); // $NON-NLS-1$
                mb.setMessage(e.getMessage());
                mb.open();
              }
            }
          };
      BusyIndicator.showWhile(fileFilterCombo.getDisplay(), r);
    } else {
      okPressed = false;
      hideCustomPanelChildren();
      dialog.dispose();
    }
  }
  public FileObject open(
      Shell applicationShell,
      String[] schemeRestrictions,
      String initialScheme,
      boolean showFileScheme,
      String fileName,
      String[] fileFilters,
      String[] fileFilterNames,
      boolean returnUserAuthenticatedFile,
      int fileDialogMode,
      boolean showLocation,
      boolean showCustomUI) {

    this.fileDialogMode = fileDialogMode;
    this.fileFilters = fileFilters;
    this.fileFilterNames = fileFilterNames;
    this.applicationShell = applicationShell;
    this.showFileScheme = showFileScheme;
    this.initialScheme = initialScheme;
    this.schemeRestrictions = schemeRestrictions;
    this.showLocation = showLocation;
    this.showCustomUI = showCustomUI;

    FileObject tmpInitialFile = initialFile;

    if (defaultInitialFile != null && rootFile == null) {
      try {
        rootFile = defaultInitialFile.getFileSystem().getRoot();
        initialFile = defaultInitialFile;
      } catch (FileSystemException ignored) {
        // well we tried
      }
    }

    createDialog(applicationShell);

    if (!showLocation) {
      comboPanel.setParent(fakeShell);
    } else {
      comboPanel.setParent(customUIPanel);
    }

    if (!showCustomUI) {
      customUIPanel.setParent(fakeShell);
    } else {
      customUIPanel.setParent(dialog);
    }

    // create our file chooser tool bar, contains parent folder combo and various controls
    createToolbarPanel(dialog);
    // create our vfs browser component
    createVfsBrowser(dialog);
    populateCustomUIPanel(dialog);
    if (fileDialogMode == VFS_DIALOG_SAVEAS) {
      createFileNamePanel(dialog, fileName);
    } else {
      // create file filter panel
      createFileFilterPanel(dialog);
    }
    // create our ok/cancel buttons
    createButtonPanel(dialog);

    initialFile = tmpInitialFile;
    // set the initial file selection
    try {
      if (initialFile != null || rootFile != null) {
        vfsBrowser.selectTreeItemByFileObject(initialFile != null ? initialFile : rootFile, true);
        updateParentFileCombo(initialFile != null ? initialFile : rootFile);
        setSelectedFile(initialFile != null ? initialFile : rootFile);
        openFileCombo.setText(
            initialFile != null ? initialFile.getName().getURI() : rootFile.getName().getURI());
      }
    } catch (FileSystemException e) {
      MessageBox box = new MessageBox(dialog.getShell());
      box.setText(Messages.getString("VfsFileChooserDialog.error")); // $NON-NLS-1$
      box.setMessage(e.getMessage());
      box.open();
    }

    // set the size and show the dialog
    int height = 550;
    int width = 800;
    dialog.setSize(width, height);
    Rectangle bounds = dialog.getDisplay().getPrimaryMonitor().getClientArea();
    int x = (bounds.width - width) / 2;
    int y = (bounds.height - height) / 2;
    dialog.setLocation(x, y);
    dialog.open();

    if (rootFile != null && fileDialogMode == VFS_DIALOG_SAVEAS) {
      if (!rootFile.getFileSystem().hasCapability(Capability.WRITE_CONTENT)) {
        MessageBox messageDialog = new MessageBox(dialog.getShell(), SWT.OK);
        messageDialog.setText(Messages.getString("VfsFileChooserDialog.warning")); // $NON-NLS-1$
        messageDialog.setMessage(
            Messages.getString("VfsFileChooserDialog.noWriteSupport")); // $NON-NLS-1$
        messageDialog.open();
      }
    }

    vfsBrowser.fileSystemTree.forceFocus();
    while (!dialog.isDisposed()) {
      if (!dialog.getDisplay().readAndDispatch()) dialog.getDisplay().sleep();
    }

    // we just woke up, we are probably disposed already..
    if (!dialog.isDisposed()) {
      hideCustomPanelChildren();
      dialog.dispose();
    }
    if (okPressed) {
      FileObject returnFile = vfsBrowser.getSelectedFileObject();
      if (returnFile != null && fileDialogMode == VFS_DIALOG_SAVEAS) {
        try {
          if (returnFile.getType().equals(FileType.FILE)) {
            returnFile = returnFile.getParent();
          }
          returnFile = returnFile.resolveFile(enteredFileName);
        } catch (FileSystemException e) {
          e.printStackTrace();
        }
      }

      // put user/pass on the filename so it comes out in the getUri call.
      if (!returnUserAuthenticatedFile) {
        // make sure to put the user/pass on the url if it's not there
        if (returnFile != null && returnFile.getName() instanceof URLFileName) {
          URLFileName urlFileName = (URLFileName) returnFile.getName();
          if (urlFileName.getUserName() == null || urlFileName.getPassword() == null) {
            // set it
            String user = "";
            String pass = "";

            UserAuthenticator userAuthenticator =
                DefaultFileSystemConfigBuilder.getInstance()
                    .getUserAuthenticator(returnFile.getFileSystem().getFileSystemOptions());

            if (userAuthenticator != null) {
              UserAuthenticationData data =
                  userAuthenticator.requestAuthentication(AUTHENTICATOR_TYPES);
              user = String.valueOf(data.getData(UserAuthenticationData.USERNAME));
              pass = String.valueOf(data.getData(UserAuthenticationData.PASSWORD));
              try {
                user = URLEncoder.encode(user, "UTF-8");
                pass = URLEncoder.encode(pass, "UTF-8");
              } catch (UnsupportedEncodingException e) {
                // ignore, just use the un encoded values
              }
            }

            // build up the url with user/pass on it
            int port = urlFileName.getPort();
            String portString = (port < 1) ? "" : (":" + port);
            String urlWithUserPass =
                urlFileName.getScheme()
                    + "://"
                    + user
                    + ":"
                    + pass
                    + "@"
                    + urlFileName.getHostName()
                    + portString
                    + urlFileName.getPath();

            try {
              returnFile = currentPanel.resolveFile(urlWithUserPass);
            } catch (FileSystemException e) {
              // couldn't resolve with user/pass on url??? interesting
              e.printStackTrace();
            }
          }
        }
      }
      return returnFile;
    } else {
      return null;
    }
  }
  public void createCustomUIPanel(final Shell dialog) {
    customUIPanel = new Composite(dialog, SWT.NONE);
    GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, false);
    customUIPanel.setLayoutData(gridData);
    customUIPanel.setLayout(new GridLayout(1, false));

    comboPanel = new Composite(customUIPanel, SWT.NONE);
    comboPanel.setLayoutData(gridData);
    comboPanel.setLayout(new GridLayout(2, false));
    comboPanel.setData("donotremove");

    Label lookInLabel = new Label(comboPanel, SWT.NONE);
    lookInLabel.setText(Messages.getString("VfsFileChooserDialog.LookIn"));
    gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false);
    lookInLabel.setLayoutData(gridData);

    customUIPicker = new Combo(comboPanel, SWT.READ_ONLY);
    gridData = new GridData(SWT.LEFT, SWT.CENTER, true, false);
    customUIPicker.setLayoutData(gridData);

    if (!showLocation) {
      comboPanel.setParent(fakeShell);
    }

    if (!showCustomUI) {
      customUIPanel.setParent(fakeShell);
    }

    customUIPicker.addSelectionListener(
        new SelectionListener() {

          public void widgetSelected(SelectionEvent event) {
            selectCustomUI();
          }

          public void widgetDefaultSelected(SelectionEvent event) {
            selectCustomUI();
          }
        });
    customUIPicker.addKeyListener(
        new KeyListener() {

          public void keyReleased(KeyEvent arg0) {
            selectCustomUI();
          }

          public void keyPressed(KeyEvent arg0) {
            selectCustomUI();
          }
        });

    boolean createdLocal = false;
    for (CustomVfsUiPanel panel : customUIPanels) {
      if (panel.getVfsScheme().equals("file")) {
        createdLocal = true;
      }
    }

    if (!createdLocal) {
      CustomVfsUiPanel localPanel =
          new CustomVfsUiPanel("file", "Local", this, SWT.None) {
            public void activate() {
              try {
                File startFile = new File(System.getProperty("user.home"));
                if (startFile == null || !startFile.exists()) {
                  startFile = File.listRoots()[0];
                }
                FileObject dot = fsm.resolveFile(startFile.toURI().toURL().toExternalForm());
                rootFile = dot.getFileSystem().getRoot();
                selectedFile = rootFile;
                setInitialFile(selectedFile);
                openFileCombo.setText(selectedFile.getName().getURI());
                resolveVfsBrowser();
              } catch (Throwable t) {
              }
            }
          };
      addVFSUIPanel(localPanel);
    }
  }