private void updateIcons() {
   if (this.widget instanceof MenuItem) {
     final MenuItem item = (MenuItem) this.widget;
     final LocalResourceManager m = new LocalResourceManager(JFaceResources.getResources());
     try {
       item.setImage(this.icon == null ? null : m.createImage(this.icon));
     } catch (final DeviceResourceException e) {
       this.icon = ImageDescriptor.getMissingImageDescriptor();
       item.setImage(m.createImage(this.icon));
       // as we replaced the failed icon, log the message once.
       StatusManager.getManager()
           .handle(
               new Status(
                   IStatus.ERROR,
                   SharedUIResources.PLUGIN_ID,
                   "Failed to load image",
                   e)); //$NON-NLS-1$
     }
     disposeOldImages();
     this.localResourceManager = m;
   } else if (this.widget instanceof ToolItem) {
     final ToolItem item = (ToolItem) this.widget;
     final LocalResourceManager m = new LocalResourceManager(JFaceResources.getResources());
     item.setDisabledImage(this.disabledIcon == null ? null : m.createImage(this.disabledIcon));
     item.setHotImage(this.hoverIcon == null ? null : m.createImage(this.hoverIcon));
     item.setImage(this.icon == null ? null : m.createImage(this.icon));
     disposeOldImages();
     this.localResourceManager = m;
   }
 }
  protected void setImageDescriptor(ImageDescriptor descriptor) {
    if (Util.equals(imageDescriptor, descriptor)) {
      return;
    }

    Image oldImage = image;
    ImageDescriptor oldDescriptor = imageDescriptor;
    image = null;
    imageDescriptor = descriptor;

    // Don't queue events triggered by image changes. We'll dispose the image
    // immediately after firing the event, so we need to fire it right away.
    immediateFirePropertyChange(IWorkbenchPartConstants.PROP_TITLE);
    if (queueEvents) {
      // If there's a PROP_TITLE event queued, remove it from the queue because
      // we've just fired it.
      queuedEvents.clear(IWorkbenchPartConstants.PROP_TITLE);
    }

    // If we had allocated the old image, deallocate it now (AFTER we fire the property change
    // -- listeners may need to clean up references to the old image)
    if (oldImage != null) {
      JFaceResources.getResources().destroy(oldDescriptor);
    }
  }
Exemplo n.º 3
0
  private static ResourceManager getImageManager() {
    if (resourceManager == null) {
      resourceManager = new LocalResourceManager(JFaceResources.getResources());
    }

    return resourceManager;
  }
Exemplo n.º 4
0
  private void updateToolBar() {
    if (toolbar != null) {
      ResourceManager parentResourceManager = JFaceResources.getResources();
      LocalResourceManager localManager = new LocalResourceManager(parentResourceManager);

      for (int i = 0; i < toolbar.getItemCount(); i++) {
        ToolItem item = toolbar.getItem(i);
        IAction action = (IAction) actionMap.get(item);
        if (action != null) {
          ImageDescriptor image = null;
          if (action.isEnabled() && action.getImageDescriptor() != null)
            image = action.getImageDescriptor();
          else if (action.isEnabled() && action.getImageDescriptor() != null)
            image = action.getDisabledImageDescriptor();
          if (image != null) item.setImage(localManager.createImageWithDefault(image));

          item.setToolTipText(action.getToolTipText());
          if (IAction.AS_CHECK_BOX == action.getStyle()) {
            item.setSelection(action.isChecked());
          }
        }
      }

      disposeOldImages();
      imageManager = localManager;

      if (toolbar.isFocusControl()) toolbar.setFocus();
    }
  }
  /* (non-Javadoc)
   * @see org.eclipse.jface.action.IContributionItem#fill(org.eclipse.swt.widgets.Menu, int)
   */
  public void fill(Menu parent, int index) {
    if (menuItem == null || menuItem.isDisposed()) {
      if (index >= 0) {
        menuItem = new MenuItem(parent, SWT.CASCADE, index);
      } else {
        menuItem = new MenuItem(parent, SWT.CASCADE);
      }

      String text = getMenuText();
      if (text != null) {
        menuItem.setText(text);
      }

      if (image != null) {
        LocalResourceManager localManager = new LocalResourceManager(JFaceResources.getResources());
        menuItem.setImage(localManager.createImage(image));
        disposeOldImages();
        imageManager = localManager;
      }

      if (!menuExist()) {
        menu = new Menu(parent);
        menu.setData(MANAGER_KEY, this);
      }

      menuItem.setMenu(menu);

      initializeMenu();

      setDirty(true);
    }
  }
  public final void dispose() {

    if (isDisposed()) {
      return;
    }

    // Store the current title, tooltip, etc. so that anyone that they can be returned to
    // anyone that held on to the disposed reference.
    partName = getPartName();
    contentDescription = getContentDescription();
    tooltip = getTitleToolTip();
    title = getTitle();

    if (state == STATE_CREATION_IN_PROGRESS) {
      IStatus result =
          WorkbenchPlugin.getStatus(
              new PartInitException(
                  NLS.bind(
                      "Warning: Blocked recursive attempt by part {0} to dispose itself during creation", //$NON-NLS-1$
                      getId())));
      WorkbenchPlugin.log(result);
      return;
    }

    doDisposeNestedParts();

    // Disposing the pane disposes the part's widgets. The part's widgets need to be disposed before
    // the part itself.
    if (pane != null) {
      // Remove the dispose listener since this is the correct place for the widgets to get disposed
      Control targetControl = getPane().getControl();
      if (targetControl != null) {
        targetControl.removeDisposeListener(prematureDisposeListener);
      }
      pane.dispose();
    }

    doDisposePart();

    if (pane != null) {
      pane.removeContributions();
    }

    clearListenerList(internalPropChangeListeners);
    clearListenerList(partChangeListeners);
    Image oldImage = image;
    ImageDescriptor oldDescriptor = imageDescriptor;
    image = null;

    state = STATE_DISPOSED;
    imageDescriptor = ImageDescriptor.getMissingImageDescriptor();
    defaultImageDescriptor = ImageDescriptor.getMissingImageDescriptor();
    immediateFirePropertyChange(IWorkbenchPartConstants.PROP_TITLE);
    clearListenerList(propChangeListeners);

    if (oldImage != null) {
      JFaceResources.getResources().destroy(oldDescriptor);
    }
  }
 private void buildViewTreePanel(Composite parent) {
   this.viewTreeViewer =
       this.buildTreePanel(
           parent,
           "View tree",
           new ItemTreeStateProviderManager(
               new ViewItemTreeContentProviderFactory(), JFaceResources.getResources()),
           new LabelProvider());
 }
  public final Image getTitleImage() {
    if (isDisposed()) {
      return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_DEF_VIEW);
    }

    if (image == null) {
      image = JFaceResources.getResources().createImageWithDefault(imageDescriptor);
    }
    return image;
  }
Exemplo n.º 9
0
  /**
   * The <code>WorkbenchPart</code> implementation of this <code>IWorkbenchPart</code> method
   * disposes the title image loaded by <code>setInitializationData</code>. Subclasses may extend.
   */
  public void dispose() {
    if (imageDescriptor != null) {
      JFaceResources.getResources().destroyImage(imageDescriptor);
    }

    // Clear out the property change listeners as we
    // should not be notifying anyone after the part
    // has been disposed.
    clearListeners();
    partChangeListeners.clear();
  }
 private void updateIcons() {
   if (widget instanceof MenuItem) {
     MenuItem item = (MenuItem) widget;
     LocalResourceManager m = new LocalResourceManager(JFaceResources.getResources());
     item.setImage(icon == null ? null : m.createImage(icon));
     disposeOldImages();
     localResourceManager = m;
   } else if (widget instanceof ToolItem) {
     ToolItem item = (ToolItem) widget;
     LocalResourceManager m = new LocalResourceManager(JFaceResources.getResources());
     // TODO: [bm] dis/hot images of item
     //			item.setDisabledImage(disabledIcon == null ? null : m
     //					.createImage(disabledIcon));
     //			item.setHotImage(hoverIcon == null ? null : m
     //					.createImage(hoverIcon));
     item.setImage(icon == null ? null : m.createImage(icon));
     disposeOldImages();
     localResourceManager = m;
   }
 }
Exemplo n.º 11
0
  /** @param parentShell */
  public CustomizeToolbarDialog(Shell parentShell) {
    super(parentShell);
    fResources = new LocalResourceManager(JFaceResources.getResources());
    fFirstTimeOpen =
        (Activator.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS_KEY) == null);
    fPreferences = Owl.getPreferenceService().getGlobalScope();

    /* Colors */
    fSeparatorBorderFg = OwlUI.getColor(fResources, new RGB(210, 210, 210));
    fSeparatorBg = OwlUI.getColor(fResources, new RGB(240, 240, 240));
  }
 public LocalResourceManager getResourceManager(Display display) {
   if (resourceManagers == null) {
     resourceManagers = new HashMap();
   }
   LocalResourceManager resources = (LocalResourceManager) resourceManagers.get(display);
   if (resources == null) {
     pruneResourceManagers();
     resources = new LocalResourceManager(JFaceResources.getResources(display));
     resourceManagers.put(display, resources);
   }
   return resources;
 }
Exemplo n.º 13
0
 /**
  * Sets or clears the title image of this part.
  *
  * @param titleImage the title image, or <code>null</code> to clear
  */
 protected void setTitleImage(Image titleImage) {
   //        Assert.isTrue(titleImage == null || !titleImage.isDisposed());
   Assert.isTrue(titleImage != null);
   // Do not send changes if they are the same
   if (this.titleImage == titleImage) {
     return;
   }
   this.titleImage = titleImage;
   firePropertyChange(IWorkbenchPart.PROP_TITLE);
   if (imageDescriptor != null) {
     JFaceResources.getResources().destroyImage(imageDescriptor);
     imageDescriptor = null;
   }
 }
Exemplo n.º 14
0
 /**
  * The <code>Wizard</code> implementation of this <code>IWizard</code> method disposes all the
  * pages controls using <code>DialogPage.dispose</code>. Subclasses should extend this method if
  * the wizard instance maintains addition SWT resource that need to be disposed.
  */
 public void dispose() {
   // notify pages
   for (int i = 0; i < pages.size(); i++) {
     try {
       ((IWizardPage) pages.get(i)).dispose();
     } catch (Exception e) {
       Status status = new Status(IStatus.ERROR, Policy.JFACE, IStatus.ERROR, e.getMessage(), e);
       Policy.getLog().log(status);
     }
   }
   // dispose of image
   if (defaultImage != null) {
     JFaceResources.getResources().destroyImage(defaultImageDescriptor);
     defaultImage = null;
   }
 }
Exemplo n.º 15
0
  /* (non-Javadoc)
   * @see org.eclipse.jface.action.IContributionItem#update(java.lang.String)
   */
  public void update(String property) {
    IContributionItem items[] = getItems();

    for (int i = 0; i < items.length; i++) {
      items[i].update(property);
    }

    if (menu != null && !menu.isDisposed() && menu.getParentItem() != null) {
      if (IAction.TEXT.equals(property)) {
        String text = getOverrides().getText(this);

        if (text == null) {
          text = getMenuText();
        }

        if (text != null) {
          ExternalActionManager.ICallback callback =
              ExternalActionManager.getInstance().getCallback();

          if (callback != null) {
            int index = text.indexOf('&');

            if (index >= 0 && index < text.length() - 1) {
              char character = Character.toUpperCase(text.charAt(index + 1));

              if (callback.isAcceleratorInUse(SWT.ALT | character) && isTopLevelMenu()) {
                if (index == 0) {
                  text = text.substring(1);
                } else {
                  text = text.substring(0, index) + text.substring(index + 1);
                }
              }
            }
          }

          menu.getParentItem().setText(text);
        }
      } else if (IAction.IMAGE.equals(property) && image != null) {
        LocalResourceManager localManager = new LocalResourceManager(JFaceResources.getResources());
        menu.getParentItem().setImage(localManager.createImage(image));
        disposeOldImages();
        imageManager = localManager;
      }
    }
  }
 private void buildControlTreePanel(Composite parent) {
   this.controlTreeViewer =
       this.buildTreePanel(
           parent,
           "Control tree",
           new ItemTreeStateProviderManager(
               new ControlItemTreeContentProviderFactory(), JFaceResources.getResources()),
           new LabelProvider());
   this.controlTreeViewer.addSelectionChangedListener(this.buildTreeSelectionChangedListener());
   this.selectedNodeModel.addPropertyChangeListener(
       PropertyValueModel.VALUE,
       new PropertyChangeListener() {
         public void propertyChanged(PropertyChangeEvent event) {
           TreeContentProviderUiTest.this.controlTreeViewer.setSelection(
               new StructuredSelection(event.getNewValue()));
         }
       });
 }
  @Override
  protected void applyCSSProperty(
      Control control, String property, CSSValue value, String pseudo, CSSEngine engine)
      throws Exception {
    if (!(control instanceof ToolBar)) return;

    ToolBar toolBar = (ToolBar) control;
    if (ICathyConstants.PROPERTY_TOOL_ITEM_COLOR.equals(property)) {
      Color color = (Color) engine.convert(value, Color.class, toolBar.getDisplay());
      toolBar.setForeground(color);

      ToolItem[] items = toolBar.getItems();
      for (ToolItem each : items) {
        String text = each.getText();
        each.setText(text);
      }
    } else if (ICathyConstants.PROPERTY_VIEW_MENU.equals(property)) {
      if (value.getCssValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
        if (((CSSPrimitiveValue) value).getPrimitiveType() == CSSPrimitiveValue.CSS_URI) {
          String imageUrl = ((CSSPrimitiveValue) value).getStringValue();
          ImageDescriptor imageDescriptor =
              ImageDescriptor.createFromURL(new URL(imageUrl.toString()));
          Image image = JFaceResources.getResources().createImage(imageDescriptor);
          if (TOOLBAR_TAG_VIEW_MENU.equals(toolBar.getData())) {
            toolBar.getItem(0).setImage(image);
          }
        }
      }
    }
    //        else if ("xswt-view-properties-pin".equals(property)) {
    //            ToolItem[] items = toolBar.getItems();
    //            for (ToolItem each : items) {
    //                Object data = each.getData();
    //                if (data instanceof ActionContributionItem) {
    //                    String id = ((ActionContributionItem) data).getId();
    //                    if (id.contains("org.eclipse.ui.views.properties.PinPropertySheetAction"))
    // {
    //
    //                    }
    //                }
    //            }
    //        }
  }
  @Override
  protected void applyCSSProperty(
      Control control, String property, CSSValue value, String pseudo, CSSEngine engine)
      throws Exception {
    if (!(control instanceof CTabFolder)) {
      return;
    }
    CTabFolder folder = (CTabFolder) control;
    CTabFolderRenderer renderer = folder.getRenderer();
    if (!(renderer instanceof ICTabFolderRendering)) return;

    ICTabFolderRendering tabFolderRendering = (ICTabFolderRendering) renderer;

    Image image = null;
    if (value.getCssValueType() == CSSValue.CSS_PRIMITIVE_VALUE) {
      if (((CSSPrimitiveValue) value).getPrimitiveType() == CSSPrimitiveValue.CSS_URI) {
        String imageUrl = ((CSSPrimitiveValue) value).getStringValue();
        ImageDescriptor imageDescriptor =
            ImageDescriptor.createFromURL(new URL(imageUrl.toString()));
        image = JFaceResources.getResources().createImage(imageDescriptor);
      }
    }

    if (ICathyConstants.PROPERTY_MAXIMIZE_IMAGE.equals(property)) {
      tabFolderRendering.setMaximizeImage(image);
    } else if (ICathyConstants.PROPERTY_MINIMIZE_IMAGE.equals(property)) {
      tabFolderRendering.setMinimizeImage(image);
    } else if (ICathyConstants.PROPERTY_CLOSE_IMAGE.equals(property)) {
      tabFolderRendering.setCloseImage(image);
    } else if (ICathyConstants.PROPERTY_CLOSE_HOVER_IMAGE.equals(property)) {
      tabFolderRendering.setClsoeHoverImage(image);
    } else if (ICathyConstants.PROPERTY_CHEVRON_VISIBLE.equals(property)) {
      ReflectionSupport<CTabFolder> reflect = new ReflectionSupport<CTabFolder>(CTabFolder.class);
      boolean chevronVisible = (Boolean) engine.convert(value, Boolean.class, null);
      Method setChevronVisible =
          reflect.getMethod(METHOD_SET_CHEVRON_VISIBLE, new Class<?>[] {boolean.class});
      reflect.executeMethod(setChevronVisible, folder, new Object[] {chevronVisible});
    }
  }
Exemplo n.º 19
0
  /**
   * The <code>IntroPart</code> implementation of this <code>IExecutableExtension</code> records the
   * configuration element in and internal state variable (accessible via <code>getConfigElement
   * </code>). It also loads the title image, if one is specified in the configuration element.
   * Subclasses may extend.
   *
   * <p>Should not be called by clients. It is called by the core plugin when creating this
   * executable extension.
   */
  @Override
  public void setInitializationData(IConfigurationElement cfig, String propertyName, Object data) {

    // Save config element.
    configElement = cfig;

    titleLabel = cfig.getAttribute(IWorkbenchRegistryConstants.ATT_LABEL);

    // Icon.
    String strIcon = cfig.getAttribute(IWorkbenchRegistryConstants.ATT_ICON);
    if (strIcon == null) {
      return;
    }

    imageDescriptor =
        AbstractUIPlugin.imageDescriptorFromPlugin(configElement.getNamespace(), strIcon);

    if (imageDescriptor == null) {
      return;
    }

    Image image = JFaceResources.getResources().createImageWithDefault(imageDescriptor);
    titleImage = image;
  }
Exemplo n.º 20
0
  /**
   * {@inheritDoc} The <code>WorkbenchPart</code> implementation of this <code>IExecutableExtension
   * </code> records the configuration element in and internal state variable (accessible via <code>
   * getConfigElement</code>). It also loads the title image, if one is specified in the
   * configuration element. Subclasses may extend.
   *
   * <p>Should not be called by clients. It is called by the core plugin when creating this
   * executable extension.
   */
  public void setInitializationData(IConfigurationElement cfig, String propertyName, Object data) {

    // Save config element.
    configElement = cfig;

    // Part name and title.
    partName = Util.safeString(cfig.getAttribute("name")); // $NON-NLS-1$;
    title = partName;

    // Icon.
    String strIcon = cfig.getAttribute("icon"); // $NON-NLS-1$
    if (strIcon == null) {
      return;
    }

    imageDescriptor =
        AbstractUIPlugin.imageDescriptorFromPlugin(configElement.getNamespace(), strIcon);

    if (imageDescriptor == null) {
      return;
    }

    titleImage = JFaceResources.getResources().createImageWithDefault(imageDescriptor);
  }
Exemplo n.º 21
0
public class SourceFilesLabelProvider extends TreeColumnViewerLabelProvider
    implements IExecutablesChangeListener {

  private SourceFilesViewer viewer;

  private LocalResourceManager resourceManager =
      new LocalResourceManager(JFaceResources.getResources());

  public SourceFilesLabelProvider(SourceFilesViewer viewer) {
    super(new CElementLabelProvider());
    this.viewer = viewer;

    // brute-force clear the cache when executables change
    ExecutablesManager.getExecutablesManager().addExecutablesChangeListener(this);
    viewer
        .getControl()
        .addDisposeListener(
            new DisposeListener() {
              @Override
              public void widgetDisposed(DisposeEvent e) {
                ExecutablesManager.getExecutablesManager()
                    .removeExecutablesChangeListener(SourceFilesLabelProvider.this);
              }
            });
  }

  @Override
  public void update(ViewerCell cell) {
    super.update(cell);

    SourceFilesViewer.TranslationUnitInfo tuInfo = null;
    Object element = cell.getElement();
    if (element instanceof ITranslationUnit) {
      tuInfo = SourceFilesViewer.fetchTranslationUnitInfo((Executable) viewer.getInput(), element);
    }

    int orgColumnIndex = cell.getColumnIndex();

    if (orgColumnIndex == 0) {
      if (element instanceof String) {
        cell.setText((String) element);
        Font italicFont =
            resourceManager.createFont(
                FontDescriptor.createFrom(viewer.getTree().getFont()).setStyle(SWT.ITALIC));
        cell.setFont(italicFont);
      } else {
        cell.setFont(viewer.getTree().getFont());
      }
    } else if (orgColumnIndex == 1) {
      cell.setText(null);
      if (tuInfo != null) {
        if (tuInfo.location != null) {
          cell.setText(tuInfo.location.toOSString());
          if (tuInfo.exists)
            cell.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLACK));
          else cell.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_GRAY));
        }
      }
      cell.setImage(null);
    } else if (orgColumnIndex == 2) {
      cell.setText(null);
      if (tuInfo != null && tuInfo.originalLocation != null) {
        cell.setText(tuInfo.originalLocation.toOSString());
        if (tuInfo.originalExists)
          cell.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLACK));
        else cell.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_GRAY));
      }
      cell.setImage(null);
    } else if (orgColumnIndex == 3) {
      cell.setText(null);
      if (tuInfo != null) {
        if (tuInfo.exists) {
          cell.setText(Long.toString(tuInfo.fileLength));
        }
      }
      cell.setImage(null);
    } else if (orgColumnIndex == 4) {
      cell.setText(null);
      if (tuInfo != null) {
        if (tuInfo.exists) {
          String dateTimeString =
              DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
                  .format(new Date(tuInfo.lastModified));
          cell.setText(dateTimeString);
        }
      }
      cell.setImage(null);
    } else if (orgColumnIndex == 5) {
      cell.setText(null);
      if (tuInfo != null) {
        if (tuInfo.location != null) {
          String fileExtension = tuInfo.location.getFileExtension();
          if (fileExtension != null) cell.setText(fileExtension.toLowerCase());
        }
      }
      cell.setImage(null);
    }
  }

  /* (non-Javadoc)
   * @see org.eclipse.cdt.debug.core.executables.IExecutablesChangeListener#executablesListChanged()
   */
  @Override
  public void executablesListChanged() {
    SourceFilesViewer.flushTranslationUnitCache();
  }

  /* (non-Javadoc)
   * @see org.eclipse.cdt.debug.core.executables.IExecutablesChangeListener#executablesChanged(java.util.List)
   */
  @Override
  public void executablesChanged(List<Executable> executables) {
    // no mapping of executable -> TU maintained; just kill all for now
    SourceFilesViewer.flushTranslationUnitCache();
  }
}
Exemplo n.º 22
0
/**
 * Allows to create a new local branch based on another branch or commit.
 *
 * <p>The source can be selected using a branch selection dialog.
 *
 * <p>The user can select a strategy for configuring "Pull". The default as read from the
 * repository's autosetupmerge and autosetuprebase configuration is suggested initially.
 */
class CreateBranchPage extends WizardPage {

  private static final String BRANCH_NAME_PROVIDER_ID =
      "org.eclipse.egit.ui.branchNameProvider"; //$NON-NLS-1$

  /**
   * Get proposed target branch name for given source branch name
   *
   * @param sourceName
   * @return target name
   */
  public String getProposedTargetName(String sourceName) {
    if (sourceName == null) return null;

    if (sourceName.startsWith(Constants.R_REMOTES))
      return myRepository.shortenRemoteBranchName(sourceName);

    if (sourceName.startsWith(Constants.R_TAGS))
      return sourceName.substring(Constants.R_TAGS.length()) + "-branch"; // $NON-NLS-1$

    return ""; //$NON-NLS-1$
  }

  private final Repository myRepository;

  private final IInputValidator myValidator;

  private final String myBaseRef;

  private final RevCommit myBaseCommit;

  private Text nameText;

  /** Whether the contents of {@code nameText} is a suggestion or was entered by the user. */
  private boolean nameIsSuggestion;

  private Button checkout;

  private UpstreamConfig upstreamConfig;

  private UpstreamConfigComponent upstreamConfigComponent;

  private Label sourceIcon;

  private Label sourceNameLabel;

  private String sourceRefName = ""; // $NON-NLS-1$

  private final LocalResourceManager resourceManager =
      new LocalResourceManager(JFaceResources.getResources());

  /**
   * Constructs this page.
   *
   * <p>If a base branch is provided, the drop down will be selected accordingly
   *
   * @param repo the repository
   * @param baseRef the branch or tag to base the new branch on, may be null
   */
  public CreateBranchPage(Repository repo, Ref baseRef) {
    super(CreateBranchPage.class.getName());
    this.myRepository = repo;
    if (baseRef != null) this.myBaseRef = baseRef.getName();
    else this.myBaseRef = null;
    this.myBaseCommit = null;
    this.myValidator =
        ValidationUtils.getRefNameInputValidator(myRepository, Constants.R_HEADS, false);
    if (baseRef != null) this.upstreamConfig = UpstreamConfig.getDefault(repo, baseRef.getName());
    else this.upstreamConfig = UpstreamConfig.NONE;
    setTitle(UIText.CreateBranchPage_Title);
    setMessage(UIText.CreateBranchPage_ChooseBranchAndNameMessage);
  }

  /**
   * Constructs this page.
   *
   * <p>If a base branch is provided, the drop down will be selected accordingly
   *
   * @param repo the repository
   * @param baseCommit the commit to base the new branch on, may be null
   */
  public CreateBranchPage(Repository repo, RevCommit baseCommit) {
    super(CreateBranchPage.class.getName());
    this.myRepository = repo;
    this.myBaseRef = null;
    this.myBaseCommit = baseCommit;
    this.myValidator =
        ValidationUtils.getRefNameInputValidator(myRepository, Constants.R_HEADS, false);
    this.upstreamConfig = UpstreamConfig.NONE;
    setTitle(UIText.CreateBranchPage_Title);
    setMessage(UIText.CreateBranchPage_ChooseNameMessage);
  }

  @Override
  public void createControl(Composite parent) {
    Composite main = new Composite(parent, SWT.NONE);
    main.setLayout(new GridLayout(4, false));

    Label sourceLabel = new Label(main, SWT.NONE);
    sourceLabel.setText(UIText.CreateBranchPage_SourceLabel);
    sourceLabel.setToolTipText(UIText.CreateBranchPage_SourceTooltip);

    sourceIcon = new Label(main, SWT.NONE);
    sourceIcon.setImage(UIIcons.getImage(resourceManager, UIIcons.BRANCH));
    sourceIcon.setLayoutData(GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER).create());

    sourceNameLabel = new Label(main, SWT.NONE);
    sourceNameLabel.setLayoutData(
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(true, false).create());

    Button selectButton = new Button(main, SWT.NONE);
    selectButton.setText(UIText.CreateBranchPage_SourceSelectButton);
    selectButton.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            selectSource();
          }
        });
    UIUtils.setButtonLayoutData(selectButton);

    Label nameLabel = new Label(main, SWT.NONE);
    nameLabel.setText(UIText.CreateBranchPage_BranchNameLabel);
    nameLabel.setLayoutData(
        GridDataFactory.fillDefaults().span(1, 1).align(SWT.BEGINNING, SWT.CENTER).create());
    nameLabel.setToolTipText(UIText.CreateBranchPage_BranchNameToolTip);

    nameText = new Text(main, SWT.BORDER);
    // give focus to the nameText if label is activated using the mnemonic
    nameLabel.addTraverseListener(
        new TraverseListener() {
          @Override
          public void keyTraversed(TraverseEvent e) {
            nameText.setFocus();
          }
        });

    nameText.addModifyListener(
        new ModifyListener() {
          @Override
          public void modifyText(ModifyEvent e) {
            nameIsSuggestion = false;
          }
        });
    // enable testing with SWTBot
    nameText.setData("org.eclipse.swtbot.widget.key", "BranchName"); // $NON-NLS-1$ //$NON-NLS-2$
    GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(nameText);

    upstreamConfigComponent = new UpstreamConfigComponent(main, SWT.NONE);
    GridDataFactory.fillDefaults()
        .grab(true, false)
        .span(4, 1)
        .applyTo(upstreamConfigComponent.getContainer());

    upstreamConfigComponent.addUpstreamConfigSelectionListener(
        new UpstreamConfigSelectionListener() {
          @Override
          public void upstreamConfigSelected(UpstreamConfig newUpstreamConfig) {
            upstreamConfig = newUpstreamConfig;
            checkPage();
          }
        });

    boolean isBare = myRepository.isBare();
    checkout = new Button(main, SWT.CHECK);
    checkout.setText(UIText.CreateBranchPage_CheckoutButton);
    // most of the time, we probably will check this out
    // unless we have a bare repository which doesn't allow
    // check out at all
    checkout.setSelection(!isBare);
    checkout.setEnabled(!isBare);
    checkout.setVisible(!isBare);
    GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(checkout);
    checkout.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            checkPage();
          }
        });

    Dialog.applyDialogFont(main);
    setControl(main);

    if (this.myBaseCommit != null) setSourceCommit(this.myBaseCommit);
    else if (myBaseRef != null) setSourceRef(myBaseRef);

    nameText.setFocus();
    // add the listener just now to avoid unneeded checkPage()
    nameText.addModifyListener(
        new ModifyListener() {
          @Override
          public void modifyText(ModifyEvent e) {
            checkPage();
          }
        });
  }

  @Override
  public void dispose() {
    resourceManager.dispose();
  }

  private void setSourceRef(String refName) {
    String shortName = Repository.shortenRefName(refName);
    sourceNameLabel.setText(shortName);
    if (refName.startsWith(Constants.R_HEADS) || refName.startsWith(Constants.R_REMOTES))
      sourceIcon.setImage(UIIcons.getImage(resourceManager, UIIcons.BRANCH));
    else if (refName.startsWith(Constants.R_TAGS))
      sourceIcon.setImage(UIIcons.getImage(resourceManager, UIIcons.TAG));
    else sourceIcon.setImage(UIIcons.getImage(resourceManager, UIIcons.CHANGESET));

    sourceRefName = refName;

    suggestBranchName(refName);
    upstreamConfig = UpstreamConfig.getDefault(myRepository, refName);
    checkPage();
  }

  private void setSourceCommit(RevCommit commit) {
    sourceNameLabel.setText(commit.abbreviate(7).name());
    sourceIcon.setImage(UIIcons.getImage(resourceManager, UIIcons.CHANGESET));

    sourceRefName = commit.name();

    upstreamConfig = UpstreamConfig.NONE;
    checkPage();
  }

  private void selectSource() {
    SourceSelectionDialog dialog =
        new SourceSelectionDialog(getShell(), myRepository, sourceRefName);
    int result = dialog.open();
    if (result == Window.OK) {
      String refName = dialog.getRefName();
      setSourceRef(refName);
      nameText.setFocus();
    }
  }

  private void checkPage() {
    try {
      upstreamConfigComponent.setUpstreamConfig(upstreamConfig);

      boolean showUpstreamConfig =
          sourceRefName.startsWith(Constants.R_HEADS)
              || sourceRefName.startsWith(Constants.R_REMOTES);
      Composite container = upstreamConfigComponent.getContainer();
      GridData gd = (GridData) container.getLayoutData();
      if (gd.exclude == showUpstreamConfig) {
        gd.exclude = !showUpstreamConfig;
        container.setVisible(showUpstreamConfig);
        container.getParent().layout(true);
        ensurePreferredHeight(getShell());
      }

      boolean basedOnLocalBranch = sourceRefName.startsWith(Constants.R_HEADS);
      if (basedOnLocalBranch && upstreamConfig != UpstreamConfig.NONE)
        setMessage(UIText.CreateBranchPage_LocalBranchWarningMessage, IMessageProvider.INFORMATION);

      if (sourceRefName.length() == 0) {
        setErrorMessage(UIText.CreateBranchPage_MissingSourceMessage);
        return;
      }
      String message = this.myValidator.isValid(nameText.getText());
      if (message != null) {
        setErrorMessage(message);
        return;
      }

      setErrorMessage(null);
    } finally {
      setPageComplete(getErrorMessage() == null && nameText.getText().length() > 0);
    }
  }

  public String getBranchName() {
    return nameText.getText();
  }

  public boolean checkoutNewBranch() {
    return checkout.getSelection();
  }

  /**
   * @param newRefName
   * @param checkoutNewBranch
   * @param monitor
   * @throws CoreException
   * @throws IOException
   */
  public void createBranch(String newRefName, boolean checkoutNewBranch, IProgressMonitor monitor)
      throws CoreException, IOException {
    monitor.beginTask(UIText.CreateBranchPage_CreatingBranchMessage, IProgressMonitor.UNKNOWN);

    final CreateLocalBranchOperation cbop;

    if (myBaseCommit != null && this.sourceRefName.equals(myBaseCommit.name()))
      cbop = new CreateLocalBranchOperation(myRepository, newRefName, myBaseCommit);
    else
      cbop =
          new CreateLocalBranchOperation(
              myRepository, newRefName, myRepository.getRef(this.sourceRefName), upstreamConfig);

    cbop.execute(monitor);

    if (checkoutNewBranch) {
      if (monitor.isCanceled()) return;
      monitor.beginTask(UIText.CreateBranchPage_CheckingOutMessage, IProgressMonitor.UNKNOWN);
      BranchOperationUI.checkout(myRepository, Constants.R_HEADS + newRefName).run(monitor);
    }
  }

  private void suggestBranchName(String ref) {
    if (nameText.getText().length() == 0 || nameIsSuggestion) {
      String branchNameSuggestion = getBranchNameSuggestionFromProvider();
      if (branchNameSuggestion == null) branchNameSuggestion = getProposedTargetName(ref);

      if (branchNameSuggestion != null) {
        nameText.setText(branchNameSuggestion);
        nameText.selectAll();
        nameIsSuggestion = true;
      }
    }
  }

  private IBranchNameProvider getBranchNameProvider() {
    IExtensionRegistry registry = Platform.getExtensionRegistry();
    IConfigurationElement[] config = registry.getConfigurationElementsFor(BRANCH_NAME_PROVIDER_ID);
    if (config.length > 0) {
      Object provider;
      try {
        provider = config[0].createExecutableExtension("class"); // $NON-NLS-1$
        if (provider instanceof IBranchNameProvider) return (IBranchNameProvider) provider;
      } catch (Throwable e) {
        Activator.logError(UIText.CreateBranchPage_CreateBranchNameProviderFailed, e);
      }
    }
    return null;
  }

  private String getBranchNameSuggestionFromProvider() {
    final AtomicReference<String> ref = new AtomicReference<String>();
    final IBranchNameProvider branchNameProvider = getBranchNameProvider();
    if (branchNameProvider != null)
      SafeRunner.run(
          new SafeRunnable() {
            @Override
            public void run() throws Exception {
              ref.set(branchNameProvider.getBranchNameSuggestion());
            }
          });
    return ref.get();
  }

  private static void ensurePreferredHeight(Shell shell) {
    int preferredHeight = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT).y;
    Point size = shell.getSize();
    if (size.y < preferredHeight) shell.setSize(size.x, preferredHeight);
  }

  private static class SourceSelectionDialog extends AbstractBranchSelectionDialog {

    public SourceSelectionDialog(Shell parentShell, Repository repository, String refToMark) {
      super(
          parentShell,
          repository,
          refToMark,
          SHOW_LOCAL_BRANCHES
              | SHOW_REMOTE_BRANCHES
              | SHOW_TAGS
              | SHOW_REFERENCES
              | SELECT_CURRENT_REF
              | EXPAND_LOCAL_BRANCHES_NODE
              | EXPAND_REMOTE_BRANCHES_NODE);
    }

    @Override
    protected void refNameSelected(String refName) {
      setOkButtonEnabled(refName != null);
    }

    @Override
    protected String getTitle() {
      return UIText.CreateBranchPage_SourceSelectionDialogTitle;
    }

    @Override
    protected String getMessageText() {
      return UIText.CreateBranchPage_SourceSelectionDialogMessage;
    }
  }
}
public class ConnectionLabelProvider extends CommonListeningLabelProvider
    implements PropertyChangeListener {
  private static final Logger logger = LoggerFactory.getLogger(ConnectionLabelProvider.class);

  private final ResourceManager resource = new LocalResourceManager(JFaceResources.getResources());

  public ConnectionLabelProvider() {
    super("org.openscada.core.ui.connection.provider"); // $NON-NLS-1$
  }

  @Override
  public void dispose() {
    this.resource.dispose();
    super.dispose();
  }

  private StyledString getConnectionString(final ConnectionHolder holder) {
    final ConnectionService service = holder.getConnectionService();

    final ConnectionDescriptor desc = holder.getConnectionInformation();

    final StyledString str = new StyledString(makeLabel(desc.getConnectionInformation()));

    if (service != null) {
      str.append(" [", StyledString.DECORATIONS_STYLER); // $NON-NLS-1$
      final Connection connection = service.getConnection();
      if (connection != null) {
        str.append(
            String.format("%s", holder.getConnectionState()),
            StyledString.DECORATIONS_STYLER); // $NON-NLS-1$
      }
      str.append("]", StyledString.DECORATIONS_STYLER); // $NON-NLS-1$
    }

    if (desc.getServiceId() != null) {
      str.append(
          String.format(" (%s)", desc.getServiceId()),
          StyledString.QUALIFIER_STYLER); // $NON-NLS-1$
    }

    return str;
  }

  private String makeLabel(final ConnectionInformation connectionInformation) {
    return connectionInformation.toMaskedString();
  }

  @Override
  public void updateLabel(final StyledViewerLabel label, final Object element) {
    if (element instanceof ConnectionDiscovererBean) {
      final ConnectionDiscovererBean bean = (ConnectionDiscovererBean) element;
      if (bean.getImageDescriptor() != null) {
        label.setImage(
            this.resource.createImage(((ConnectionDiscovererBean) element).getImageDescriptor()));
      }
      label.setText(bean.getName());
    } else if (element instanceof ConnectionHolder) {
      final Image image =
          this.resource.createImage(
              ImageDescriptor.createFromFile(
                  ConnectionLabelProvider.class, "icons/connection.gif")); // $NON-NLS-1$
      label.setImage(image);

      label.setStyledText(getConnectionString((ConnectionHolder) element));
    }
  }

  @Override
  protected void addListenerTo(final Object next) {
    super.addListenerTo(next);
    if (next instanceof ConnectionHolder) {
      ((ConnectionHolder) next).addPropertyChangeListener(this);
    }
  }

  @Override
  protected void removeListenerFrom(final Object next) {
    if (next instanceof ConnectionHolder) {
      ((ConnectionHolder) next).removePropertyChangeListener(this);
    }
    super.removeListenerFrom(next);
  }

  public void propertyChange(final PropertyChangeEvent evt) {
    logger.debug("Detected a property change: {}", evt); // $NON-NLS-1$
    fireChangeEvent(Arrays.asList(evt.getSource()));
  }
}
Exemplo n.º 24
0
 /**
  * @param parentShell
  * @param folderName
  */
 public AggregateNewsDialog(Shell parentShell, String folderName) {
   super(parentShell);
   fFolderName = folderName;
   fResources = new LocalResourceManager(JFaceResources.getResources());
   fPreferences = Owl.getPreferenceService().getGlobalScope();
 }
Exemplo n.º 25
0
  /** Instantiates a new {@link ModelLabelProvider}. */
  public ModelLabelProvider() {

    this.resources = new LocalResourceManager(JFaceResources.getResources());
  }
 /** Creates a new workbench label provider. */
 public CopiedWorkbenchLabelProvider() {
   PlatformUI.getWorkbench().getEditorRegistry().addPropertyListener(editorRegistryListener);
   this.resourceManager = new LocalResourceManager(JFaceResources.getResources());
 }
Exemplo n.º 27
0
 /*
  * (non-Javadoc) Method declared on IWizard.
  */
 public Image getDefaultPageImage() {
   if (defaultImage == null) {
     defaultImage = JFaceResources.getResources().createImageWithDefault(defaultImageDescriptor);
   }
   return defaultImage;
 }
 public GoogleCredentialDialog(Shell parentShell) {
   super(parentShell);
   fResources = new LocalResourceManager(JFaceResources.getResources());
 }
/**
 * The small summary below the SQL invocation overview.
 *
 * @author Ivan Senic
 */
public class SqlInvocSummaryTextInputController extends AbstractTextInputController {

  /** Constant for the slowest80/20 color id. */
  private static final String SLOWEST8020_COLOR = "slowest8020Color";

  /** Link for slowest 80% sqls. */
  private static final String SLOWEST80_LINK = "slowest80Link";

  /** Link for slowest 20% sqls. */
  private static final String SLOWEST20_LINK = "slowest20Link";

  /** Slowest 80/20 string. */
  private static final String SLOWEST_80_20 = "Slowest 80%/20%:";

  /** SQLs duration in invocation string. */
  private static final String SQLS_DURATION_IN_INVOCATION = "SQLs duration in invocation:";

  /** Total duration string. */
  private static final String TOTAL_DURATION = "Total duration:";

  /** Total SQLs string. */
  private static final String TOTAL_SQLS = "Total SQLs:";

  /** Reset link to be added to the slowest 80/20 count when selection is active. */
  private static final String RESET_LINK = "<a href=\"reset\">[RESET]</a>";

  /** System {@link SWT#COLOR_DARK_GREEN} color. */
  private static final RGB GREEN_RGB;

  /** System {@link SWT#COLOR_DARK_YELLOW} color. */
  private static final RGB YELLOW_RGB;

  /** System {@link SWT#COLOR_RED} color. */
  private static final RGB RED_RGB;

  /** Local resource manager for color creation. */
  private ResourceManager resourceManager = new LocalResourceManager(JFaceResources.getResources());

  /** Main composite. */
  private Composite main;

  /** Total count SQL field. */
  private FormText totalSql;

  /** Total SQL duration field. */
  private FormText totalDuration;

  /** Percentage in invocation. */
  private FormText percentageOfDuration;

  /** Slowest 80%/20% count. */
  private FormText slowestCount;

  /** HYperlink settings so that we can change the link color. */
  private HyperlinkSettings slowestHyperlinkSettings;

  /** List that will be passed to display slowest 80%. */
  private Collection<SqlStatementData> slowest80List = new ArrayList<>();

  /** List that will be passed to display slowest 20%. */
  private Collection<SqlStatementData> slowest20List = new ArrayList<>();

  /** Keep the source invocations. */
  private List<InvocationSequenceData> sourceInvocations;

  /** Content displayed in slowest 80/20 without the link. */
  private String slowestContent;

  /** If reset link is displayed. */
  private boolean resetDisplayed;

  static {
    Display display = Display.getDefault();
    GREEN_RGB = display.getSystemColor(SWT.COLOR_DARK_GREEN).getRGB();
    YELLOW_RGB = display.getSystemColor(SWT.COLOR_DARK_YELLOW).getRGB();
    RED_RGB = display.getSystemColor(SWT.COLOR_RED).getRGB();
  }

  /** {@inheritDoc} */
  @Override
  public void createPartControl(Composite parent, FormToolkit toolkit) {
    main = toolkit.createComposite(parent, SWT.BORDER);
    main.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    GridLayout gl = new GridLayout(8, false);
    main.setLayout(gl);

    toolkit
        .createLabel(main, null)
        .setImage(InspectIT.getDefault().getImage(InspectITImages.IMG_DATABASE));

    totalSql = toolkit.createFormText(main, false);
    totalSql.setToolTipText("Total amount of SQL Statements executed in the invocation");
    totalSql.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

    toolkit
        .createLabel(main, null)
        .setImage(InspectIT.getDefault().getImage(InspectITImages.IMG_TIME));

    totalDuration = toolkit.createFormText(main, false);
    totalDuration.setToolTipText("Duration sum of all SQL Statements executed in the invocation");
    totalDuration.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

    toolkit
        .createLabel(main, null)
        .setImage(InspectIT.getDefault().getImage(InspectITImages.IMG_INVOCATION));

    percentageOfDuration = toolkit.createFormText(main, false);
    percentageOfDuration.setToolTipText(
        "Percentage of the time spent in the invocation on SQL Statements execution");
    percentageOfDuration.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));

    toolkit
        .createLabel(main, null)
        .setImage(InspectIT.getDefault().getImage(InspectITImages.IMG_HELP));

    slowestCount = toolkit.createFormText(main, false);
    slowestCount.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
    slowestCount.setToolTipText(
        "Amount of slowest SQL Statements that take 80%/20% time of total SQL execution duration");

    // remove left and right margins from the parent
    Layout parentLayout = parent.getLayout();
    if (parentLayout instanceof GridLayout) {
      ((GridLayout) parentLayout).marginWidth = 0;
      ((GridLayout) parentLayout).marginHeight = 0;
    }

    setDefaultText();

    slowestHyperlinkSettings = new HyperlinkSettings(parent.getDisplay());
    slowestHyperlinkSettings.setHyperlinkUnderlineMode(HyperlinkSettings.UNDERLINE_HOVER);
    slowestCount.setHyperlinkSettings(slowestHyperlinkSettings);
    slowestCount.addHyperlinkListener(getHyperlinkAdapter());
  }

  /** {@inheritDoc} */
  @SuppressWarnings("unchecked")
  @Override
  public void setDataInput(List<? extends DefaultData> data) {
    if (CollectionUtils.isNotEmpty(data)) {
      DefaultData defaultData = data.get(0);
      if (defaultData instanceof InvocationSequenceData) {
        updateRepresentation((List<InvocationSequenceData>) data);
      }
    } else {
      setDefaultText();
    }
  }

  /**
   * Updates the representation of the text form.
   *
   * @param invocations Invocations to display.
   */
  @SuppressWarnings("unchecked")
  private void updateRepresentation(List<InvocationSequenceData> invocations) {
    sourceInvocations = invocations;
    resetDisplayed = false;

    MutableDouble duration = new MutableDouble(0d);
    List<SqlStatementData> sqlList = new ArrayList<>();
    InvocationSequenceDataHelper.collectSqlsInInvocations(invocations, sqlList, duration);
    double totalInvocationsDuration = 0d;
    for (InvocationSequenceData inv : invocations) {
      totalInvocationsDuration += inv.getDuration();
    }
    double percentage = (duration.toDouble() / totalInvocationsDuration) * 100;

    slowest80List.clear();
    int slowest80 = getSlowestSqlCount(duration.toDouble(), sqlList, 0.8d, slowest80List);
    int slowest20 = sqlList.size() - slowest80;
    slowest20List = CollectionUtils.subtract(sqlList, slowest80List);

    totalSql.setText(
        "<form><p><b>" + TOTAL_SQLS + "</b> " + sqlList.size() + "</p></form>", true, false);
    totalDuration.setText(
        "<form><p><b>"
            + TOTAL_DURATION
            + "</b> "
            + NumberFormatter.formatDouble(duration.doubleValue())
            + " ms</p></form>",
        true,
        false);

    String formatedPercentage = NumberFormatter.formatDouble(percentage, 1);
    if (CollectionUtils.isNotEmpty(sqlList)) {
      Color durationInInvocationColor =
          ColorFormatter.getPerformanceColor(
              GREEN_RGB, YELLOW_RGB, RED_RGB, percentage, 20d, 80d, resourceManager);
      percentageOfDuration.setColor("durationInInvocationColor", durationInInvocationColor);
      percentageOfDuration.setText(
          "<form><p><b>"
              + SQLS_DURATION_IN_INVOCATION
              + "</b> <span color=\"durationInInvocationColor\">"
              + formatedPercentage
              + "%</span></p></form>",
          true,
          false);
    } else {
      percentageOfDuration.setText(
          "<form><p><b>"
              + SQLS_DURATION_IN_INVOCATION
              + "</b> "
              + formatedPercentage
              + "%</p></form>",
          true,
          false);
    }

    String slowest80String = getCountAndPercentage(slowest80, sqlList.size());
    String slowest20String = getCountAndPercentage(slowest20, sqlList.size());
    if (CollectionUtils.isNotEmpty(sqlList)) {
      double slowest80Percentage = ((double) slowest80 / sqlList.size()) * 100;
      if (Double.isNaN(slowest80Percentage)) {
        slowest80Percentage = 0;
      }
      Color color8020 =
          ColorFormatter.getPerformanceColor(
              GREEN_RGB, YELLOW_RGB, RED_RGB, slowest80Percentage, 70d, 10d, resourceManager);
      slowestCount.setColor(SLOWEST8020_COLOR, color8020);
      slowestHyperlinkSettings.setForeground(color8020);

      StringBuilder text = new StringBuilder("<b>" + SLOWEST_80_20 + "</b> ");
      if (slowest80 > 0) {
        text.append("<a href=\"" + SLOWEST80_LINK + "\">" + slowest80String + "</a>");
      } else {
        text.append("<span color=\"" + SLOWEST8020_COLOR + "\">" + slowest80String + "</span>");
      }
      text.append(" / ");
      if (slowest20 > 0) {
        text.append("<a href=\"" + SLOWEST20_LINK + "\">" + slowest20String + "</a>");
      } else {
        text.append("<span color=\"" + SLOWEST8020_COLOR + "\">" + slowest20String + "</span>");
      }
      slowestContent = text.toString();
    } else {
      slowestContent = "<b>" + SLOWEST_80_20 + "</b> " + slowest80String + " / " + slowest20String;
    }
    slowestCount.setText("<form><p>" + slowestContent + "</p></form>", true, false);

    main.layout();
  }

  /**
   * Returns the {@link HyperlinkAdapter} to handle the Hyperlink clicks.
   *
   * @return Returns the {@link HyperlinkAdapter} to handle the Hyperlink clicks.
   */
  private HyperlinkAdapter getHyperlinkAdapter() {
    return new HyperlinkAdapter() {
      @Override
      public void linkActivated(final HyperlinkEvent e) {
        Display.getDefault()
            .asyncExec(
                new Runnable() {
                  @Override
                  public void run() {
                    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
                    IWorkbenchPage page = window.getActivePage();
                    IRootEditor rootEditor = (IRootEditor) page.getActiveEditor();
                    if (SLOWEST80_LINK.equals(e.getHref())) {
                      rootEditor.setDataInput(new ArrayList<>(slowest80List));
                      showResetFor8020(true);
                    } else if (SLOWEST20_LINK.equals(e.getHref())) {
                      rootEditor.setDataInput(new ArrayList<>(slowest20List));
                      showResetFor8020(true);
                    } else {
                      rootEditor.setDataInput(sourceInvocations);
                      showResetFor8020(false);
                    }
                  }
                });
      }
    };
  }

  /**
   * Define if reset button should be displayed in the 80/20 test.
   *
   * @param show If <code>true</code> reset link will be show, otherwise hidden.
   */
  private void showResetFor8020(boolean show) {
    if (show && !resetDisplayed) {
      resetDisplayed = true;
      slowestCount.setText(
          "<form><p>" + slowestContent + " " + RESET_LINK + "</p></form>", true, false);
    } else if (!show && resetDisplayed) {
      resetDisplayed = false;
      slowestCount.setText("<form><p>" + slowestContent + "</p></form>", true, false);
    }
  }

  /** Sets default text that has no informations displayed. */
  private void setDefaultText() {
    resetDisplayed = false;
    totalSql.setText("<form><p><b>" + TOTAL_SQLS + "</b></p></form>", true, false);
    totalDuration.setText("<form><p><b>" + TOTAL_DURATION + "</b></p></form>", true, false);
    percentageOfDuration.setText(
        "<form><p><b>" + SQLS_DURATION_IN_INVOCATION + "</b></p></form>", true, false);
    slowestCount.setText("<form><p><b>" + SLOWEST_80_20 + "</b></p></form>", true, false);
  }

  /**
   * Returns string representation of count and percentage.
   *
   * @param count Count.
   * @param totalCount Total count.
   * @return {@link String} representation.
   */
  private String getCountAndPercentage(int count, int totalCount) {
    if (0 == totalCount) {
      return "0(0%)";
    }
    return count
        + "("
        + NumberFormatter.formatDouble(((double) count / totalCount) * 100, 0)
        + "%)";
  }

  /**
   * Calculates how much slowest SQL can fit into the given percentage of total duration.
   *
   * @param totalDuration Total duration of all SQLs.
   * @param sqlStatementDataList List of SQL. Note that there is a side effect of list sorting.
   * @param percentage Wanted percentages to be calculated.
   * @param resultList List to add the resulting statements to.
   * @return Return the count of SQL.
   */
  private int getSlowestSqlCount(
      double totalDuration,
      List<SqlStatementData> sqlStatementDataList,
      double percentage,
      Collection<SqlStatementData> resultList) {
    // sort first
    Collections.sort(
        sqlStatementDataList,
        new Comparator<SqlStatementData>() {
          @Override
          public int compare(SqlStatementData o1, SqlStatementData o2) {
            return ObjectUtils.compare(o2.getDuration(), o1.getDuration());
          }
        });

    int result = 0;
    double currentDurationSum = 0;
    for (SqlStatementData sqlStatementData : sqlStatementDataList) {
      if ((currentDurationSum / totalDuration) < percentage) {
        result++;
        resultList.add(sqlStatementData);
      } else {
        break;
      }
      currentDurationSum += sqlStatementData.getDuration();
    }
    return result;
  }

  /** {@inheritDoc} */
  @Override
  public void dispose() {
    resourceManager.dispose();
    super.dispose();
  }
}
Exemplo n.º 30
0
  static class CommitStatusLabelProvider extends BaseLabelProvider implements IStyledLabelProvider {

    private Image DEFAULT =
        PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE);

    private ResourceManager resourceManager =
        new LocalResourceManager(JFaceResources.getResources());

    private final Image SUBMODULE = UIIcons.REPOSITORY.createImage();

    private Image getEditorImage(CommitItem item) {
      if (!item.submodule) {
        Image image = DEFAULT;
        String name = new Path(item.path).lastSegment();
        if (name != null) {
          ImageDescriptor descriptor =
              PlatformUI.getWorkbench().getEditorRegistry().getImageDescriptor(name);
          image = (Image) this.resourceManager.get(descriptor);
        }
        return image;
      } else return SUBMODULE;
    }

    private Image getDecoratedImage(Image base, ImageDescriptor decorator) {
      DecorationOverlayIcon decorated =
          new DecorationOverlayIcon(base, decorator, IDecoration.BOTTOM_RIGHT);
      return (Image) this.resourceManager.get(decorated);
    }

    public StyledString getStyledText(Object element) {
      return new StyledString();
    }

    public Image getImage(Object element) {
      CommitItem item = (CommitItem) element;
      ImageDescriptor decorator = null;
      switch (item.status) {
        case UNTRACKED:
          decorator = UIIcons.OVR_UNTRACKED;
          break;
        case ADDED:
        case ADDED_INDEX_DIFF:
          decorator = UIIcons.OVR_STAGED_ADD;
          break;
        case REMOVED:
        case REMOVED_NOT_STAGED:
        case REMOVED_UNTRACKED:
          decorator = UIIcons.OVR_STAGED_REMOVE;
          break;
        default:
          break;
      }
      return decorator != null
          ? getDecoratedImage(getEditorImage(item), decorator)
          : getEditorImage(item);
    }

    @Override
    public void dispose() {
      SUBMODULE.dispose();
      resourceManager.dispose();
      super.dispose();
    }
  }