<commit_before>/*
 * Copyright 2000-2015 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.ui.mac;

import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.PathChooserDialog;
import com.intellij.openapi.fileChooser.impl.FileChooserUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.openapi.wm.impl.IdeMenuBar;
import com.intellij.projectImport.ProjectOpenProcessor;
import com.intellij.ui.mac.foundation.Foundation;
import com.intellij.ui.mac.foundation.ID;
import com.intellij.ui.mac.foundation.MacUtil;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import com.sun.jna.Callback;
import com.sun.jna.Pointer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;

/**
 * @author spleaner
 */
@SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod")
public class MacFileChooserDialogImpl implements PathChooserDialog {
  private static final int OK = 1;

  private static final Map<ID, MacFileChooserDialogImpl> ourImplMap = new HashMap<ID, MacFileChooserDialogImpl>(2);

  private final FileChooserDescriptor myChooserDescriptor;
  private final Project myProject;
  private Consumer<List<VirtualFile>> myCallback;

  private static final Callback SHOULD_ENABLE_CALLBACK = new Callback() {
    @SuppressWarnings("UnusedDeclaration")
    public boolean callback(ID self, String selector, ID panel, ID url) {
      try {
        return checkFile(self, url, true);  // allow any directory - ability to select nested directories
      }
      catch (Exception e) {
        return false;
      }
    }
  };

  private static final Callback VALIDATE_URL_CALLBACK = new Callback() {
    @SuppressWarnings("UnusedDeclaration")
    public boolean callback(ID self, String selector, ID panel, ID url, ID outError) {
      try {
        return checkFile(self, url, false);
      }
      catch (Exception e) {
        if (!ID.NIL.equals(outError)) {
          ID domain = Foundation.nsString(ApplicationNamesInfo.getInstance().getProductName());
          ID dict = Foundation.createDict(new String[]{"NSLocalizedDescription"}, new Object[]{e.getMessage()});
          ID error = Foundation.invoke("NSError", "errorWithDomain:code:userInfo:", domain, 100, dict);
          new Pointer(outError.longValue()).setLong(0, error.longValue());
        }
        return false;
      }
    }
  };

  private static boolean checkFile(@NotNull ID self, ID url, boolean quickCheck) throws Exception {
    MacFileChooserDialogImpl impl = ourImplMap.get(self);
    if (impl == null) {
      return true;  // already removed from the map: the file is likely to be valid since the user was able to select it
    }

    if (url == null || url.intValue() == 0) {
      return false;
    }

    ID filename = Foundation.invoke(url, "path");
    String path = Foundation.toStringViaUTF8(filename);
    if (path == null) {
      return false;
    }

    VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);
    if (file == null || quickCheck && file.isDirectory()) {
      return true;
    }

    if (!impl.myChooserDescriptor.isFileSelectable(file)) {
      return false;
    }

    if (!quickCheck) {
      VirtualFile[] files = {file};
      impl.myChooserDescriptor.validateSelectedFiles(files);
    }

    return true;
  }

  private static final Callback OPEN_PANEL_DID_END = new Callback() {
    @SuppressWarnings("UnusedDeclaration")
    public void callback(ID self, String selector, ID openPanelDidEnd, ID returnCode, ID contextInfo) {
      final MacFileChooserDialogImpl impl = ourImplMap.remove(self);

      try {
        //noinspection SSBasedInspection
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            final IdeMenuBar bar = getMenuBar();
            if (bar != null) {
              bar.enableUpdates();
            }
          }
        });

        final List<String> resultPaths = processResult(returnCode, openPanelDidEnd);
        if (resultPaths.size() > 0) {
          //noinspection SSBasedInspection
          SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
              final List<VirtualFile> files = getChosenFiles(resultPaths);
              if (files.size() > 0) {
                FileChooserUtil.setLastOpenedFile(impl.myProject, files.get(files.size() - 1));
                impl.myCallback.consume(files);
              }
            }
          });
        } else if (impl.myCallback instanceof FileChooser.FileChooserConsumer) {
          //noinspection SSBasedInspection
          SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
              ((FileChooser.FileChooserConsumer)impl.myCallback).cancelled();
            }
          });
        }
      }
      finally {
        invoke(contextInfo, "setDelegate:", ID.NIL);
        Foundation.cfRelease(self);
        Foundation.cfRelease(contextInfo);
        JDK7WindowReorderingWorkaround.enableReordering();
      }
    }
  };

  @NotNull
  private static List<String> processResult(final ID result, final ID panel) {
    final List<String> resultPaths = new ArrayList<String>();
<commit_msg>MacFileChooserDialogImpl: use modality-aware invokeLater and allow modal dumb mode from refresh (EA-71525 - Throwable: DumbServiceImpl.scheduleCacheUpdate)<commit_after>/*
 * Copyright 2000-2015 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.ui.mac;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.PathChooserDialog;
import com.intellij.openapi.fileChooser.impl.FileChooserUtil;
import com.intellij.openapi.project.DumbModePermission;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.openapi.wm.impl.IdeMenuBar;
import com.intellij.projectImport.ProjectOpenProcessor;
import com.intellij.ui.mac.foundation.Foundation;
import com.intellij.ui.mac.foundation.ID;
import com.intellij.ui.mac.foundation.MacUtil;
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
import com.sun.jna.Callback;
import com.sun.jna.Pointer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;

/**
 * @author spleaner
 */
@SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod")
public class MacFileChooserDialogImpl implements PathChooserDialog {
  private static final int OK = 1;

  private static final Map<ID, MacFileChooserDialogImpl> ourImplMap = new HashMap<ID, MacFileChooserDialogImpl>(2);

  private final FileChooserDescriptor myChooserDescriptor;
  private final Project myProject;
  private Consumer<List<VirtualFile>> myCallback;

  private static final Callback SHOULD_ENABLE_CALLBACK = new Callback() {
    @SuppressWarnings("UnusedDeclaration")
    public boolean callback(ID self, String selector, ID panel, ID url) {
      try {
        return checkFile(self, url, true);  // allow any directory - ability to select nested directories
      }
      catch (Exception e) {
        return false;
      }
    }
  };

  private static final Callback VALIDATE_URL_CALLBACK = new Callback() {
    @SuppressWarnings("UnusedDeclaration")
    public boolean callback(ID self, String selector, ID panel, ID url, ID outError) {
      try {
        return checkFile(self, url, false);
      }
      catch (Exception e) {
        if (!ID.NIL.equals(outError)) {
          ID domain = Foundation.nsString(ApplicationNamesInfo.getInstance().getProductName());
          ID dict = Foundation.createDict(new String[]{"NSLocalizedDescription"}, new Object[]{e.getMessage()});
          ID error = Foundation.invoke("NSError", "errorWithDomain:code:userInfo:", domain, 100, dict);
          new Pointer(outError.longValue()).setLong(0, error.longValue());
        }
        return false;
      }
    }
  };

  private static boolean checkFile(@NotNull ID self, ID url, boolean quickCheck) throws Exception {
    MacFileChooserDialogImpl impl = ourImplMap.get(self);
    if (impl == null) {
      return true;  // already removed from the map: the file is likely to be valid since the user was able to select it
    }

    if (url == null || url.intValue() == 0) {
      return false;
    }

    ID filename = Foundation.invoke(url, "path");
    String path = Foundation.toStringViaUTF8(filename);
    if (path == null) {
      return false;
    }

    VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);
    if (file == null || quickCheck && file.isDirectory()) {
      return true;
    }

    if (!impl.myChooserDescriptor.isFileSelectable(file)) {
      return false;
    }

    if (!quickCheck) {
      VirtualFile[] files = {file};
      impl.myChooserDescriptor.validateSelectedFiles(files);
    }

    return true;
  }

  private static final Callback OPEN_PANEL_DID_END = new Callback() {
    @SuppressWarnings("UnusedDeclaration")
    public void callback(ID self, String selector, ID openPanelDidEnd, ID returnCode, ID contextInfo) {
      final MacFileChooserDialogImpl impl = ourImplMap.remove(self);

      try {
        //noinspection SSBasedInspection
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            final IdeMenuBar bar = getMenuBar();
            if (bar != null) {
              bar.enableUpdates();
            }
          }
        });

        final List<String> resultPaths = processResult(returnCode, openPanelDidEnd);
        if (resultPaths.size() > 0) {
          ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
              DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL, new Runnable() {
                @Override
                public void run() {
                  final List<VirtualFile> files = getChosenFiles(resultPaths);
                  if (files.size() > 0) {
                    FileChooserUtil.setLastOpenedFile(impl.myProject, files.get(files.size() - 1));
                    impl.myCallback.consume(files);
                  }
                }
              });
            }
          });
        } else if (impl.myCallback instanceof FileChooser.FileChooserConsumer) {
          ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
              ((FileChooser.FileChooserConsumer)impl.myCallback).cancelled();
            }
          });
        }
      }
      finally {
        invoke(contextInfo, "setDelegate:", ID.NIL);
        Foundation.cfRelease(self);
        Foundation.cfRelease(contextInfo);
        JDK7WindowReorderingWorkaround.enableReordering();
      }
    }
  };

  @NotNull
  private static List<String> processResult(final ID result, final ID panel) {
    final List<String> resultPaths = new ArrayList<String>();

{'fraction_non_alphanumeric': 0.10101311084624554, 'fraction_numerical': 0.003948152562574494, 'mean_word_length': 3.21904462602137, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '536035', 'n_tokens_mistral': 3928, 'n_tokens_neox': 3791, 'n_words': 928}