List of usage examples for org.eclipse.jface.dialogs ProgressMonitorDialog open
@Override public int open()
From source file:eu.numberfour.n4js.ui.dialog.ModuleSpecifierSelectionDialog.java
License:Open Source License
/** * Processes the initial string selection. * * For existing resources it just sets the initial selection to the specified file system resource. * * In the case that the initial module specifier points to a non-existing location, a dialog is displayed which * allows the user to automatically create not yet existing folders. * * @param initialModuleSpecifier// w w w . j av a 2s .c o m * The module specifier * @return A {@link IWorkbenchAdapter} adaptable object or null on failure */ private Object processInitialSelection(String initialModuleSpecifier) { IPath sourceFolderPath = sourceFolder.getFullPath(); IPath initialModulePath = new Path(initialModuleSpecifier); // Use the root element source folder for an empty initial selection if (initialModuleSpecifier.isEmpty()) { return this.sourceFolder; } // Use the root element source folder for invalid module specifiers if (!WorkspaceWizardValidatorUtils.isValidFolderPath(initialModulePath)) { return this.sourceFolder; } // The project relative path of a module specifier IPath fullPath = sourceFolderPath.append(new Path(initialModuleSpecifier)); // If the module specifier refers to an existing n4js resource if (!fullPath.hasTrailingSeparator()) { IFile n4jsModuleFile = workspaceRoot .getFile(fullPath.addFileExtension(N4JSGlobals.N4JS_FILE_EXTENSION)); IFile n4jsdModuleFile = workspaceRoot .getFile(fullPath.addFileExtension(N4JSGlobals.N4JSD_FILE_EXTENSION)); // Just use it as initial selection if (n4jsModuleFile.exists()) { return n4jsModuleFile; } if (n4jsdModuleFile.exists()) { return n4jsdModuleFile; } } //// Otherwise use the existing part of the path as initial selection: // If the module specifier specifies the module name, extract it and remove its segment. if (isModuleFileSpecifier(initialModulePath)) { initialModuleName = initialModulePath.lastSegment(); initialModulePath = initialModulePath.removeLastSegments(1); } IResource selection = this.sourceFolder; // Accumulate path segments to search for the longest existing path IPath accumulatedPath = sourceFolderPath; // Collect the paths of all non-existing segments // These are relative to the last existing segment of the path List<IPath> nonExistingSegmentPaths = new ArrayList<>(); for (Iterator<String> segmentIterator = Arrays.asList(initialModulePath.segments()) .iterator(); segmentIterator.hasNext(); /**/) { accumulatedPath = accumulatedPath.append(segmentIterator.next()); // Results in null if non-existing IResource nextSegmentResource = workspaceRoot.findMember(accumulatedPath); // If the current segment is an existing file and not the last specifier segment // show a file overlap error message if (null != nextSegmentResource && !(nextSegmentResource instanceof IContainer) && segmentIterator.hasNext()) { MessageDialog.open(MessageDialog.ERROR, getShell(), SPECIFIER_OVERLAPS_WITH_FILE_TITLE, String .format(SPECIFIER_OVERLAPS_WITH_FILE_MESSAGE, initialModuleSpecifier, accumulatedPath), SWT.NONE); return selection; } // If the segment exist go ahead with the next one if (null != nextSegmentResource && nextSegmentResource.exists()) { selection = nextSegmentResource; } else { // If not add it to the list of non existing segments. nonExistingSegmentPaths.add(accumulatedPath.makeRelativeTo(selection.getFullPath())); } } // If any non-existing folders need to be created if (nonExistingSegmentPaths.size() > 0) { // Ask the user if he wants to create the missing folders boolean create = MessageDialog.open(MessageDialog.QUESTION, getShell(), NON_EXISTING_MODULE_LOCATION_TITLE, NON_EXISTING_MODULE_LOCATION_MESSAGE, SWT.NONE); // Create the missing folders if (create) { ProgressMonitorDialog progressMonitorDialog = new ProgressMonitorDialog(getShell()); progressMonitorDialog.open(); IProgressMonitor progressMonitor = progressMonitorDialog.getProgressMonitor(); IPath deepestPath = nonExistingSegmentPaths.get(nonExistingSegmentPaths.size() - 1); selection = createFolderPath(deepestPath, (IContainer) selection, progressMonitor); progressMonitor.done(); progressMonitorDialog.close(); } } return selection; }
From source file:goko.handlers.SaveHandler.java
License:Open Source License
@Execute public void execute(IEclipseContext context, @Named(IServiceConstants.ACTIVE_SHELL) Shell shell, @Named(IServiceConstants.ACTIVE_PART) final MContribution contribution) throws InvocationTargetException, InterruptedException { final IEclipseContext pmContext = context.createChild(); ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell); dialog.open(); dialog.run(true, true, new IRunnableWithProgress() { @Override/*from ww w . j a v a 2 s . c o m*/ public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { pmContext.set(IProgressMonitor.class.getName(), monitor); if (contribution != null) { // Object clientObject = contribution.getObject(); // ContextInjectionFactory.invoke(clientObject, Persist.class, //$NON-NLS-1$ // pmContext, null); } } }); pmContext.dispose(); }
From source file:gov.redhawk.ide.sdr.ui.internal.handlers.LaunchDomainManagerWithOptions.java
License:Open Source License
@Override public Object execute(final ExecutionEvent event) throws ExecutionException { final ISelection selection = HandlerUtil.getActiveMenuSelection(event); displayContext = HandlerUtil.getActiveShell(event); dmReg = ScaPlugin.getDefault().getDomainManagerRegistry(displayContext); final Shell shell = HandlerUtil.getActiveShell(event); if (selection instanceof IStructuredSelection) { final IStructuredSelection ss = (IStructuredSelection) selection; for (final Object obj : ss.toArray()) { if (obj instanceof SdrRoot) { final SdrRoot sdrRoot = (SdrRoot) obj; Assert.isNotNull(sdrRoot); if (sdrRoot.getLoadStatus() == null) { ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell); try { dialog.run(true, true, new IRunnableWithProgress() { @Override public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Loading Target SDR..", IProgressMonitor.UNKNOWN); try { CorbaUtils.invoke(new Callable<Object>() { @Override public Object call() throws Exception { sdrRoot.load(monitor); return null; } }, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); }/* w w w. j av a 2s . co m*/ } }); } catch (InvocationTargetException e) { StatusManager.getManager().handle(new Status(IStatus.ERROR, SdrUiPlugin.PLUGIN_ID, "Failed to load SDR.", e.getCause()), StatusManager.SHOW | StatusManager.LOG); } catch (InterruptedException e) { return null; } } final DomainManagerConfiguration domain = sdrRoot.getDomainConfiguration(); if (domain == null) { StatusManager.getManager().handle(new Status(IStatus.ERROR, SdrUiPlugin.PLUGIN_ID, "No Domain Configuration available."), StatusManager.SHOW); continue; } model.setDomainName(domain.getName()); final LaunchDomainManagerWithOptionsDialog dialog = new LaunchDomainManagerWithOptionsDialog( shell, model, sdrRoot); if (dialog.open() == IStatus.OK) { deviceManagers = dialog.getDeviceManagerLaunchConfigurations(); prepareDomainManager(domain, event); } } } } return null; }
From source file:it.eng.spagobi.studio.core.services.dataset.DeployDatasetService.java
License:Mozilla Public License
/** if document has meadata associated do the automated deploy * /*from ww w. j ava 2s . c o m*/ * @return if automated eply has been done */ public boolean tryAutomaticDeploy() { logger.debug("IN"); IStructuredSelection sel = (IStructuredSelection) selection; // go on only if ysou selected a document Object objSel = sel.toList().get(0); org.eclipse.core.internal.resources.File fileSel = null; fileSel = (org.eclipse.core.internal.resources.File) objSel; projectname = fileSel.getProject().getName(); //if file has document metadata associated upload it, else call wizard String datasetId = null; String datasetLabel = null; String datasetCategory = null; try { datasetId = fileSel.getPersistentProperty(SpagoBIStudioConstants.DATASET_ID); datasetLabel = fileSel.getPersistentProperty(SpagoBIStudioConstants.DATASET_LABEL); datasetCategory = fileSel.getPersistentProperty(SpagoBIStudioConstants.DATASET_CATEGORY); } catch (CoreException e) { logger.error("Error in retrieving dataset Label", e); } // IF File selected has already an id of datasetassociated do the upload wiyhout asking further informations boolean automatic = false; boolean newDeployFromOld = false; if (datasetId != null) { logger.debug("Query already associated to dataset" + datasetId + " - " + datasetLabel + " - of category " + datasetCategory); final Integer idInteger = Integer.valueOf(datasetId); final String label2 = datasetLabel; final org.eclipse.core.internal.resources.File fileSel2 = fileSel; final NoDocumentException datasetException = new NoDocumentException(); final NoActiveServerException noActiveServerException = new NoActiveServerException(); final NotAllowedOperationStudioException notAllowedOperationStudioException = new NotAllowedOperationStudioException(); IRunnableWithProgress op = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { monitor.beginTask( "Deploying to dataset existing dataset with label: " + label2 + " and ID: " + idInteger, IProgressMonitor.UNKNOWN); if (projectname == null) { projectname = fileSel2.getProject().getName(); } try { logger.debug("dataset associated, upload the query to dataset " + label2); SpagoBIServerObjectsFactory spagoBIServerObjects = new SpagoBIServerObjectsFactory( projectname); // check dataset still exists IDataSet ds = spagoBIServerObjects.getServerDatasets().getDataSet(idInteger); if (ds == null) { datasetException.setNoDocument(true); logger.warn("Dataset no more present on server: with id " + idInteger); } else { logger.debug("update query to dataset"); String queryStr = null; String adaptedQueryStrList = null; try { JSONObject obj = JSONReader.createJSONObject(fileSel2); queryStr = obj.optString("query"); logger.debug("query is " + queryStr); adaptedQueryStrList = DeployDatasetService.adaptQueryToList(queryStr); logger.debug("adapted query list is " + adaptedQueryStrList); //solvedeccoqui // only the query may be modified by meta so it is the only refreshed ds.addToConfiguration(Dataset.QBE_JSON_QUERY, adaptedQueryStrList); //ds.setJsonQuery(adaptedQueryStrList); datasetException.setNoDocument(false); Integer dsId = spagoBIServerObjects.getServerDatasets().saveDataSet(ds); if (ds == null) { logger.error("Error while uploading dataset on server; check log on server"); MessageDialog.openError( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error on deploy", "Error while uploading dataset; check server log to have details"); } BiObjectUtilities.setFileDataSetMetaData(fileSel2, ds); } catch (Exception e) { logger.error("error in reading JSON object, update failed", e); } } } catch (NoActiveServerException e1) { // no active server found noActiveServerException.setNoServer(true); } catch (RemoteException e) { if (e.getClass().toString().equalsIgnoreCase( "class it.eng.spagobi.sdk.exceptions.NotAllowedOperationException")) { logger.error("Current User has no permission to deploy dataset", e); notAllowedOperationStudioException.setNotAllowed(true); } else { logger.error("Error comunicating with server", e); MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error comunicating with server", "Error while uploading the template: missing comunication with server"); } } monitor.done(); if (monitor.isCanceled()) logger.error("Operation not ended", new InterruptedException("The long running operation was cancelled")); } }; ProgressMonitorDialog dialog = new ProgressMonitorDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()); try { dialog.run(true, true, op); } catch (InvocationTargetException e1) { logger.error("Error comunicating with server", e1); MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "Missing comunication with server; check server definition and if service is avalaible"); dialog.close(); return false; } catch (InterruptedException e1) { logger.error("Error comunicating with server", e1); MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "Missing comunication with server; check server definition and if service is avalaible"); dialog.close(); return false; } if (datasetException.isNoDocument()) { logger.error("Document no more present"); MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error upload", "Dataset with ID " + idInteger + " no more present on server; you can do a new deploy"); sbdw.setNewDeployFromOld(true); newDeployFromOld = true; } if (noActiveServerException.isNoServer()) { logger.error("No server is defined active"); MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "No server is defined active"); return false; } dialog.close(); if (notAllowedOperationStudioException.isNotAllowed()) { logger.error("Current User has no permission to deploy dataset"); MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "", "Current user has no permission to deploy dataset"); return false; } if (!newDeployFromOld) { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Deploy succesfull", "Deployed to the associated dataset with label: " + datasetLabel + " and ID: " + idInteger + " succesfull"); logger.debug( "Deployed to the associated document " + datasetLabel + " succesfull: ID: is " + idInteger); automatic = true; } } else { automatic = false; } if (!automatic || newDeployFromOld) { logger.debug("deploy a new Dataset: start wizard"); // init wizard sbdw.init(PlatformUI.getWorkbench(), sel); // Create the wizard dialog WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), sbdw); dialog.setPageSize(650, 300); // Open the wizard dialog dialog.open(); } logger.debug("OUT"); return automatic; }
From source file:it.eng.spagobi.studio.core.services.template.DeployTemplateService.java
License:Mozilla Public License
/** if document has meadata associated do the automated deploy * /* w w w.j a v a2s. c o m*/ * @return if automated eply has been done */ public boolean doAutomaticDeploy() { logger.debug("IN"); IStructuredSelection sel = (IStructuredSelection) selection; // go on only if you selected a document Object objSel = sel.toList().get(0); org.eclipse.core.internal.resources.File fileSel = null; fileSel = (org.eclipse.core.internal.resources.File) objSel; projectname = fileSel.getProject().getName(); //if file has document metadata associated upload it, else call wizard String document_idString = null; String document_label = null; try { document_idString = fileSel.getPersistentProperty(SpagoBIStudioConstants.DOCUMENT_ID); document_label = fileSel.getPersistentProperty(SpagoBIStudioConstants.DOCUMENT_LABEL); } catch (CoreException e) { logger.error("Error in retrieving document Label", e); } // IF File selected has already and id of document associated do the upload wiyhout asking further informations boolean newDeploy = false; if (document_idString != null) { logger.debug("Template already associated to document " + document_idString); final Integer idInteger = Integer.valueOf(document_idString); final String label2 = document_label; final org.eclipse.core.internal.resources.File fileSel2 = fileSel; final NoDocumentException documentException = new NoDocumentException(); final NoActiveServerException noActiveServerException = new NoActiveServerException(); IRunnableWithProgress op = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { monitor.beginTask("Deploying to document " + label2, IProgressMonitor.UNKNOWN); if (projectname == null) { projectname = fileSel2.getProject().getName(); } try { // document associated, upload the template SpagoBIServerObjectsFactory spagoBIServerObjects = new SpagoBIServerObjectsFactory( projectname); URI uri = fileSel2.getLocationURI(); File fileJava = new File(uri.getPath()); FileDataSource fileDataSource = new FileDataSource(fileJava); DataHandler dataHandler = new DataHandler(fileDataSource); Template template = new Template(); template.setFileName(fileSel2.getName()); template.setContent(dataHandler); // check document still exists //Document doc=spagoBIServerObjects.getServerDocuments().getDocumentById(idInteger); Document doc = spagoBIServerObjects.getServerDocuments().getDocumentByLabel(label2); if (doc == null) { documentException.setNoDocument(true); logger.warn( "Document not retrieved; check it is still on server and you have enough permission to reach it" + idInteger); return; } else { documentException.setNoDocument(false); // **** Label defined inside template (Ext Chart case) *** // in thecaseof an extChart also te dataset must be re-assigned because it could have been changed String labelInsideXml = null; try { labelInsideXml = fileSel2 .getPersistentProperty(SpagoBIStudioConstants.DATASET_LABEL_INSIDE); } catch (CoreException e) { logger.warn( "Errorin finding dataset label nto template, go on anyway using server one"); } IDataSet found = null; if (labelInsideXml != null) { // EXT CHART CASE logger.debug("Set dataset document on server to " + labelInsideXml); IDataSet[] datasets = spagoBIServerObjects.getServerDatasets().getDataSetList(); // get the id of the new datset for (int i = 0; i < datasets.length && found == null; i++) { if (datasets[i].getLabel().equals(labelInsideXml)) { found = datasets[i]; } } if (found != null) { Integer id = found.getId(); doc.setDataSetId(id); logger.debug("update document with new dataset reference"); } else { logger.error("dataset " + labelInsideXml + " not found in server. delete dataset association"); doc.setDataSetId(null); } spagoBIServerObjects.getServerDocuments().saveNewDocument(doc, template, null); } else { // OTHER DOCUMENTS CASE spagoBIServerObjects.getServerDocuments().uploadTemplate(idInteger, template); } // ALl documents case // in case of dataset definition changed the dataset label as file metadata must be changed if (found != null) { try { fileSel2.setPersistentProperty(SpagoBIStudioConstants.DATASET_ID, found.getId().toString()); fileSel2.setPersistentProperty(SpagoBIStudioConstants.DATASET_LABEL, found.getLabel()); fileSel2.setPersistentProperty(SpagoBIStudioConstants.DATASET_NAME, found.getName()); fileSel2.setPersistentProperty(SpagoBIStudioConstants.DATASET_DESCRIPTION, found.getDescription()); } catch (CoreException e) { logger.error( "Errorn updating file metadata about new dataset associated: go on anyway"); } } } } catch (NoActiveServerException e1) { // no active server found noActiveServerException.setNoServer(true); return; } catch (RemoteException e) { logger.error("Error comunicating with server", e); MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error comunicating with server", "Error while uploading the template: missing comunication with server"); return; } monitor.done(); if (monitor.isCanceled()) logger.error("Operation not ended", new InterruptedException("The long running operation was cancelled")); } }; ProgressMonitorDialog dialog = new ProgressMonitorDialog( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()); try { dialog.run(true, true, op); } catch (InvocationTargetException e1) { logger.error("Error comunicating with server", e1); MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "Missing comunication with server; check server definition and if service is avalaible"); dialog.close(); return false; } catch (InterruptedException e1) { logger.error("Error comunicating with server", e1); MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "Missing comunication with server; check server definition and if service is avalaible"); dialog.close(); return false; } if (documentException.isNoDocument()) { logger.error( "Document not retrieved; check it is still on server and you have enough permission to reach it"); MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error upload", "Document not retrieved; check it is still on server and you have enough permission to reach it: make a new deploy"); newDeploy = true; sbdw.setNewDeployFromOld(true); } if (noActiveServerException.isNoServer()) { logger.error("No server is defined active"); MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "No server is defined active"); return false; } dialog.close(); if (!newDeploy) { MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Deploy succesfull", "Deployed to the associated document " + document_label + " succesfull"); logger.debug("Deployed to the associated document " + document_label + " succesfull"); } } else { newDeploy = true; } if (newDeploy) { logger.debug("deploy a new Document: start wizard"); // init wizard sbdw.init(PlatformUI.getWorkbench(), sel); // Create the wizard dialog WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), sbdw); // { // @Override // protected void configureShell(Shell newShell) { // super.configureShell(newShell); // newShell.setSize(1300, 600); // } // }; // Open the wizard dialog dialog.open(); } logger.debug("OUT"); return true; }
From source file:LinGUIne.handlers.SaveHandler.java
License:Open Source License
@Execute public void execute(IEclipseContext context, @Named(IServiceConstants.ACTIVE_SHELL) Shell shell, @Named(IServiceConstants.ACTIVE_PART) final MContribution contribution) throws InvocationTargetException, InterruptedException { final IEclipseContext pmContext = context.createChild(); ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell); dialog.open(); dialog.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { pmContext.set(IProgressMonitor.class.getName(), monitor); if (contribution != null) { Object clientObject = contribution.getObject(); ContextInjectionFactory.invoke(clientObject, Persist.class, pmContext, null); }/*from w w w.j av a2s . co m*/ } }); pmContext.dispose(); }
From source file:net.ostis.confman.ui.handlers.SaveHandler.java
License:Open Source License
@Execute public void execute(final IEclipseContext context, @Named(IServiceConstants.ACTIVE_SHELL) final Shell shell, @Named(IServiceConstants.ACTIVE_PART) final MContribution contribution) throws InvocationTargetException, InterruptedException { final IEclipseContext pmContext = context.createChild(); final ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell); dialog.open(); dialog.run(true, true, new IRunnableWithProgress() { @Override//ww w .j av a 2 s.co m public void run(final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { pmContext.set(IProgressMonitor.class.getName(), monitor); if (contribution != null) { final Object clientObject = contribution.getObject(); // ContextInjectionFactory.invoke(clientObject, Persist.class, //$NON-NLS-1$ // pmContext, null); } } }); pmContext.dispose(); }
From source file:net.refractions.udig.ui.ShutdownTaskList.java
License:Open Source License
private ProgressMonitorDialog getDialog(IWorkbench workbench) { Shell shell = new Shell(Display.getCurrent()); ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell); dialog.open(); return dialog; }
From source file:net.sf.commonclipse.Generator.java
License:Apache License
/** * Generates the appropriate method in <code>type</code>. * @param type IType/*from w ww .j av a 2 s. c om*/ * @param shell Shell */ public void generate(IType type, Shell shell) { ICompilationUnit cu = (ICompilationUnit) type.getAncestor(IJavaElement.COMPILATION_UNIT); // first check if file is writable IResource resource; try { resource = cu.getCorrespondingResource(); } catch (JavaModelException e) { MessageDialog.openError(shell, CCMessages.getString("Generator.errortitle"), e.getMessage()); //$NON-NLS-1$ return; } if (resource != null && resource.getResourceAttributes().isReadOnly()) { IStatus status = ResourcesPlugin.getWorkspace().validateEdit(new IFile[] { (IFile) resource }, shell); if (!status.isOK()) { MessageDialog.openError(shell, CCMessages.getString("Generator.errortitle"), CCMessages //$NON-NLS-1$ .getString("Generator.readonly")); //$NON-NLS-1$ return; } } resource = null; if (!validate(type, shell)) { return; } ProgressMonitorDialog progressDialog = new ProgressMonitorDialog(shell); progressDialog.open(); try { IProgressMonitor monitor = progressDialog.getProgressMonitor(); generateMethod(type, cu, shell, monitor); } catch (JavaModelException ex) { MessageDialog.openError(shell, CCMessages.getString("Generator.errortitle"), ex.getMessage()); //$NON-NLS-1$ } progressDialog.close(); }
From source file:net.sf.eclipsensis.installoptions.actions.PreviewAction.java
License:Open Source License
private void doPreview(final INIFile iniFile, final File file) { final Shell shell = mEditor.getSite().getShell(); BusyIndicator.showWhile(shell.getDisplay(), new Runnable() { public void run() { final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell) { @Override//from w ww . ja v a 2 s . co m protected void configureShell(Shell shell) { super.configureShell(shell); Rectangle rect = shell.getDisplay().getBounds(); shell.setLocation(rect.x + rect.width + 1, rect.y + rect.height + 1); } @Override protected Rectangle getConstrainedShellBounds(Rectangle preferredSize) { Rectangle rect = shell.getDisplay().getBounds(); return new Rectangle(rect.x + rect.width + 1, rect.y + rect.height + 1, preferredSize.width, preferredSize.height); } }; pmd.open(); try { ModalContext.run(new IRunnableWithProgress() { private File createPreviewFile(File previewFile, INIFile inifile, final NSISLanguage lang) throws IOException { File previewFile2 = previewFile; INIFile inifile2 = inifile; if (previewFile2 == null) { previewFile2 = File.createTempFile("preview", ".ini"); //$NON-NLS-1$ //$NON-NLS-2$ previewFile2.deleteOnExit(); } inifile2 = inifile2.copy(); InstallOptionsDialog dialog = InstallOptionsDialog.loadINIFile(inifile2); DialogSize dialogSize; if (getId().equals(PREVIEW_MUI_ID)) { dialogSize = DialogSizeManager.getDialogSize(cMUIDialogSizeName); } else { dialogSize = DialogSizeManager.getDialogSize(cClassicDialogSizeName); } if (dialogSize == null) { dialogSize = DialogSizeManager.getDefaultDialogSize(); } dialog.setDialogSize(dialogSize); Font font = FontUtility.getFont(lang); for (Iterator<InstallOptionsWidget> iter = dialog.getChildren().iterator(); iter .hasNext();) { InstallOptionsWidget widget = iter.next(); if (widget instanceof InstallOptionsPicture) { final InstallOptionsPicture picture = (InstallOptionsPicture) widget; final Dimension dim = widget.toGraphical(widget.getPosition(), font).getSize(); final Map<Dimension, File> cache; switch (picture.getSWTImageType()) { case SWT.IMAGE_BMP: cache = cBitmapCache; break; case SWT.IMAGE_ICO: cache = cIconCache; break; default: continue; } final File[] imageFile = new File[] { cache.get(dim) }; if (!IOUtility.isValidFile(imageFile[0])) { shell.getDisplay().syncExec(new Runnable() { public void run() { Image widgetImage = picture.getImage(); ImageData data = widgetImage.getImageData(); data.width = dim.width; data.height = dim.height; data.type = picture.getSWTImageType(); Image bitmap = new Image(shell.getDisplay(), data); GC gc = new GC(bitmap); gc.setBackground(shell.getDisplay() .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); gc.setForeground( shell.getDisplay().getSystemColor(SWT.COLOR_BLACK)); gc.fillRectangle(0, 0, dim.width, dim.height); Rectangle rect = widgetImage.getBounds(); int x, y, width, height; if (rect.width > dim.width) { x = 0; width = dim.width; } else { x = (dim.width - rect.width) / 2; width = rect.width; } if (rect.height > dim.height) { y = 0; height = dim.height; } else { y = (dim.height - rect.height) / 2; height = rect.height; } gc.drawImage(widgetImage, 0, 0, rect.width, rect.height, x, y, width, height); gc.setLineStyle(SWT.LINE_CUSTOM); gc.setLineDash(DashedLineBorder.DASHES); gc.drawRectangle(0, 0, dim.width - 1, dim.height - 1); gc.dispose(); ImageLoader loader = new ImageLoader(); loader.data = new ImageData[] { bitmap.getImageData() }; try { imageFile[0] = File.createTempFile("preview", //$NON-NLS-1$ picture.getFileExtension()); imageFile[0].deleteOnExit(); loader.save(imageFile[0].getAbsolutePath(), picture.getSWTImageType()); cache.put(dim, imageFile[0]); } catch (IOException e) { imageFile[0] = null; InstallOptionsPlugin.getDefault().log(e); cache.remove(dim); } } }); } if (imageFile[0] != null) { picture.setPropertyValue(InstallOptionsModel.PROPERTY_TEXT, imageFile[0].getAbsolutePath()); } } } inifile2 = dialog.updateINIFile(); IOUtility.writeContentToFile(previewFile2, inifile2.toString().getBytes()); return previewFile2; } public void run(IProgressMonitor monitor) { try { monitor.beginTask( InstallOptionsPlugin.getResourceString("previewing.script.task.name"), //$NON-NLS-1$ IProgressMonitor.UNKNOWN); String pref = InstallOptionsPlugin.getDefault().getPreferenceStore() .getString(IInstallOptionsConstants.PREFERENCE_PREVIEW_LANG); NSISLanguage lang; if (pref.equals("")) { //$NON-NLS-1$ lang = NSISLanguageManager.getInstance().getDefaultLanguage(); } else { lang = NSISLanguageManager.getInstance().getLanguage(pref); if (lang == null) { lang = NSISLanguageManager.getInstance().getDefaultLanguage(); InstallOptionsPlugin.getDefault().getPreferenceStore() .setValue(IInstallOptionsConstants.PREFERENCE_PREVIEW_LANG, ""); //$NON-NLS-1$ } } PreviewCacheKey key = new PreviewCacheKey(file, lang); File previewFile = cPreviewCache.get(key); if (previewFile == null || file.lastModified() > previewFile.lastModified()) { previewFile = createPreviewFile(previewFile, iniFile, lang); cPreviewCache.put(key, previewFile); } Map<String, String> symbols = mSettings.getSymbols(); symbols.put("PREVIEW_INI", previewFile.getAbsolutePath()); //$NON-NLS-1$ symbols.put("PREVIEW_LANG", lang.getName()); //$NON-NLS-1$ Locale locale = NSISLanguageManager.getInstance() .getLocaleForLangId(lang.getLangId()); if (getId().equals(PREVIEW_MUI_ID)) { symbols.put("PREVIEW_TITLE", //$NON-NLS-1$ InstallOptionsPlugin.getResourceString(locale, "preview.setup.title")); //$NON-NLS-1$ symbols.put("PREVIEW_SUBTITLE", InstallOptionsPlugin.getResourceString(locale, //$NON-NLS-1$ "preview.setup.subtitle")); //$NON-NLS-1$ } else { symbols.put("PREVIEW_BRANDING", InstallOptionsPlugin.getResourceString(locale, //$NON-NLS-1$ "preview.setup.branding")); //$NON-NLS-1$ } symbols.put("PREVIEW_NAME", //$NON-NLS-1$ InstallOptionsPlugin.getResourceString(locale, "preview.setup.name")); //$NON-NLS-1$ if (EclipseNSISPlugin.getDefault().isWinVista() && NSISPreferences.getInstance() .getNSISVersion().compareTo(INSISVersions.VERSION_2_21) >= 0) { symbols.put("WINDOWS_VISTA", ""); //$NON-NLS-1$ //$NON-NLS-2$ } mSettings.setSymbols(symbols); final File previewScript = getPreviewScript(); long timestamp = System.currentTimeMillis(); MakeNSISResults results = null; results = MakeNSISRunner.compile(previewScript, mSettings, cDummyConsole, new INSISConsoleLineProcessor() { public NSISConsoleLine processText(String text) { return NSISConsoleLine.info(text); } public void reset() { } }); if (results != null) { if (results.getReturnCode() != 0) { List<NSISScriptProblem> errors = results.getProblems(); final String error; if (!Common.isEmptyCollection(errors)) { Iterator<NSISScriptProblem> iter = errors.iterator(); StringBuffer buf = new StringBuffer(iter.next().getText()); while (iter.hasNext()) { buf.append(INSISConstants.LINE_SEPARATOR) .append(iter.next().getText()); } error = buf.toString(); } else { error = InstallOptionsPlugin.getResourceString("preview.compile.error"); //$NON-NLS-1$ } shell.getDisplay().asyncExec(new Runnable() { public void run() { Common.openError(shell, error, InstallOptionsPlugin.getShellImage()); } }); } else { final File outfile = new File(results.getOutputFileName()); if (IOUtility.isValidFile(outfile) && outfile.lastModified() > timestamp) { MakeNSISRunner.testInstaller(outfile.getAbsolutePath(), null, true); } } } } catch (final Exception e) { InstallOptionsPlugin.getDefault().log(e); shell.getDisplay().asyncExec(new Runnable() { public void run() { Common.openError(shell, e.getMessage(), InstallOptionsPlugin.getShellImage()); } }); } finally { monitor.done(); } } }, true, pmd.getProgressMonitor(), shell.getDisplay()); } catch (Exception e) { InstallOptionsPlugin.getDefault().log(e); Common.openError(shell, e.getMessage(), InstallOptionsPlugin.getShellImage()); } finally { pmd.close(); } } }); }