2 * Copyright 2000-2015 JetBrains s.r.o.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package com.intellij.openapi.externalSystem.service.project.manage;
18 import com.intellij.compiler.CompilerConfiguration;
19 import com.intellij.ide.util.projectWizard.ModuleBuilder;
20 import com.intellij.openapi.application.ApplicationManager;
21 import com.intellij.openapi.diagnostic.Logger;
22 import com.intellij.openapi.externalSystem.model.DataNode;
23 import com.intellij.openapi.externalSystem.model.ProjectKeys;
24 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
25 import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType;
26 import com.intellij.openapi.externalSystem.model.project.ModuleData;
27 import com.intellij.openapi.externalSystem.model.project.OrderAware;
28 import com.intellij.openapi.externalSystem.model.project.ProjectData;
29 import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider;
30 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
31 import com.intellij.openapi.externalSystem.util.ExternalSystemBundle;
32 import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
33 import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil;
34 import com.intellij.openapi.module.ModifiableModuleModel;
35 import com.intellij.openapi.module.Module;
36 import com.intellij.openapi.project.Project;
37 import com.intellij.openapi.roots.*;
38 import com.intellij.openapi.ui.DialogWrapper;
39 import com.intellij.openapi.util.Computable;
40 import com.intellij.openapi.util.Key;
41 import com.intellij.openapi.util.Pair;
42 import com.intellij.openapi.util.io.FileUtil;
43 import com.intellij.openapi.vfs.VfsUtilCore;
44 import com.intellij.pom.java.LanguageLevel;
45 import com.intellij.ui.CheckBoxList;
46 import com.intellij.ui.IdeBorderFactory;
47 import com.intellij.ui.components.JBScrollPane;
48 import com.intellij.util.ArrayUtil;
49 import com.intellij.util.Consumer;
50 import com.intellij.util.Function;
51 import com.intellij.util.SmartList;
52 import com.intellij.util.containers.ContainerUtil;
53 import com.intellij.util.containers.ContainerUtilRt;
54 import org.jetbrains.annotations.NotNull;
55 import org.jetbrains.annotations.Nullable;
60 import java.util.List;
63 * @author Vladislav.Soroka
66 public abstract class AbstractModuleDataService<E extends ModuleData> extends AbstractProjectDataService<E, Module> {
68 public static final Key<ModuleData> MODULE_DATA_KEY = Key.create("MODULE_DATA_KEY");
69 public static final Key<Module> MODULE_KEY = Key.create("LINKED_MODULE");
70 public static final Key<Map<OrderEntry, OrderAware>> ORDERED_DATA_MAP_KEY = Key.create("ORDER_ENTRY_DATA_MAP");
71 public static final Key<Set<String>> ORPHAN_MODULE_FILES = Key.create("ORPHAN_FILES");
73 private static final Logger LOG = Logger.getInstance(AbstractModuleDataService.class);
76 public void importData(@NotNull final Collection<DataNode<E>> toImport,
77 @Nullable ProjectData projectData,
78 @NotNull final Project project,
79 @NotNull IdeModifiableModelsProvider modelsProvider) {
80 if (toImport.isEmpty()) {
84 final Collection<DataNode<E>> toCreate = filterExistingModules(toImport, modelsProvider, project);
85 if (!toCreate.isEmpty()) {
86 createModules(toCreate, modelsProvider, project);
89 final boolean isOneToOneMapping = projectData != null && ExternalSystemApiUtil.isOneToOneMapping(project, projectData);
91 for (DataNode<E> node : toImport) {
92 Module module = node.getUserData(MODULE_KEY);
94 setModuleOptions(module, node);
96 final ModifiableModuleModel modifiableModel = modelsProvider.getModifiableModuleModel();
97 final String[] groupPath;
98 if (isOneToOneMapping || projectData == null) {
99 groupPath = node.getData().getIdeModuleGroup();
102 final String externalProjectGroup = projectData.getInternalName() + " modules";
103 groupPath = node.getData().getIdeModuleGroup() == null
104 ? new String[]{externalProjectGroup}
105 : ArrayUtil.prepend(externalProjectGroup, node.getData().getIdeModuleGroup());
107 modifiableModel.setModuleGroupPath(module, groupPath);
108 ModifiableRootModel modifiableRootModel = modelsProvider.getModifiableRootModel(module);
109 syncPaths(module, modifiableRootModel, node.getData());
110 setLanguageLevel(modifiableRootModel, node.getData());
115 private void createModules(@NotNull Collection<DataNode<E>> toCreate,
116 @NotNull IdeModifiableModelsProvider modelsProvider,
117 @NotNull Project project) {
118 for (final DataNode<E> module : toCreate) {
119 ModuleData data = module.getData();
120 final Module created = modelsProvider.newModule(data.getModuleFilePath(), data.getModuleTypeId());
121 module.putUserData(MODULE_KEY, created);
122 Set<String> orphanFiles = project.getUserData(ORPHAN_MODULE_FILES);
123 if (orphanFiles != null) {
124 orphanFiles.remove(created.getModuleFilePath());
127 // Ensure that the dependencies are clear (used to be not clear when manually removing the module and importing it via gradle)
128 final ModifiableRootModel modifiableRootModel = modelsProvider.getModifiableRootModel(created);
129 modifiableRootModel.inheritSdk();
131 RootPolicy<Object> visitor = new RootPolicy<Object>() {
133 public Object visitLibraryOrderEntry(LibraryOrderEntry libraryOrderEntry, Object value) {
134 modifiableRootModel.removeOrderEntry(libraryOrderEntry);
139 public Object visitModuleOrderEntry(ModuleOrderEntry moduleOrderEntry, Object value) {
140 modifiableRootModel.removeOrderEntry(moduleOrderEntry);
145 for (OrderEntry orderEntry : modifiableRootModel.getOrderEntries()) {
146 orderEntry.accept(visitor, null);
152 private Collection<DataNode<E>> filterExistingModules(@NotNull Collection<DataNode<E>> modules,
153 @NotNull IdeModifiableModelsProvider modelsProvider,
154 @NotNull Project project) {
155 Collection<DataNode<E>> result = ContainerUtilRt.newArrayList();
156 for (DataNode<E> node : modules) {
157 ModuleData moduleData = node.getData();
158 Module module = modelsProvider.findIdeModule(moduleData.getInternalName());
159 if (module == null) {
163 if (!FileUtil.pathsEqual(module.getModuleFilePath(), moduleData.getModuleFilePath())) {
164 modelsProvider.getModifiableModuleModel().disposeModule(module);
166 Set<String> orphanFiles = project.getUserData(ORPHAN_MODULE_FILES);
167 if (orphanFiles == null) {
168 project.putUserData(ORPHAN_MODULE_FILES, orphanFiles = ContainerUtil.newHashSet());
170 orphanFiles.add(module.getModuleFilePath());
173 node.putUserData(MODULE_KEY, module);
180 private static void syncPaths(@NotNull Module module, @NotNull ModifiableRootModel modifiableModel, @NotNull ModuleData data) {
181 CompilerModuleExtension extension = modifiableModel.getModuleExtension(CompilerModuleExtension.class);
182 if (extension == null) {
183 //modifiableModel.dispose();
184 LOG.warn(String.format("Can't sync paths for module '%s'. Reason: no compiler extension is found for it", module.getName()));
187 String compileOutputPath = data.getCompileOutputPath(ExternalSystemSourceType.SOURCE);
188 extension.setCompilerOutputPath(compileOutputPath != null ? VfsUtilCore.pathToUrl(compileOutputPath) : null);
190 String testCompileOutputPath = data.getCompileOutputPath(ExternalSystemSourceType.TEST);
191 extension.setCompilerOutputPathForTests(testCompileOutputPath != null ? VfsUtilCore.pathToUrl(testCompileOutputPath) : null);
193 extension.inheritCompilerOutputPath(data.isInheritProjectCompileOutputPath());
197 public void removeData(@NotNull final Computable<Collection<Module>> toRemoveComputable,
198 @NotNull final Collection<DataNode<E>> toIgnore,
199 @NotNull final ProjectData projectData,
200 @NotNull final Project project,
201 @NotNull final IdeModifiableModelsProvider modelsProvider) {
202 final Collection<Module> toRemove = toRemoveComputable.compute();
203 final List<Module> modules = new SmartList<Module>(toRemove);
204 for (DataNode<E> moduleDataNode : toIgnore) {
205 final Module module = modelsProvider.findIdeModule(moduleDataNode.getData());
206 ContainerUtil.addIfNotNull(modules, module);
209 if (modules.isEmpty()) {
213 ContainerUtil.removeDuplicates(modules);
215 for (Module module : modules) {
216 if (module.isDisposed()) continue;
217 unlinkModuleFromExternalSystem(module);
220 ruleOrphanModules(modules, project, projectData.getOwner(), new Consumer<List<Module>>() {
222 public void consume(final List<Module> modules) {
223 for (Module module : modules) {
224 if (module.isDisposed()) continue;
225 String path = module.getModuleFilePath();
226 final ModifiableModuleModel moduleModel = modelsProvider.getModifiableModuleModel();
227 moduleModel.disposeModule(module);
228 ModuleBuilder.deleteModuleFile(path);
235 * There is a possible case that an external module has been un-linked from ide project. There are two ways to process
236 * ide modules which correspond to that external project:
239 * <li>Remove them from ide project as well;</li>
240 * <li>Keep them at ide project as well;</li>
243 * This method handles that situation, i.e. it asks a user what should be done and acts accordingly.
245 * @param orphanModules modules which correspond to the un-linked external project
246 * @param project current ide project
247 * @param externalSystemId id of the external system which project has been un-linked from ide project
249 private static void ruleOrphanModules(@NotNull final List<Module> orphanModules,
250 @NotNull final Project project,
251 @NotNull final ProjectSystemId externalSystemId,
252 @NotNull final Consumer<List<Module>> result) {
253 ExternalSystemApiUtil.executeOnEdt(true, new Runnable() {
256 List<Module> toRemove = ContainerUtil.newSmartList();
257 if (ApplicationManager.getApplication().isHeadlessEnvironment()) {
258 toRemove.addAll(orphanModules);
261 final JPanel content = new JPanel(new GridBagLayout());
262 content.add(new JLabel(ExternalSystemBundle.message("orphan.modules.text", externalSystemId.getReadableName())),
263 ExternalSystemUiUtil.getFillLineConstraints(0));
265 final CheckBoxList<Module> orphanModulesList = new CheckBoxList<Module>();
266 orphanModulesList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
267 orphanModulesList.setItems(orphanModules, new Function<Module, String>() {
269 public String fun(Module module) {
270 return module.getName();
273 for (Module module : orphanModules) {
274 orphanModulesList.setItemSelected(module, true);
276 orphanModulesList.setBorder(IdeBorderFactory.createEmptyBorder(8));
277 content.add(orphanModulesList, ExternalSystemUiUtil.getFillLineConstraints(0));
278 content.setBorder(IdeBorderFactory.createEmptyBorder(0, 0, 8, 0));
280 DialogWrapper dialog = new DialogWrapper(project) {
282 setTitle(ExternalSystemBundle.message("import.title", externalSystemId.getReadableName()));
288 protected JComponent createCenterPanel() {
289 return new JBScrollPane(content);
293 protected Action[] createActions() {
294 return new Action[]{getOKAction()};
300 for (int i = 0; i < orphanModules.size(); i++) {
301 Module module = orphanModules.get(i);
302 if (orphanModulesList.isItemSelected(i)) {
303 toRemove.add(module);
307 result.consume(toRemove);
312 public static void unlinkModuleFromExternalSystem(@NotNull Module module) {
313 module.clearOption(ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY);
314 module.clearOption(ExternalSystemConstants.LINKED_PROJECT_ID_KEY);
315 module.clearOption(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY);
316 module.clearOption(ExternalSystemConstants.ROOT_PROJECT_PATH_KEY);
317 module.clearOption(ExternalSystemConstants.EXTERNAL_SYSTEM_MODULE_GROUP_KEY);
318 module.clearOption(ExternalSystemConstants.EXTERNAL_SYSTEM_MODULE_VERSION_KEY);
321 protected void setModuleOptions(Module module, DataNode<E> moduleDataNode) {
322 ModuleData moduleData = moduleDataNode.getData();
323 module.putUserData(MODULE_DATA_KEY, moduleData);
325 module.setOption(ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY, moduleData.getOwner().toString());
326 module.setOption(ExternalSystemConstants.LINKED_PROJECT_ID_KEY, moduleData.getId());
327 module.setOption(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY, moduleData.getLinkedExternalProjectPath());
328 final ProjectData projectData = moduleDataNode.getData(ProjectKeys.PROJECT);
329 module.setOption(ExternalSystemConstants.ROOT_PROJECT_PATH_KEY, projectData != null ? projectData.getLinkedExternalProjectPath() : "");
331 if (moduleData.getGroup() != null) {
332 module.setOption(ExternalSystemConstants.EXTERNAL_SYSTEM_MODULE_GROUP_KEY, moduleData.getGroup());
334 if (moduleData.getVersion() != null) {
335 module.setOption(ExternalSystemConstants.EXTERNAL_SYSTEM_MODULE_VERSION_KEY, moduleData.getVersion());
338 // clear maven option
339 module.clearOption("org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule");
343 public void postProcess(@NotNull Collection<DataNode<E>> toImport,
344 @Nullable ProjectData projectData,
345 @NotNull Project project,
346 @NotNull IdeModifiableModelsProvider modelsProvider) {
347 for (DataNode<E> moduleDataNode : toImport) {
348 final Module module = moduleDataNode.getUserData(MODULE_KEY);
349 if (module == null) continue;
350 final Map<OrderEntry, OrderAware> orderAwareMap = moduleDataNode.getUserData(ORDERED_DATA_MAP_KEY);
351 if (orderAwareMap != null) {
352 rearrangeOrderEntries(orderAwareMap, modelsProvider.getModifiableRootModel(module));
354 setBytecodeTargetLevel(project, module, moduleDataNode.getData());
359 public void onSuccessImport(@NotNull Project project) {
360 final Set<String> orphanFiles = project.getUserData(ORPHAN_MODULE_FILES);
361 if (orphanFiles != null && !orphanFiles.isEmpty()) {
362 ExternalSystemApiUtil.executeOnEdt(false, new Runnable() {
365 for (String orphanFile : orphanFiles) {
366 ModuleBuilder.deleteModuleFile(orphanFile);
370 project.putUserData(ORPHAN_MODULE_FILES, null);
374 protected void rearrangeOrderEntries(@NotNull Map<OrderEntry, OrderAware> orderEntryDataMap,
375 @NotNull ModifiableRootModel modifiableRootModel) {
376 final OrderEntry[] orderEntries = modifiableRootModel.getOrderEntries();
377 final int length = orderEntries.length;
378 final OrderEntry[] newOrder = new OrderEntry[length];
379 final PriorityQueue<Pair<OrderEntry, OrderAware>> priorityQueue = new PriorityQueue<Pair<OrderEntry, OrderAware>>(
380 11, new Comparator<Pair<OrderEntry, OrderAware>>() {
382 public int compare(Pair<OrderEntry, OrderAware> o1, Pair<OrderEntry, OrderAware> o2) {
383 int order1 = o1.second.getOrder();
384 int order2 = o2.second.getOrder();
385 return order1 != order2 ? order1 < order2 ? -1 : 1 : 0;
390 for (int i = 0; i < length; i++) {
391 OrderEntry orderEntry = orderEntries[i];
392 final OrderAware orderAware = orderEntryDataMap.get(orderEntry);
393 if (orderAware == null) {
394 newOrder[i] = orderEntry;
398 priorityQueue.add(Pair.create(orderEntry, orderAware));
402 Pair<OrderEntry, OrderAware> pair;
403 while ((pair = priorityQueue.poll()) != null) {
404 final OrderEntry orderEntry = pair.first;
405 final OrderAware orderAware = pair.second;
406 final int order = orderAware.getOrder() != -1 ? orderAware.getOrder() : length - 1;
407 final int newPlace = findNewPlace(newOrder, order - shift);
408 assert newPlace != -1;
409 newOrder[newPlace] = orderEntry;
412 if (LOG.isDebugEnabled()) {
413 final boolean changed = !ArrayUtil.equals(orderEntries, newOrder, new Comparator<OrderEntry>() {
415 public int compare(OrderEntry o1, OrderEntry o2) {
416 return o1.compareTo(o2);
419 LOG.debug(String.format("rearrange status (%s): %s", modifiableRootModel.getModule(), changed ? "modified" : "not modified"));
421 modifiableRootModel.rearrangeOrderEntries(newOrder);
424 private static int findNewPlace(OrderEntry[] newOrder, int newIndex) {
426 while (idx < 0 || (idx < newOrder.length && newOrder[idx] != null)) {
429 if (idx >= newOrder.length) {
431 while (idx >= 0 && (idx >= newOrder.length || newOrder[idx] != null)) {
435 return idx == -1 ? -1 : idx;
438 private void setLanguageLevel(@NotNull ModifiableRootModel modifiableRootModel, E data) {
439 LanguageLevel level = LanguageLevel.parse(data.getSourceCompatibility());
442 modifiableRootModel.getModuleExtension(LanguageLevelModuleExtension.class).setLanguageLevel(level);
444 catch (IllegalArgumentException e) {
450 private void setBytecodeTargetLevel(@NotNull Project project, @NotNull Module module, @NotNull E data) {
451 String targetLevel = data.getTargetCompatibility();
452 if (targetLevel != null) {
453 CompilerConfiguration configuration = CompilerConfiguration.getInstance(project);
454 configuration.setBytecodeTargetLevel(module, targetLevel);