Java Code Examples for com.intellij.openapi.vfs.VirtualFileManager

The following examples show how to use com.intellij.openapi.vfs.VirtualFileManager. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: lsp4intellij   Source File: IntellijLanguageClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void initComponent() {
    try {
        // Adds project listener.
        ApplicationManager.getApplication().getMessageBus().connect().subscribe(ProjectManager.TOPIC,
                new LSPProjectManagerListener());
        // Adds editor listener.
        EditorFactory.getInstance().addEditorFactoryListener(new LSPEditorListener(), this);
        // Adds VFS listener.
        VirtualFileManager.getInstance().addVirtualFileListener(new VFSListener());
        // Adds document event listener.
        ApplicationManager.getApplication().getMessageBus().connect().subscribe(AppTopics.FILE_DOCUMENT_SYNC,
                new LSPFileDocumentManagerListener());

        // in case if JVM forcefully exit.
        Runtime.getRuntime().addShutdownHook(new Thread(() -> projectToLanguageWrappers.values().stream()
                .flatMap(Collection::stream).filter(RUNNING).forEach(s -> s.stop(true))));

        LOG.info("Intellij Language Client initialized successfully");
    } catch (Exception e) {
        LOG.warn("Fatal error occurred when initializing Intellij language client.", e);
    }
}
 
Example 2
Source Project: markdown-image-kit   Source File: UploadActionBase.java    License: MIT License 6 votes vote down vote up
/**
 * 所有子类都走这个逻辑, 做一些前置判断和解析 markdown image mark
 *
 * @param event the an action event
 */
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
    // 先刷新一次, 避免才添加的文件未被添加的 VFS 中, 导致找不到文件的问题
    VirtualFileManager.getInstance().syncRefresh();

    final Project project = event.getProject();
    if (project != null) {
        EventData data = new EventData()
            .setActionEvent(event)
            .setProject(project)
            // 使用子类的具体 client
            .setClient(getClient())
            .setClientName(getName());

        // 开启后台任务
        new ActionTask(project, MikBundle.message("mik.action.upload.process", getName()), ActionManager.buildUploadChain(data)).queue();
    }
}
 
Example 3
Source Project: consulo   Source File: LibraryRootsComponent.java    License: Apache License 2.0 6 votes vote down vote up
private Set<VirtualFile> getNotExcludedRoots() {
  Set<VirtualFile> roots = new LinkedHashSet<VirtualFile>();
  String[] excludedRootUrls = getLibraryEditor().getExcludedRootUrls();
  Set<VirtualFile> excludedRoots = new HashSet<VirtualFile>();
  for (String url : excludedRootUrls) {
    ContainerUtil.addIfNotNull(excludedRoots, VirtualFileManager.getInstance().findFileByUrl(url));
  }
  for (OrderRootType type : OrderRootType.getAllTypes()) {
    VirtualFile[] files = getLibraryEditor().getFiles(type);
    for (VirtualFile file : files) {
      if (!VfsUtilCore.isUnder(file, excludedRoots)) {
        roots.add(PathUtil.getLocalFile(file));
      }
    }
  }
  return roots;
}
 
Example 4
Source Project: consulo   Source File: LocalHistoryImpl.java    License: Apache License 2.0 6 votes vote down vote up
protected void initHistory() {
  ChangeListStorage storage;
  try {
    storage = new ChangeListStorageImpl(getStorageDir());
  }
  catch (Throwable e) {
    LocalHistoryLog.LOG.warn("cannot create storage, in-memory  implementation will be used", e);
    storage = new InMemoryChangeListStorage();
  }
  myChangeList = new ChangeList(storage);
  myVcs = new LocalHistoryFacade(myChangeList);

  myGateway = new IdeaGateway();

  myEventDispatcher = new LocalHistoryEventDispatcher(myVcs, myGateway);

  CommandProcessor.getInstance().addCommandListener(myEventDispatcher, this);

  myConnection = myBus.connect();
  myConnection.subscribe(VirtualFileManager.VFS_CHANGES, myEventDispatcher);

  VirtualFileManager fm = VirtualFileManager.getInstance();
  fm.addVirtualFileManagerListener(myEventDispatcher, this);
}
 
Example 5
Source Project: code-generator   Source File: TemplateUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static void generateSourceFile(String source, String baseDir) {
    String packageName = extractPackage(source);
    String className = extractClassName(source);
    String sourcePath = buildSourcePath(baseDir, className, packageName);
    VirtualFileManager manager = VirtualFileManager.getInstance();
    VirtualFile virtualFile = manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(sourcePath));
    if (virtualFile == null || !virtualFile.exists() || userConfirmedOverride(className)) {
        ApplicationManager.getApplication().runWriteAction(() -> {
            try {
                if (virtualFile != null && virtualFile.exists()) {
                    virtualFile.setBinaryContent(source.getBytes("utf8"));

                } else {
                    File file = new File(sourcePath);
                    FileUtils.writeStringToFile(file, source, "utf8");
                    manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(sourcePath));
                }
            } catch (IOException e) {
                log.error(e);
            }
        });
    }
}
 
Example 6
Source Project: intellij-thrift   Source File: ThriftFacetConf.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void reset() {
  final List<Generator> list = translators.getData();
  list.clear();
  try {
    for (Generator g : config.getGenerators()) {
      list.add(g.clone());
    }
  }
  catch (CloneNotSupportedException e) {
    throw new RuntimeException("Failed to clone generator settings");
  }

  final List<VirtualFile> includes = includesList.getData();
  includes.clear();
  for (String inc : config.getIncludes()) {
    includes.add(VirtualFileManager.getInstance().findFileByUrl(inc));
  }

  cleanOnBuildCheckBox.setSelected(config.isCleanOutput());
  modified = false;
}
 
Example 7
Source Project: consulo   Source File: SMTestProxy.java    License: Apache License 2.0 6 votes vote down vote up
protected Location getLocation(@Nonnull Project project, @Nonnull GlobalSearchScope searchScope, String locationUrl) {
  if (locationUrl != null && myLocator != null) {
    String protocolId = VirtualFileManager.extractProtocol(locationUrl);
    if (protocolId != null) {
      String path = VirtualFileManager.extractPath(locationUrl);
      if (!DumbService.isDumb(project) || DumbService.isDumbAware(myLocator)) {
        return DumbService.getInstance(project).computeWithAlternativeResolveEnabled(() -> {
          List<Location> locations = myLocator.getLocation(protocolId, path, myMetainfo, project, searchScope);
          return !locations.isEmpty() ? locations.get(0) : null;
        });
      }
    }
  }

  return null;
}
 
Example 8
Source Project: consulo   Source File: DirectoryUrl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object[] createPath(final Project project) {
  if (moduleName != null) {
    final Module module = ApplicationManager.getApplication().runReadAction(new Computable<Module>() {
      @Nullable
      @Override
      public Module compute() {
        return ModuleManager.getInstance(project).findModuleByName(moduleName);
      }
    });
    if (module == null) return null;
  }
  final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
  final VirtualFile file = virtualFileManager.findFileByUrl(url);
  if (file == null) return null;
  final PsiDirectory directory = ApplicationManager.getApplication().runReadAction(new Computable<PsiDirectory>() {
    @Nullable
    @Override
    public PsiDirectory compute() {
      return PsiManager.getInstance(project).findDirectory(file);
    }
  });
  if (directory == null) return null;
  return new Object[]{directory};
}
 
Example 9
Source Project: consulo   Source File: PlatformDocumentationUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
public static List<String> getHttpRoots(final String[] roots, String relPath) {
  final ArrayList<String> result = new ArrayList<String>();
  for (String root : roots) {
    final VirtualFile virtualFile = VirtualFileManager.getInstance().findFileByUrl(root);
    if (virtualFile != null) {
      if (virtualFile.getFileSystem() instanceof HttpFileSystem) {
        String url = virtualFile.getUrl();
        if (!url.endsWith("/")) url += "/";
        result.add(url + relPath);
      }
      else {
        VirtualFile file = virtualFile.findFileByRelativePath(relPath);
        if (file != null) result.add(file.getUrl());
      }
    }
  }

  return result.isEmpty() ? null : result;
}
 
Example 10
Source Project: consulo   Source File: HighlightingSettingsPerFile.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void loadState(Element element) {
  List children = element.getChildren(SETTING_TAG);
  for (final Object aChildren : children) {
    final Element child = (Element)aChildren;
    final String url = child.getAttributeValue(FILE_ATT);
    if (url == null) continue;
    final VirtualFile fileByUrl = VirtualFileManager.getInstance().findFileByUrl(url);
    if (fileByUrl != null) {
      final List<FileHighlightingSetting> settings = new ArrayList<FileHighlightingSetting>();
      int index = 0;
      while (child.getAttributeValue(ROOT_ATT_PREFIX + index) != null) {
        final String attributeValue = child.getAttributeValue(ROOT_ATT_PREFIX + index++);
        settings.add(Enum.valueOf(FileHighlightingSetting.class, attributeValue));
      }
      myHighlightSettings.put(fileByUrl, settings.toArray(new FileHighlightingSetting[settings.size()]));
    }
  }
}
 
Example 11
Source Project: consulo   Source File: CompilerPathsImpl.java    License: Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
public static String getModuleOutputPath(final Module module, final ContentFolderTypeProvider contentFolderType) {
  final String outPathUrl;
  final Application application = ApplicationManager.getApplication();
  final ModuleCompilerPathsManager pathsManager = ModuleCompilerPathsManager.getInstance(module);

  if (application.isDispatchThread()) {
    outPathUrl = pathsManager.getCompilerOutputUrl(contentFolderType);
  }
  else {
    outPathUrl = application.runReadAction(new Computable<String>() {
      @Override
      public String compute() {
        return pathsManager.getCompilerOutputUrl(contentFolderType);
      }
    });
  }

  return outPathUrl != null ? VirtualFileManager.extractPath(outPathUrl) : null;
}
 
Example 12
Source Project: consulo   Source File: UnindexedFilesUpdater.java    License: Apache License 2.0 6 votes vote down vote up
private void scheduleInitialVfsRefresh() {
  ProjectRootManagerEx.getInstanceEx(myProject).markRootsForRefresh();

  Application app = ApplicationManager.getApplication();
  if (!app.isCommandLine()) {
    long sessionId = VirtualFileManager.getInstance().asyncRefresh(null);
    MessageBusConnection connection = app.getMessageBus().connect();
    connection.subscribe(ProjectManager.TOPIC, new ProjectManagerListener() {
      @Override
      public void projectClosed(@Nonnull Project project, @Nonnull UIAccess uiAccess) {
        if (project == myProject) {
          RefreshQueue.getInstance().cancelSession(sessionId);
          connection.disconnect();
        }
      }
    });
  }
  else {
    VirtualFileManager.getInstance().syncRefresh();
  }
}
 
Example 13
Source Project: intellij-haxe   Source File: HaxeFileUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find a file, given a path.  If the path is not absolute, then try as relative
 * to other given paths.
 *
 * @param path Path to test.  Null or empty path is not an error, but will return a null result.
 * @param rootPaths Variable number of other root paths to search.
 * @return null if the file could not be located; a VirtualFile if it could.
 */
@Nullable
public static VirtualFile locateFile(String path, String... rootPaths) {
  if (null == path || path.isEmpty()) {
    return null;
  }

  String tryPath = fixUrl(path);

  VirtualFileManager vfs = VirtualFileManager.getInstance();
  VirtualFile file = vfs.findFileByUrl(tryPath);
  if (null == file && !isAbsolutePath(tryPath)) {
    String nonUrlPath = vfs.extractPath(path);
    for (String root : rootPaths) {
      if (null != root && !root.isEmpty()) {
        tryPath = fixUrl(joinPath(root, nonUrlPath));
        file = vfs.findFileByUrl(tryPath);
        if (null != file) {
          break;
        }
      }
    }
  }

  return file;
}
 
Example 14
Source Project: consulo   Source File: EditorBasedStatusBarPopup.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void install(@Nonnull StatusBar statusBar) {
  super.install(statusBar);
  registerCustomListeners();
  EditorFactory.getInstance().getEventMulticaster().addDocumentListener(new DocumentListener() {
    @Override
    public void documentChanged(@Nonnull DocumentEvent e) {
      Document document = e.getDocument();
      updateForDocument(document);
    }
  }, this);
  if (myWriteableFileRequired) {
    ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(VirtualFileManager.VFS_CHANGES, new BulkVirtualFileListenerAdapter(new VirtualFileListener() {
      @Override
      public void propertyChanged(@Nonnull VirtualFilePropertyEvent event) {
        if (VirtualFile.PROP_WRITABLE.equals(event.getPropertyName())) {
          updateForFile(event.getFile());
        }
      }
    }));
  }
}
 
Example 15
@Nullable
private Location<?> getLocation(String url) {
  String protocol = VirtualFileManager.extractProtocol(url);
  if (protocol == null) {
    return null;
  }
  String path = VirtualFileManager.extractPath(url);
  assertThat(handler.getTestLocator()).isNotNull();
  @SuppressWarnings("rawtypes")
  List<Location> locations =
      handler
          .getTestLocator()
          .getLocation(protocol, path, getProject(), GlobalSearchScope.allScope(getProject()));
  assertThat(locations).hasSize(1);
  return locations.get(0);
}
 
Example 16
Source Project: consulo   Source File: LocalFsFinder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public LookupFile find(@Nonnull final String path) {
  final VirtualFile byUrl = VirtualFileManager.getInstance().findFileByUrl(path);
  if (byUrl != null) {
    return new VfsFile(this, byUrl);
  }

  String toFind = normalize(path);
  if (toFind.length() == 0) {
    File[] roots = File.listRoots();
    if (roots.length > 0) {
      toFind = roots[0].getAbsolutePath();
    }
  }
  final File file = new File(toFind);
  // '..' and '.' path components will be eliminated
  VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file);
  if (vFile != null) {
    return new VfsFile(this, vFile);
  } else if (file.isAbsolute()) {
    return new IoFile(new File(path));
  }
  return null;
}
 
Example 17
Source Project: consulo   Source File: LightFilePointer.java    License: Apache License 2.0 6 votes vote down vote up
private void refreshFile() {
  VirtualFile file = myFile;
  if (file != null && file.isValid()) return;
  VirtualFileManager vfManager = VirtualFileManager.getInstance();
  VirtualFile virtualFile = vfManager.findFileByUrl(myUrl);
  if (virtualFile == null && !myRefreshed) {
    myRefreshed = true;
    Application application = ApplicationManager.getApplication();
    if (application.isDispatchThread() || !application.isReadAccessAllowed()) {
      virtualFile = vfManager.refreshAndFindFileByUrl(myUrl);
    }
    else {
      application.executeOnPooledThread(() -> vfManager.refreshAndFindFileByUrl(myUrl));
    }
  }

  myFile = virtualFile != null && virtualFile.isValid() ? virtualFile : null;
}
 
Example 18
Source Project: intellij   Source File: BlazeWebGoTestEventsHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private Location<?> getLocation(String url) {
  String protocol = VirtualFileManager.extractProtocol(url);
  if (protocol == null) {
    return null;
  }
  String path = VirtualFileManager.extractPath(url);
  assertThat(handler.getTestLocator()).isNotNull();
  @SuppressWarnings("rawtypes")
  List<Location> locations =
      handler
          .getTestLocator()
          .getLocation(protocol, path, getProject(), GlobalSearchScope.allScope(getProject()));
  assertThat(locations).hasSize(1);
  return locations.get(0);
}
 
Example 19
Source Project: consulo   Source File: PersistentFileSetManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void loadState(Element state) {
  final VirtualFileManager vfManager = VirtualFileManager.getInstance();
  for (Object child : state.getChildren(FILE_ELEMENT)) {
    if (child instanceof Element) {
      final Element fileElement = (Element)child;
      final Attribute filePathAttr = fileElement.getAttribute(PATH_ATTR);
      if (filePathAttr != null) {
        final String filePath = filePathAttr.getValue();
        VirtualFile vf = vfManager.findFileByUrl(filePath);
        if (vf != null) {
          myFiles.add(vf);
        }
      }
    }
  }
}
 
Example 20
Source Project: p4ic4idea   Source File: IdeaLightweightExtension.java    License: Apache License 2.0 6 votes vote down vote up
private void initializeApplication(Application application) {
    DefaultPicoContainer pico = new DefaultPicoContainer();
    when(application.getPicoContainer()).thenReturn(pico);

    MessageBus bus = new SingleThreadedMessageBus(null);
    when(application.getMessageBus()).thenReturn(bus);

    // Service setup.  See ServiceManager
    pico.registerComponent(service(PasswordSafe.class, new MockPasswordSafe()));
    pico.registerComponent(service(VcsContextFactory.class, new MockVcsContextFactory()));

    VirtualFileManager vfm = mock(VirtualFileManager.class);
    when(application.getComponent(VirtualFileManager.class)).thenReturn(vfm);

    AccessToken readToken = mock(AccessToken.class);
    when(application.acquireReadActionLock()).thenReturn(readToken);

    ApplicationInfo appInfo = mock(ApplicationInfo.class);
    when(appInfo.getApiVersion()).thenReturn("IC-182.1.1");
    registerApplicationService(ApplicationInfo.class, appInfo);
}
 
Example 21
Source Project: consulo   Source File: ModuleManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public Module newModule(@Nonnull @NonNls String name, @Nullable @NonNls String dirPath) {
  assertWritable();

  final String dirUrl = dirPath == null ? null : VirtualFileManager.constructUrl(StandardFileSystems.FILE_PROTOCOL, dirPath);

  ModuleEx moduleEx = null;
  if (dirUrl != null) {
    moduleEx = getModuleByDirUrl(dirUrl);
  }

  if (moduleEx == null) {
    moduleEx = createModule(name, dirUrl, null);
    initModule(moduleEx);
  }
  return moduleEx;
}
 
Example 22
Source Project: intellij-pants-plugin   Source File: PantsUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void synchronizeFiles() {
  /**
   * Run in SYNC in unit test mode, and {@link com.twitter.intellij.pants.testFramework.PantsIntegrationTestCase.doImport}
   * is required to be wrapped in WriteAction. Otherwise it will run in async mode.
   */
  if (ApplicationManager.getApplication().isUnitTestMode() && ApplicationManager.getApplication().isWriteAccessAllowed()) {
    ApplicationManager.getApplication().runWriteAction(() -> {
      FileDocumentManager.getInstance().saveAllDocuments();
      SaveAndSyncHandler.getInstance().refreshOpenFiles();
      VirtualFileManager.getInstance().refreshWithoutFileWatcher(false); /** synchronous */
    });
  }
  else {
    ApplicationManager.getApplication().invokeLater(() -> {
      FileDocumentManager.getInstance().saveAllDocuments();
      SaveAndSyncHandler.getInstance().refreshOpenFiles();
      VirtualFileManager.getInstance().refreshWithoutFileWatcher(true); /** asynchronous */
    });
  }
}
 
Example 23
Source Project: floobits-intellij   Source File: Listener.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized void shutdown() {
    if (connection != null) {
        connection.disconnect();
        connection = null;
    }
    if (em != null) {
        em.removeSelectionListener(this);
        em.removeDocumentListener(this);
        em.removeCaretListener(this);
        em.removeVisibleAreaListener(this);
        em = null;
    }
    if (virtualFileAdapter != null) {
        VirtualFileManager.getInstance().removeVirtualFileListener(virtualFileAdapter);
        virtualFileAdapter = null;
    }

}
 
Example 24
Source Project: consulo   Source File: OrderEntryAppearanceServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
private static CellAppearanceEx formatRelativePath(@Nonnull final ContentFolder folder, @Nonnull final Image icon) {
  LightFilePointer folderFile = new LightFilePointer(folder.getUrl());
  VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(folder.getContentEntry().getUrl());
  if (file == null) return FileAppearanceService.getInstance().forInvalidUrl(folderFile.getPresentableUrl());

  String contentPath = file.getPath();
  String relativePath;
  SimpleTextAttributes textAttributes;
  VirtualFile folderFileFile = folderFile.getFile();
  if (folderFileFile == null) {
    String absolutePath = folderFile.getPresentableUrl();
    relativePath = absolutePath.startsWith(contentPath) ? absolutePath.substring(contentPath.length()) : absolutePath;
    textAttributes = SimpleTextAttributes.ERROR_ATTRIBUTES;
  }
  else {
    relativePath = VfsUtilCore.getRelativePath(folderFileFile, file, File.separatorChar);
    textAttributes = SimpleTextAttributes.REGULAR_ATTRIBUTES;
  }

  relativePath = StringUtil.isEmpty(relativePath) ? "." + File.separatorChar : relativePath;
  return new SimpleTextCellAppearance(relativePath, icon, textAttributes);
}
 
Example 25
Source Project: Intellij-Plugin   Source File: ExtractConceptHandler.java    License: Apache License 2.0 6 votes vote down vote up
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile psiFile) {
    this.psiFile = psiFile;
    this.editor = editor;
    try {
        List<PsiElement> steps = getSteps(this.editor, this.psiFile);
        if (steps.size() == 0)
            throw new RuntimeException("Cannot Extract to Concept, selected text contains invalid elements");
        ExtractConceptInfoCollector collector = new ExtractConceptInfoCollector(editor, builder.getTextToTableMap(), steps, project);
        ExtractConceptInfo info = collector.getAllInfo();
        if (!info.cancelled) {
            VirtualFileManager.getInstance().refreshWithoutFileWatcher(false);
            FileDocumentManager.getInstance().saveAllDocuments();
            Api.ExtractConceptResponse response = makeExtractConceptRequest(steps, info.fileName, info.conceptName, false, psiFile);
            if (!response.getIsSuccess()) throw new RuntimeException(response.getError());
            new UndoHandler(response.getFilesChangedList(), project, "Extract Concept").handle();
        }
    } catch (Exception e) {
        Messages.showErrorDialog(e.getMessage(), "Extract To Concept");
    }
}
 
Example 26
Source Project: r2m-plugin-android   Source File: AddControllerForm.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onGenerateFinished(boolean result, File file) {
    SaveAndSyncHandlerImpl.refreshOpenFiles();
    VirtualFileManager.getInstance().refreshWithoutFileWatcher(false);
    ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
    project.getBaseDir().refresh(false, true);

    if (null == JavaPsiFacade.getInstance(project).findPackage("com.magnet.android.mms.async")) {
        showMissingDependencies();
    }

    if (!result) {
        showCloseDialog(file);
    } else {
        getThis().setVisible(true);
    }
}
 
Example 27
Source Project: consulo   Source File: VFileCreateEvent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param requestor
 * @param parent
 * @param childName
 * @param isDirectory
 * @param attributes null means should read from the created file
 * @param symlinkTarget
 * @param isFromRefresh
 * @param children null means children not available (e.g. the created file is not a directory) or unknown
 */
public VFileCreateEvent(Object requestor,
                        @Nonnull VirtualFile parent,
                        @Nonnull String childName,
                        boolean isDirectory,
                        @Nullable FileAttributes attributes,
                        @Nullable String symlinkTarget,
                        boolean isFromRefresh,
                        @Nullable ChildInfo[] children) {
  super(requestor, isFromRefresh);
  myParent = parent;
  myDirectory = isDirectory;
  myAttributes = attributes;
  mySymlinkTarget = symlinkTarget;
  myChildren = children;
  myChildNameId = VirtualFileManager.getInstance().storeName(childName);
}
 
Example 28
Source Project: consulo   Source File: BookmarkManager.java    License: Apache License 2.0 5 votes vote down vote up
private void readExternal(Element element) {
  for (final Object o : element.getChildren()) {
    Element bookmarkElement = (Element)o;

    if ("bookmark".equals(bookmarkElement.getName())) {
      String url = bookmarkElement.getAttributeValue("url");
      String line = bookmarkElement.getAttributeValue("line");
      String description = StringUtil.notNullize(bookmarkElement.getAttributeValue("description"));
      String mnemonic = bookmarkElement.getAttributeValue("mnemonic");

      Bookmark b = null;
      VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url);
      if (file != null) {
        if (line != null) {
          try {
            int lineIndex = Integer.parseInt(line);
            b = addTextBookmark(file, lineIndex, description);
          }
          catch (NumberFormatException e) {
            // Ignore. Will miss bookmark if line number cannot be parsed
          }
        }
        else {
          b = addFileBookmark(file, description);
        }
      }

      if (b != null && mnemonic != null && mnemonic.length() == 1) {
        setMnemonic(b, mnemonic.charAt(0));
      }
    }
  }
}
 
Example 29
Source Project: consulo   Source File: LocationProviderUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractProtocol() {
  assertEquals(null, VirtualFileManager.extractProtocol(""));
  assertEquals(null, VirtualFileManager.extractProtocol("file:/"));

  assertEquals("file", VirtualFileManager.extractProtocol("file://"));
  assertEquals("file", VirtualFileManager.extractProtocol("file:///some/path/file.rb:24"));
  assertEquals("file", VirtualFileManager.extractProtocol("file://./some/path/file.rb:24"));

  assertEquals("ruby_qn", VirtualFileManager.extractProtocol("ruby_qn://"));
  assertEquals("ruby_qn", VirtualFileManager.extractProtocol("ruby_qn://A::B.method"));
}
 
Example 30
Source Project: spring-javaformat   Source File: FileMonitor.java    License: Apache License 2.0 5 votes vote down vote up
public FileMonitor(Project project, Trigger trigger, VirtualFileManager fileManager) {
	super(project, trigger);
	this.fileManager = fileManager;
	this.listener = new Listener();
	fileManager.addVirtualFileListener(this.listener);
	check();
}