在本文中,我们将为您详细介绍运行shell脚本文件,启动javaapplication的相关知识,并且为您解答关于shell脚本启动java程序的疑问,此外,我们还会提供一些关于com.intelli
在本文中,我们将为您详细介绍运行shell脚本文件,启动java application的相关知识,并且为您解答关于shell脚本启动java程序的疑问,此外,我们还会提供一些关于com.intellij.openapi.application.ApplicationActivationListener的实例源码、com.intellij.openapi.application.ApplicationBundle的实例源码、com.intellij.openapi.application.Application的实例源码、com.intellij.openapi.application.ex.ApplicationUtil的实例源码的有用信息。
本文目录一览:- 运行shell脚本文件,启动java application(shell脚本启动java程序)
- com.intellij.openapi.application.ApplicationActivationListener的实例源码
- com.intellij.openapi.application.ApplicationBundle的实例源码
- com.intellij.openapi.application.Application的实例源码
- com.intellij.openapi.application.ex.ApplicationUtil的实例源码
运行shell脚本文件,启动java application(shell脚本启动java程序)
nohup ./start.sh &
&表示后台运行
com.intellij.openapi.application.ApplicationActivationListener的实例源码
public PlaybackRunner(String script,StatusCallback callback,final boolean useDirectActionCall,boolean stopOnAppDeactivation,boolean useTypingTargets) { myScript = script; myCallback = callback; myUseDirectActionCall = useDirectActionCall; myUseTypingTargets = useTypingTargets; myStopOnAppDeactivation = stopOnAppDeactivation; myAppListener = new ApplicationActivationListener.Adapter() { @Override public void applicationDeactivated(IdeFrame ideFrame) { if (myStopOnAppDeactivation) { myCallback.message(null,"App lost focus,stopping...",StatusCallback.Type.message); stop(); } } }; }
private boolean isAppActive() { Application app = ApplicationManager.getApplication(); if (app != null && myAppListener == null) { myAppListener = new ApplicationActivationListener.Adapter() { @Override public void applicationActivated(IdeFrame ideFrame) { hideProgress(ideFrame.getProject(),myCurrentProcessId); _setokBadge(ideFrame,false); _setTextBadge(ideFrame,null); } }; app.getMessageBus().connect().subscribe(ApplicationActivationListener.TOPIC,myAppListener); } return app != null && app.isActive(); }
public void addRequest(@Nonnull final Runnable request,final int delay,boolean runWithActiveFrameOnly) { if (runWithActiveFrameOnly && !ApplicationManager.getApplication().isActive()) { final MessageBus bus = ApplicationManager.getApplication().getMessageBus(); final MessageBusConnection connection = bus.connect(this); connection.subscribe(ApplicationActivationListener.TOPIC,new ApplicationActivationListener() { @Override public void applicationActivated(IdeFrame ideFrame) { connection.disconnect(); addRequest(request,delay); } }); } else { addRequest(request,delay); } }
public PlaybackRunner(String script,StatusCallback.Type.message); stop(); } } }; }
private void updateConnection() { final ApplicationEx app = ApplicationManagerEx.getApplicationEx(); boolean value = PropertiesComponent.getInstance().getBoolean(KEY); if(value) { myConnection = app.getMessageBus().connect(); myConnection.subscribe(ApplicationActivationListener.TOPIC,myListener); } else { if(myConnection != null) { myConnection.disconnect(); } } }
public void afterValueChanged(RegistryValue value) { if (value.asBoolean()) { ourConnection = app.getMessageBus().connect(); ourConnection.subscribe(ApplicationActivationListener.TOPIC,LISTENER); } else { ourConnection.disconnect(); } }
public void addRequest(@NotNull final Runnable request,new ApplicationActivationListener.Adapter() { @Override public void applicationActivated(IdeFrame ideFrame) { connection.disconnect(); addRequest(request,delay); } }); } else { addRequest(request,delay); } }
public void show(final Component component,int x,int y) { if (!component.isShowing()) { //noinspection HardCodedStringLiteral throw new IllegalArgumentException("component must be shown on the screen"); } removeAll(); // Fill menu. Only after filling menu has non zero size. int x2 = Math.max(0,Math.min(x,component.getWidth() - 1)); // fit x into [0,width-1] int y2 = Math.max(0,Math.min(y,component.getHeight() - 1)); // fit y into [0,height-1] myContext = myDataContextProvider != null ? myDataContextProvider.get() : DataManager.getInstance().getDataContext(component,x2,y2); Utils.fillMenu(myGroup,this,true,myPresentationFactory,myContext,myPlace,false,false); if (getComponentCount() == 0) { return; } if (myApp != null) { if (myApp.isActive()) { Component frame = UIUtil.findUltimateParent(component); if (frame instanceof IdeFrame) { myFrame = (IdeFrame)frame; } myConnection = myApp.getMessageBus().connect(); myConnection.subscribe(ApplicationActivationListener.TOPIC,ActionPopupMenuImpl.this); } } super.show(component,x,y); }
private MountainLionNotifications() { final MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(); connection.subscribe(ApplicationActivationListener.TOPIC,new ApplicationActivationListener.Adapter() { @Override public void applicationActivated(IdeFrame ideFrame) { cleanupDeliverednotifications(); } }); connection.subscribe(AppLifecycleListener.TOPIC,new AppLifecycleListener.Adapter() { @Override public void appClosing() { cleanupDeliverednotifications(); } }); }
private static boolean setActive(Application application,Window window) { IdeFrame ideFrame = getIdeFrameFromWindow(window); state = State.ACTIVE; LOG.debug("The app is in the active state"); if (ideFrame != null) { application.getMessageBus().syncpublisher(ApplicationActivationListener.TOPIC).applicationActivated(ideFrame); return true; } return false; }
/** * Adds IntelliJ listeners including already opened windows and * registers shutdown and debugger listeners. */ public void attachListeners() { WatchDogEventType.START_IDE.process(this); connection.subscribe(ApplicationActivationListener.TOPIC,new IntelliJActivationListener()); activityListener = new GeneralActivityListener(project.getName()); EditorFactory.getInstance().addEditorFactoryListener(editorWindowListener,parent); attachDebuggerListeners(); }
public void afterValueChanged(RegistryValue value) { if (value.asBoolean()) { ourConnection = app.getMessageBus().connect(); ourConnection.subscribe(ApplicationActivationListener.TOPIC,LISTENER); } else { ourConnection.disconnect(); } }
@Override public void show(final Component component,LaterInvocator.isInModalContext()); if (getComponentCount() == 0) { return; } if (myApp != null) { if (myApp.isActive()) { Component frame = UIUtil.findUltimateParent(component); if (frame instanceof IdeFrame) { myFrame = (IdeFrame)frame; } myConnection = myApp.getMessageBus().connect(); myConnection.subscribe(ApplicationActivationListener.TOPIC,ActionPopupMenuImpl.this); } } super.show(component,y); }
private MountainLionNotifications() { final MessageBusConnection connection = ApplicationManager.getApplication().getMessageBus().connect(); connection.subscribe(ApplicationActivationListener.TOPIC,new AppLifecycleListener() { @Override public void appClosing() { cleanupDeliverednotifications(); } }); }
private static boolean setActive(Application application,Window window) { IdeFrame ideFrame = getIdeFrameFromWindow(window); state = State.ACTIVE; LOG.debug("The app is in the active state"); if (ideFrame != null) { application.getMessageBus().syncpublisher(ApplicationActivationListener.TOPIC).applicationActivated(ideFrame); return true; } return false; }
@SuppressWarnings("UnusedParameters") // the dependencies are needed to ensure correct loading order public FocusManagerImpl(ServiceManagerImpl serviceManager,WindowManager wm,UiActivityMonitor monitor) { myApp = ApplicationManager.getApplication(); myQueue = IdeEventQueue.getInstance(); myActivityMonitor = monitor; myFocusedComponentAlarm = new EdtAlarm(); myForcedFocusRequestsAlarm = new EdtAlarm(); myIdleAlarm = new EdtAlarm(); final AppListener myAppListener = new AppListener(); myApp.getMessageBus().connect().subscribe(ApplicationActivationListener.TOPIC,myAppListener); IdeEventQueue.getInstance().adddispatcher(new IdeEventQueue.Eventdispatcher() { @Override public boolean dispatch(AWTEvent e) { if (e instanceof FocusEvent) { final FocusEvent fe = (FocusEvent)e; final Component c = fe.getComponent(); if (c instanceof Window || c == null) return false; Component parent = UIUtil.findUltimateParent(c); if (parent instanceof IdeFrame) { myLastFocused.put((IdeFrame)parent,c); } } else if (e instanceof WindowEvent) { Window wnd = ((WindowEvent)e).getwindow(); if (e.getID() == WindowEvent.WINDOW_CLOSED) { if (wnd instanceof IdeFrame) { myLastFocused.remove(wnd); myLastFocusedAtDeactivation.remove(wnd); } } } return false; } },this); KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertychangelistener("focusedWindow",new Propertychangelistener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getNewValue() instanceof IdeFrame) { myLastFocusedFrame = (IdeFrame)evt.getNewValue(); } } }); }
public ActionCallback run() { myStopRequested = false; myRegistryValues.clear(); final UiActivityMonitor activityMonitor = UiActivityMonitor.getInstance(); activityMonitor.clear(); activityMonitor.setActive(true); myCurrentStageDepth.clear(); myPassedStages.clear(); myContextTimestamp++; ApplicationManager.getApplication().getMessageBus().connect(ApplicationManager.getApplication()).subscribe(ApplicationActivationListener.TOPIC,myAppListener); try { myActionCallback = new ActionCallback(); myActionCallback.doWhenProcessed(new Runnable() { @Override public void run() { stop(); SwingUtilities.invokelater(new Runnable() { @Override public void run() { activityMonitor.setActive(false); restoreRegistryValues(); } }); } }); myRobot = new Robot(); parse(); new Thread("playback runner") { @Override public void run() { if (myUseDirectActionCall) { executeFrom(0,getScriptDir()); } else { IdeEventQueue.getInstance().doWhenReady(new Runnable() { public void run() { executeFrom(0,getScriptDir()); } }); } } }.start(); } catch (AWTException e) { LOG.error(e); } return myActionCallback; }
protected JComponent createCenterPanel() { JPanel panel = new MyPanel(); myUiUpdater = new MergingUpdateQueue("FileChooserUpdater",200,panel); disposer.register(mydisposable,myUiUpdater); new UiNotifyConnector(panel,myUiUpdater); panel.setBorder(JBUI.Borders.empty()); createTree(); final DefaultActionGroup group = createActionGroup(); ActionToolbar toolBar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNowN,group,true); toolBar.setTargetComponent(panel); final JPanel toolbarPanel = new JPanel(new BorderLayout()); toolbarPanel.add(toolBar.getComponent(),BorderLayout.CENTER); myTextFieldAction = new TextFieldAction() { public void linkSelected(final LinkLabel aSource,final Object aLinkData) { toggleshowtextField(); } }; toolbarPanel.add(myTextFieldAction,BorderLayout.EAST); JPanel extraToolbarPanel = createExtraToolbarPanel(); if(extraToolbarPanel != null){ toolbarPanel.add(extraToolbarPanel,BorderLayout.soUTH); } myPathTextFieldWrapper = new JPanel(new BorderLayout()); myPathTextFieldWrapper.setBorder(JBUI.Borders.emptyBottom(2)); myPathTextField = new FileTextFieldImpl.Vfs( FileChooserFactoryImpl.getMacroMap(),getdisposable(),new LocalFsFinder.FileChooserFilter(myChooserDescriptor,myFileSystemTree)) { protected void onTextChanged(final String newValue) { myUiUpdater.cancelAllUpdates(); updateTreeFromPath(newValue); } }; disposer.register(mydisposable,myPathTextField); myPathTextFieldWrapper.add(myPathTextField.getField(),BorderLayout.CENTER); if (getRecentFiles().length > 0) { myPathTextFieldWrapper.add(createHistoryButton(),BorderLayout.EAST); } mynorthPanel = new JPanel(new BorderLayout()); mynorthPanel.add(toolbarPanel,BorderLayout.norTH); updateTextFieldShowing(); panel.add(mynorthPanel,BorderLayout.norTH); registerMouseListener(group); JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myFileSystemTree.getTree()); //scrollPane.setBorder(BorderFactory.createLineBorder(new Color(148,154,156))); panel.add(scrollPane,BorderLayout.CENTER); panel.setPreferredSize(JBUI.size(400)); panel.add(new JLabel(DRAG_N_DROP_HINT,SwingConstants.CENTER),BorderLayout.soUTH); ApplicationManager.getApplication().getMessageBus().connect(getdisposable()) .subscribe(ApplicationActivationListener.TOPIC,new ApplicationActivationListener.Adapter() { @Override public void applicationActivated(IdeFrame ideFrame) { DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_MODAL,new Runnable() { @Override public void run() { ((SaveAndSyncHandlerImpl)SaveAndSyncHandler.getInstance()).maybeRefresh(ModalityState.current()); } }); } }); return panel; }
@SuppressWarnings("UnusedParameters") // the dependencies are needed to ensure correct loading order public FocusManagerImpl(ServiceManagerImpl serviceManager,UiActivityMonitor monitor) { myApp = ApplicationManager.getApplication(); myQueue = IdeEventQueue.getInstance(); myActivityMonitor = monitor; myFocusedComponentAlaram = new EdtAlarm(); myForcedFocusRequestsAlarm = new EdtAlarm(); myIdleAlarm = new EdtAlarm(); final AppListener myAppListener = new AppListener(); myApp.getMessageBus().connect().subscribe(ApplicationActivationListener.TOPIC,myAppListener); IdeEventQueue.getInstance().adddispatcher(new IdeEventQueue.Eventdispatcher() { public boolean dispatch(AWTEvent e) { if (e instanceof FocusEvent) { final FocusEvent fe = (FocusEvent)e; final Component c = fe.getComponent(); if (c instanceof Window || c == null) return false; Component parent = SwingUtilities.getwindowAncestor(c); if (parent instanceof IdeFrame) { myLastFocused.put((IdeFrame)parent,new WeakReference<Component>(c)); } } else if (e instanceof WindowEvent) { Window wnd = ((WindowEvent)e).getwindow(); if (e.getID() == WindowEvent.WINDOW_CLOSED) { if (wnd instanceof IdeFrame) { myLastFocused.remove((IdeFrame)wnd); myLastFocusedAtDeactivation.remove((IdeFrame)wnd); } } } return false; } },new Propertychangelistener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getNewValue() instanceof IdeFrame) { myLastFocusedFrame = (IdeFrame)evt.getNewValue(); } } }); }
public ActionCallback run() { myStopRequested = false; myRegistryValues.clear(); final UiActivityMonitor activityMonitor = UiActivityMonitor.getInstance(); activityMonitor.clear(); activityMonitor.setActive(true); myCurrentStageDepth.clear(); myPassedStages.clear(); myContextTimestamp++; ApplicationManager.getApplication().getMessageBus().connect(myOnStop).subscribe(ApplicationActivationListener.TOPIC,myAppListener); try { myActionCallback = new ActionCallback(); myActionCallback.doWhenProcessed(new Runnable() { @Override public void run() { stop(); SwingUtilities.invokelater(new Runnable() { @Override public void run() { activityMonitor.setActive(false); restoreRegistryValues(); } }); } }); myRobot = new Robot(); parse(); new Thread() { @Override public void run() { if (myUseDirectActionCall) { executeFrom(0,getScriptDir()); } }); } } }.start(); } catch (AWTException e) { LOG.error(e); } return myActionCallback; }
@SuppressWarnings("UnusedParameters") // the dependencies are needed to ensure correct loading order public FocusManagerImpl(ServiceManagerImpl serviceManager,UiActivityMonitor monitor) { myApp = ApplicationManager.getApplication(); myQueue = IdeEventQueue.getInstance(); myActivityMonitor = monitor; myFocusedComponentAlarm = new EdtAlarm(); myForcedFocusRequestsAlarm = new EdtAlarm(); final AppListener myAppListener = new AppListener(); myApp.getMessageBus().connect().subscribe(ApplicationActivationListener.TOPIC,myAppListener); IdeEventQueue.getInstance().adddispatcher(e -> { if (e instanceof FocusEvent) { final FocusEvent fe = (FocusEvent)e; final Component c = fe.getComponent(); if (c instanceof Window || c == null) return false; Component parent = UIUtil.findUltimateParent(c); if (parent instanceof IdeFrame) { myLastFocused.put((IdeFrame)parent,c); } } else if (e instanceof WindowEvent) { Window wnd = ((WindowEvent)e).getwindow(); if (e.getID() == WindowEvent.WINDOW_CLOSED) { if (wnd instanceof IdeFrame) { myLastFocused.remove(wnd); myLastFocusedAtDeactivation.remove(wnd); } } } return false; },new Propertychangelistener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getNewValue() instanceof IdeFrame) { myLastFocusedFrame = (IdeFrame)evt.getNewValue(); } } }); }
public ActionCallback run() { myStopRequested = false; myRegistryValues.clear(); final UiActivityMonitor activityMonitor = UiActivityMonitor.getInstance(); activityMonitor.clear(); activityMonitor.setActive(true); myCurrentStageDepth.clear(); myPassedStages.clear(); myContextTimestamp++; ApplicationManager.getApplication().getMessageBus().connect(myOnStop).subscribe(ApplicationActivationListener.TOPIC,getScriptDir()); } }); } } }.start(); } catch (AWTException e) { LOG.error(e); } return myActionCallback; }
public FocusDrawer() { super("focus debugger"); Application app = ApplicationManager.getApplication(); app.getMessageBus().connect().subscribe(ApplicationActivationListener.TOPIC,this); }
protected JComponent createCenterPanel() { JPanel panel = new MyPanel(); myUiUpdater = new MergingUpdateQueue("FileChooserUpdater",BorderLayout.EAST); JPanel extraToolbarPanel = createExtraToolbarPanel(); if (extraToolbarPanel != null) { toolbarPanel.add(extraToolbarPanel,BorderLayout.soUTH); } myPathTextFieldWrapper = new JPanel(new BorderLayout()); myPathTextFieldWrapper.setBorder(JBUI.Borders.emptyBottom(2)); myPathTextField = new FileTextFieldImpl.Vfs(FileChooserFactoryImpl.getMacroMap(),BorderLayout.CENTER); panel.setPreferredSize(JBUI.size(400)); JLabel hintLabel = new JLabel(DRAG_N_DROP_HINT,SwingConstants.CENTER); hintLabel.setForeground(JBColor.gray); hintLabel.setFont(JBUI.Fonts.smallFont()); panel.add(hintLabel,BorderLayout.soUTH); ApplicationManager.getApplication().getMessageBus().connect(getdisposable()) .subscribe(ApplicationActivationListener.TOPIC,new ApplicationActivationListener() { @Override public void applicationActivated(IdeFrame ideFrame) { ((SaveAndSyncHandlerImpl)SaveAndSyncHandler.getInstance()).maybeRefresh(ModalityState.current()); } }); return panel; }
com.intellij.openapi.application.ApplicationBundle的实例源码
private void onSaveAs() { if (mySchemesTableModel.isProjectScheme(getSelectedScheme())) { int rowToSelect = mySchemesTableModel.exportProjectScheme(); if (rowToSelect > 0) { mySchemesTable.getSelectionModel().setSelectionInterval(rowToSelect,rowToSelect); } } else { CodeStyleScheme[] schemes = CodeStyleSchemes.getInstance().getSchemes(); ArrayList<String> names = new ArrayList<String>(); for (CodeStyleScheme scheme : schemes) { names.add(scheme.getName()); } String selectedname = getSelectedScheme().getName(); SaveSchemeDialog saveDialog = new SaveSchemeDialog(myParent,ApplicationBundle.message("title.save.code.style.scheme.as"),names,selectedname); if (saveDialog.showAndGet()) { int row = mySchemesTableModel.createNewScheme(getSelectedScheme(),saveDialog.getSchemeName()); mySchemesTable.getSelectionModel().setSelectionInterval(row,row); } } }
protected void initTables() { initBooleanField("JD_ALIGN_ParaM_COMMENTS",ApplicationBundle.message("checkBox.align.parameter.descriptions"),ALIGNMENT_GROUP); initBooleanField("JD_ALIGN_EXCEPTION_COMMENTS",ApplicationBundle.message("checkBox.align.thrown.exception.descriptions"),ALIGNMENT_GROUP); initBooleanField("JD_ADD_BLANK_AFTER_DESCRIPTION",ApplicationBundle.message("checkBox.after.description"),BLANK_LInes_GROUP); initBooleanField("JD_ADD_BLANK_AFTER_PARM_COMMENTS",ApplicationBundle.message("checkBox.after.parameter.descriptions"),BLANK_LInes_GROUP); initBooleanField("JD_ADD_BLANK_AFTER_RETURN",ApplicationBundle.message("checkBox.after.return.tag"),BLANK_LInes_GROUP); initBooleanField("JD_KEEP_INVALID_TAGS",ApplicationBundle.message("checkBox.keep.invalid.tags"),INVALID_TAGS_GROUP); initBooleanField("JD_KEEP_EMPTY_ParaMETER",ApplicationBundle.message("checkBox.keep.empty.param.tags"),INVALID_TAGS_GROUP); initBooleanField("JD_KEEP_EMPTY_RETURN",ApplicationBundle.message("checkBox.keep.empty.return.tags"),INVALID_TAGS_GROUP); initBooleanField("JD_KEEP_EMPTY_EXCEPTION",ApplicationBundle.message("checkBox.keep.empty.throws.tags"),INVALID_TAGS_GROUP); initBooleanField("JD_LEADING_ASTERISKS_ARE_ENABLED",ApplicationBundle.message("checkBox.enable.leading.asterisks"),OTHER_GROUP); initBooleanField("JD_USE_THROWS_NOT_EXCEPTION",ApplicationBundle.message("checkBox.use.throws.rather.than.exception"),OTHER_GROUP); initBooleanField("WRAP_COMMENTS",ApplicationBundle.message("checkBox.wrap.at.right.margin"),OTHER_GROUP); initBooleanField("JD_P_AT_EMPTY_LInes",ApplicationBundle.message("checkBox.generate.p.on.empty.lines"),OTHER_GROUP); initBooleanField("JD_KEEP_EMPTY_LInes",ApplicationBundle.message("checkBox.keep.empty.lines"),OTHER_GROUP); initBooleanField("JD_DO_NOT_WRAP_ONE_LINE_COMMENTS",ApplicationBundle.message("checkBox.do.not.wrap.one.line.comments"),OTHER_GROUP); initBooleanField("JD_PRESERVE_LINE_FeedS",ApplicationBundle.message("checkBox.preserve.line.Feeds"),OTHER_GROUP); initBooleanField("JD_ParaM_DESCRIPTION_ON_NEW_LINE",ApplicationBundle.message("checkBox.param.description.on.new.line"),OTHER_GROUP); }
@Nullable private static NotificationLabels getNotificationLabels(@NotNull CommonCodeStyleSettings.IndentOptions userOptions,@NotNull CommonCodeStyleSettings.IndentOptions detectedOptions) { if (userOptions.USE_TAB_CHaraCTER) { if (!detectedOptions.USE_TAB_CHaraCTER) { return new NotificationLabels(ApplicationBundle.message("code.style.space.indent.detected",detectedOptions.INDENT_SIZE),ApplicationBundle.message("code.style.detector.use.tabs")); } } else { String restoretoSpaces = ApplicationBundle.message("code.style.detector.use.spaces",userOptions.INDENT_SIZE); if (detectedOptions.USE_TAB_CHaraCTER) { return new NotificationLabels(ApplicationBundle.message("code.style.tab.usage.detected",userOptions.INDENT_SIZE),restoretoSpaces); } if (userOptions.INDENT_SIZE != detectedOptions.INDENT_SIZE) { return new NotificationLabels(ApplicationBundle.message("code.style.different.indent.size.detected",detectedOptions.INDENT_SIZE,restoretoSpaces); } } return null; }
public void editMacro() { if (getSelectedRowCount() != 1) { return; } final int selectedRow = getSelectedRow(); final Couple<String> pair = myMacros.get(selectedRow); final String title = ApplicationBundle.message("title.edit.variable"); final String macroName = pair.getFirst(); final PathMacroEditor macroEditor = new PathMacroEditor(title,macroName,pair.getSecond(),new EditValidator()); if (macroEditor.showAndGet()) { myMacros.remove(selectedRow); myMacros.add(Couple.of(macroEditor.getName(),macroEditor.getValue())); Collections.sort(myMacros,MACRO_COMParaTOR); myTableModel.fireTableDataChanged(); } }
@Override protected JComponent createnorthPanel() { JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; gc.weightx = 0; gc.insets = new Insets(5,5,5); panel.add(new JLabel(ApplicationBundle.message("label.name")),gc); gc = new GridBagConstraints(); gc.gridx = 1; gc.gridy = 0; gc.weightx = 1; gc.fill = GridBagConstraints.HORIZONTAL; gc.gridwidth = 2; gc.insets = new Insets(0,0); panel.add(mySchemeName,gc); panel.setPreferredSize(JBUI.size(220,40)); return panel; }
@Override protected void doOKAction() { if (getSchemeName().trim().isEmpty()) { Messages.showMessageDialog(getContentPane(),ApplicationBundle.message("error.scheme.must.have.a.name"),CommonBundle.getErrorTitle(),Messages.getErrorIcon()); return; } else if ("default".equals(getSchemeName())) { Messages.showMessageDialog(getContentPane(),ApplicationBundle.message("error.illegal.scheme.name"),Messages.getErrorIcon()); return; } else if (myExistingNames.contains(getSchemeName())) { Messages.showMessageDialog( getContentPane(),ApplicationBundle.message("error.a.scheme.with.this.name.already.exists.or.was.deleted.without.applying.the.changes"),Messages.getErrorIcon() ); return; } super.doOKAction(); }
@Override public void actionPerformed(@NotNull AnActionEvent event) { if (!isAvailable()) return; Project project = event.getProject(); CreateDesktopEntryDialog dialog = new CreateDesktopEntryDialog(project); if (!dialog.showAndGet()) { return; } final boolean globalEntry = dialog.myGlobalEntryCheckBox.isSelected(); ProgressManager.getInstance().run(new Task.Backgroundable(project,ApplicationBundle.message("desktop.entry.title")) { @Override public void run(@NotNull ProgressIndicator indicator) { createDesktopEntry(getProject(),indicator,globalEntry); } }); }
@Override public void actionPerformed(AnActionEvent e) { new Thread("show delayed msg") { @Override public void run() { super.run(); //noinspection EmptyCatchBlock TimeoutUtil.sleep(3000); //noinspection SSBasedinspection SwingUtilities.invokelater(new Runnable() { @Override public void run() { MessageDialogBuilder.yesNo("nothing happens after that","Some message goes here").yesText( ApplicationBundle.message("command.exit")).noText( CommonBundle.message("button.cancel")).show(); } }); } }.start(); }
@Nullable protected String validate(int index) { if (myRulesModel.getSize() < index) { return null; } final Object target = myRulesModel.getElementAt(index); if (target instanceof StdArrangementMatchRule) { for (int i = 0; i < index; i++) { final Object element = myRulesModel.getElementAt(i); if (element instanceof StdArrangementMatchRule && target.equals(element)) { return ApplicationBundle.message("arrangement.settings.validation.duplicate.matching.rule"); } } } return null; }
public ArrangementRuleAliasDialog(@Nullable Project project,@NotNull ArrangementStandardSettingsManager settingsManager,@NotNull ArrangementColorsProvider colorsProvider,@NotNull Collection<StdArrangementRuleAliasToken> tokens,@NotNull Set<String> tokensInUse) { super(project,false); final List<StdArrangementRuleAliasToken> tokenList = ContainerUtil.newArrayList(tokens); myEditor = new ArrangementRuleAliasesListEditor(settingsManager,colorsProvider,tokenList,tokensInUse); if (!tokenList.isEmpty()) { myEditor.selectItem(tokenList.get(0)); } setTitle(ApplicationBundle.message("arrangement.settings.section.rule.custom.token.title")); init(); }
public ArrangementGroupingRulesPanel(@NotNull ArrangementStandardSettingsManager settingsManager,@NotNull ArrangementColorsProvider colorsProvider) { super(new GridBagLayout()); myControl = new ArrangementGroupingRulesControl(settingsManager,colorsProvider); TitleWithToolbar top = new TitleWithToolbar( ApplicationBundle.message("arrangement.settings.section.groups"),ArrangementConstants.ACTION_GROUP_GROUPING_RULES_CONTROL_TOOLBAR,ArrangementConstants.GROUPING_RULES_CONTROL_TOOLBAR_PLACE,myControl ); add(top,new GridBag().coverLine().fillCellHorizontally().weightx(1)); add(myControl,new GridBag().fillCell().weightx(1).weighty(1).insets(0,ArrangementConstants.HORIZONTAL_PADDING,0)); }
@Override public void searchResultsUpdated(SearchResults sr) { if (myComponent.getSearchTextComponent().getText().isEmpty()) { updateUIWithEmptyResults(); } else { int matches = sr.getMatchesCount(); boolean tooManyMatches = matches > mySearchResults.getMatchesLimit(); myComponent.setStatusText(tooManyMatches ? ApplicationBundle.message("editorsearch.toomuch",mySearchResults.getMatchesLimit()) : ApplicationBundle.message("editorsearch.matches",matches)); myClickToHighlightLabel.setVisible(tooManyMatches); if (!tooManyMatches && matches <= 0) { myComponent.setNotFoundBackground(); } else { myComponent.setRegularBackground(); } } myComponent.updateActions(); }
@Override public void customize(JList list,Integer value,int index,boolean selected,boolean hasFocus) { int tabPlacement = value.intValue(); String text; if (UISettings.TABS_NONE == tabPlacement) { text = ApplicationBundle.message("comboBox.tab.placement.none"); } else if (SwingConstants.TOP == tabPlacement) { text = ApplicationBundle.message("comboBox.tab.placement.top"); } else if (SwingConstants.LEFT == tabPlacement) { text = ApplicationBundle.message("comboBox.tab.placement.left"); } else if (SwingConstants.BottOM == tabPlacement) { text = ApplicationBundle.message("comboBox.tab.placement.bottom"); } else if (SwingConstants.RIGHT == tabPlacement) { text = ApplicationBundle.message("comboBox.tab.placement.right"); } else { throw new IllegalArgumentException("unkNown tabPlacement: " + tabPlacement); } setText(text); }
@Override protected void init() { super.init(); myEnableCheckBox = new JCheckBox(ApplicationBundle.message("checkBox.enable.javadoc.formatting")); myEnableCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); } }); myPanel.setBorder(new CustomLineBorder(OnePixelDivider.BACKGROUND,1,0)); myJavaDocPanel.add(BorderLayout.CENTER,myPanel); myJavaDocPanel.add(myEnableCheckBox,BorderLayout.norTH); }
protected void addComponents() { super.addComponents(); myLabelIndent = new JTextField(4); add(myLabelIndentLabel = new JLabel(ApplicationBundle.message("editBox.indent.label.indent")),myLabelIndent); myLabelIndentAbsolute = new JCheckBox(ApplicationBundle.message("checkBox.indent.absolute.label.indent")); add(myLabelIndentAbsolute,true); myCbDontIndentTopLevelMembers = new JCheckBox(ApplicationBundle.message("checkBox.do.not.indent.top.level.class.members")); add(myCbDontIndentTopLevelMembers); myCbUseRelativeIndent = new JCheckBox(ApplicationBundle.message("checkBox.use.relative.indents")); add(myCbUseRelativeIndent); }
private void composePanel() { myPanel = new JPanel(new GridBagLayout()); myComboBox = new ComboBox(); for (QualifyJavadocoptions options : QualifyJavadocoptions.values()) { myComboBox.addItem(options); } myComboBox.setRenderer(new ListCellRendererWrapper() { @Override public void customize(final JList list,final Object value,final int index,final boolean selected,final boolean hasFocus) { if (value instanceof QualifyJavadocoptions) { setText(((QualifyJavadocoptions)value).getPresentableText()); } } }); JLabel title = new JLabel(ApplicationBundle.message("radio.use.fully.qualified.class.names.in.javadoc")); myPanel.setBorder(BorderFactory.createEmptyBorder(5,0)); GridBagConstraints left = new GridBagConstraints(); left.anchor = GridBagConstraints.WEST; GridBagConstraints right = new GridBagConstraints(); right.anchor = GridBagConstraints.WEST; right.weightx = 1.0; right.insets = new Insets(0,0); myPanel.add(title,left); myPanel.add(myComboBox,right); }
private JPanel createGeneralOptionsPanel() { OptionGroup group = new OptionGroup(ApplicationBundle.message("title.general")); myCbUseSingleClassImports = new JCheckBox(ApplicationBundle.message("checkBox.use.single.class.import")); group.add(myCbUseSingleClassImports); myCbUseFQClassNames = new JCheckBox(ApplicationBundle.message("checkBox.use.fully.qualified.class.names")); group.add(myCbUseFQClassNames); myCbInsertInnerClassImports = new JCheckBox(ApplicationBundle.message("checkBox.insert.imports.for.inner.classes")); group.add(myCbInsertInnerClassImports); myFqnInJavadocoption = new FullyQualifiednamesInJavadocoptionProvider(mySettings); group.add(myFqnInJavadocoption.getPanel()); myClassCountField = new JTextField(3); myNamesCountField = new JTextField(3); final JPanel panel = new JPanel(new GridBagLayout()); panel.add(new JLabel(ApplicationBundle.message("editBox.class.count.to.use.import.with.star")),new GridBagConstraints(0,GridBagConstraints.RELATIVE,0.0,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(0,3,0),0)); panel.add(myClassCountField,new GridBagConstraints(1,1.0,0)); panel.add(new JLabel(ApplicationBundle.message("editBox.names.count.to.use.static.import.with.star")),0)); panel.add(myNamesCountField,0)); group.add(panel); return group.createPanel(); }
@Override protected String getActionText(final AnActionEvent e) { String text = ApplicationBundle.message("action.add"); if (e.getPresentation().isEnabled()) { final DomElementsGroupNode selectednode = getDomElementsGroupNode(getTreeView(e)); if (selectednode != null) { final Type type = selectednode.getChildDescription().getType(); text += " " + TypePresentationService.getService().getTypePresentableName(ReflectionUtil.getRawType(type)); } } return text; }
public JavaCodeFoldingOptionsprovider() { super(JavaCodeFoldingSettings.getInstance()); checkBox("INLINE_ParaMETER_NAMES_FOR_LIteraL_CALL_ARGUMENTS",ApplicationBundle.message("checkBox.collapse.boolean.parameters")); checkBox("COLLAPSE_ONE_LINE_METHODS",ApplicationBundle.message("checkBox.collapse.one.line.methods")); checkBox("COLLAPSE_ACCESSORS",ApplicationBundle.message("checkBox.collapse.simple.property.accessors")); checkBox("COLLAPSE_INNER_CLASSES",ApplicationBundle.message("checkBox.collapse.inner.classes")); checkBox("COLLAPSE_ANONYMOUS_CLASSES",ApplicationBundle.message("checkBox.collapse.anonymous.classes")); checkBox("COLLAPSE_ANNOTATIONS",ApplicationBundle.message("checkBox.collapse.annotations")); checkBox("COLLAPSE_CLOSURES",ApplicationBundle.message("checkBox.collapse.closures")); checkBox("COLLAPSE_CONSTRUCTOR_GENERIC_ParaMETERS",ApplicationBundle.message("checkBox.collapse.generic.constructor.parameters")); checkBox("COLLAPSE_I18N_MESSAGES",ApplicationBundle.message("checkBox.collapse.i18n.messages")); checkBox("COLLAPSE_SUPPRESS_WARNINGS",ApplicationBundle.message("checkBox.collapse.suppress.warnings")); checkBox("COLLAPSE_END_OF_LINE_COMMENTS",ApplicationBundle.message("checkBox.collapse.end.of.line.comments")); }
@Override public JComponent createComponent() { mySuppressWay = new JCheckBox(ApplicationBundle.message("checkBox.suppress.with.suppresswarnings")); final JPanel panel = new JPanel(new BorderLayout()); panel.add(mySuppressWay,BorderLayout.WEST); return panel; }
@NotNull @Override public JComponent createComponent() { if (myJdkPanel == null) { myJdkPanel = new JPanel(new GridBagLayout()); myCbProjectJdk = new JdkComboBox(myJdksModel); myCbProjectJdk.insertItemAt(new JdkComboBox.NoneJdkComboBoxItem(),0); myCbProjectJdk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (myFreeze) return; myJdksModel.setProjectSdk(myCbProjectJdk.getSelectedJdk()); clearCaches(); } }); myJdkPanel.add(new JLabel(ProjectBundle.message("module.libraries.target.jdk.project.radio")),GridBagConstraints.norTHWEST,4,0)); myJdkPanel.add(myCbProjectJdk,0)); final JButton setUpButton = new JButton(ApplicationBundle.message("button.new")); myCbProjectJdk.setSetupButton(setUpButton,myProject,myJdksModel,new JdkComboBox.NoneJdkComboBoxItem(),null,false); myJdkPanel.add(setUpButton,0)); final JButton editButton = new JButton(ApplicationBundle.message("button.edit")); myCbProjectJdk.setEditButton(editButton,new Computable<Sdk>() { @Override @Nullable public Sdk compute() { return myJdksModel.getProjectSdk(); } }); myJdkPanel.add(editButton,new GridBagConstraints(GridBagConstraints.RELATIVE,0)); } return myJdkPanel; }
public void addMacro() { final String title = ApplicationBundle.message("title.add.variable"); final PathMacroEditor macroEditor = new PathMacroEditor(title,"",new AddValidator(title)); if (macroEditor.showAndGet()) { final String name = macroEditor.getName(); myMacros.add(Couple.of(name,MACRO_COMParaTOR); final int index = indexOfMacroWithName(name); LOG.assertTrue(index >= 0); myTableModel.fireTableDataChanged(); setRowSelectionInterval(index,index); } }
public String getColumnName(int columnIndex) { switch (columnIndex) { case NAME_COLUMN: return ApplicationBundle.message("column.name"); case VALUE_COLUMN: return ApplicationBundle.message("column.value"); } return null; }
public boolean isOK(String name,String value) { if(name.length() == 0) return false; if (hasMacroWithName(name)) { Messages.showErrorDialog(PathMacroTable.this,ApplicationBundle.message("error.variable.already.exists",name),myTitle); return false; } return true; }
@Override public void initialize(@NotNull ManagingFS managingFS,@NotNull FileWatcherNotificationSink notificationSink) { myManagingFS = managingFS; myNotificationSink = notificationSink; boolean disabled = Boolean.parseBoolean(System.getProperty(PROPERTY_WATCHER_disABLED)); myExecutable = getExecutable(); if (disabled) { LOG.info("Native file watcher is disabled"); } else if (myExecutable == null) { LOG.info("Native file watcher is not supported on this platform"); } else if (!myExecutable.exists()) { notifyOnFailure(ApplicationBundle.message("watcher.exe.not.found"),null); } else if (!myExecutable.canExecute()) { notifyOnFailure(ApplicationBundle.message("watcher.exe.not.exe",myExecutable),new NotificationListener() { @Override public void hyperlinkUpdate(@NotNull Notification notification,@NotNull HyperlinkEvent event) { ShowFilePathAction.openFile(myExecutable); } }); } else { try { startupProcess(false); LOG.info("Native file watcher is operational."); } catch (IOException e) { LOG.warn(e.getMessage()); notifyOnFailure(ApplicationBundle.message("watcher.Failed.to.start"),null); } } }
private void startupProcess(boolean restart) throws IOException { if (myIsShuttingDown) { return; } if (ShutDownTracker.isShutdownHookRunning()) { myIsShuttingDown = true; return; } if (myStartAttemptCount++ > MAX_PROCESS_LAUNCH_ATTEMPT_COUNT) { notifyOnFailure(ApplicationBundle.message("watcher.Failed.to.start"),null); return; } if (restart) { shutdownProcess(); } LOG.info("Starting file watcher: " + myExecutable); ProcessBuilder processBuilder = new ProcessBuilder(myExecutable.getAbsolutePath()); Process process = processBuilder.start(); myProcessHandler = new MyProcessHandler(process); myProcessHandler.addProcessListener(new MyProcessAdapter()); myProcessHandler.startNotify(); if (restart) { List<String> recursive = myRecursiveWatchRoots; List<String> flat = myFlatWatchRoots; if (recursive.size() + flat.size() > 0) { setWatchRoots(recursive,flat,true); } } }
public void notifyOnFailure(final String cause,@Nullable final NotificationListener listener) { LOG.warn(cause); if (myFailureShownToTheUser.compareAndSet(false,true)) ApplicationManager.getApplication().invokelater(new Runnable() { @Override public void run() { String title = ApplicationBundle.message("watcher.slow.sync"); Notifications.Bus.notify(NOTIFICATION_GROUP.getValue().createNotification(title,cause,NotificationType.WARNING,listener)); } },ModalityState.NON_MODAL); }
public void deleteElement(@NotNull DataContext dataContext) { final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext); if (files == null || files.length == 0) return; Project project = CommonDataKeys.PROJECT.getData(dataContext); String message = createConfirmationMessage(files); int returnValue = Messages.showOkCancelDialog(message,UIBundle.message("delete.dialog.title"),ApplicationBundle.message("button.delete"),CommonBundle.getCancelButtonText(),Messages.getQuestionIcon()); if (returnValue != Messages.OK) return; Arrays.sort(files,FileComparator.getInstance()); final List<String> problems = ContainerUtil.newLinkedList(); new WriteCommandAction.Simple(project) { @Override protected void run() throws Throwable { for (final VirtualFile file : files) { try { file.delete(this); } catch (IOException e) { LOG.info(e); problems.add(file.getName()); } } } }.execute(); if (!problems.isEmpty()) { reportDeletionProblem(problems); } }
private void updateState() { if (!myFailureDetected) { try { // This might not work in all cases,but hopefully is a more reliable method than the current one (checking for font smoothing) // see https://msdn.microsoft.com/en-us/library/aa380798%28v=vs.85%29.aspx boolean newValue = User32.INSTANCE.GetSystemMetrics(0x1000) != 0; // 0x1000 is SM_REMOTESESSION LOG.debug("Detected remote desktop: ",newValue); if (newValue != myRemoteDesktopConnected) { myRemoteDesktopConnected = newValue; if (myRemoteDesktopConnected) { // We postpone notification to avoid recursive initialization of RemoteDesktopDetector // (in case it's initialized by request from com.intellij.notification.EventLog) ApplicationManager.getApplication().invokelater(new Runnable() { public void run() { Notifications.Bus.notify(new Notification(Notifications.SYstem_MESSAGES_GROUP_ID,ApplicationBundle.message("remote.desktop.detected.title"),ApplicationBundle .message("remote.desktop.detected.message"),NotificationType.informatION)); } }); } } } catch (Throwable e) { myRemoteDesktopConnected = false; myFailureDetected = true; LOG.warn("Error while calling GetSystemMetrics",e); } } }
private static void install(File entryFile,boolean globalEntry) throws IOException,ExecutionException { if (globalEntry) { String prompt = ApplicationBundle.message("desktop.entry.sudo.prompt"); exec(new GeneralCommandLine("xdg-desktop-menu","install","--mode","system",entryFile.getAbsolutePath()),prompt); exec(new GeneralCommandLine("xdg-desktop-menu","forceupdate","system"),prompt); } else { exec(new GeneralCommandLine("xdg-desktop-menu","user",null); exec(new GeneralCommandLine("xdg-desktop-menu","user"),null); } }
protected CreateLauncherScriptDialog(Project project) { super(project); init(); setTitle(ApplicationBundle.message("launcher.script.title")); String productName = ApplicationNamesInfo.getInstance().getProductName(); myTitle.setText(myTitle.getText().replace("$APP_NAME$",productName)); myNameField.setText(defaultScriptName()); }
@Override public Map<String,Set<String>> findPossibleExtension(@NotNull String prefix,final Project project) { loadHugeFilesIfNecessary(); final boolean perProject = CodeStyleFacade.getInstance(project).projectUsesOwnSettings(); final Map<String,Set<String>> result = new THashMap<String,Set<String>>(); int count = 0; final Set<String> prefixes = getProcessedWordsWithoutstemming(prefix); for (String opt : prefixes) { Set<OptionDescription> configs = getAcceptableDescriptions(opt); if (configs == null) continue; for (OptionDescription description : configs) { String groupName = description.getGroupName(); if (perProject) { if (Comparing.strEqual(groupName,ApplicationBundle.message("title.global.code.style"))) { groupName = ApplicationBundle.message("title.project.code.style"); } } else { if (Comparing.strEqual(groupName,ApplicationBundle.message("title.project.code.style"))) { groupName = ApplicationBundle.message("title.global.code.style"); } } Set<String> foundHits = result.get(groupName); if (foundHits == null) { foundHits = new THashSet<String>(); result.put(groupName,foundHits); } foundHits.add(description.getHit()); count++; } } if (count > LOAD_FACTOR) { result.clear(); } return result; }
@Override protected void addTabOptions() { super.addTabOptions(); myCbSmartTabs = new JCheckBox(ApplicationBundle.message("checkBox.indent.smart.tabs")); add(myCbSmartTabs,true); }
@Override protected void addComponents() { super.addComponents(); myContinuationIndentField = createIndentTextField(); myContinuationIndentLabel = new JLabel(ApplicationBundle.message("editBox.indent.continuation.indent")); add(myContinuationIndentLabel,myContinuationIndentField); myCbKeepIndentsOnEmptyLines = new JCheckBox(ApplicationBundle.message("checkBox.indent.keep.indents.on.empty.lines")); add(myCbKeepIndentsOnEmptyLines); }
@Override public void setEnabled(final boolean enabled) { super.setEnabled(enabled); boolean smartTabsChecked = enabled && myCbUseTab.isSelected(); boolean smartTabsValid = smartTabsChecked && isSmartTabValid(getUIIndent(),getUITabSize()); myCbSmartTabs.setEnabled(smartTabsValid); myCbSmartTabs.setToolTipText( smartTabsChecked && !smartTabsValid ? ApplicationBundle.message("tooltip.indent.must.be.multiple.of.tab.size.for.smart.tabs.to.operate") : null); myContinuationIndentField.setEnabled(enabled); myContinuationIndentLabel.setEnabled(enabled); }
private JComponent createSettingsPanel() { JPanel result = new JPanel(new FlowLayout(FlowLayout.RIGHT,0)); result.add(new JLabel(ApplicationBundle.message("label.font.size"))); myFontSizeSlider = new JSlider(SwingConstants.HORIZONTAL,FontSize.values().length - 1,3); myFontSizeSlider.setMinorTickSpacing(1); myFontSizeSlider.setPaintTicks(true); myFontSizeSlider.setPaintTrack(true); myFontSizeSlider.setSnapToTicks(true); UIUtil.setSliderIsFilled(myFontSizeSlider,true); result.add(myFontSizeSlider); result.setBorder(BorderFactory.createLineBorder(JBColor.border(),1)); myFontSizeSlider.addchangelistener(new changelistener() { @Override public void stateChanged(ChangeEvent e) { if (myIgnoreFontSizeSliderChange) { return; } EditorColorsManager colorsManager = EditorColorsManager.getInstance(); EditorColoRSScheme scheme = colorsManager.getGlobalScheme(); scheme.setQuickDocFontSize(FontSize.values()[myFontSizeSlider.getValue()]); applyFontSize(); } }); String tooltipText = ApplicationBundle.message("quickdoc.tooltip.font.size.by.wheel"); result.setToolTipText(tooltipText); myFontSizeSlider.setToolTipText(tooltipText); result.setVisible(false); result.setopaque(true); myFontSizeSlider.setopaque(true); return result; }
@Override public boolean iteration() { if (myStopformatting) { return true; } if (!myFilesCountingFinished) { updateIndicatorText(ApplicationBundle.message("bulk.reformat.prepare.progress.text"),""); countingIteration(); return true; } updateIndicatorFraction(myFilesProcessed); if (myfiletreeIterator.hasNext()) { final PsiFile file = myfiletreeIterator.next(); myFilesProcessed++; if (file.isWritable() && canBeFormatted(file) && acceptedByFilters(file)) { updateIndicatorText(ApplicationBundle.message("bulk.reformat.process.progress.text"),getPresentablePath(file)); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { DumbService.getInstance(myProject).withAlternativeResolveEnabled(new Runnable() { @Override public void run() { performFileProcessing(file); } }); } }); } } return true; }
protected void handleFiletooBigException(Logger logger,FilesTooBigForDiffException e,@NotNull PsiFile file) { logger.info("Error while calculating changed ranges for: " + file.getVirtualFile(),e); if (!ApplicationManager.getApplication().isUnitTestMode()) { Notification notification = new Notification(ApplicationBundle.message("reformat.changed.text.file.too.big.notification.groupId"),ApplicationBundle.message("reformat.changed.text.file.too.big.notification.title"),ApplicationBundle.message("reformat.changed.text.file.too.big.notification.text",file.getName()),NotificationType.informatION); notification.notify(file.getProject()); } }
@Nullable private static Pattern compilePattern(CodeStyleSettings settings,JTextField field,String patternText) { try { return Pattern.compile(patternText); } catch (PatternSyntaxException pse) { settings.FORMATTER_TAGS_ACCEPT_REGEXP = false; showError(field,ApplicationBundle.message("settings.code.style.general.formatter.marker.invalid.regexp")); return null; } }
void export() { ListPopup popup = JBPopupFactory.getInstance().createListPopup( new BaseListPopupStep<String>(ApplicationBundle.message("scheme.exporter.ui.export.as.title"),enumExporters()) { @Override public PopupStep onChosen(final String selectedValue,boolean finalChoice) { return doFinalStep(new Runnable() { @Override public void run() { exportSchemeUsing(selectedValue); } }); } }); popup.showInCenterOf(myParentComponent); }
com.intellij.openapi.application.Application的实例源码
@NotNull @Override protected void invokeDialog(AnActionEvent e,Project project,PsiDirectory dir) { BaseDialog dialog = new BaseDialog("请输入基类前缀:",project); dialog.show(); if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) { String prefix = dialog.getClassNamePrefix(); if(prefix != null && !prefix.isEmpty()){ Application application = ApplicationManager.getApplication(); application.runWriteAction(() -> { PsiElement createdElement = createProjectDir(dir,prefix); final IdeView view = e.getData(LangDataKeys.IDE_VIEW); if(view != null&&createdElement != null){ view.selectElement(createdElement); } }); } } }
public void scheduleCourseListUpdate(Application application) { if (!checkNeeded()) { return; } application.getMessageBus().connect(application).subscribe(AppLifecycleListener.TOPIC,new AppLifecycleListener() { @Override public void appFrameCreated(String[] commandLineArgs,@NotNull Ref<Boolean> willOpenProject) { long timetoNextCheck = StudySettings.getInstance().getLastTimeChecked() + CHECK_INTERVAL - System.currentTimeMillis(); if (timetoNextCheck <= 0) { myCheckRunnable.run(); } else { queueNextCheck(timetoNextCheck); } } }); }
@NotNull @Override protected void invokeDialog(AnActionEvent e,project); dialog.show(); if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) { String prefix = dialog.getClassNamePrefix(); if(prefix != null && !prefix.isEmpty()){ Application application = ApplicationManager.getApplication(); application.runWriteAction(() -> { PsiElement[] elements = createProjectDir(dir,prefix); final IdeView view = e.getData(LangDataKeys.IDE_VIEW); if(view != null){ for (PsiElement element : elements) { view.selectElement(element); } } }); } } }
@Override public void refreshIoFiles(@NotNull Iterable<File> files,boolean async,boolean recursive,@Nullable Runnable onFinish) { final VirtualFileManagerEx manager = (VirtualFileManagerEx)VirtualFileManager.getInstance(); Application app = ApplicationManager.getApplication(); boolean fireCommonRefreshSession = app.isdispatchThread() || app.isWriteAccessAllowed(); if (fireCommonRefreshSession) manager.fireBeforeRefreshStart(false); try { List<VirtualFile> filesToRefresh = new ArrayList<VirtualFile>(); for (File file : files) { final VirtualFile virtualFile = refreshAndFindFileByIoFile(file); if (virtualFile != null) { filesToRefresh.add(virtualFile); } } RefreshQueue.getInstance().refresh(async,recursive,onFinish,filesToRefresh); } finally { if (fireCommonRefreshSession) manager.fireAfterRefreshFinish(false); } }
public static void showError(final Project project,final String message,final boolean error) { final Application application = ApplicationManager.getApplication(); if (application.isUnitTestMode()) { return; } final String title = VcsBundle.message("patch.apply.dialog.title"); final Runnable messageShower = new Runnable() { @Override public void run() { if (error) { Messages.showErrorDialog(project,message,title); } else { Messages.showInfoMessage(project,title); } } }; WaitForProgresstoShow.runorinvokelaterAboveProgress(new Runnable() { @Override public void run() { messageShower.run(); } },null,project); }
public final void actionPerformed(final AnActionEvent anActionEvent) { logger.debug("entered actionPerformed"); // we're being called on the Swing event dispatch thread. Spin off another thread to do the // rearranging and let Swing's thread go. // Thread t = new Thread(new Runnable() { // public void run() // { // //To change body of implemented methods use Options | File Templates. final Application application = ApplicationManager.getApplication(); application.runWriteAction(new RearrangeIt(anActionEvent.getDataContext())); // } // },"RearrangerThread"); // t.start(); // new RearrangeIt(anActionEvent.getDataContext()).run(); }
public final void actionPerformed(final AnActionEvent anActionEvent) { logger.debug("entered actionPerformed"); // we're being called on the Swing event dispatch thread. Spin off another thread to do the // rearranging and let Swing's thread go. // Thread t = new Thread(new Runnable() { // public void run() // { // //To change body of implemented methods use Options | File Templates. final Application application = ApplicationManager.getApplication(); application.runWriteAction(new RearrangeIt(anActionEvent.getDataContext())); // } // },"RearrangerThread"); // t.start(); // new RearrangeIt(anActionEvent.getDataContext()).run(); }
public LocalFileSystemImpl(@NotNull ManagingFS managingFS) { myManagingFS = managingFS; myWatcher = new FileWatcher(myManagingFS); if (myWatcher.isOperational()) { final int PERIOD = 1000; Runnable runnable = new Runnable() { public void run() { final Application application = ApplicationManager.getApplication(); if (application == null || application.isdisposed()) return; storeRefreshStatusToFiles(); JobScheduler.getScheduler().schedule(this,PERIOD,TimeUnit.MILLISECONDS); } }; JobScheduler.getScheduler().schedule(runnable,TimeUnit.MILLISECONDS); } }
@NotNull @Override protected PsiElement[] create(String componentName,PsiDirectory directory) { List<PsiElement> elements = new LinkedList<>(); Application application = ApplicationManager.getApplication(); application.runWriteAction(() -> { PsiDirectory componentDirectory = directory.createsubdirectory(componentName); elements.add(componentDirectory); String[] fileNames = getrequiredFileNames(componentName); for (String fileName : fileNames) { PsiFile file = componentDirectory.createFile(fileName); elements.add(file); } }); return elements.toArray(new PsiElement[elements.size()]); }
@Override public void beforeApplicationLoaded(@NotNull Application application,@NotNull String configPath) { // Invoke later is necessary to make showWarning work. // setFrameIcon is called to change icon of welcome screen and it is unclear // if invoke later can be invoked to early (in the future) so setFrameIcon // is called again on ClassicIcon#projectOpened just in case. // Important here is only setDockIcon and this would work without invoke later also. application.invokelater(new Runnable() { @Override public void run() { if (SystemInfo.isMac) { setDockIcon(); } else { ClassicIcon.setFrameIcon(null); } } }); }
private void setUpFileWatcher() { final Application application = ApplicationManager.getApplication(); if (application.isdisposeInProgress() || !myWatcher.isOperational()) return; application.assertReadAccessAllowed(); synchronized (myLock) { final WatchRequestImpl[] watchRequests = normalizeRootsForRefresh(); final List<String> myRecursiveRoots = new ArrayList<String>(); final List<String> myFlatRoots = new ArrayList<String>(); for (WatchRequestImpl watchRequest : watchRequests) { if (watchRequest.isToWatchRecursively()) { myRecursiveRoots.add(watchRequest.myFSRootPath); } else { myFlatRoots.add(watchRequest.myFSRootPath); } } myWatcher.setWatchRoots(myRecursiveRoots,myFlatRoots); } }
/** * Get the value of an attribute in the {@link com.intellij.psi.xml.XmlFile} safely (meaning it will acquire the read lock first). */ @Nullable public static String getRoottagAttributeSafely(@NotNull final XmlFile file,@NotNull final String attribute,@Nullable final String namespace) { Application application = ApplicationManager.getApplication(); if (!application.isReadAccessAllowed()) { return application.runReadAction(new Computable<String>() { @Nullable @Override public String compute() { return getRoottagAttributeSafely(file,attribute,namespace); } }); } else { XmlTag tag = file.getRoottag(); if (tag != null) { XmlAttribute attr = namespace != null ? tag.getAttribute(attribute,namespace) : tag.getAttribute(attribute); if (attr != null) { return attr.getValue(); } } return null; } }
public static void run(final Project project,final Runnable action) { final ProjectLevelVcsManager plVcsManager = ProjectLevelVcsManager.getInstance(project); plVcsManager.startBackgroundVcsOperation(); try { action.run(); } finally { final Application application = ApplicationManager.getApplication(); if (application.isdispatchThread()) { application.executeOnPooledThread(new Runnable() { public void run() { plVcsManager.stopBackgroundVcsOperation(); } }); } else { plVcsManager.stopBackgroundVcsOperation(); } } }
@Override public void doFix(@NotNull final Project project,ProblemDescriptor descriptor) { final PsiElement constant = descriptor.getPsiElement(); final Application application = ApplicationManager.getApplication(); application.invokelater(new Runnable() { @Override public void run() { if (!constant.isValid()) return; final JavaRefactoringActionHandlerFactory factory = JavaRefactoringActionHandlerFactory.getInstance(); final RefactoringActionHandler introduceHandler = factory.createIntroduceConstantHandler(); final DataManager dataManager = DataManager.getInstance(); final DataContext dataContext = dataManager.getDataContext(); introduceHandler.invoke(project,new PsiElement[]{constant},dataContext); } },project.getdisposed()); }
@NotNull public static IdeFocusManager getGlobalInstance() { IdeFocusManager fm = null; Application app = ApplicationManager.getApplication(); if (app != null && app.hasComponent(IdeFocusManager.class)) { fm = app.getComponent(IdeFocusManager.class); } if (fm == null) { // happens when app is semi-initialized (e.g. when IDEA server dialog is shown) fm = PassthroughIdeFocusManager.getInstance(); } return fm; }
private static void show(final Project project,final MessageType type,final boolean showOverChangesView,@Nullable final NamedRunnable[] notificationListener) { final Application application = ApplicationManager.getApplication(); if (application.isHeadlessEnvironment()) return; final Runnable showErrorAction = new Runnable() { public void run() { new VcsBalloonProblemNotifier(project,type,showOverChangesView,notificationListener).run(); } }; if (application.isdispatchThread()) { showErrorAction.run(); } else { application.invokelater(showErrorAction); } }
@NotNull @Override public NamednodeMap getAttributes() { Application application = ApplicationManager.getApplication(); if (!application.isReadAccessAllowed()) { return application.runReadAction(new Computable<NamednodeMap>() { @Override public NamednodeMap compute() { return getAttributes(); } }); } if (myAttributes == null) { XmlAttribute[] attributes = mytag.getAttributes(); if (attributes.length == 0) { myAttributes = EMPTY_ATTRIBUTES; } else { myAttributes = new DomNamednodeMap(this,attributes); } } return myAttributes; }
public void clear() { final List<MyNotification> notifications; synchronized (myLock) { notifications = new ArrayList<MyNotification>(myState.values()); myState.clear(); } final Application application = ApplicationManager.getApplication(); final Runnable runnable = new Runnable() { public void run() { for (MyNotification notification : notifications) { notification.expire(); } } }; if (application.isdispatchThread()) { runnable.run(); } else { application.invokelater(runnable,ModalityState.NON_MODAL,myProject.getdisposed()); } }
private static void checkCanPaint(Graphics g) { if (UIUtil.isPrinting(g)) return; /* wtf?? if (!isdisplayable()) { LOG.assertTrue(false,logSwingPath()); } */ final Application application = ApplicationManager.getApplication(); if (application != null) { application.assertIsdispatchThread(); } else if (!SwingUtilities.isEventdispatchThread()) { throw new RuntimeException(Thread.currentThread().toString()); } }
private void applyModifiersFromregistry() { Application app = ApplicationManager.getApplication(); if (app != null && app.isUnitTestMode()) { return; } Set<String> vksSet = new THashSet<String>(); ContainerUtil.addAll(vksSet,getModifierRegistryValue().split(" ")); myModifierVks.clear(); int mask = getModifierMask(vksSet); myModifierVks.addAll(getModifiersVKs(mask)); reassignActionShortcut(SWITCH_UP,mask,KeyEvent.VK_UP); reassignActionShortcut(SWITCH_DOWN,KeyEvent.VK_DOWN); reassignActionShortcut(SWITCH_LEFT,KeyEvent.VK_LEFT); reassignActionShortcut(SWITCH_RIGHT,KeyEvent.VK_RIGHT); reassignActionShortcut(SWITCH_APPLY,KeyEvent.VK_ENTER); }
/** * Attach this path to a {@link DynamicWizard},linking it to that wizard's state. */ @Override public final void attachToWizard(@NotNull DynamicWizard wizard) { Application application = ApplicationManager.getApplication(); if (application != null && !application.isUnitTestMode()) { application.assertIsdispatchThread(); } myWizard = wizard; myUpdateQueue = wizard.getUpdateQueue(); Map<String,Object> myCurrentValues = myState.flatten(); myState = new ScopedStateStore(ScopedStateStore.Scope.PATH,myWizard.getState(),this); for (String keyName : myCurrentValues.keySet()) { myState.put(myState.createKey(keyName,Object.class),myCurrentValues.get(keyName)); } init(); myIsInitialized = true; }
private void updateActions(boolean Now,final boolean transparentOnly,final boolean forced) { final Runnable updateRunnable = new MyUpdateRunnable(this,transparentOnly,forced); final Application app = ApplicationManager.getApplication(); if (Now || app.isUnitTestMode()) { updateRunnable.run(); } else { final IdeFocusManager fm = IdeFocusManager.getInstance(null); if (!app.isHeadlessEnvironment()) { if (app.isdispatchThread() && myComponent.isShowing()) { fm.doWhenFocusSettlesDown(updateRunnable); } else { UiNotifyConnector.doWhenFirstShown(myComponent,new Runnable() { @Override public void run() { fm.doWhenFocusSettlesDown(updateRunnable); } }); } } } }
@Override public void projectClosed() { final Application app = ApplicationManager.getApplication(); Runnable cleanupinspectionProfilesRunnable = new Runnable() { @Override public void run() { for (inspectionProfileWrapper wrapper : myName2Profile.values()) { wrapper.cleanup(myProject); } fireProfilesShutdown(); } }; if (app.isUnitTestMode() || app.isHeadlessEnvironment()) { cleanupinspectionProfilesRunnable.run(); } else { app.executeOnPooledThread(cleanupinspectionProfilesRunnable); } }
@Nullable public static <T> T getService(@NotNull Module module,@NotNull Class<T> serviceClass) { //noinspection unchecked T instance = (T)module.getpicocontainer().getComponentInstance(serviceClass.getName()); if (instance == null) { instance = module.getComponent(serviceClass); if (instance != null) { Application app = ApplicationManager.getApplication(); String message = serviceClass.getName() + " requested as a service,but it is a component - convert it to a service or change call to module.getComponent()"; if (app.isUnitTestMode()) { LOG.error(message); } else { LOG.warn(message); } } } return instance; }
@Nullable private static <T> T doGetService(@NotNull ComponentManager componentManager,@NotNull Class<T> serviceClass) { @SuppressWarnings("unchecked") T instance = (T)componentManager.getpicocontainer().getComponentInstance(serviceClass.getName()); if (instance == null) { instance = componentManager.getComponent(serviceClass); if (instance != null) { Application app = ApplicationManager.getApplication(); String message = serviceClass.getName() + " requested as a service,but it is a component - convert it to a service or change call to " + (componentManager == app ? "ApplicationManager.getApplication().getComponent()" : "project.getComponent()"); if (app.isUnitTestMode()) { LOG.error(message); } else { LOG.warn(message); } } } return instance; }
@NotNull public static IdeaPluginDescriptorImpl[] loadDescriptors(@Nullable StartupProgress progress,@NotNull List<String> errors) { if (ClassUtilCore.isLoadingOfExternalPluginsdisabled()) { return IdeaPluginDescriptorImpl.EMPTY_ARRAY; } final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>(); int pluginsCount = countPlugins(PathManager.getPluginsPath()) + countPlugins(PathManager.getPreInstalledpluginsPath()); loadDescriptors(PathManager.getPluginsPath(),result,progress,pluginsCount); Application application = ApplicationManager.getApplication(); boolean fromSources = false; if (application == null || !application.isUnitTestMode()) { int size = result.size(); loadDescriptors(PathManager.getPreInstalledpluginsPath(),pluginsCount); fromSources = size == result.size(); } loadDescriptorsFromProperty(result); loadDescriptorsFromClasspath(result,getClassLoaderUrls(),fromSources ? progress : null); return topoSortPlugins(result,errors); }
public void dispose() { super.dispose(); addToinvokelater(new Runnable() { public void run() { disconnectListeners(); if (!myRunningTestNodes.isEmpty()) { Application application = ApplicationManager.getApplication(); if (!application.isHeadlessEnvironment() && !application.isUnitTestMode()) { logProblem("Not all events were processed!"); } } myRunningTestNodes.clear(); myNodeByIdMap.clear(); } }); }
@NotNull private static String getUrl(@NotNull IdeaPluginDescriptor descriptor,@Nullable String host,@Nullable BuildNumber buildNumber) throws URISyntaxException,MalformedURLException { if (host != null && descriptor instanceof PluginNode) { String url = ((PluginNode)descriptor).getDownloadUrl(); return new URI(url).isAbsolute() ? url : new URL(new URL(host),url).toExternalForm(); } else { Application app = ApplicationManager.getApplication(); ApplicationInfoEx appInfo = ApplicationInfoImpl.getShadowInstance(); String buildNumberAsstring = buildNumber != null ? buildNumber.asstring() : app != null ? ApplicationInfo.getInstance().getApiVersion() : appInfo.getBuild().asstring(); String uuid = app != null ? UpdateChecker.getInstallationUID(PropertiesComponent.getInstance()) : UUID.randomUUID().toString(); URIBuilder uriBuilder = new URIBuilder(appInfo.getPluginsDownloadUrl()); uriBuilder.addParameter("action","download"); uriBuilder.addParameter("id",descriptor.getPluginId().getIdString()); uriBuilder.addParameter("build",buildNumberAsstring); uriBuilder.addParameter("uuid",uuid); return uriBuilder.build().toString(); } }
@Override public void waitForSmartMode() { if (!isDumb()) { return; } final Application application = ApplicationManager.getApplication(); if (application.isReadAccessAllowed() || application.isdispatchThread()) { throw new AssertionError("Don't invoke waitForSmartMode from inside read action in dumb mode"); } final Semaphore semaphore = new Semaphore(); semaphore.down(); runWhenSmart(new Runnable() { @Override public void run() { semaphore.up(); } }); while (true) { if (semaphore.waitFor(50)) { return; } ProgressManager.checkCanceled(); } }
@Nullable public static VirtualFile findValidParentUnderReadAction(final FilePath file) { if (file.getVirtualFile() != null) return file.getVirtualFile(); final Computable<VirtualFile> computable = new Computable<VirtualFile>() { @Override public VirtualFile compute() { return findValidParent(file); } }; final Application application = ApplicationManager.getApplication(); if (application.isReadAccessAllowed()) { return computable.compute(); } else { return application.runReadAction(computable); } }
public static VirtualFile waitForTheFile(final String path) { final VirtualFile[] file = new VirtualFile[1]; final Application app = ApplicationManager.getApplication(); Runnable action = new Runnable() { @Override public void run() { app.runWriteAction(new Runnable() { @Override public void run() { file[0] = LocalFileSystem.getInstance().refreshAndFindFileByPath(path); } }); } }; if (app.isdispatchThread()) { action.run(); } else { app.invokeAndWait(action,ModalityState.defaultModalityState()); } return file[0]; }
@Override public boolean isSoftWrappingEnabled() { if (!myUseSoftWraps || myEditor.isOneLineMode() || myEditor.isPurePaintingMode()) { return false; } // We check that current thread is EDT because attempt to retrieve information about visible area width may fail otherwise Application application = ApplicationManager.getApplication(); Thread lastEdt = myLastEdt.get(); Thread currentThread = Thread.currentThread(); if (lastEdt != currentThread) { if (application.isdispatchThread()) { myLastEdt = new SoftReference<Thread>(currentThread); } else { myLastEdt = new SoftReference<Thread>(null); return false; } } if (application.isUnitTestMode()) return true; Rectangle visibleArea = myEditor.getScrollingModel().getVisibleArea(); return visibleArea.width > 0 && visibleArea.height > 0; }
public void setPreviewText(@Nonnull String text) { final CommandProcessor processor = CommandProcessor.getInstance(); processor.executeCommand(null,() -> { final Application application = ApplicationManager.getApplication(); application.runWriteAction(() -> { previewDocument.replaceString(INITIAL_OFFSET,previewDocument.getTextLength(),text); final int textLength = previewDocument.getTextLength(); final CaretModel caret = previewEditor.getCaretModel(); if (caret.getoffset() >= textLength) { caret.movetoOffset(textLength); } }); },null); }
public void setJson(@NotNull String json) { final CommandProcessor processor = CommandProcessor.getInstance(); processor.executeCommand(project,() -> { final Application application = ApplicationManager.getApplication(); application.runWriteAction(() -> { jsonDocument.replaceString(INITIAL_OFFSET,jsonDocument.getTextLength(),json); final int textLength = jsonDocument.getTextLength(); final CaretModel caret = jsoneditor.getCaretModel(); if (caret.getoffset() >= textLength) { caret.movetoOffset(textLength); } }); },null); }
@Nonnull @CheckReturnValue protected Application getApplication() { if (fixture == null) { throw new AssertionError("getApplication() must call after setUp()"); } return ApplicationManager.getApplication(); }
public static void generateFromStudentCourse(Project project,Course course) { StudyTaskManager.getInstance(project).setCourse(course); course.setCourseMode(CCUtils.COURSE_MODE); final VirtualFile baseDir = project.getBaseDir(); final Application application = ApplicationManager.getApplication(); application.invokeAndWait(() -> application.runWriteAction(() -> { final VirtualFile[] children = baseDir.getChildren(); for (VirtualFile child : children) { StudyUtils.deleteFile(child); } StudyGenerator.createCourse(course,baseDir); })); baseDir.refresh(false,true); int index = 1; int taskIndex = 1; for (Lesson lesson : course.getLessons()) { final VirtualFile lessonDir = project.getBaseDir().findChild(EduNames.LESSON + String.valueOf(index)); lesson.setIndex(index); if (lessonDir == null) continue; for (Task task : lesson.getTaskList()) { final VirtualFile taskDir = lessonDir.findChild(EduNames.TASK + String.valueOf(taskIndex)); task.setIndex(taskIndex); task.setLesson(lesson); if (taskDir == null) continue; for (final Map.Entry<String,TaskFile> entry : task.getTaskFiles().entrySet()) { application.invokeAndWait(() -> application.runWriteAction(() -> createAnswerFile(project,taskDir,entry))); } taskIndex += 1; } index += 1; taskIndex = 1; } course.initCourse(true); application.invokeAndWait(() -> StudyUtils.registerStudyToolWindow(course,project)); synchronize(project); }
private void hotSwapSessions( final List<DebuggerSession> sessions ) { HotSwapProgressImpl findClassesProgress = new HotSwapProgressImpl( getIjProject() ); ApplicationManager.getApplication().executeOnPooledThread( () -> { final Map<DebuggerSession,Map<String,HotSwapFile>> modifiedClasses = scanForModifiedClassesWithProgress( sessions,findClassesProgress ); final Application application = ApplicationManager.getApplication(); if( modifiedClasses.isEmpty() ) { final String message = DebuggerBundle.message( "status.hotswap.uptodate" ); NotificationGroup.toolWindowGroup( "HotSwap",ToolWindowId.DEBUG ).createNotification( message,NotificationType.informatION ).notify( getIjProject() ); return; } application.invokelater( () -> { if( !modifiedClasses.isEmpty() ) { final HotSwapProgressImpl progress = new HotSwapProgressImpl( getIjProject() ); if( modifiedClasses.keySet().size() == 1 ) { //noinspection ConstantConditions progress.setSessionForActions( ContainerUtil.getFirstItem( modifiedClasses.keySet() ) ); } application.executeOnPooledThread( () -> reloadModifiedClasses( modifiedClasses,progress ) ); } },ModalityState.NON_MODAL ); } ); }
@Override @Nullable public Position getPosition(@NonNull final Node node) { Application application = ApplicationManager.getApplication(); if (application.isReadAccessAllowed()) { return getPositionImmediate(node); } return application.runReadAction(new Computable<Position>() { @Override @Nullable public Position compute() { return getPositionImmediate(node); } }); }
private void askUserTodisablePlugins(Collection<IdeaPluginDescriptor> conflictingPlugins) { final String text = formatMessage(conflictingPlugins); NotificationGroup ng = NotificationGroup.balloonGroup("Conflicting Plugins"); ng.createNotification(PLUGIN_NAME,text,NotificationType.WARNING,(notification,event) -> { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { for (IdeaPluginDescriptor foreignPlugin : conflictingPlugins) { PluginManager.disablePlugin(foreignPlugin.getPluginId().toString()); } Application application = ApplicationManager.getApplication(); application.restart(); } }).notify(project); }
/** * must be called from within an IDEA read-action thread. * * @param project * @param document * @param psiFile */ void buildLiveRearrangerData(final Project project,final Document document,final PsiFile psiFile,final int cursorOffset) { /** * Per instructions from IntelliJ,we have to commit any changes to the document to the Psi * tree. */ final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); documentManager.commitDocument(document); final RearrangerSettings settings = new RearrangerSettings(); // use default settings with no rules settings.setAskBeforeRearranging(true); final Runnable task = new Runnable() { public void run() { logger.debug("liveRearrangeDocument task started"); liveRearrangeDocument(project,psiFile,settings,document,cursorOffset); } }; Thread t = new Thread(new Runnable() { public void run() { logger.debug("started thread " + Thread.currentThread().getName()); final Application application = ApplicationManager.getApplication(); application.runReadAction(new Runnable() { public void run() { logger.debug("enter application.runReadAction() on thread " + Thread.currentThread().getName()); task.run(); logger.debug("exit application.runReadAction() on thread " + Thread.currentThread().getName()); }}); } },"Live Rearranger parser"); t.start(); logger.debug("exit buildLiveRearrangerData on thread " + Thread.currentThread().getName()); }
com.intellij.openapi.application.ex.ApplicationUtil的实例源码
private void processVirtualFile(@Nonnull final VirtualFile vfile,@Nonnull final ProgressIndicator progress,@Nonnull final Processor<? super PsiFile> localProcessor,@Nonnull final AtomicBoolean canceled) throws ApplicationUtil.CannotRunReadActionException { final PsiFile file = ApplicationUtil.tryRunReadAction(() -> vfile.isValid() ? myManager.findFile(vfile) : null); if (file != null && !(file instanceof PsiBinaryFile)) { // load contents outside read action if (FileDocumentManager.getInstance().getCachedDocument(vfile) == null) { // cache bytes in vfs try { vfile.contentsToByteArray(); } catch (IOException ignored) { } } ApplicationUtil.tryRunReadAction(() -> { final Project project = myManager.getProject(); if (project.isdisposed()) throw new ProcessCanceledException(); if (DumbService.isDumb(project)) throw ApplicationUtil.CannotRunReadActionException.create(); List<PsiFile> psiRoots = file.getViewProvider().getAllFiles(); Set<PsiFile> processed = new THashSet<>(psiRoots.size() * 2,(float)0.5); for (final PsiFile psiRoot : psiRoots) { progress.checkCanceled(); assert psiRoot != null : "One of the roots of file " + file + " is null. All roots: " + psiRoots + "; ViewProvider: " + file.getViewProvider() + "; Virtual file: " + file.getViewProvider().getVirtualFile(); if (!processed.add(psiRoot)) continue; if (!psiRoot.isValid()) { continue; } if (!localProcessor.process(psiRoot)) { canceled.set(true); break; } } }); } }
/** * Executes a {@code runnable} in an "impatient" mode. * In this mode any attempt to grab read lock * will fail (i.e. throw {@link ApplicationUtil.CannotRunReadActionException}) * if there is a pending write lock request. */ void executeByImpatientReader(@Nonnull Runnable runnable) throws ApplicationUtil.CannotRunReadActionException { checkReadThreadAccess(); Reader status = R.get(); boolean old = status.impatientReads; try { status.impatientReads = true; runnable.run(); } finally { status.impatientReads = old; } }
/** * Executes a {@code runnable} in an "impatient" mode. * In this mode any attempt to call {@link #runReadAction(Runnable)} * would fail (i.e. throw {@link ApplicationUtil.CannotRunReadActionException}) * if there is a pending write action. */ public void executeByImpatientReader(@Nonnull Runnable runnable) throws ApplicationUtil.CannotRunReadActionException { if (isdispatchThread()) { runnable.run(); } else { myLock.executeByImpatientReader(runnable); } }
/** * @param files to scan for references in this pass. * @param totalSize the number of files to scan in both passes. Can be different from <code>files.size()</code> in case of * two-pass scan,where we first scan files containing container name and then all the rest files. * @param alreadyProcessedFiles the number of files scanned in prevIoUs pass. * @return true if completed */ private boolean processpsiFileRoots(@NotNull List<VirtualFile> files,final int totalSize,int alreadyProcessedFiles,@NotNull final ProgressIndicator progress,@NotNull final Processor<? super PsiFile> localProcessor) { myManager.startBatchFilesProcessingMode(); try { final AtomicInteger counter = new AtomicInteger(alreadyProcessedFiles); final AtomicBoolean canceled = new AtomicBoolean(false); boolean completed = true; while (true) { List<VirtualFile> FailedList = new SmartList<VirtualFile>(); final List<VirtualFile> FailedFiles = Collections.synchronizedList(FailedList); final Processor<VirtualFile> processor = new Processor<VirtualFile>() { @Override public boolean process(final VirtualFile vfile) { try { TooManyUsagesstatus.getFrom(progress).pauseProcessingIfTooManyUsages(); processVirtualFile(vfile,progress,localProcessor,canceled,counter,totalSize); } catch (ApplicationUtil.CannotRunReadActionException action) { FailedFiles.add(vfile); } return !canceled.get(); } }; if (ApplicationManager.getApplication().isWriteAccessAllowed() || ((ApplicationEx)ApplicationManager.getApplication()).isWriteActionPending()) { // no point in processing in separate threads - they are doomed to fail to obtain read action anyway completed &= ContainerUtil.process(files,processor); } else { completed &= JobLauncher.getInstance().invokeConcurrentlyUnderProgress(files,false,processor); } if (FailedFiles.isEmpty()) { break; } // we Failed to run read action in job launcher thread // run read action in our thread instead to wait for a write action to complete and resume parallel processing DumbService.getInstance(myManager.getProject()).runReadActionInSmartMode(EmptyRunnable.getInstance()); files = FailedList; } return completed; } finally { myManager.finishBatchFilesProcessingMode(); } }
private void processVirtualFile(@NotNull final VirtualFile vfile,@NotNull final Processor<? super PsiFile> localProcessor,@NotNull final AtomicBoolean canceled,@NotNull AtomicInteger counter,int totalSize) throws ApplicationUtil.CannotRunReadActionException { final PsiFile file = ApplicationUtil.tryRunReadAction(new Computable<PsiFile>() { @Override public PsiFile compute() { return vfile.isValid() ? myManager.findFile(vfile) : null; } }); if (file != null && !(file instanceof PsiBinaryFile)) { // load contents outside read action if (FileDocumentManager.getInstance().getCachedDocument(vfile) == null) { // cache bytes in vfs try { vfile.contentsToByteArray(); } catch (IOException ignored) { } } ApplicationUtil.tryRunReadAction(new Computable<Void>() { @Override public Void compute() { final Project project = myManager.getProject(); if (project.isdisposed()) throw new ProcessCanceledException(); if (DumbService.isDumb(project)) throw new ApplicationUtil.CannotRunReadActionException(); List<PsiFile> psiRoots = file.getViewProvider().getAllFiles(); Set<PsiFile> processed = new THashSet<PsiFile>(psiRoots.size() * 2,(float)0.5); for (final PsiFile psiRoot : psiRoots) { progress.checkCanceled(); assert psiRoot != null : "One of the roots of file " + file + " is null. All roots: " + psiRoots + "; ViewProvider: " + file.getViewProvider() + "; Virtual file: " + file.getViewProvider().getVirtualFile(); if (!processed.add(psiRoot)) continue; if (!psiRoot.isValid()) { continue; } if (!localProcessor.process(psiRoot)) { canceled.set(true); break; } } return null; } }); } if (progress.isRunning()) { double fraction = (double)counter.incrementAndGet() / totalSize; progress.setFraction(fraction); } }
@NotNull public static CharSequence loadText(@NotNull final VirtualFile file) { if (file instanceof LightVirtualFile) { return ((LightVirtualFile)file).getContent(); } if (file.isDirectory()) { throw new AssertionError("'" + file.getPresentableurl() + "' is a directory"); } FileType fileType = file.getFileType(); if (fileType.isBinary()) { final BinaryFileDecompiler decompiler = BinaryFileTypeDecompilers.INSTANCE.forFileType(fileType); if (decompiler != null) { CharSequence text; Application app = ApplicationManager.getApplication(); if (app != null && app.isdispatchThread() && !app.isWriteAccessAllowed() && !GraphicsEnvironment.isHeadless()) { final Ref<CharSequence> result = Ref.create(ArrayUtil.EMPTY_CHAR_SEQUENCE); final Ref<Throwable> error = Ref.create(); ProgressManager.getInstance().run(new Task.Modal(null,"Decompiling " + file.getName(),true) { @Override public void run(@NotNull ProgressIndicator indicator) { indicator.setIndeterminate(true); try { result.set(ApplicationUtil.runWithCheckCanceled(new Callable<CharSequence>() { @Override public CharSequence call() { return decompiler.decompile(file); } },indicator)); } catch (Throwable t) { error.set(t); } } }); ExceptionUtil.rethrowUnchecked(error.get()); text = result.get(); } else { text = decompiler.decompile(file); } StringUtil.assertValidSeparators(text); return text; } throw new IllegalArgumentException("Attempt to load text for binary file which doesn't have a decompiler plugged in: " + file.getPresentableurl() + ". File type: " + fileType.getName()); } try { byte[] bytes = file.contentsToByteArray(); return getTextByBinaryPresentation(bytes,file); } catch (IOException e) { return ArrayUtil.EMPTY_CHAR_SEQUENCE; } }
@Override public int getStartPosition() { return ApplicationUtil.tryRunReadAction(() -> selectionModel.getSelectionStart()); }
@Override public int getEndPosition() { return ApplicationUtil.tryRunReadAction(() -> selectionModel.getSelectionEnd()); }
@Override public Optional<String> getText() { String text = ApplicationUtil.tryRunReadAction(() -> selectionModel.getSelectedText()); return Optional.ofNullable(text); }
public static boolean processFilesConcurrentlyDespiteWriteActions(@Nonnull Project project,@Nonnull List<VirtualFile> files,@Nonnull final Processor<VirtualFile> localProcessor) { ApplicationEx app = (ApplicationEx)ApplicationManager.getApplication(); final AtomicBoolean canceled = new AtomicBoolean(false); while (true) { List<VirtualFile> FailedList = new SmartList<>(); final List<VirtualFile> FailedFiles = Collections.synchronizedList(FailedList); final Processor<VirtualFile> processor = vfile -> { try { boolean result = localProcessor.process(vfile); if (!result) { canceled.set(true); } return result; } catch (ApplicationUtil.CannotRunReadActionException action) { FailedFiles.add(vfile); } return !canceled.get(); }; boolean completed; if (app.isWriteAccessAllowed() || app.isReadAccessAllowed() && app.isWriteActionPending()) { // no point in processing in separate threads - they are doomed to fail to obtain read action anyway completed = ContainerUtil.process(files,processor); } else if (app.isWriteActionPending()) { completed = true; // we don't have read action Now so wait for write action to complete FailedFiles.addAll(files); } else { // try to run parallel read actions but fail as soon as possible completed = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(files,true,processor); } if (!completed) { return false; } if (FailedFiles.isEmpty()) { break; } // we Failed to run read action in job launcher thread // run read action in our thread instead to wait for a write action to complete and resume parallel processing DumbService.getInstance(project).runReadActionInSmartMode(EmptyRunnable.getInstance()); files = FailedList; } return true; }
private void throwIfImpatient(Reader status) { // when client explicitly runs in non-cancelable block do not throw from within nested read actions if (status.impatientReads && writeRequested && !ProgressManager.getInstance().isInNonCancelableSection() && CoreProgressManager.ENABLED) { throw ApplicationUtil.CannotRunReadActionException.create(); } }
关于运行shell脚本文件,启动java application和shell脚本启动java程序的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于com.intellij.openapi.application.ApplicationActivationListener的实例源码、com.intellij.openapi.application.ApplicationBundle的实例源码、com.intellij.openapi.application.Application的实例源码、com.intellij.openapi.application.ex.ApplicationUtil的实例源码的相关信息,请在本站寻找。
本文标签: