/*
Need to add and remove an event listener to catch activation state
Using FileOpenPicker will suspend the app and it's required to catch the PickSingleFileAndContinue
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx
180747
function(eventArgs) {
        if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickFileContinuation) {
            var file = eventArgs.files[0];
            if (!file) {
                errorCallback("User didn't choose a file.");
                webUIApp.removeEventListener("activated", filePickerActivationHandler);
                return;
            }
            if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) {
                if (targetHeight > 0 && targetWidth > 0) {
                    resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType);
                }
                else {
                    var storageFolder = getAppData().localFolder;
                    file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) {
                        if(destinationType == Camera.DestinationType.NATIVE_URI) {
                            successCallback("ms-appdata:///local/" + storageFile.name);
                        }
                        else {
                            successCallback(URL.createObjectURL(storageFile));
                        }
                    }, function () {
                        errorCallback("Can't access localStorage folder.");
                    });
                }
            }
            else {
                if (targetHeight > 0 && targetWidth > 0) {
                    resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight);
                } else {
                    fileIO.readBufferAsync(file).done(function (buffer) {
                        var strBase64 =encodeToBase64String(buffer);
                        successCallback(strBase64);
                    }, errorCallback);
                }
            }
            webUIApp.removeEventListener("activated", filePickerActivationHandler);
        }
    }
389384
function _handleDeleteFilter(e) {
        // Remove the filter set from the preferences and
        // clear the active filter set index from view state.
        var filterSets        = PreferencesManager.get("fileFilters") || [],
            activeFilterIndex = PreferencesManager.getViewState("activeFileFilter"),
            filterIndex       = $(e.target).parent().data("index") - FIRST_FILTER_INDEX;

        // Don't let the click bubble upward.
        e.stopPropagation();

        filterSets.splice(filterIndex, 1);
        PreferencesManager.set("fileFilters", filterSets);

        if (activeFilterIndex === filterIndex) {
            // Removing the active filter, so clear the active filter
            // both in the view state.
            setActiveFilter(null);
        } else if (activeFilterIndex > filterIndex) {
            // Adjust the active filter index after the removal of a filter set before it.
            --activeFilterIndex;
            setActiveFilter(filterSets[activeFilterIndex], activeFilterIndex);
        }

        _updatePicker();
        _doPopulate();
        _picker.refresh();
    }
585295
function(opts) {
				var o = opts || {};
				selectCheckbox && selectAllCheckbox.find('input').prop('checked', false);
				if (Object.keys(selectedFiles).length) {
					selectLock = false;
					selectedFiles = {};
					cwd.find('[id].'+clSelected).trigger(evtUnselect);
					selectCheckbox && cwd.find('input:checkbox').prop('checked', false);
				}
				!o.notrigger && trigger();
				selectCheckbox && selectAllCheckbox.data('pending', false);
				cwd.removeClass('elfinder-cwd-allselected');
			}
1104632
function dropFile() {
        // Check for File API support
        // if (typeof window.File === 'undefined' ||
        //     typeof window.FileReader === 'undefined') {
        //   alert('The File APIs are not fully supported in this browser.');
        // }

        $("#preview").bind('dragover', function () {
            $("#paper").addClass('hover');
            return false;
        }).bind("dragend", function () {
            $("#paper").removeClass('hover');
            return false;
        }).bind("drop", function (e) {
            $("#paper").removeClass('hover');
            e.stopPropagation();
            e.preventDefault();

            renderImportedFile(e.originalEvent.dataTransfer.files[0]);
            return false;
        });
    }
1224309
@Override
	public void actionPerformed(ActionEvent evt) {
		// Perform action...
		JFileChooser chooser = new JFileChooser();
		String txt = textField.getText();

		if ( config == null) {
			System.out.println("config == null, calling getWebStartConfig...");
			config = WebStartMain.getWebStartConfig();
		}
		if ( txt != null){
			chooser.setCurrentDirectory(new java.io.File(txt));
			config.setPdbFilePath(txt);

		}
		chooser.setDialogTitle("Choose directory that contains your PDB files");
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		//
		// disable the "All files" option.
		//
		chooser.setAcceptAllFileFilterUsed(false);
		//


//		In response to a button click:
		int returnVal = chooser.showOpenDialog(null);
		if ( returnVal == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			textField.setText(file.getAbsolutePath());
			textField.repaint();
		}

	}
1005541
private void buttonChooseFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonChooseFileActionPerformed
    final File theFile = new File(this.textFieldFilePath.getText().trim());
    final File parent = theFile.getParentFile();

    final JFileChooser chooser = new JFileChooser(parent == null ? this.projectFolder : parent);
    if (theFile.isFile()) {
      chooser.setSelectedFile(theFile);
    }
    chooser.setApproveButtonText("Select");
    chooser.setDialogTitle("Select file");
    chooser.setMultiSelectionEnabled(false);
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
      final File selected = chooser.getSelectedFile();
      this.textFieldFilePath.setText(selected.getAbsolutePath());
    }
  }
271683
protected void updateActivation(Activation value, String xmlTag, Counter counter, Element element)
   {
      boolean shouldExist = value != null;
      Element root = updateElement(counter, element, xmlTag, shouldExist);
      if (shouldExist)
      {
         Counter innerCount = new Counter(counter.getDepth() + 1);
         findAndReplaceSimpleElement(innerCount, root, "activeByDefault",
                  (value.isActiveByDefault() == false) ? null : String.valueOf(value.isActiveByDefault()), "false");
         findAndReplaceSimpleElement(innerCount, root, "jdk", value.getJdk(), null);
         updateActivationOS(value.getOs(), "os", innerCount, root);
         updateActivationProperty(value.getProperty(), "property", innerCount, root);
         updateActivationFile(value.getFile(), "file", innerCount, root);
      }
   }
871168
@Override
    public boolean accept(File file) {
        //All directories are added in the least that can be read by the Application
        if (file.isDirectory()&&file.canRead())
        {   return true;
        }
        else if(properties.selection_type==DialogConfigs.DIR_SELECT)
        {   /*  True for files, If the selection type is Directory type, ie.
             *  Only directory has to be selected from the list, then all files are
             *  ignored.
             */
            return false;
        }
        else
        {   /*  Check whether name of the file ends with the extension. Added if it
             *  does.
             */
            String name = file.getName().toLowerCase(Locale.getDefault());
            for (String ext : validExtensions) {
                if (name.endsWith(ext)) {
                    return true;
                }
            }
        }
        return false;
    }
207199
private void checkResumableDownloadEnabled(int downloadId) {
		synchronized (mCurrentRequests) {
			for (DownloadRequest request : mCurrentRequests) {
				if (downloadId == -1 && !request.isResumable()) {
					Log.e("ThinDownloadManager",
							String.format(Locale.getDefault(), "This request has not enabled resume feature hence request will be cancelled. Request Id: %d", request.getDownloadId()));
				} else if ((request.getDownloadId() == downloadId && !request.isResumable())) {
					throw new IllegalStateException("You cannot pause the download, unless you have enabled Resume feature in DownloadRequest.");
				} else {
					//ignored, It can not be a scenario to happen.
				}
			}
		}
	}
470843
function addToWorkingSetAndSelect(fullPath) {
        DeprecationWarning.deprecationWarning("Use FileViewController.openFileAndAddToWorkingSet() instead of FileViewController.addToWorkingSetAndSelect().", true);
        var result = new $.Deferred();
        openFileAndAddToWorkingSet(fullPath)
            .done(function (file) {
                var doc;

                if (file) {
                    doc = DocumentManager.getOpenDocumentForPath(file.fullPath);
                }

                result.resolve(doc);
            })
            .fail(function (err) {
                result.reject(err);
            });
        return result.promise();
    }
578485
protected void openFileChooser()
   {
      if (m_model.getShowDialog())
      {
         if (m_fileChooser.showSaveDialog(m_parent) == JFileChooser.APPROVE_OPTION)
         {
            FileNameExtensionFilter filter = (FileNameExtensionFilter) m_fileChooser.getFileFilter();
            String description = filter.getDescription();
            m_model.setType(description.substring(0, description.indexOf(' ')));
            m_model.setFile(null);
            m_model.setFile(m_fileChooser.getSelectedFile());
         }
         m_model.setShowDialog(false);
      }
   }
114716
def eventFilter( self, object, event ):
        
        if ( object == self._filepathEdit and \
             self._filepathEdit.isReadOnly() and \
             event.type() == event.MouseButtonPress and \
             event.button() == Qt.LeftButton ):
            self.pickFilepath()
            
        return False
1112552
function _updatePicker() {
        var filter = getActiveFilter();
        if (filter && filter.patterns.length) {
            var label = filter.name || _getCondensedForm(filter.patterns);
            _picker.setButtonLabel(StringUtils.format(Strings.EXCLUDE_FILE_FILTER, label));
        } else {
            _picker.setButtonLabel(Strings.NO_FILE_FILTER);
        }
    }
1032548
private void buttonImportSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonImportSettingsActionPerformed

        BaseFileChooser fileChooser = new BaseFileChooser();
        fileChooser.setAcceptAllFileFilterUsed(true);
        fileChooser.addChoosableFileFilter(new FileExtensionFilter("txt"));
        if(lastfile!=null)
            fileChooser.setSelectedFile(new File(lastfile));
        if (fileChooser.showOpenDialog(this.buttonImportSettings) == BaseFileChooser.APPROVE_OPTION) {
            lastfile = fileChooser.getSelectedFile().getPath();
            loadOptionsFromFile(fileChooser.getSelectedFile().getPath());
        }
    }
943595
protected void onFileChoose(JFileChooser fileChooser, ActionEvent actionEvent)
	{
		final int returnVal = fileChooser.showOpenDialog(parent);

		if (returnVal == JFileChooser.APPROVE_OPTION)
		{
			final File file = fileChooser.getSelectedFile();
			onApproveOption(file, actionEvent);
		}
		else
		{
			onCancel(actionEvent);
		}
	}
276692
def open_filechooser(title, parent=None, patterns=None,
                     folder=None, filter=None, multiple=False,
                     _before_run=None, action=None):
    

    assert not (patterns and filter)
    if multiple:
        if action is not None and action != gtk.FILE_CHOOSER_ACTION_OPEN:
            raise ValueError('`multiple` is only valid for the action '
                             '`gtk.FILE_CHOOSER_ACTION_OPEN`.')
        action = gtk.FILE_CHOOSER_ACTION_OPEN
    else:
        assert action is not None
    filechooser = gtk.FileChooserDialog(title,
                                        parent,
                                        action,
                                        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                         gtk.STOCK_OPEN, gtk.RESPONSE_OK))
    if multiple:
        filechooser.set_select_multiple(True)

    if patterns or filter:
        if not filter:
            filter = gtk.FileFilter()
            for pattern in patterns:
                filter.add_pattern(pattern)
        filechooser.set_filter(filter)
    filechooser.set_default_response(gtk.RESPONSE_OK)

    if folder:
        filechooser.set_current_folder(folder)

    try:
        if _before_run is not None:
            _before_run(filechooser)
        response = filechooser.run()
        if response not in (gtk.RESPONSE_OK, gtk.RESPONSE_NONE):
            return

        if multiple:
            return filechooser.get_filenames()
        else:
            return filechooser.get_filename()
    finally:
        _destroy(filechooser)
70033
function blockResizeStart() {
			var lastListeningElement;

			// We'll attach only one listener at a time, instead of adding it to every img, input, hr etc.
			// Listener will be attached upon selectionChange, we'll also check if there was any element that
			// got listener before (lastListeningElement) - if so we need to remove previous listener.
			editor.editable().attachListener( editor, 'selectionChange', function() {
				var selectedElement = editor.getSelection().getSelectedElement();

				if ( selectedElement ) {
					if ( lastListeningElement ) {
						lastListeningElement.detachEvent( 'onresizestart', resizeStartListener );
						lastListeningElement = null;
					}

					// IE requires using attachEvent, because it does not work using W3C compilant addEventListener,
					// tested with IE10.
					selectedElement.$.attachEvent( 'onresizestart', resizeStartListener );
					lastListeningElement = selectedElement.$;
				}
			} );
		}