/*
   * EnumFormatEtc([in] dwDirection, [out] ppenumFormatetc)
   * Ownership of ppenumFormatetc transfers from callee to caller so reference count on ppenumFormatetc
   * must be incremented before returning.  Caller is responsible for releasing ppenumFormatetc.
   */
  private int EnumFormatEtc(int dwDirection, long /*int*/ ppenumFormatetc) {
    // only allow getting of data - SetData is not currently supported
    if (dwDirection == COM.DATADIR_SET) return COM.E_NOTIMPL;

    // what types have been registered?
    TransferData[] allowedDataTypes = new TransferData[0];
    for (int i = 0; i < transferAgents.length; i++) {
      Transfer transferAgent = transferAgents[i];
      if (transferAgent != null) {
        TransferData[] formats = transferAgent.getSupportedTypes();
        TransferData[] newAllowedDataTypes =
            new TransferData[allowedDataTypes.length + formats.length];
        System.arraycopy(allowedDataTypes, 0, newAllowedDataTypes, 0, allowedDataTypes.length);
        System.arraycopy(formats, 0, newAllowedDataTypes, allowedDataTypes.length, formats.length);
        allowedDataTypes = newAllowedDataTypes;
      }
    }

    OleEnumFORMATETC enumFORMATETC = new OleEnumFORMATETC();
    enumFORMATETC.AddRef();

    FORMATETC[] formats = new FORMATETC[allowedDataTypes.length];
    for (int i = 0; i < formats.length; i++) {
      formats[i] = allowedDataTypes[i].formatetc;
    }
    enumFORMATETC.setFormats(formats);

    OS.MoveMemory(ppenumFormatetc, new long /*int*/[] {enumFORMATETC.getAddress()}, OS.PTR_SIZEOF);
    return COM.S_OK;
  }
  public void setActive(boolean b) {
    // the function is called 3 times when leaving this perspective this odd
    // logic is here so it doesn't reload the data when leaving this perspective
    if (b) {
      if (!this.isActive) {
        System.out.println("create eclResults setActive");
        if (System.getProperties().getProperty("resultsFile") != null
            && !System.getProperties().getProperty("resultsFile").equals("")) {
          String xmlFile = System.getProperties().getProperty("resultsFile");
          ArrayList<String> resultFiles = parseData("resultsFile");
          for (int i = 0; i < resultFiles.size(); i++) {
            openResultsXML(resultFiles.get(i));
          }
          // openResultsXML(xmlFile);
          System.getProperties().setProperty("resultsFile", "");
        }
        int len = folder.getItemCount();
        folder.setSelection(len - 1);
        this.isActive = true;
      } else {
        this.isActive = false;
      }

    } else {
      System.out.println("create eclResults setActive -- deactivate");
    }
  }
  public ArrayList parseData(String propName) {
    ArrayList<String> files = new ArrayList();
    String saltData = "";
    try {
      if (System.getProperty(propName) != null) {
        saltData = System.getProperty(propName);
      }
      StringTokenizer fileTokens = new StringTokenizer(saltData, ",");
      while (fileTokens.hasMoreElements()) {
        String file = fileTokens.nextToken();

        if (file != null && !file.equals("null") && !file.equals("")) {
          System.out.println("Built tab from list" + file);

          files.add(file);
        }
      }
      saltData = "";
    } catch (Exception e) {
      System.out.println("Failed to open files ");
    }
    // just incase it was a signle node
    if (saltData != null && !saltData.equals("null") && !saltData.equals("")) {
      System.out.println("Built tab from single " + saltData);
      files.add(saltData);
    }
    System.setProperty(propName, "");
    return files;
  }
  public void openProfiles_old() {
    String saltData = "";
    try {
      if (System.getProperty("saltData") != null) {
        saltData = System.getProperty("saltData");
      }
      StringTokenizer fileTokens = new StringTokenizer(saltData, ",");
      while (fileTokens.hasMoreElements()) {
        String file = fileTokens.nextToken();

        if (file != null && !file.equals("null") && !file.equals("")) {
          System.out.println("Built tab from list" + file);
          buildProfileTab(file);
        }
      }
      saltData = "";
    } catch (Exception e) {
      System.out.println("Failed to open files ");
    }
    // just incase it was a signle node
    if (saltData != null && !saltData.equals("null") && !saltData.equals("")) {
      System.out.println("Built tab from single " + saltData);
      buildProfileTab(saltData);
    }
    System.setProperty("saltData", "");
  }
Exemple #5
0
  public ILaunchConfiguration getSelectedLaunchConfiguration() {
    if (!fLaunchConfigButton.getSelection()) return null;

    String configName = fLaunchConfigCombo.getText();
    try {
      ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
      ILaunchConfigurationType type =
          manager.getLaunchConfigurationType(EclipseLaunchShortcut.CONFIGURATION_TYPE);
      ILaunchConfigurationType type2 =
          manager.getLaunchConfigurationType(IPDELauncherConstants.OSGI_CONFIGURATION_TYPE);
      ILaunchConfiguration[] configs = manager.getLaunchConfigurations(type);
      ILaunchConfiguration[] configs2 = manager.getLaunchConfigurations(type2);
      ILaunchConfiguration[] configurations =
          new ILaunchConfiguration[configs.length + configs2.length];
      System.arraycopy(configs, 0, configurations, 0, configs.length);
      System.arraycopy(configs2, 0, configurations, configs.length, configs2.length);
      for (int i = 0; i < configurations.length; i++) {
        if (configurations[i].getName().equals(configName)
            && !DebugUITools.isPrivate(configurations[i])) return configurations[i];
      }
    } catch (CoreException e) {
      PDEPlugin.logException(e);
    }
    return null;
  }
 /**
  * This implementation of <code>dragOver</code> provides a default drag under effect for the
  * feedback specified in <code>event.feedback</code>. The class description lists the FEEDBACK
  * constants that are applicable to the class.
  *
  * <p>For additional information see <code>DropTargetAdapter.dragOver</code>.
  *
  * <p>Subclasses that override this method should call <code>super.dragOver(event)</code> to get
  * the default drag under effect implementation.
  *
  * @param event the information associated with the drag over event
  * @see DropTargetAdapter
  * @see DropTargetEvent
  * @see DND#FEEDBACK_SELECT
  * @see DND#FEEDBACK_SCROLL
  */
 public void dragOver(DropTargetEvent event) {
   Table table = (Table) control;
   long /*int*/ handle = table.handle;
   int effect = checkEffect(event.feedback);
   Point coordinates = new Point(event.x, event.y);
   coordinates = table.toControl(coordinates);
   long /*int*/[] path = new long /*int*/[1];
   OS.gtk_tree_view_get_path_at_pos(handle, coordinates.x, coordinates.y, path, null, null, null);
   int index = -1;
   if (path[0] != 0) {
     long /*int*/ indices = OS.gtk_tree_path_get_indices(path[0]);
     if (indices != 0) {
       int[] temp = new int[1];
       OS.memmove(temp, indices, 4);
       index = temp[0];
     }
   }
   if ((effect & DND.FEEDBACK_SCROLL) == 0) {
     scrollBeginTime = 0;
     scrollIndex = -1;
   } else {
     if (index != -1 && scrollIndex == index && scrollBeginTime != 0) {
       if (System.currentTimeMillis() >= scrollBeginTime) {
         if (coordinates.y < table.getItemHeight()) {
           OS.gtk_tree_path_prev(path[0]);
         } else {
           OS.gtk_tree_path_next(path[0]);
         }
         if (path[0] != 0) {
           OS.gtk_tree_view_scroll_to_cell(handle, path[0], 0, false, 0, 0);
           OS.gtk_tree_path_free(path[0]);
           path[0] = 0;
           OS.gtk_tree_view_get_path_at_pos(
               handle, coordinates.x, coordinates.y, path, null, null, null);
         }
         scrollBeginTime = 0;
         scrollIndex = -1;
       }
     } else {
       scrollBeginTime = System.currentTimeMillis() + SCROLL_HYSTERESIS;
       scrollIndex = index;
     }
   }
   if (path[0] != 0) {
     int position = 0;
     if ((effect & DND.FEEDBACK_SELECT) != 0) position = OS.GTK_TREE_VIEW_DROP_INTO_OR_BEFORE;
     // if ((effect & DND.FEEDBACK_INSERT_BEFORE) != 0) position = OS.GTK_TREE_VIEW_DROP_BEFORE;
     // if ((effect & DND.FEEDBACK_INSERT_AFTER) != 0) position = OS.GTK_TREE_VIEW_DROP_AFTER;
     if (position != 0) {
       OS.gtk_tree_view_set_drag_dest_row(handle, path[0], OS.GTK_TREE_VIEW_DROP_INTO_OR_BEFORE);
     } else {
       OS.gtk_tree_view_set_drag_dest_row(handle, 0, OS.GTK_TREE_VIEW_DROP_BEFORE);
     }
   } else {
     OS.gtk_tree_view_set_drag_dest_row(handle, 0, OS.GTK_TREE_VIEW_DROP_BEFORE);
   }
   if (path[0] != 0) OS.gtk_tree_path_free(path[0]);
 }
 public void show(int effect, int x, int y) {
   effect = checkEffect(effect);
   int handle = table.handle;
   Point coordinates = new Point(x, y);
   coordinates = table.toControl(coordinates);
   LVHITTESTINFO pinfo = new LVHITTESTINFO();
   pinfo.x = coordinates.x;
   pinfo.y = coordinates.y;
   OS.SendMessage(handle, OS.LVM_HITTEST, 0, pinfo);
   if ((effect & DND.FEEDBACK_SCROLL) == 0) {
     scrollBeginTime = 0;
     scrollIndex = -1;
   } else {
     if (pinfo.iItem != -1 && scrollIndex == pinfo.iItem && scrollBeginTime != 0) {
       if (System.currentTimeMillis() >= scrollBeginTime) {
         int top = Math.max(0, OS.SendMessage(handle, OS.LVM_GETTOPINDEX, 0, 0));
         int count = OS.SendMessage(handle, OS.LVM_GETITEMCOUNT, 0, 0);
         int index =
             (scrollIndex - 1 < top)
                 ? Math.max(0, scrollIndex - 1)
                 : Math.min(count - 1, scrollIndex + 1);
         OS.SendMessage(handle, OS.LVM_ENSUREVISIBLE, index, 0);
         scrollBeginTime = 0;
         scrollIndex = -1;
       }
     } else {
       scrollBeginTime = System.currentTimeMillis() + SCROLL_HYSTERESIS;
       scrollIndex = pinfo.iItem;
     }
   }
   LVITEM lvItem = new LVITEM();
   lvItem.stateMask = OS.LVIS_DROPHILITED;
   OS.SendMessage(handle, OS.LVM_SETITEMSTATE, -1, lvItem);
   if (pinfo.iItem != -1 && (effect & DND.FEEDBACK_SELECT) != 0) {
     lvItem.state = OS.LVIS_DROPHILITED;
     OS.SendMessage(handle, OS.LVM_SETITEMSTATE, pinfo.iItem, lvItem);
   }
   // Insert mark only supported on Windows XP with manifest
   //	if (OS.COMCTL32_MAJOR >= 6) {
   //		if ((effect & DND.FEEDBACK_INSERT_BEFORE) != 0 || (effect & DND.FEEDBACK_INSERT_AFTER) != 0)
   // {
   //			LVINSERTMARK lvinsertmark = new LVINSERTMARK();
   //			lvinsertmark.cbSize = LVINSERTMARK.sizeof;
   //			lvinsertmark.dwFlags = (effect & DND.FEEDBACK_INSERT_BEFORE) != 0 ? 0 : OS.LVIM_AFTER;
   //			lvinsertmark.iItem = pinfo.iItem == -1 ? 0 : pinfo.iItem;
   //			int hItem = pinfo.iItem;
   //			OS.SendMessage (handle, OS.LVM_SETINSERTMARK, 0, lvinsertmark);
   //		} else {
   //			OS.SendMessage (handle, OS.LVM_SETINSERTMARK, 0, 0);
   //		}
   //	}
   return;
 }
 private String getLineDelimiter() {
   BundleInputContext inputContext = getBundleContext();
   if (inputContext != null) {
     return inputContext.getLineDelimiter();
   }
   return System.getProperty("line.separator"); // $NON-NLS-1$
 }
  public void createButtonPanel(Shell dialog) {
    Composite buttonPanel = new Composite(dialog, SWT.NONE);
    GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, false);
    buttonPanel.setLayoutData(gridData);
    buttonPanel.setLayout(new GridLayout(4, false));

    String buttonAlign =
        System.getProperty("org.pentaho.di.buttonPosition", "right")
            .toLowerCase(); //$NON-NLS-1$ //$NON-NLS-2$

    if (!"left".equals(buttonAlign)) { // $NON-NLS-1$
      Label emptyLabel = new Label(buttonPanel, SWT.NONE);
      gridData = new GridData(SWT.FILL, SWT.FILL, true, false);
      emptyLabel.setLayoutData(gridData);
    }
    okButton = new Button(buttonPanel, SWT.PUSH);
    okButton.setText(Messages.getString("VfsFileChooserDialog.ok")); // $NON-NLS-1$
    gridData = new GridData(SWT.FILL, SWT.FILL, false, false);
    gridData.widthHint = 90;
    okButton.setLayoutData(gridData);
    okButton.addSelectionListener(this);
    cancelButton = new Button(buttonPanel, SWT.PUSH);
    cancelButton.setText(Messages.getString("VfsFileChooserDialog.cancel")); // $NON-NLS-1$
    cancelButton.addSelectionListener(this);
    gridData = new GridData(SWT.FILL, SWT.FILL, false, false);
    gridData.widthHint = 90;
    cancelButton.setLayoutData(gridData);
    if ("center".equals(buttonAlign)) { // $NON-NLS-1$
      Label emptyLabel = new Label(buttonPanel, SWT.NONE);
      gridData = new GridData(SWT.FILL, SWT.FILL, true, false);
      emptyLabel.setLayoutData(gridData);
    }
  }
Exemple #10
0
  /**
   * Initialize the toolbar with icons and selection listeners in the appropriate part of the window
   */
  public void initToolbar() {

    Device dev = shell.getDisplay();
    try {
      exitImg = new Image(dev, "img/exit.png");
      //            openImg = new Image(dev, "img/open.png");
      playImg = new Image(dev, "img/play.png");
      //            pauseImg = new Image(dev, "img/pause.png");

    } catch (Exception e) {
      System.out.println("Cannot load images");
      System.out.println(e.getMessage());
      System.exit(1);
    }

    ToolBar toolBar = new ToolBar(shell, SWT.BORDER);

    GridData gridData = new GridData();
    gridData.horizontalAlignment = GridData.FILL;
    gridData.grabExcessHorizontalSpace = true;
    toolBar.setLayoutData(gridData);

    ToolItem exit = new ToolItem(toolBar, SWT.PUSH);
    exit.setImage(exitImg);

    // ToolItem open = new ToolItem(toolBar, SWT.PUSH);
    // exit.setImage(openImg);

    ToolItem play = new ToolItem(toolBar, SWT.PUSH);
    play.setImage(playImg);

    //        ToolItem pause = new ToolItem(toolBar, SWT.PUSH);
    //        pause.setImage(pauseImg);

    toolBar.pack();

    exit.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            System.exit(0);
          }
        });

    // open.addSelectionListener(new SelectionAdapter() {
    //     @Override
    //     public void widgetSelected(SelectionEvent e) {
    //         FileDialog dialog = new FileDialog(shell, SWT.NULL);
    //         String path = dialog.open();
    //     }
    // });

    play.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetSelected(SelectionEvent e) {
            controller.RunAnimation();
          }
        });
  }
  public void openUrl(String url) {
    String os = System.getProperty("os.name");
    Runtime runtime = Runtime.getRuntime();
    try {
      // Block for Windows Platform
      if (os.startsWith("Windows")) {
        String cmd = "rundll32 url.dll,FileProtocolHandler " + url;
        Process p = runtime.exec(cmd);

        // Block for Mac OS
      } else if (os.startsWith("Mac OS")) {
        Class fileMgr = Class.forName("com.apple.eio.FileManager");
        Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class});
        openURL.invoke(null, new Object[] {url});

        // Block for UNIX Platform
      } else {
        String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
        String browser = null;
        for (int count = 0; count < browsers.length && browser == null; count++)
          if (runtime.exec(new String[] {"which", browsers[count]}).waitFor() == 0)
            browser = browsers[count];

        if (browser == null) throw new Exception("Could not find web browser");
        else runtime.exec(new String[] {browser, url});
      }
    } catch (Exception x) {
      System.err.println("Exception occurd while invoking Browser!");
      x.printStackTrace();
    }
  }
 private void handleDelete() {
   IStructuredSelection ssel = (IStructuredSelection) fPluginTable.getSelection();
   if (ssel.size() > 0) {
     Object[] objects = ssel.toArray();
     IProductPlugin[] plugins = new IProductPlugin[objects.length];
     System.arraycopy(objects, 0, plugins, 0, objects.length);
     getProduct().removePlugins(plugins);
     updateRemoveButtons(true, true);
   }
 }
 static char[] mbcsToWcs(String codePage, byte[] buffer) {
   char[] chars = new char[buffer.length];
   int charCount =
       OS.MultiByteToWideChar(
           OS.CP_ACP, OS.MB_PRECOMPOSED, buffer, buffer.length, chars, chars.length);
   if (charCount == chars.length) return chars;
   char[] result = new char[charCount];
   System.arraycopy(chars, 0, result, 0, charCount);
   return result;
 }
 private void exitMenuItemWidgetSelected(SelectionEvent evt) {
   try {
     // Save app settings to file
     appSettings.store(new FileOutputStream("appsettings.ini"), "");
   } catch (FileNotFoundException e) {
   } catch (IOException e) {
   }
   getShell().dispose();
   System.exit(1);
 }
 /**
  * Return the computer full name. <br>
  *
  * @return the name or <b>null</b> if the name cannot be found
  */
 public static String getComputerFullName() {
   String uname = System.getProperty("user.name");
   if (uname == null || uname.isEmpty()) {
     try {
       final InetAddress addr = InetAddress.getLocalHost();
       uname = addr.getHostName();
     } catch (final Exception e) {
     }
   }
   return uname;
 }
Exemple #16
0
  public List getCategories() {
    List concepts = null;
    try {
      //		GetReturnType request = new GetReturnType();
      //		request.setType("limited");

      GetCategoriesType request = new GetCategoriesType();
      request.setType("core");
      request.setHiddens(false);
      request.setSynonyms(false);

      OntologyResponseMessage msg = new OntologyResponseMessage();
      StatusType procStatus = null;
      while (procStatus == null || !procStatus.getType().equals("DONE")) {
        String response = OntServiceDriver.getCategories(request, "FIND");
        procStatus = msg.processResult(response);
        //				if  other error codes
        //				TABLE_ACCESS_DENIED and USER_INVALID, DATABASE ERROR
        if (procStatus.getType().equals("ERROR")) {
          System.setProperty("errorMessage", procStatus.getValue());
          return concepts;
        }
        procStatus.setType("DONE");
      }
      ConceptsType allConcepts = msg.doReadConcepts();
      if (allConcepts != null) concepts = allConcepts.getConcept();

    } catch (AxisFault e) {
      log.error(e.getMessage());
      System.setProperty("errorMessage", "Ontology cell unavailable");
    } catch (I2B2Exception e) {
      log.error(e.getMessage());
      System.setProperty("errorMessage", e.getMessage());
    } catch (Exception e) {
      log.error(e.getMessage());
      System.setProperty("errorMessage", "Remote server unavailable");
    }

    return concepts;
  }
Exemple #17
0
  private void initPaths() {

    sootClasspath.initialize();

    // platform location
    platform_location = getSootSelection().getJavaProject().getProject().getLocation().toOSString();
    platform_location =
        platform_location.substring(
            0, platform_location.lastIndexOf(System.getProperty("file.separator")));
    // external jars location - may need to change don't think I use this anymore
    setOutputLocation(
        platform_location + getFileHandler().getSootOutputFolder().getFullPath().toOSString());
  }
 static String getProfilePath() {
   String baseDir;
   /* Use the character encoding for the default locale */
   TCHAR buffer = new TCHAR(0, OS.MAX_PATH);
   if (OS.SHGetFolderPath(0, OS.CSIDL_APPDATA, 0, OS.SHGFP_TYPE_CURRENT, buffer) == OS.S_OK) {
     baseDir = buffer.toString(0, buffer.strlen());
   } else {
     baseDir = System.getProperty("user.home"); // $NON-NLS-1$
   }
   return baseDir
       + Mozilla.SEPARATOR_OS
       + "Mozilla"
       + Mozilla.SEPARATOR_OS
       + "eclipse"; //$NON-NLS-1$ //$NON-NLS-2$
 }
Exemple #19
0
 static synchronized void loadLibrary() {
   if (loaded) return;
   loaded = true;
   Toolkit.getDefaultToolkit();
   /*
    * Note that the jawt library is loaded explicitly
    * because it cannot be found by the library loader.
    * All exceptions are caught because the library may
    * have been loaded already.
    */
   try {
     System.loadLibrary("jawt");
   } catch (Throwable e) {
   }
   Library.loadLibrary("swt-awt");
 }
  private String buildFileDialog() {

    // file field
    FileDialog fd = new FileDialog(parentShell, SWT.SAVE);

    fd.setText("Open");
    fd.setFilterPath("C:/");
    String[] filterExt = {"*.xml", "*.csv", "*.*"};
    fd.setFilterExtensions(filterExt);
    String selected = fd.open();
    if (!(fd.getFileName()).equalsIgnoreCase("")) {
      return fd.getFilterPath() + System.getProperty("file.separator") + fd.getFileName();
    } else {
      return "";
    }
  }
 /**
  * Returns an array of listeners who will be notified when a drag and drop operation is in
  * progress, by sending it one of the messages defined in the <code>DragSourceListener</code>
  * interface.
  *
  * @return the listeners who will be notified when a drag and drop operation is in progress
  * @exception SWTException
  *     <ul>
  *       <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  *       <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  *     </ul>
  *
  * @see DragSourceListener
  * @see #addDragListener
  * @see #removeDragListener
  * @see DragSourceEvent
  * @since 3.4
  */
 public DragSourceListener[] getDragListeners() {
   Listener[] listeners = getListeners(DND.DragStart);
   int length = listeners.length;
   DragSourceListener[] dragListeners = new DragSourceListener[length];
   int count = 0;
   for (int i = 0; i < length; i++) {
     Listener listener = listeners[i];
     if (listener instanceof DNDListener) {
       dragListeners[count] = (DragSourceListener) ((DNDListener) listener).getEventListener();
       count++;
     }
   }
   if (count == length) return dragListeners;
   DragSourceListener[] result = new DragSourceListener[count];
   System.arraycopy(dragListeners, 0, result, 0, count);
   return result;
 }
 static byte[] wcsToMbcs(String codePage, String string, boolean terminate) {
   int byteCount;
   char[] chars = new char[string.length()];
   string.getChars(0, chars.length, chars, 0);
   byte[] bytes = new byte[byteCount = chars.length * 2 + (terminate ? 1 : 0)];
   byteCount =
       OS.WideCharToMultiByte(OS.CP_ACP, 0, chars, chars.length, bytes, byteCount, null, null);
   if (terminate) {
     byteCount++;
   } else {
     if (bytes.length != byteCount) {
       byte[] result = new byte[byteCount];
       System.arraycopy(bytes, 0, result, 0, byteCount);
       bytes = result;
     }
   }
   return bytes;
 }
Exemple #23
0
 private String[] splitString(String text) {
   String[] lines = new String[1];
   int start = 0, pos;
   do {
     pos = text.indexOf('\n', start);
     if (pos == -1) {
       lines[lines.length - 1] = text.substring(start);
     } else {
       boolean crlf = (pos > 0) && (text.charAt(pos - 1) == '\r');
       lines[lines.length - 1] = text.substring(start, pos - (crlf ? 1 : 0));
       start = pos + 1;
       String[] newLines = new String[lines.length + 1];
       System.arraycopy(lines, 0, newLines, 0, lines.length);
       lines = newLines;
     }
   } while (pos != -1);
   return lines;
 }
 public static boolean test() {
   int fail = 0;
   String url;
   String pluginPath = System.getProperty("PLUGIN_PATH");
   if (verbose) System.out.println("PLUGIN_PATH <" + pluginPath + ">");
   if (pluginPath == null)
     url = Browser5.class.getClassLoader().getResource("browser5.html").toString();
   else url = pluginPath + "/data/browser5.html";
   String[] urls = {url};
   for (int i = 0; i < urls.length; i++) {
     // TEST1 TEMPORARILY NOT RUN FOR MOZILLA
     if (!isMozilla) {
       boolean result = test1(urls[i]);
       if (verbose) System.out.print(result ? "." : "E");
       if (!result) fail++;
     }
   }
   return fail == 0;
 }
 @Override
 public Object execute(ExecutionEvent event) throws ExecutionException {
   IWorkbenchPart part = HandlerUtil.getActivePartChecked(event);
   ISelection selection = HandlerUtil.getCurrentSelectionChecked(event);
   if (part instanceof MarketDataView && selection instanceof IStructuredSelection) {
     MarketDataView view = (MarketDataView) part;
     IStructuredSelection sselection = (IStructuredSelection) selection;
     StringBuilder builder = new StringBuilder();
     for (Object obj : sselection.toArray()) {
       if (obj instanceof MarketDataViewItem) {
         MarketDataViewItem item = (MarketDataViewItem) obj;
         builder.append(item);
         builder.append(System.getProperty("line.separator")); // $NON-NLS-1$
       }
     }
     view.getClipboard()
         .setContents(
             new Object[] {builder.toString()}, new Transfer[] {TextTransfer.getInstance()});
   }
   return null;
 }
 private void updateArgumentPreview(IArgumentsInfo launcherArguments) {
   StringBuffer buffer = new StringBuffer();
   String delim = System.getProperty("line.separator"); // $NON-NLS-1$
   String args =
       launcherArguments.getCompleteProgramArguments(
           TAB_LABELS[fLastTab], TAB_ARCHLABELS[fLastArch[fLastTab]]);
   if (args.length() > 0) {
     buffer.append(PDEUIMessages.ArgumentsSection_program);
     buffer.append(delim);
     buffer.append(args);
     buffer.append(delim);
     buffer.append(delim);
   }
   args =
       launcherArguments.getCompleteVMArguments(
           TAB_LABELS[fLastTab], TAB_ARCHLABELS[fLastArch[fLastTab]]);
   if (args.length() > 0) {
     buffer.append(PDEUIMessages.ArgumentsSection_vm);
     buffer.append(delim);
     buffer.append(args);
   }
   fPreviewArgs.setValue(buffer.toString());
 }
  /** Create tray icon and register frame listeners. */
  public void init() {
    // register error handler to avoid application crash on concurrent X access from SWT and AWT
    try {
      OS.gdk_error_trap_push();
    } catch (NoClassDefFoundError e) {
      // ignore
    }
    final String systemLookAndFeelClassName = UIManager.getSystemLookAndFeelClassName();
    try {
      // workaround for bug when SWT and AWT both try to access Gtk
      if (systemLookAndFeelClassName.indexOf("gtk") >= 0) {
        System.setProperty("swing.defaultlaf", UIManager.getCrossPlatformLookAndFeelClassName());
      } else {
        System.setProperty("swing.defaultlaf", systemLookAndFeelClassName);
      }
    } catch (Exception e) {
      DavGatewayTray.warn(new BundleMessage("LOG_UNABLE_TO_SET_LOOK_AND_FEEL"));
    }

    new Thread("SWT") {
      @Override
      public void run() {
        try {
          display = new Display();
          shell = new Shell(display);

          final Tray tray = display.getSystemTray();
          if (tray != null) {

            trayItem = new TrayItem(tray, SWT.NONE);
            trayItem.setToolTipText(BundleMessage.format("UI_DAVMAIL_GATEWAY"));

            awtImage = DavGatewayTray.loadImage(AwtGatewayTray.TRAY_PNG);
            image = loadSwtImage(AwtGatewayTray.TRAY_PNG);
            image2 = loadSwtImage(AwtGatewayTray.TRAY_ACTIVE_PNG);
            inactiveImage = loadSwtImage(AwtGatewayTray.TRAY_INACTIVE_PNG);

            trayItem.setImage(image);

            // create a popup menu
            final Menu popup = new Menu(shell, SWT.POP_UP);
            trayItem.addListener(
                SWT.MenuDetect,
                new Listener() {
                  public void handleEvent(Event event) {
                    display.asyncExec(
                        new Runnable() {
                          public void run() {
                            popup.setVisible(true);
                          }
                        });
                  }
                });

            MenuItem aboutItem = new MenuItem(popup, SWT.PUSH);
            aboutItem.setText(BundleMessage.format("UI_ABOUT"));
            aboutItem.addListener(
                SWT.Selection,
                new Listener() {
                  public void handleEvent(Event event) {
                    display.asyncExec(
                        new Runnable() {
                          public void run() {
                            if (aboutFrame == null) {
                              aboutFrame = new AboutFrame();
                            }
                            aboutFrame.update();
                            aboutFrame.setVisible(true);
                            aboutFrame.toFront();
                            aboutFrame.requestFocus();
                          }
                        });
                  }
                });

            trayItem.addListener(
                SWT.DefaultSelection,
                new Listener() {
                  public void handleEvent(Event event) {
                    display.asyncExec(
                        new Runnable() {
                          public void run() {
                            // create frame on first call
                            if (settingsFrame == null) {
                              settingsFrame = new SettingsFrame();
                            }
                            settingsFrame.reload();
                            settingsFrame.setVisible(true);
                            settingsFrame.toFront();
                            settingsFrame.requestFocus();
                          }
                        });
                  }
                });

            // create menu item for the default action
            MenuItem defaultItem = new MenuItem(popup, SWT.PUSH);
            defaultItem.setText(BundleMessage.format("UI_SETTINGS"));
            defaultItem.addListener(
                SWT.Selection,
                new Listener() {
                  public void handleEvent(Event event) {
                    display.asyncExec(
                        new Runnable() {
                          public void run() {
                            // create frame on first call
                            if (settingsFrame == null) {
                              settingsFrame = new SettingsFrame();
                            }
                            settingsFrame.reload();
                            settingsFrame.setVisible(true);
                            settingsFrame.toFront();
                            settingsFrame.requestFocus();
                          }
                        });
                  }
                });

            MenuItem logItem = new MenuItem(popup, SWT.PUSH);
            logItem.setText(BundleMessage.format("UI_SHOW_LOGS"));
            logItem.addListener(
                SWT.Selection,
                new Listener() {
                  public void handleEvent(Event event) {
                    display.asyncExec(
                        new Runnable() {
                          public void run() {

                            Logger rootLogger = Logger.getRootLogger();
                            LF5Appender lf5Appender =
                                (LF5Appender) rootLogger.getAppender("LF5Appender");
                            if (lf5Appender == null) {
                              logBrokerMonitor =
                                  new LogBrokerMonitor(LogLevel.getLog4JLevels()) {
                                    @Override
                                    protected void closeAfterConfirm() {
                                      hide();
                                    }
                                  };
                              lf5Appender = new LF5Appender(logBrokerMonitor);
                              lf5Appender.setName("LF5Appender");
                              rootLogger.addAppender(lf5Appender);
                            }
                            lf5Appender.getLogBrokerMonitor().show();
                          }
                        });
                  }
                });

            MenuItem exitItem = new MenuItem(popup, SWT.PUSH);
            exitItem.setText(BundleMessage.format("UI_EXIT"));
            exitItem.addListener(
                SWT.Selection,
                new Listener() {
                  public void handleEvent(Event event) {
                    DavGateway.stop();
                  }
                });

            // display settings frame on first start
            if (Settings.isFirstStart()) {
              // create frame on first call
              if (settingsFrame == null) {
                settingsFrame = new SettingsFrame();
              }
              settingsFrame.setVisible(true);
              settingsFrame.toFront();
              settingsFrame.requestFocus();
            }

            synchronized (mainThread) {
              // ready
              isReady = true;
              mainThread.notifyAll();
            }

            while (!shell.isDisposed()) {
              if (!display.readAndDispatch()) {
                display.sleep();
              }
            }

            dispose();
          }
        } catch (Exception exc) {
          DavGatewayTray.error(exc);
        }
        // make sure we do exit
        System.exit(0);
      }
    }.start();
    while (true) {
      // wait for SWT init
      try {
        synchronized (mainThread) {
          if (isReady) {
            break;
          }
          mainThread.wait(1000);
        }
      } catch (InterruptedException e) {
        DavGatewayTray.error(new BundleMessage("LOG_ERROR_WAITING_FOR_SWT_INIT"), e);
      }
    }
  }
Exemple #28
0
 static {
   System.setProperty("apple.awt.usingSWT", "true");
 }
Exemple #29
0
/** This is the What's New window */
public class WelcomeWindow {

  private static final String lineSeparator = System.getProperty("line.separator");

  Display display;
  Shell shell;
  Color black, white, light, grey, green, blue, fg, bg;
  String sWhatsNew;
  Font monospace;

  private Composite cWhatsNew;

  private Label labelLoading;

  public WelcomeWindow(Shell parentShell) {
    try {
      init(parentShell);
    } catch (Throwable t) {
    }
  }

  public void init(Shell parentShell) {
    shell = ShellFactory.createShell(parentShell, SWT.BORDER | SWT.TITLE | SWT.CLOSE | SWT.RESIZE);
    Utils.setShellIcon(shell);
    if (Constants.isOSX) monospace = new Font(shell.getDisplay(), "Courier", 12, SWT.NORMAL);
    else monospace = new Font(shell.getDisplay(), "Courier New", 8, SWT.NORMAL);

    shell.setText(
        MessageText.getString("window.welcome.title", new String[] {Constants.AZUREUS_VERSION}));

    display = shell.getDisplay();

    GridLayout layout = new GridLayout();
    shell.setLayout(layout);

    GridData data;

    cWhatsNew = new Composite(shell, SWT.BORDER);
    data = new GridData(GridData.FILL_BOTH);
    cWhatsNew.setLayoutData(data);
    cWhatsNew.setLayout(new FillLayout());

    Button bClose = new Button(shell, SWT.PUSH);
    bClose.setText(MessageText.getString("Button.close"));
    data = new GridData();
    data.widthHint = 70;
    data.horizontalAlignment = Constants.isOSX ? SWT.CENTER : SWT.RIGHT;
    bClose.setLayoutData(data);

    Listener closeListener =
        new Listener() {
          public void handleEvent(Event event) {
            close();
          }
        };

    bClose.addListener(SWT.Selection, closeListener);
    shell.addListener(SWT.Close, closeListener);

    shell.setDefaultButton(bClose);

    shell.addListener(
        SWT.Traverse,
        new Listener() {
          public void handleEvent(Event e) {
            if (e.character == SWT.ESC) {
              close();
            }
          }
        });

    shell.setSize(750, 500);
    Utils.centreWindow(shell);
    shell.layout();
    shell.open();
    pullWhatsNew(cWhatsNew);
  }

  private void pullWhatsNew(Composite cWhatsNew) {
    labelLoading = new Label(cWhatsNew, SWT.CENTER);
    labelLoading.setText(MessageText.getString("installPluginsWizard.details.loading"));
    shell.layout(true, true);
    shell.update();

    getWhatsNew(1);
  }

  public void setWhatsNew() {
    Utils.execSWTThread(
        new AERunnable() {
          public void runSupport() {
            _setWhatsNew();
          }
        });
  }

  public void _setWhatsNew() {

    if (sWhatsNew.indexOf("<html") >= 0 || sWhatsNew.indexOf("<HTML") >= 0) {
      BrowserWrapper browser = Utils.createSafeBrowser(cWhatsNew, SWT.NONE);
      if (browser != null) {
        browser.setText(sWhatsNew);
      } else {
        try {
          File tempFile = File.createTempFile("AZU", ".html");
          tempFile.deleteOnExit();
          FileUtil.writeBytesAsFile(tempFile.getAbsolutePath(), sWhatsNew.getBytes("utf8"));
          Utils.launch(tempFile.getAbsolutePath());
          shell.dispose();
          return;
        } catch (IOException e) {
        }
      }
    } else {

      StyledText helpPanel = new StyledText(cWhatsNew, SWT.VERTICAL | SWT.HORIZONTAL);

      helpPanel.setEditable(false);
      try {
        helpPanel.setRedraw(false);
        helpPanel.setWordWrap(false);
        helpPanel.setFont(monospace);

        black = ColorCache.getColor(display, 0, 0, 0);
        white = ColorCache.getColor(display, 255, 255, 255);
        light = ColorCache.getColor(display, 200, 200, 200);
        grey = ColorCache.getColor(display, 50, 50, 50);
        green = ColorCache.getColor(display, 30, 80, 30);
        blue = ColorCache.getColor(display, 20, 20, 80);
        int style;
        boolean setStyle;

        helpPanel.setForeground(grey);

        String[] lines = sWhatsNew.split("\\r?\\n");
        for (int i = 0; i < lines.length; i++) {
          String line = lines[i];

          setStyle = false;
          fg = grey;
          bg = white;
          style = SWT.NORMAL;

          char styleChar;
          String text;

          if (line.length() < 2) {
            styleChar = ' ';
            text = " " + lineSeparator;
          } else {
            styleChar = line.charAt(0);
            text = line.substring(1) + lineSeparator;
          }

          switch (styleChar) {
            case '*':
              text = "  * " + text;
              fg = green;
              setStyle = true;
              break;
            case '+':
              text = "     " + text;
              fg = black;
              bg = light;
              style = SWT.BOLD;
              setStyle = true;
              break;
            case '!':
              style = SWT.BOLD;
              setStyle = true;
              break;
            case '@':
              fg = blue;
              setStyle = true;
              break;
            case '$':
              bg = blue;
              fg = white;
              style = SWT.BOLD;
              setStyle = true;
              break;
            case ' ':
              text = "  " + text;
              break;

            default:
              text = styleChar + text;
          }

          helpPanel.append(text);

          if (setStyle) {
            int lineCount = helpPanel.getLineCount() - 1;
            int charCount = helpPanel.getCharCount();
            //          System.out.println("Got Linecount " + lineCount + ", Charcount " +
            // charCount);

            int lineOfs = helpPanel.getOffsetAtLine(lineCount - 1);
            int lineLen = charCount - lineOfs;
            //          System.out.println("Setting Style : " + lineOfs + ", " + lineLen);
            helpPanel.setStyleRange(new StyleRange(lineOfs, lineLen, fg, bg, style));
            helpPanel.setLineBackground(lineCount - 1, 1, bg);
          }
        }

        helpPanel.setRedraw(true);
      } catch (Exception e) {
        System.out.println("Unable to load help contents because:" + e);
        // e.printStackTrace();
      }
    }

    if (labelLoading != null && !labelLoading.isDisposed()) {
      labelLoading.dispose();
    }
    shell.layout(true, true);
  }

  private void getWhatsNew(final int phase) {
    String helpFile = null;
    if (phase == 1) {
      helpFile = MessageText.getString("window.welcome.file");

      if (!helpFile.toLowerCase().startsWith(Constants.SF_WEB_SITE)) {
        getWhatsNew(2);
        return;
      }
    } else {
      helpFile = MessageText.getString("window.welcome.file");

      InputStream stream;
      stream = getClass().getResourceAsStream(helpFile);
      if (stream == null) {
        String helpFullPath = "/org/gudy/azureus2/internat/whatsnew/" + helpFile;
        stream = getClass().getResourceAsStream(helpFullPath);
      }
      if (stream == null) {
        stream = getClass().getResourceAsStream("/ChangeLog.txt");
      }
      if (stream == null) {
        sWhatsNew = "Welcome Window: Error loading resource: " + helpFile;
      } else {
        try {
          sWhatsNew = FileUtil.readInputStreamAsString(stream, 65535, "utf8");
          stream.close();
        } catch (IOException e) {
          Debug.out(e);
        }
      }
      setWhatsNew();
      return;
    }

    final String url = helpFile;

    new AEThread2("getWhatsNew", true) {

      public void run() {

        String s;
        ResourceDownloaderFactory rdf = ResourceDownloaderFactoryImpl.getSingleton();
        try {
          ResourceDownloader rd = rdf.create(new URL(url));
          InputStream is = rd.download();
          int length = is.available();
          byte data[] = new byte[length];
          is.read(data);
          is.close();
          s = new String(data);
        } catch (ResourceDownloaderException rde) {
          // We don't need a stack trace - it's arguable that we even need any
          // errors at all - the below line is better, but suppressed output might
          // be better.
          // Debug.outNoStack("Error downloading from " + url + ", " + rde, true);
          s = "";
        } catch (Exception e) {
          Debug.out(e);
          s = "";
        }
        sWhatsNew = s;

        if (sWhatsNew == null || sWhatsNew.length() == 0) {
          getWhatsNew(phase + 1);
          return;
        }

        Utils.execSWTThread(
            new AERunnable() {
              public void runSupport() {
                if (cWhatsNew != null && !cWhatsNew.isDisposed()) {
                  setWhatsNew();
                }
              }
            });
      }
    }.start();
  }

  private void close() {
    monospace.dispose();
    shell.dispose();
  }

  public static void main(String[] args) {
    // Locale.setDefault(new Locale("nl", "NL"));
    // MessageText.changeLocale(new Locale("nl", "NL"));
    System.out.println(Locale.getDefault().getCountry());
    new WelcomeWindow(null);
    Display display = Display.getDefault();
    while (true) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
  }
}
  private void openAddressBook() {
    FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);

    fileDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"});
    fileDialog.setFilterNames(
        new String[] {
          resAddressBook.getString("Book_filter_name") + " (*.adr)",
          resAddressBook.getString("All_filter_name") + " (*.*)"
        });
    String name = fileDialog.open();

    if (name == null) return;
    File file = new File(name);
    if (!file.exists()) {
      displayError(
          resAddressBook.getString("File")
              + file.getName()
              + " "
              + resAddressBook.getString("Does_not_exist"));
      return;
    }

    Cursor waitCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT);
    shell.setCursor(waitCursor);

    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    String[] data = new String[0];
    try {
      fileReader = new FileReader(file.getAbsolutePath());
      bufferedReader = new BufferedReader(fileReader);
      String nextLine = bufferedReader.readLine();
      while (nextLine != null) {
        String[] newData = new String[data.length + 1];
        System.arraycopy(data, 0, newData, 0, data.length);
        newData[data.length] = nextLine;
        data = newData;
        nextLine = bufferedReader.readLine();
      }
    } catch (FileNotFoundException e) {
      displayError(resAddressBook.getString("File_not_found") + "\n" + file.getName());
      return;
    } catch (IOException e) {
      displayError(resAddressBook.getString("IO_error_read") + "\n" + file.getName());
      return;
    } finally {

      shell.setCursor(null);

      if (fileReader != null) {
        try {
          fileReader.close();
        } catch (IOException e) {
          displayError(resAddressBook.getString("IO_error_close") + "\n" + file.getName());
          return;
        }
      }
    }

    String[][] tableInfo = new String[data.length][table.getColumnCount()];
    int writeIndex = 0;
    for (int i = 0; i < data.length; i++) {
      String[] line = decodeLine(data[i]);
      if (line != null) tableInfo[writeIndex++] = line;
    }
    if (writeIndex != data.length) {
      String[][] result = new String[writeIndex][table.getColumnCount()];
      System.arraycopy(tableInfo, 0, result, 0, writeIndex);
      tableInfo = result;
    }
    Arrays.sort(tableInfo, new RowComparator(0));

    for (int i = 0; i < tableInfo.length; i++) {
      TableItem item = new TableItem(table, SWT.NONE);
      item.setText(tableInfo[i]);
    }
    shell.setText(resAddressBook.getString("Title_bar") + fileDialog.getFileName());
    isModified = false;
    this.file = file;
  }