예제 #1
0
    def bg(self, panel2, e):
        bground = JFrame()
        bground.setTitle("Change Background")
        bground.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        bground.setSize(350, 100)
        bground.setLocationRelativeTo(None)
        bground.setVisible(True)
        bground.setResizable(False)

        panel = JPanel()
        #panel.setBackground(Color(46, 64, 96))
        bground.getContentPane().add(panel)

        path = JLabel("File:")
        panel.add(path)

        path2 = JTextField()
        path2.setPreferredSize(Dimension(180, 20))
        panel.add(path2)

        browse = JButton("Browse file",
                         actionPerformed=lambda e: self.browse(path2, e))
        panel.add(browse)

        change = JButton(
            "Change",
            actionPerformed=lambda e: self.change(path2.getText(), panel2, e))
        panel.add(change)

        bground.add(panel)
예제 #2
0
class CoordinateChooser:
    def buttonPressed(self, event):
        # The OK button was pressed; proceed to compute and plot moment arms
        # relative to the selected coordinate.
        coordIndex = self.cb.selectedIndex
        coordName = self.data[coordIndex]
        self.frame.setVisible(False)
        ComputeAndPlotMomentArms(coordIndex)

    def __init__(self):
        # Populate and display window for selecting a coordinate from the
        # specified motion (kinematics) file.
        self.frame = JFrame("Coordinate chooser")
        self.frame.setSize(350, 100)
        self.frame.setLayout(BorderLayout())
        self.frame.setLocationRelativeTo(None)

        self.data = coordList
        self.cb = JComboBox(self.data, preferredSize=(200, 25))
        self.frame.add(self.cb, BorderLayout.WEST)

        btn = JButton('OK',
                      preferredSize=(75, 25),
                      actionPerformed=self.buttonPressed)
        self.frame.add(btn, BorderLayout.EAST)

        self.label = JLabel('Please select the coordinate to use in the \
			moment arm calculations',
                            preferredSize=(325, 50))
        self.frame.add(self.label, BorderLayout.NORTH)

        self.frame.setVisible(True)
예제 #3
0
    def onInfo(self, e):
        info = JFrame()
        info.setTitle("Info")
        info.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        info.setSize(410, 400)
        info.setLocationRelativeTo(None)
        info.setResizable(False)
        info.setVisible(True)

        panel = JPanel()
        #panel.setBackground(Color(46, 64, 96))
        #panel.setLayout(GridLayout(0, 2))

        logo = JLabel(ImageIcon("/icons/logo.jpg"))
        panel.add(logo)

        f = Font("", Font.ITALIC, 40)
        title = JLabel("Stylus OS 1.0 beta")
        title.setFont(f)
        panel.add(title)

        f = Font("", Font.ITALIC, 14)
        copyright = JLabel(
            "Copyright (c) 2016 Niccolo' Ciavarella. All rights reserved.")
        copyright.setFont(f)
        panel.add(copyright)

        info.getContentPane().add(panel)
        info.add(panel)
예제 #4
0
    def initResultados(self):
        diag = JFrame()
        self.lineas = list()
        self.areaResultados = JTextArea()
        numLineas = self.readResultados()

        panelResultados = JPanel()
        #panelResultados.setAutoscrolls(True)
        panelResultados.setBorder(BorderFactory.createEtchedBorder())
        panelResultados.setLayout(GridLayout(0, 1))

        pane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                           JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        pane.viewport.view = self.areaResultados

        #pane.getViewport().add(panelResultados)

        diag.setTitle("RESULTADOS OBTENIDOS")

        diag.setSize(1000, 450)
        diag.setLayout(BorderLayout())
        diag.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        diag.setLocationRelativeTo(None)
        diag.setVisible(True)

        panelResultados.add(pane)
        diag.add(panelResultados, BorderLayout.CENTER)
예제 #5
0
    def show_errors(self, label):
        """Display error messages."""
        top_label = JLabel(label, JLabel.CENTER)

        frame = JFrame(self.ext_name)
        frame.setSize(550, 300)
        frame.setLayout(GridLayout(1, 1))

        frame.add(top_label)
        frame.setLocationRelativeTo(None)
        frame.setVisible(True)
예제 #6
0
    def show_pannel(self):
        # BP_STDOUT.println("Event code: %s" % self.contextMenuInvocation.getInputEvent())
        # self.scannerInstance.show_pannel.show()
        window = JFrame()
        window.setLayout(None)
        window.setTitle("Xcrpter")
        window.setSize(720, 540)
        window.setLocationRelativeTo(None)
        window.setResizable(True)
        window.setContentPane(self.scannerInstance.xpannel)
        window.setVisible(True)

        self.scannerInstance.xpannel.setPlain("")
        self.scannerInstance.xpannel.setVisible(True)
예제 #7
0
    class SwingExample:
        def __init__(self):
            self.mainFrame = None
            self.mainTabbedPane = JTabbedPane()

        def start(self):
            self.mainFrame = JFrame("SwingTest")
            self.mainFrame.setSize(800, 600)
            self.mainFrame.setLocationRelativeTo(None)
            self.mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
            self.mainFrame.add(self.mainTabbedPane)
            self.mainFrame.setVisible(True)

        def addToTabbedPane(self, tabName, component):
            self.mainTabbedPane.addTab(tabName, component)

        def main(self):
            self.addToTabbedPane("Beautify", BeautifierPanel())
            self.addToTabbedPane("Options", BeautifierOptionsPanel(None))

            self.start()
class MainApp:
    def __init__(self):
        # Make the frame and set its properties
        self.frame = JFrame(
            "File Translator",
            defaultCloseOperation=WindowConstants.EXIT_ON_CLOSE,
            layout=GridBagLayout())
        self.frame.setSize(1200, 800)

        # Make a GridBagLayout for this frame
        gridbag = GridBagLayout()
        constraints = GridBagConstraints()
        constraints.fill = GridBagConstraints.CENTER

        # Make sure to have a panel to hold everything
        self.loginPanel = JPanel(GridLayout(0, 2))
        self.frame.add(self.loginPanel)
        gridbag.setConstraints(self.loginPanel, constraints)
        self.loginPanel.setLayout(gridbag)

        # Entry for the path
        self.usernameField = JTextField('', 30)
        self.loginPanel.add(JLabel("username:"******"password:"))
        self.loginPanel.add(self.textField)

        # Make a button to enter the information
        self.loginButton = JButton('Enter', actionPerformed=enter_button)
        self.loginPanel.add(self.loginButton)
        self.frame.add(self.loginPanel)

        # Make everything visible and make sure it starts at centre of screen
        self.frame.pack()
        self.frame.setLocationRelativeTo(None)
        self.frame.setVisible(True)
예제 #9
0
    def onExit(self, e):
        exit = JFrame()
        exit.setTitle("Exit Stylus")
        exit.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        exit.setSize(250, 225)
        exit.setLocationRelativeTo(None)
        exit.setVisible(True)
        exit.setResizable(False)

        panel = JPanel()
        panel.setBorder(BorderFactory.createEtchedBorder())
        panel.setLayout(GridLayout(0, 1))
        exit.getContentPane().add(panel)

        icon1 = ImageIcon("/icons/shutdown.png")
        poweroff = JButton("Shutdown", icon1, actionPerformed=self.shutdown)
        panel.add(poweroff)

        icon2 = ImageIcon("/icons/reboot.png")
        reboot = JButton("  Reboot    ", icon2, actionPerformed=self.reboot)
        panel.add(reboot)

        exit.add(panel)
예제 #10
0
def makeRegistrationUI(original_images, original_calibration, coarse_affines, params, images, minC, maxC, cropped, cropped_imp):
  """
  Register cropped images either all to all or all to the first one,
  and print out a config file with the coarse affines,
  the ROI for cropping, and the refined affines post-crop.

  original_images: the original, raw images, with original dimensions.
  original_calibration: the calibration of the images as they are on disk.
  coarse_affines: list of AffineTransform3D, one per image, that specify the translation between images
                  as manually set using the makeTranslationUI.
  params: dictionary with parameters for registering the given cropped images.
          This includes a calibration that is likely [1.0, 1.0, 1.0] as the cropped images
          are expected to have been scaled to isotropy.
  images: the list of near-original images but scaled (by calibration) to isotropy.
          (These are really views of the original images, using nearest neighbor interpolation
           to scale them to isotropy.)
  minC, maxC: the minimum and maximum coordinates of a ROI with which the cropped images were made.
  cropped: the list of images that have been scaled to isotropy, translated and cropped by the ROI.
           (These are really interval views of the images, the latter using nearest neighbor interpolation.)
  cropped_imp: the ImagePlus holding the virtual stack of cropped image views.

  The computed registration will merge the scaling to isotropy + first transform (a translation)
   + roi cropping translation + the params["modelclass"] registration transform, to read directly
   from the original images using a nearest interpolation, for best performance (piling two nearest
   interpolations over one another would result in very slow access to pixel data).
  """

  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()

  calibration = params["calibration"]
  params["cal X"] = calibration[0]
  params["cal Y"] = calibration[1]
  params["cal Z"] = calibration[2]

  # Add a label and a text field for every parameter, with titles for every block
  strings = [["Calibration",
              "cal X", "cal Y", "cal Z"],
             ["Difference of Gaussian",
              "minPeakValue", "sigmaSmaller", "sigmaLarger"],
             ["Feature extraction",
              "radius", "min_angle", "max_per_peak",
              "angle_epsilon", "len_epsilon_sq",
              "pointmatches_nearby", "pointmatches_search_radius"],
             ["RANSAC parameters for the model",
              "maxEpsilon", "minInlierRatio", "minNumInliers",
              "n_iterations", "maxTrust"],
             ["All to all registration",
              "maxAllowedError", "maxPlateauwidth", "maxIterations", "damp"]]
  # Insert all as fields, with values populated from the params dictionary
  # and updating dynamically the params dictionary
  params = dict(params) # copy, will be updated
  insertFloatFields(panel, gb, gc, params, strings)

  # Identity transforms prior to registration
  affines = [affine3D([1, 0, 0, 0,
                       0, 1, 0, 0,
                       0, 0, 1, 0]) for img in cropped]
  
  def run():
    exe = newFixedThreadPool(min(len(cropped), numCPUs()))
    try:
      # Dummy for in-RAM reading of isotropic images
      img_filenames = [str(i) for i in xrange(len(cropped))]
      loader = InRAMLoader(dict(zip(img_filenames, cropped)))
      getCalibration = params.get("getCalibration", None)
      if not getCalibration:
        getCalibration = lambda img: [1.0] * cropped[0].numDimensions()
      csv_dir = params["csv_dir"]
      modelclass = params["modelclass"]
      # Matrices describing the registration on the basis of the cropped images
      matrices = computeOptimizedTransforms(img_filenames, loader, getCalibration,
                                            csv_dir, exe, modelclass, params)
      # Store outside, so they can be e.g. printed, and used beyond here
      for matrix, affine in zip(matrices, affines):
        affine.set(*matrix)

      # Combine the transforms: scaling (by calibration)
      #                         + the coarse registration (i.e. manual translations)
      #                         + the translation introduced by the ROI cropping
      #                         + the affine matrices computed above over the cropped images.
      coarse_matrices = []
      for coarse_affine in coarse_affines:
        matrix = zeros(12, 'd')
        coarse_affine.toArray(matrix)
        coarse_matrices.append(matrix)

      # NOTE: both coarse_matrices and matrices are from the camera X to camera 0. No need to invert them.
      # NOTE: uses identity calibration because the coarse_matrices already include the calibration scaling to isotropy
      transforms = mergeTransforms([1.0, 1.0, 1.0], coarse_matrices, [minC, maxC], matrices, invert2=False)

      print "calibration:", [1.0, 1.0, 1.0]
      print "cmTransforms:\n    %s\n    %s\n    %s\n    %s" % tuple(str(m) for m in coarse_matrices)
      print "ROI", [minC, maxC]
      print "fineTransformsPostROICrop:\n    %s\n    %s\n    %s\n    %s" % tuple(str(m) for m in matrices)
      print "invert2:", False
      
      # Show registered images
      registered = [transformedView(img, transform, interval=cropped[0])
                    for img, transform in izip(original_images, transforms)]
      registered_imp = showAsStack(registered, title="Registered with %s" % params["modelclass"].getSimpleName())
      registered_imp.setDisplayRange(cropped_imp.getDisplayRangeMin(), cropped_imp.getDisplayRangeMax())

      """
      # TEST: same as above, but without merging the transforms. WORKS, same result
      # Copy into ArrayImg, otherwise they are rather slow to browse
      def copy(img1, affine):
        # Copy in two steps. Otherwise the nearest neighbor interpolation on top of another
        # nearest neighbor interpolation takes a huge amount of time
        dimensions = Intervals.dimensionsAsLongArray(img1)
        aimg1 = ArrayImgs.unsignedShorts(dimensions)
        ImgUtil.copy(ImgView.wrap(img1, aimg1.factory()), aimg1)
        img2 = transformedView(aimg1, affine)
        aimg2 = ArrayImgs.unsignedShorts(dimensions)
        ImgUtil.copy(ImgView.wrap(img2, aimg2.factory()), aimg2)
        return aimg2
      futures = [exe.submit(Task(copy, img, affine)) for img, affine in izip(cropped, affines)]
      aimgs = [f.get() for f in futures]
      showAsStack(aimgs, title="DEBUG Registered with %s" % params["modelclass"].getSimpleName())
      """
    except:
      print sys.exc_info()
    finally:
      exe.shutdown()
      SwingUtilities.invokeLater(lambda: run_button.setEnabled(True))

  def launchRun(event):
    # Runs on the event dispatch thread
    run_button.setEnabled(False) # will be re-enabled at the end of run()
    # Fork:
    Thread(run).start()


  def printAffines(event):
    for i, affine in enumerate(affines):
      matrix = zeros(12, 'd')
      affine.toArray(matrix)
      msg = "# Refined post-crop affine matrix " + str(i) + ": \n" + \
            "affine" + str(i) + ".set(*[%f, %f, %f, %f,\n %f, %f, %f, %f,\n %f, %f, %f, %f])" % tuple(matrix.tolist())
      # Print everywhere
      print msg
      IJ.log(msg)
      System.out.println(msg)

  def prepareDeconvolutionScriptUI(event):
    """
    # DEBUG generateDeconvolutionScriptUI: generate params as a loadable serialized file
    with open("/tmp/parameters.pickle", 'w') as f:
      import pickle
      def asArrays(affines):
        arrays = []
        for affine in affines:
          matrix = zeros(12, 'd')
          affine.toArray(matrix)
          arrays.append(matrix)
        return arrays
        
      pickle.dump([params["srcDir"], params["tgtDir"], calibration,
                   asArrays(coarse_affines), [minC, maxC], asArrays(affines)], f)
    """
    generateDeconvolutionScriptUI(params["srcDir"], params["tgtDir"], calibration,
                                  coarse_affines, [minC, maxC], affines)
  
  # Buttons
  panel_buttons = JPanel()
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 2
  gb.setConstraints(panel_buttons, gc)
  panel.add(panel_buttons)
  
  run_button = JButton("Run")
  run_button.addActionListener(launchRun)
  gb.setConstraints(run_button, gc)
  panel_buttons.add(run_button)
  
  print_button = JButton("Print affines")
  print_button.addActionListener(printAffines)
  panel_buttons.add(print_button)

  prepare_button = JButton("Prepare deconvolution script")
  prepare_button.addActionListener(prepareDeconvolutionScriptUI)
  panel_buttons.add(prepare_button)

  frame = JFrame("Registration")
  frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
  frame.addWindowListener(CloseControl())
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(True)
예제 #11
0
def makeTranslationUI(affines, imp, show=True, print_button_text="Print transforms"):
  """
  A GUI to control the translation components of a list of AffineTransform3D instances.
  When updated, the ImagePlus is refreshed.

  affines: a list (will be read multiple times) of one affine transform per image.
  imp: the ImagePlus that hosts the virtual stack with the transformed images.
  show: defaults to True, whether to make the GUI visible.
  print_button_text: whatever you want the print button to read like, defaults to "Print transforms".
   
  Returns the JFrame, the main JPanel and the lower JButton panel.
  """
  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()
  gc.anchor = GBC.WEST
  gc.fill = GBC.NONE

  # Column labels
  gc.gridy = 0
  for i, title in enumerate(["Camera", "translation X", "translation Y", "translation Z"]):
    gc.gridx = i
    gc.anchor = GBC.CENTER
    label = JLabel(title)
    gb.setConstraints(label, gc)
    panel.add(label)

  gc.anchor = GBC.WEST
  listeners = []
  
  # One row per affine to control: skip the first
  for i, affine in enumerate(affines[1:]):
    gc.gridx = 0
    gc.gridy += 1
    label = JLabel("CM0%i: " % (i + 1))
    gb.setConstraints(label, gc)
    panel.add(label)
    # One JTextField per dimension
    for dimension, translation in enumerate(affine.getTranslation()):
      tf = JTextField(str(translation), 10)
      listener = MatrixTextFieldListener(affine, dimension, tf, imp)
      listeners.append(listener)
      imp.addImageListener(listener) # to disable the JTextField when closed
      tf.addKeyListener(listener)
      tf.addMouseWheelListener(listener)
      gc.gridx += 1
      gb.setConstraints(tf, gc)
      panel.add(tf)

  # Documentation for the user
  help_lines = ["Type a number and push enter,",
                "or use the scroll wheel."]
  gc.gridx = 0
  gc.gridwidth = 4
  for line in help_lines:
    gc.gridy += 1
    help = JLabel(line)
    gb.setConstraints(help, gc)
    panel.add(help)

  # Buttons
  printButton = JButton(print_button_text)
  
  def printTransforms(event):
    for i, aff in enumerate(affines): # print all, including the first
      matrix = zeros(12, 'd')
      aff.toArray(matrix)
      msg = "# Coarse affine matrix " + str(i) + ": \n" + \
            "affine" + str(i) + ".set(*[%f, %f, %f, %f,\n %f, %f, %f, %f,\n %f, %f, %f, %f])" % tuple(matrix.tolist())
      # Print everywhere
      print msg
      IJ.log(msg)
      System.out.println(msg)
      
  
  printButton.addActionListener(printTransforms)
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 4
  button_panel = JPanel()
  button_panel.add(printButton)
  gb.setConstraints(button_panel, gc)
  panel.add(button_panel)

  frame = JFrame("Translation control")
  frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
  frame.addWindowListener(CloseControl(destroyables=listeners))
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(show)

  return frame, panel, button_panel
예제 #12
0
    def guiFrame(self):

        frame = JFrame("PyNews")
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        frame.setLocationRelativeTo(None)
        frame.setSize(600, 200)
        frame.setResizable(False)

        frame.setLayout(GridLayout(5, 3, 10, 10))

        # logo
        self.logo = JLabel("  PyNews")

        # query input
        self.input_field = JTextField(30)

        # search button
        self.src_button = JButton("Search!", actionPerformed=self.pyNewsSearch)

        # expand button
        self.exp_button = JButton("Expand!", actionPerformed=self.expandNews)
        self.exp_button.setEnabled(False)

        # open button
        self.opn_button = JButton("Open!", actionPerformed=self.openNews)
        self.opn_button.setEnabled(False)

        # open html button
        self.htm_button = JButton("HTML-Open!", actionPerformed=self.openHTML)
        self.htm_button.setEnabled(False)

        # write to file button
        self.wrt_button = JButton("CSV-Write!",
                                  actionPerformed=self.writeToCSV)
        self.wrt_button.setEnabled(False)

        # checkboxes
        self.categories = [
            "authors", "publish_date", "top_image", "movies", "text",
            "article_html", "summary", "keywords"
        ]
        self.checkboxes = []

        for cat in self.categories:
            self.checkboxes.append(JCheckBox(cat))

        # add to frame

        frame.add(self.logo)
        frame.add(self.input_field)
        frame.add(self.src_button)
        frame.add(self.exp_button)
        for cb in self.checkboxes[:2]:
            frame.add(cb)
        frame.add(self.opn_button)
        for cb in self.checkboxes[2:4]:
            frame.add(cb)
        frame.add(self.htm_button)
        for cb in self.checkboxes[4:6]:
            frame.add(cb)
        frame.add(self.wrt_button)
        for cb in self.checkboxes[6:8]:
            frame.add(cb)
        print("got to end ")
        frame.setVisible(True)
예제 #13
0
'''
Created on Sep 9, 2013

@author: ccole
'''

from javax.swing import JFrame
from src import MainPanel

f = JFrame('Python Image Game')
f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
f.setSize(300, 300)
f.setLocationRelativeTo(None)
f.setVisible(True)

f.add(MainPanel())
예제 #14
0
class Gui(MouseAdapter):
    IMG_MIN_SIZE = 200
    IMG_MAX_SIZE = 500

    def __init__(self):
        self.pos1 = None
        self.puzzle = None

    def mouseEntered(self, event):
        self.in_canvas = True

    def mouseExited(self, event):
        self.in_canvas = False

    def mouseReleased(self, event):
        if not self.in_canvas or self.puzzle == None:
            return

        width = self.images_dict[0].getWidth()
        height = self.images_dict[0].getHeight()

        def valid_pos(pos):
            return pos >= 0 and pos < self.puzzle.level()

        x = (event.getX() - self.canvas.initial_x) / width
        y = (event.getY() - self.canvas.initial_y) / height

        if not valid_pos(x) or not valid_pos(y):
            return

        pos = Point(x, y)
        if self.pos1 != None: #then is second click
            if self.pos1.equals(pos):
                self.pos1 = None
            else:
                self.play_event(self.pos1.y, self.pos1.x, pos.y, pos.x)
                self.pos1 = None
        else:
            self.pos1 = pos
        self.canvas.set_selected(self.pos1)
        self.canvas.repaint()

    def draw(self):

        try:
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        except:
            pass

        self.images_dict = dict()
        self.canvas = Canvas(self.images_dict, None)
        self.canvas.addMouseListener(self)

        self.frame = JFrame("SimplePyzzle", visible = 1)
        self.frame.setMinimumSize(Dimension(300, 300))
        self.frame.setLocationRelativeTo(None)
        self.generate_button = JButton("Generate Puzzle")
        self.bottom_panel = JPanel()

        self.combo_box_list = [9, 16, 25, 36, 49]
        self.combo_box = JComboBox(self.combo_box_list)

        self.frame.contentPane.add(self.canvas, BorderLayout.CENTER)
        self.frame.contentPane.add(self.bottom_panel, BorderLayout.SOUTH)
        self.bottom_panel.add(self.generate_button, BorderLayout.EAST)
        self.bottom_panel.add(self.combo_box, BorderLayout.WEST)

        self.generate_button.actionPerformed = self.generate_board

        self.frame.setSize(500, 500)
        self.frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE;
        self.frame.pack()

    def generate_board(self, event):

        chooser = JFileChooser()
        status = chooser.showOpenDialog(self.frame)
        if status != JFileChooser.APPROVE_OPTION:
            return

        imageFile = chooser.getSelectedFile()

        self.puzzle = SimplePyzzle(float(int(self.combo_box.getSelectedItem())))
        self.draw_board()
        self.load_images(imageFile, self.puzzle.level())
        self.canvas.set_puzzle(self.puzzle)
        width = self.images_dict[0].getWidth()
        height = self.images_dict[0].getHeight()
        size = Dimension(width * self.puzzle.level(), height * self.puzzle.level())
        self.frame.setPreferredSize(size)
        self.frame.setSize(size)

    def show_error(self, error):
        JOptionPane.showMessageDialog(self.frame, \
                                    error, \
                                    "Error!", \
                                    JOptionPane.ERROR_MESSAGE)

    def load_images(self, file, length):

        try:
            image = ImageIO.read(file);
        except IIOException:
            self.show_error(u"You have to pick an image!")
            return

        image_biggest_side = image.getWidth() if image.getWidth() > image.getHeight\
            else image.getHeight()
        imageSize = image_biggest_side
        if image_biggest_side > Gui.IMG_MAX_SIZE:
            imageSize = Gui.IMG_MAX_SIZE

        if image_biggest_side < Gui.IMG_MIN_SIZE:
            imageSize = Gui.IMG_MIN_SIZE

        resized_image = resize_image(image, imageSize, imageSize)

        images = split_image(resized_image, length)
        self.images_dict.clear()
        for i in range(len(images)):
            self.images_dict[i] = images[i]

    def play_event(self, x1, y1, x2, y2):
          status = self.puzzle.play(x1, y1, x2, y2)
          self.draw_board()
          if status == SimplePyzzle.END_GAME:
              JOptionPane.showMessageDialog (None, \
                                  "Grats! You solved the puzzle", \
                                  "Puzzle solved!", \
                                   JOptionPane.INFORMATION_MESSAGE);

    def draw_board(self):
        self.canvas.repaint()
예제 #15
0
class GraphicsWindow(ActionListener, KeyListener, MouseInputListener):
    """
    Creates a :py:class:`~jygsaw.graphicswindow.GraphicsWindow` with a :py:class:`~jygsaw.graphicswindow.Canvas`
    object that can be drawn on. Takes a title, window width, and window height.
    An optional background color can be specified.
    """
    def __init__(self, title, w, h, backgroundColor=white):
        assert w > 0, "GraphicsWindow width must be greater than zero"
        assert h > 0, "GraphicsWindow height must be greater than zero"

        self._SHAPELIST_MAX_LENGTH = 200

        self.objs = []  # List of GraphicsObjects
        self.backgroundColor = backgroundColor

        self.frame = JFrame(
            title, defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
            size=(w, h))

        self.frame.setLocationRelativeTo(None)
        self.frame.contentPane = Canvas(self, self.objs, self.backgroundColor)
        self.frame.contentPane.setPreferredSize(Dimension(w, h))

        self.frame.addMouseListener(self)
        self.frame.addMouseMotionListener(self)
        self.frame.addKeyListener(self)

        # MouseEvent attributes
        self.mouseEventType = 0
        self.mouseX = 0
        self.mouseY = 0

        # Mouse callbacks
        self.onMouseClicked = None
        self.onMouseDragged = None
        self.onMouseMoved = None
        self.onMousePressed = None
        self.onMouseReleased = None
        self.onMouseDragged = None
        self.onMouseExited = None
        self.onMouseEntered = None

        # KeyEvent booleans keyPressed, keyTyped
        self.keyEventType = 0
        self.keyP = False
        self.keyT = False

        # Key callbacks
        self.onKeyPressed = None
        self.onKeyReleased = None
        self.onKeyTyped = None

        # Key values
        self.lastKeyChar = None
        self.lastKeyCode = None

        self.charsPressed = Set()

        # Event queue
        self.eventQueue = Queue()

        self.mainRunning = False

        # not needed, user_draw is /called directly from onDraw
        self.onDraw = None

    def setVisible(self, isVisible):
        """Sets the window to visible."""
        assert isinstance(isVisible, bool), "Variable is not a boolean."
        self.frame.pack()
        self.frame.visible = isVisible

    def draw(self, *params):
        """
        Takes any number of :py:class:`~jygsaw.graphicsobject.GraphicsObject`
        or :py:class:`~jygsaw.shape.Shape` objects, or :py:class:`~jygsaw.group.Group`,
        and draws them on the Canvas. If a shape is drawn without specifying a color
        the default color is used. The default stroke option
        (:py:class:`True` or :py:class:`False`) and *strokeColor* is saved in each object.
        """
        for arg in params:
            if isinstance(arg, GraphicsObject) or isinstance(arg, Shape):
                if arg.color is None:
                    arg.color = self.frame.contentPane.defaultColor
                arg.strokeColor = self.frame.contentPane.strokeColor
                arg.stroke = self.frame.contentPane.stroke
                arg.filled = self.frame.contentPane.filled
                arg.strokeWidth = self.frame.contentPane.strokeWidth
                if isinstance(arg, Text):
                    arg.font = self.frame.contentPane.font
                    arg.size = self.frame.contentPane.textSize
                self.objs.append(arg)

                if len(self.objs) > self._SHAPELIST_MAX_LENGTH:
                    warn("You have more than " + str(self._SHAPELIST_MAX_LENGTH) +
                         " to be drawn. You may want to add a clearHalf() call to your" +
                         " code to avoid slowing your system.")

            elif isinstance(arg, Group):
                for obj in arg.group:
                    if obj.color is None:
                        obj.color = self.frame.contentPane.defaultColor
                    obj.strokeColor = self.frame.contentPane.strokeColor
                    obj.stroke = self.frame.contentPane.stroke
                    obj.filled = self.frame.contentPane.filled
                    arg.strokeWidth = self.frame.contentPane.strokeWidth
                    if isinstance(arg, Text):
                        arg.font = self.frame.contentPane.font
                        arg.size = self.frame.contentPane.textSize
                    self.objs.append(obj)

                    if len(self.objs) > self._SHAPELIST_MAX_LENGTH:
                        warn("You have more than " + str(self._SHAPELIST_MAX_LENGTH) +
                             " to be drawn. You may want to add a clearHalf() call to your" +
                             " code to avoid slowing your system.")
            else:
                raise Exception("Passed in something that's not a Group or GraphicsObject.")

    def setDefaultColor(self, c):
        """Sets the default color of the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(c, Color), "The object passed is not a Color object."
        self.frame.contentPane.defaultColor = c

    def setStrokeColor(self, c):
        """Sets the stroke color in the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(c, Color), "The object passed is not a Color object."
        self.frame.contentPane.strokeColor = c

    def setStroke(self, b):
        """Turns stroke on or off in the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(b, bool), "Variable given is not a boolean."
        self.frame.contentPane.stroke = b

    def setStrokeWidth(self, w):
        """Sets the width of the stroke in the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(w, int), "Variable given is not an integer."
        self.frame.contentPane.strokeWidth = w

    def setFilled(self, f):
        """Turns fill on or off in the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(f, bool), "Variable given is not a boolean."
        self.frame.contentPane.filled = f

    def setBackgroundColor(self, c):
        """Sets the background color of the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(c, Color), "The object passed is not a Color object."
        self.frame.contentPane.backgroundColor = c
        self.background = c

    def setFont(self, f):
        """Sets the font of the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        self.frame.contentPane.font = f

    def setTextSize(self, s):
        """Sets the text size of the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert s >= 0 and isinstance(
            s, int), "Font size must be greater than or equal to 0"
        self.frame.contentPane.textSize = s

    def getBackgroundColor(self):
        """Returns the background color of the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        return self.background

    def redraw(self, delay=0.0):
        """
        Redraws the :py:class:`~jygsaw.graphicswindow.Canvas`.
        Only returns when done. An optional float can also be used to sleep after redrawing.
        """
        # Use non-blocking redraw because there is no one-to-one relation
        # between calling cavas.repaint() and execution of paintComponent()
        #
        if SwingUtilities.isEventDispatchThread():
            self.frame.contentPane.repaint()
        else:
            self.frame.contentPane.blocking_redraw()
        sleep(delay)

    def clear(self):
        """
        Clears the screen so that only the background is visible.
        Also deletes all :py:class:`~jygsaw.graphicsobject.GraphicsObject` and :py:class:`~jygsaw.shape.Shape` and objects.
        """
        self.objs = []
        self.frame.contentPane.objs = self.objs

    def clearHalfIfFull(self):
        """Clears the window of half of its shapes if the shape list has more shapes
        than the window's limit.
        """

        if len(self.objs) >= self._SHAPELIST_MAX_LENGTH:
            self.objs = self.objs[len(self.objs)/2:]
            self.frame.contentPane.objs = self.objs

    def mouseEntered(self, e):
        """
        Runs when the mouse enters the window.
        Sets the mouse coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouseEntered` function, if any.
        """
        self.mouseEventType = e.getID()
        self.mouseX = e.getX()
        self.mouseY = e.getY() - 25
        if self.mainRunning:
            if self.onMouseEntered:
                self.onMouseEntered()
        else:
            self.eventQueue.put(e)
        if debug:
            print (self.mouseX, self.mouseY)

    def mouseClicked(self, e):
        """
        Runs when the mouse is clicked.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouseClicked` function, if any.
        """
        self.mouseEventType = e.getID()
        self.mouseX = e.getX()
        self.mouseY = e.getY() - 25
        if self.mainRunning:
            if self.onMouseClicked:
                self.onMouseClicked()
        else:
            self.eventQueue.put(e)

    def mouseExited(self, e):
        """
        Runs when the mouse exits the window.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouseExited` function, if any.
        """
        self.mouseEventType = e.getID()
        self.mouseX = e.getX()
        self.mouseY = e.getY() - 25
        if self.mainRunning:
            if self.onMouseExited:
                self.onMouseExited()
        else:
            self.eventQueue.put(e)

    def mousePressed(self, e):
        """
        Runs when the mouse button is pressed.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mousePressed` function, if any.
        """
        self.mouseEventType = e.getID()
        self.mouseX = e.getX()
        self.mouseY = e.getY() - 25
        if self.mainRunning:
            if self.onMousePressed:
                self.onMousePressed()
        else:
            self.eventQueue.put(e)

    def mouseReleased(self, e):
        """
        Runs when the mouse button is released.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouseReleased` function, if any.
        """
        self.mouseEventType = e.getID()
        if self.mainRunning:
            if self.onMouseReleased:
                self.onMouseReleased()
        else:
            self.eventQueue.put(e)

    def mouseMoved(self, e):
        """
        Runs when the mouse is moved.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouseMoved` function, if any.
        """
        self.mouseEventType = e.getID()
        self.mouseX = e.getX()
        self.mouseY = e.getY() - 25
        if self.mainRunning:
            if self.onMouseMoved:
                self.onMouseMoved()
        else:
            self.eventQueue.put(e)
        if debug:
            print '(%d, %d)' % (self.mouseX, self.mouseY)

    def mouseDragged(self, e):
        """
        Runs when the mouse is dragged.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouseDragged` function, if any.
        """
        self.mouseEventType = e.getID()
        self.mouseX = e.getX()
        self.mouseY = e.getY() - 25
        if self.mainRunning:
            if self.onMouseDragged:
                self.onMouseDragged()
        else:
            self.eventQueue.put(e)

    def keyTyped(self, e):
        """
        Sets the last key character and code when a key is typed. Calls a
        user-provided :py:meth:`keyTyped` function, if any.
        """
        self.keyEventType = e.getID()

        if debug:
            print e.getKeyCode()

        if self.mainRunning:
            if self.onKeyTyped:
                self.onKeyTyped()
        else:
            self.eventQueue.put(e)

    def keyPressed(self, e):
        """
        Sets the last key character and code when a key is pressed. Calls a
        user-provided :py:meth:`keyPressed` function, if any.
        """
        self.keyEventType = e.getID()
        self.lastKeyCode = e.getKeyCode()
        self.lastKeyChar = e.getKeyChar()
        self.charsPressed.add(e.getKeyText(e.getKeyCode()).upper())

        if debug:
            print "Key pressed:"
            print e.getKeyText(e.getKeyCode())
            print e.getKeyCode()

        if self.mainRunning:
            if self.onKeyPressed:
                self.onKeyPressed()
        else:
            self.eventQueue.put(e)

    def keyReleased(self, e):
        """
        Sets the last key character and code when a key is released. Calls a
        user-provided :py:meth:`keyReleased` function, if any.
        """
        self.keyEventType = e.getID()
        self.charsPressed.remove(e.getKeyText(e.getKeyCode()).upper())

        if debug:
            print "Key released:"
            print e.getKeyText(e.getKeyCode())
            print e.getKeyCode()

        if self.mainRunning:
            if self.onKeyReleased:
                self.onKeyReleased()
        else:
            self.eventQueue.put(e)

    def _is_key_pressed(self):
        return bool(self.charsPressed)

    isKeyPressed = property(_is_key_pressed, ':py:class:`True` if any keys are pressed, else :py:class:`False`.')

    def _get_width(self):
        """Get the width of the canvas."""
        return self.frame.contentPane.width

    width = property(_get_width, 'Width of Canvas in pixels.')

    def _get_height(self):
        """Get the height of the canvas."""
        return self.frame.contentPane.height

    height = property(_get_height, 'Height of Canvas in pixels.')
예제 #16
0
class GraphicsWindow(ActionListener, KeyListener, MouseInputListener):
    """
    Creates a :py:class:`~jygsaw.graphicswindow.GraphicsWindow` with a
    :py:class:`~jygsaw.graphicswindow.Canvas` object that can be drawn on.
    Takes a title, window width, and window height.
    An optional background color can be specified.
    """
    colors = [BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN,
              LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW]

    def __init__(self, title, w, h, bg_color=WHITE):
        assert w > 0, "GraphicsWindow width must be greater than zero"
        assert h > 0, "GraphicsWindow height must be greater than zero"

        self.objs = []  # List of GraphicsObjects
        self.bg_color = bg_color

        self.frame = JFrame(
            title, defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
            size=(w, h))

        self.frame.setLocationRelativeTo(None)
        self.frame.contentPane = Canvas(self, self.objs, self.bg_color)
        self.frame.contentPane.setPreferredSize(Dimension(w, h))

        self.frame.addMouseListener(self)
        self.frame.addMouseMotionListener(self)
        self.frame.addKeyListener(self)

        # MouseEvent attributes
        self.mouse_x = 0
        self.mouse_y = 0
        self.mouse_buttons = Set()

        # Mouse callbacks
        self.on_mouse_clicked = None
        self.on_mouse_dragged = None
        self.on_mouse_moved = None
        self.on_mouse_pressed = None
        self.on_mouse_released = None
        self.on_mouse_exited = None
        self.on_mouse_entered = None

        # Key callbacks
        self.on_key_pressed = None
        self.on_key_released = None
        self.on_key_typed = None

        # Key values
        self.last_key_char = None
        self.last_key_code = None

        self.chars_pressed = Set()
        self.codes_pressed = Set()

        # Event queue
        self.event_queue = Queue()
        self.main_running = False

        # not needed, user_draw is called directly from on_draw
        self.on_draw = None

    def set_visible(self, visible):
        """Sets the window to visible."""
        assert isinstance(visible, bool), "Variable is not a boolean."
        self.frame.pack()
        self.frame.visible = visible

    def draw(self, *params):
        """
        Takes any number of :py:class:`~jygsaw.graphicsobject.GraphicsObject`
        or :py:class:`~jygsaw.shape.Shape` objects, or :py:class:`~jygsaw.group.Group`,
        and draws them on the Canvas. If a shape is drawn without specifying a color
        the default color is used. The default stroke option
        (:py:class:`True` or :py:class:`False`) and *stroke_color* is saved in each object.
        """
        for arg in params:
            if isinstance(arg, GraphicsObject) or isinstance(arg, Shape):
                if arg.color is None:
                    arg.color = self.frame.contentPane.default_color
                arg.stroke_color = self.frame.contentPane.stroke_color
                arg.stroke = self.frame.contentPane.stroke
                arg.filled = self.frame.contentPane.filled
                arg.stroke_width = self.frame.contentPane.stroke_width
                if isinstance(arg, Text):
                    arg.font = self.frame.contentPane.font
                    arg.size = self.frame.contentPane.text_size
                self.objs.append(arg)
            elif isinstance(arg, Group):
                for obj in arg.group:
                    if obj.color is None:
                        obj.color = self.frame.contentPane.default_color
                    obj.stroke_color = self.frame.contentPane.stroke_color
                    obj.stroke = self.frame.contentPane.stroke
                    obj.filled = self.frame.contentPane.filled
                    arg.stroke_width = self.frame.contentPane.stroke_width
                    if isinstance(arg, Text):
                        arg.font = self.frame.contentPane.font
                        arg.size = self.frame.contentPane.text_size
                    self.objs.append(obj)
            else:
                raise Exception("Passed in something that's not a Group or GraphicsObject.")

    def set_default_color(self, c):
        """Sets the default color of the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(c, Color), "The object passed is not a Color object."
        self.frame.contentPane.default_color = c

    def set_stroke_color(self, c):
        """Sets the stroke color in the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(c, Color), "The object passed is not a Color object."
        self.frame.contentPane.stroke_color = c

    def set_stroke(self, b):
        """Turns stroke on or off in the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(b, bool), "Variable given is not a boolean."
        self.frame.contentPane.stroke = b

    def set_stroke_width(self, w):
        """Sets the width of the stroke in the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(w, int), "Variable given is not an integer."
        self.frame.contentPane.stroke_width = w

    def set_filled(self, f):
        """Turns fill on or off in the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(f, bool), "Variable given is not a boolean."
        self.frame.contentPane.filled = f

    def set_bg_color(self, c):
        """Sets the background color of the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert isinstance(c, Color), "The object passed is not a Color object."
        self.frame.contentPane.background_color = c
        self.background = c

    def set_font(self, f):
        """Sets the font of the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        self.frame.contentPane.font = f

    def set_text_size(self, s):
        """Sets the text size of the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        assert s >= 0 and isinstance(
            s, int), "Font size must be greater than or equal to 0"
        self.frame.contentPane.text_size = s

    def get_bg_color(self):
        """Returns the background color of the :py:class:`~jygsaw.graphicswindow.Canvas`."""
        return self.background

    def redraw(self, delay=0.0):
        """
        Redraws the :py:class:`~jygsaw.graphicswindow.Canvas`.
        Only returns when done. An optional float can also be used to sleep after redrawing.
        """
        # Use non-blocking redraw because there is no one-to-one relation
        # between calling cavas.repaint() and execution of paintComponent()
        #
        if SwingUtilities.isEventDispatchThread():
            self.frame.contentPane.repaint()
        else:
            self.frame.contentPane.blocking_redraw()
        sleep(delay)

    def clear(self):
        """
        Clears the screen so that only the background is visible.
        Also deletes all :py:class:`~jygsaw.graphicsobject.GraphicsObject` and :py:class:`~jygsaw.shape.Shape` and objects.
        """
        self.objs = []
        self.frame.contentPane.objs = self.objs

    def mouseEntered(self, e):
        """
        Runs when the mouse enters the window.
        Sets the mouse coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouse_entered` function, if any.
        """
        pos = self.frame.contentPane.getMousePosition()
        if pos:
            self.mouse_x = pos.x
            self.mouse_y = pos.y
        if self.main_running:
            if self.on_mouse_entered:
                self.on_mouse_entered()
        else:
            self.event_queue.put(e)
        if debug:
            print (self.mouse_x, self.mouse_y)

    def mouseClicked(self, e):
        """
        Runs when the mouse is clicked.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouse_clicked` function, if any.
        """
        pos = self.frame.contentPane.getMousePosition()
        if pos:
            self.mouse_x = pos.x
            self.mouse_y = pos.y
        if self.main_running:
            if self.on_mouse_clicked:
                self.on_mouse_clicked()
        else:
            self.event_queue.put(e)

    def mouseExited(self, e):
        """
        Runs when the mouse exits the window.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouse_exited` function, if any.
        """
        pos = self.frame.contentPane.getMousePosition()
        if pos:
            self.mouse_x = pos.x
            self.mouse_y = pos.y
        if self.main_running:
            if self.on_mouse_exited:
                self.on_mouse_exited()
        else:
            self.event_queue.put(e)

    def mousePressed(self, e):
        """
        Runs when the mouse button is pressed.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouse_pressed` function, if any.
        """
        pos = self.frame.contentPane.getMousePosition()
        if pos:
            self.mouse_x = pos.x
            self.mouse_y = pos.y
        self.mouse_buttons.add(e.getButton())
        if self.main_running:
            if self.on_mouse_pressed:
                self.on_mouse_pressed()
        else:
            self.event_queue.put(e)

    def mouseReleased(self, e):
        """
        Runs when the mouse button is released.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouse_released` function, if any.
        """
        pos = self.frame.contentPane.getMousePosition()
        if pos:
            self.mouse_x = pos.x
            self.mouse_y = pos.y
        self.mouse_buttons.remove(e.getButton())
        if self.main_running:
            if self.on_mouse_released:
                self.on_mouse_released()
        else:
            self.event_queue.put(e)

    def mouseMoved(self, e):
        """
        Runs when the mouse is moved.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouse_moved` function, if any.
        """
        pos = self.frame.contentPane.getMousePosition()
        if pos:
            self.mouse_x = pos.x
            self.mouse_y = pos.y
        if self.main_running:
            if self.on_mouse_moved:
                self.on_mouse_moved()
        else:
            self.event_queue.put(e)
        if debug:
            print '(%d, %d)' % (self.mouse_x, self.mouse_y)

    def mouseDragged(self, e):
        """
        Runs when the mouse is dragged.
        Sets the mouse X and Y coordinates to the current mouse position.
        Calls a user-provided :py:meth:`mouseDragged` function, if any.
        """
        pos = self.frame.contentPane.getMousePosition()
        if pos:
            self.mouse_x = pos.x
            self.mouse_y = pos.y
        if self.main_running:
            if self.on_mouse_dragged:
                self.on_mouse_dragged()
        else:
            self.event_queue.put(e)

    def keyTyped(self, e):
        """
        Sets the last key character and code when a key is typed. Calls a
        user-provided :py:meth:`keyTyped` function, if any.
        """
        if debug:
            print e.getKeyCode()

        if self.main_running:
            if self.on_key_typed:
                self.on_key_typed()
        else:
            self.event_queue.put(e)

    def keyPressed(self, e):
        """
        Sets the last key character and code when a key is pressed. Calls a
        user-provided :py:meth:`key_pressed` function, if any.
        """
        self.last_key_code = e.getKeyCode()
        self.last_key_char = e.getKeyChar()
        self.chars_pressed.add(e.getKeyText(e.getKeyCode()).upper())
        self.codes_pressed.add(e.getKeyCode())

        if debug:
            print "Key pressed:"
            print e.getKeyText(e.getKeyCode())
            print e.getKeyCode()

        if self.main_running:
            if self.on_key_pressed:
                self.on_key_pressed()
        else:
            self.event_queue.put(e)

    def keyReleased(self, e):
        """
        Sets the last key character and code when a key is released. Calls a
        user-provided :py:meth:`key_released` function, if any.
        """
        self.chars_pressed.remove(e.getKeyText(e.getKeyCode()).upper())
        self.codes_pressed.remove(e.getKeyCode())

        if debug:
            print "Key released:"
            print e.getKeyText(e.getKeyCode())
            print e.getKeyCode()

        if self.main_running:
            if self.on_key_released:
                self.on_key_released()
        else:
            self.event_queue.put(e)

    def _is_key_pressed(self):
        return bool(self.chars_pressed)

    isKeyPressed = property(_is_key_pressed, ':py:class:`True` if any keys are pressed, else :py:class:`False`.')

    def _get_width(self):
        """Get the width of the canvas."""
        return self.frame.contentPane.width

    width = property(_get_width, 'Width of Canvas in pixels.')

    def _get_height(self):
        """Get the height of the canvas."""
        return self.frame.contentPane.height

    height = property(_get_height, 'Height of Canvas in pixels.')
예제 #17
0
파일: main.py 프로젝트: pavithra03/neofelis
  def getArguments(self):
    """
    This function brings up a window to retreive any required arguments.  It uses a window with fields for each argument, filled with any arguments already given.
    While this window is visible the program will wait, once it is no longer visible all the arguments will be filled with the entries in the fields.
    """

    class LocationAction(AbstractAction):
      """
      Action to set the text of a text field to a folder or directory.
      """
      def __init__(self, field):
        AbstractAction.__init__(self, "...")
        self.field = field

      def actionPerformed(self, event):
        fileChooser = JFileChooser()
        fileChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
        if fileChooser.showOpenDialog(None) == JFileChooser.APPROVE_OPTION:
          self.field.text = fileChooser.selectedFile.absolutePath
    
    class HelpAction(AbstractAction):
      """
      Displays a help page in a web browser.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Help")

      def actionPerformed(self, event):
        browsers = ["google-chrome", "firefox", "opera", "epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla"]
        osName = System.getProperty("os.name")
        helpHTML = ClassLoader.getSystemResource("help.html").toString()
        if osName.find("Mac OS") == 0:
          Class.forName("com.apple.eio.FileManager").getDeclaredMethod( "openURL", [String().getClass()]).invoke(None, [helpHTML])
        elif osName.find("Windows") == 0:
          Runtime.getRuntime().exec( "rundll32 url.dll,FileProtocolHandler " + helpHTML)
        else:
          browser = None
          for b in browsers:
            if browser == None and Runtime.getRuntime().exec(["which", b]).getInputStream().read() != -1:
              browser = b
              Runtime.getRuntime().exec([browser, helpHTML])

    class OKAction(AbstractAction):
      """
      Action for starting the pipeline.  This action will simply make the window invisible.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Ok")

      def actionPerformed(self, event):
        frame.setVisible(False)

    class CancelAction(AbstractAction):
      """
      Action for canceling the pipeline.  Exits the program.
      """
      def __init__(self):
        AbstractAction.__init__(self, "Cancel")

      def actionPerformed(self, event):
        sys.exit(0)

    frame = JFrame("Neofelis")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    constraints = GridBagConstraints()
    contentPane = JPanel(GridBagLayout())
    frame.setContentPane(contentPane)
    blastField = JTextField(self.blastLocation)
    genemarkField = JTextField(self.genemarkLocation)
    transtermField = JTextField(self.transtermLocation)
    tRNAscanField = JTextField(self.tRNAscanLocation)
    databaseLocationField = JTextField(os.path.split(self.database)[0])
    databaseField = JTextField(os.path.split(self.database)[1])
    matrixField = JTextField(str(self.matrix))
    eValueField = JTextField(str(self.eValue))
    minLengthField = JTextField(str(self.minLength))
    scaffoldingDistanceField = JTextField(str(self.scaffoldingDistance))
    promoterScoreField = JTextField(str(self.promoterScoreCutoff))
    queryField = JTextField(self.sources[0])

    constraints.gridx = 0
    constraints.gridy = 0
    constraints.gridwidth = 1
    constraints.gridheight = 1
    constraints.fill = GridBagConstraints.HORIZONTAL
    constraints.weightx = 0
    constraints.weighty = 0
    contentPane.add(JLabel("Blast Location"), constraints)
    constraints.gridy = 1
    contentPane.add(JLabel("Genemark Location"), constraints)
    constraints.gridy = 2
    contentPane.add(JLabel("Transterm Location"), constraints)
    constraints.gridy = 3
    contentPane.add(JLabel("tRNAscan Location"), constraints)
    constraints.gridy = 4
    contentPane.add(JLabel("Databases Location"), constraints)
    constraints.gridy = 5
    contentPane.add(JLabel("Database"), constraints)
    constraints.gridy = 6
    contentPane.add(JLabel("Matrix(Leave blank to use heuristic matrix)"), constraints)
    constraints.gridy = 7
    contentPane.add(JLabel("E Value"), constraints)
    constraints.gridy = 8
    contentPane.add(JLabel("Minimum Intergenic Length"), constraints)
    constraints.gridy = 9
    contentPane.add(JLabel("Scaffold Distance"), constraints)
    constraints.gridy = 10
    contentPane.add(JLabel("Promoter Score Cutoff"), constraints)
    constraints.gridy = 11
    contentPane.add(JLabel("Query"), constraints)
    constraints.gridx = 1
    constraints.gridy = 0
    constraints.weightx = 1
    contentPane.add(blastField, constraints)
    constraints.gridy = 1
    contentPane.add(genemarkField, constraints)
    constraints.gridy = 2
    contentPane.add(transtermField, constraints)
    constraints.gridy = 3
    contentPane.add(tRNAscanField, constraints)
    constraints.gridy = 4
    contentPane.add(databaseLocationField, constraints)
    constraints.gridy = 5
    contentPane.add(databaseField, constraints)
    constraints.gridy = 6
    contentPane.add(matrixField, constraints)
    constraints.gridy = 7
    contentPane.add(eValueField, constraints)
    constraints.gridy = 8
    contentPane.add(minLengthField, constraints)
    constraints.gridy = 9
    contentPane.add(scaffoldingDistanceField, constraints)
    constraints.gridy = 10
    contentPane.add(promoterScoreField, constraints)
    constraints.gridy = 11
    contentPane.add(queryField, constraints)
    constraints.gridx = 2
    constraints.gridy = 0
    constraints.weightx = 0
    constraints.fill = GridBagConstraints.NONE
    constraints.anchor = GridBagConstraints.LINE_END
    contentPane.add(JButton(LocationAction(blastField)), constraints)
    constraints.gridy = 1
    contentPane.add(JButton(LocationAction(genemarkField)), constraints)
    constraints.gridy = 2
    contentPane.add(JButton(LocationAction(transtermField)), constraints)
    constraints.gridy = 3
    contentPane.add(JButton(LocationAction(tRNAscanField)), constraints)
    constraints.gridy = 4
    contentPane.add(JButton(LocationAction(databaseLocationField)), constraints)
    constraints.gridy = 11
    contentPane.add(JButton(LocationAction(queryField)), constraints)

    constraints.gridx = 0
    constraints.gridy = 12
    constraints.anchor = GridBagConstraints.LINE_START
    contentPane.add(JButton(HelpAction()), constraints)
    constraints.gridx = 1
    constraints.anchor = GridBagConstraints.LINE_END
    contentPane.add(JButton(OKAction()), constraints)
    constraints.gridx = 2
    contentPane.add(JButton(CancelAction()), constraints)

    frame.pack()
    frame.setLocationRelativeTo(None)
    frame.setVisible(True)

    while frame.isVisible():
      pass

    self.blastLocation = blastField.getText()
    self.genemarkLocation = genemarkField.getText()
    self.transtermLocation = transtermField.getText()
    self.database = databaseLocationField.getText() + "/" + databaseField.getText()
    self.matrix = matrixField.getText()
    self.eValue = float(eValueField.getText())
    self.minLength = int(minLengthField.getText())
    self.scaffoldingDistance = int(scaffoldingDistanceField.getText())
    self.promoterScoreCutoff = float(promoterScoreField.getText())
    self.sources = [queryField.getText()]
예제 #18
0
button = JButton("selected?", actionPerformed=click)
addButton = JButton("add 7", actionPerformed=add)
remButton = JButton("remove element", actionPerformed=rem)
chButton = JButton("Change to list B", actionPerformed=change)



listModel = DefaultListModel()
[listModel.addElement(e) for e in liste]
li = JList(listModel)
spane = JScrollPane(li) # making the list scrollable. li is now inside container JScrollPane


#b = JButton("press", actionPerformed=rem)
p.add(spane)
p.add(button)
p.add(addButton)
p.add(remButton)
p.add(chButton)
f.add(p)
f.pack()
f.setLocationRelativeTo(None)
f.setVisible(True)

print f.getParent()
print f.getLocationOnScreen()
print f.getContentPane().getSize()


예제 #19
0
    def __init__(self):
        

        frame = JFrame("S1riu5 Spy")
        frame.setSize(700, 690)
        frame.setLocationRelativeTo(None);
        frame.setLayout(BorderLayout())

        tabPane = JTabbedPane(JTabbedPane.TOP)

        #第一个Tab用来做C段查询

        eachIp = self.getIp(HOSTDOMAIN)

        iList = eachIp.split(".")

        theIP = iList[0] + "." + iList[1] + "." + iList[2] + ".1/24"  

        panel1 = JPanel()
        label = JLabel("IP CIDR:")
        self.textfield1 = JTextField(theIP, 15)
        button = JButton("SCAN", actionPerformed = self.cNmapScan)
        self.textArea = JTextArea(40, 65)
        self.textArea.append("IP: " + eachIp)
        self.textArea.setLineWrap(True)                  #激活自动换行功能 
        self.textArea.setWrapStyleWord(True);            # 激活断行不断字功能
                   
        panel1.add(label)
        panel1.add(self.textfield1)
        panel1.add(button)
        panel1.add(JScrollPane(self.textArea))            #设置自动滚动条
        tabPane.addTab("C segment query ", panel1)
        



        #第二个Tab用来做子域名查询



        theName = self.getDomain1(HOSTDOMAIN)

        self.textArea2 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea2.setLineWrap(True)                  #激活自动换行功能 
        self.textArea2.setWrapStyleWord(True)           # 激活断行不断字功能
                   


        label2 = JLabel("Domain: ")
        self.textfield2 = JTextField(theName, 15)
        button2 = JButton("SCAN", actionPerformed = self.subDomain)
        self.panel2 = JPanel()
        self.panel2.add(label2)
        self.panel2.add(self.textfield2)
        self.panel2.add(button2)
        #self.panel2.add(scrollPane)
        self.panel2.add(JScrollPane(self.textArea2))
        tabPane.addTab("subDomains", self.panel2)


        #第三个Tab用来做敏感文件扫描

        self.tableData0 = [["1", "2"]]
        colNames2 = ('url','http code')
        dataModel3 = DefaultTableModel(self.tableData0, colNames2)
        self.table3 = JTable(dataModel3)
##
 
        label3 = JLabel("URL: ")
        self.textfield3 = JTextField(HOSTDOMAIN, 15)
        self.textArea3 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea3.setLineWrap(True)                  #激活自动换行功能 
        self.textArea3.setWrapStyleWord(True)          # 激活断行不断字功能
        a = 0
        b = 0 
        self.label4 = JLabel(str(a) + "/" + str(b))
#
        self.chkbox1 = JCheckBox('ASP')
        self.chkbox2 = JCheckBox('ASPX')
        self.chkbox3 = JCheckBox('JSP')
        self.chkbox4 = JCheckBox('PHP')
        self.chkbox5 = JCheckBox('MDB')
        self.chkbox6 = JCheckBox('DIR')
        button3 = JButton("SCAN", actionPerformed = self.senFileScan)
        panel3 = JPanel()

        panel3.add(label3)
        panel3.add(self.textfield3)
        panel3.add(self.chkbox1)
        panel3.add(self.chkbox2)
        panel3.add(self.chkbox3)
        panel3.add(self.chkbox4)
        panel3.add(self.chkbox5)
        panel3.add(self.chkbox6)
        panel3.add(button3)
        panel3.add(self.label4)
        panel3.add(JScrollPane(self.textArea3))


#
        tabPane.addTab("Sebsitive File", panel3)
#
        frame.add(tabPane)
        frame.setVisible(True)
예제 #20
0
def generateDeconvolutionScriptUI(srcDir,
                                  tgtDir,
                                  calibration,
                                  preCropAffines,
                                  ROI,
                                  postCropAffines):
  """
  Open an UI to automatically generate a script to:
  1. Register the views of each time point TM folder, and deconvolve them.
  2. Register deconvolved time points to each other, for a range of consecutive time points.

  Will ask for the file path to the kernel file,
  and also for the range of time points to process,
  and for the deconvolution iterations for CM00-CM01, and CM02-CM03.
  """

  template = """
# AUTOMATICALLY GENERATED - %s

import sys, os
sys.path.append("%s")
from lib.isoview import deconvolveTimePoints
from mpicbg.models import RigidModel3D, TranslationModel3D
from net.imglib2.img.display.imagej import ImageJFunctions as IL

# The folder with the sequence of TM\d+ folders, one per time point in the 4D series.
# Each folder should contain 4 KLB files, one per camera view of the IsoView microscope.
srcDir = "%s"

# A folder to save deconvolved images in, and CSV files describing features, point matches and transformations
targetDir = "%s"

# Path to the volume describing the point spread function (PSF)
kernelPath = "%s"

calibration = [%s] # An array with 3 floats (identity--all 1.0--because the coarse affines, that is,
                   # the camera transformations, already include the scaling to isotropy computed using the original calibration.

# The transformations of each timepoint onto the camera at index zero.
def cameraTransformations(dims0, dims1, dims2, dims3, calibration):
  return {
    0: [%s],
    1: [%s],
    2: [%s],
    3: [%s]
  }

# Deconvolution parameters
paramsDeconvolution = {
  "blockSizes": None, # None means the image size + kernel size. Otherwise specify like e.g. [[128, 128, 128]] for img in images]
  "CM_0_1_n_iterations": %i,
  "CM_2_3_n_iterations": %i,
}

# Joint dictionary of parameters
params = {}
params.update(paramsDeconvolution)

# A region of interest for each camera view, for cropping after registration but prior to deconvolution
roi = ([%s], # array of 3 integers, top-left coordinates
       [%s]) # array of 3 integers, bottom-right coordinates

# All 4 cameras relative to CM00
fineTransformsPostROICrop = \
   [[1, 0, 0, 0,
     0, 1, 0, 0,
     0, 0, 1, 0],
    [%s],
    [%s],
    [%s]]

deconvolveTimePoints(srcDir, targetDir, kernelPath, calibration,
                    cameraTransformations, fineTransformsPostROICrop,
                    params, roi, fine_fwd=True, subrange=range(%i, %i))
  """

  od = OpenDialog("Choose kernel file", srcDir)
  kernel_path = od.getPath()
  if not kernel_path:
    JOptionPane.showMessageDialog(None, "Can't proceed without a filepath to the kernel", "Alert", JOptionPane.ERROR_MESSAGE)
    return

  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()

  msg = ["Edit parameters, then push the button",
         "to generate a script that, when run,",
         "will execute the deconvolution for each time point",
         "saving two 3D stacks per time point as ZIP files",
         "in the target directory under subfolder 'deconvolved'.",
         "Find the script in a new Script Editor window.",
         " "]
  gc.gridy = -1 # init
  for line in msg:
    label = JLabel(line)
    gc.anchor = GBC.WEST
    gc.gridx = 0
    gc.gridy += 1
    gc.gridwidth = 2
    gc.gridheight = 1
    gb.setConstraints(label, gc)
    panel.add(label)

  strings = [["Deconvolution iterations",
              "CM_0_1_n_iterations", "CM_2_3_n_iterations"],
             ["Range",
              "First time point", "Last time point"]]
  params = {"CM_0_1_n_iterations": 5,
            "CM_2_3_n_iterations": 7,
            "First time point": 0,
            "Last time point": -1} # -1 means last
  insertFloatFields(panel, gb, gc, params, strings)

  def asString(affine):
    matrix = zeros(12, 'd')
    affine.toArray(matrix)
    return ",".join(imap(str, matrix))

  def generateScript(event):
    script = template % (str(datetime.now()),
                         filter(lambda path: path.endswith("IsoView-GCaMP"), sys.path)[-1],
                         srcDir,
                         tgtDir,
                         kernel_path,
                         ", ".join(imap(str, calibration)),
                         asString(preCropAffines[0]),
                         asString(preCropAffines[1]),
                         asString(preCropAffines[2]),
                         asString(preCropAffines[3]),
                         params["CM_0_1_n_iterations"],
                         params["CM_2_3_n_iterations"],
                         ", ".join(imap(str, ROI[0])),
                         ", ".join(imap(str, ROI[1])),
                         asString(postCropAffines[1]),
                         asString(postCropAffines[2]),
                         asString(postCropAffines[3]),
                         params["First time point"],
                         params["Last time point"])
    tab = None
    for frame in JFrame.getFrames():
      if str(frame).startswith("org.scijava.ui.swing.script.TextEditor["):
        try:
          tab = frame.newTab(script, "python")
          break
        except:
          print sys.exc_info()
    if not tab:
      try:
        now = datetime.now()
        with open(os.path.join(System.getProperty("java.io.tmpdir"),
                               "script-%i-%i-%i_%i:%i.py" % (now.year, now.month, now.day,
                                                             now.hour, now.minute)), 'w') as f:
          f.write(script)
      except:
        print sys.exc_info()
        print script
  

  gen = JButton("Generate script")
  gen.addActionListener(generateScript)
  gc.anchor = GBC.CENTER
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 2
  gb.setConstraints(gen, gc)
  panel.add(gen)

  frame = JFrame("Generate deconvolution script")
  frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(True)
예제 #21
0
class Pipeline():
  def __init__(self):
    #If a swing interface is asked for this will be the JFrame.
    self.frame = None
    #Keeps track of the number of queries processed.
    self.jobCount = 0
    #Keeps track of the query currently being processed.
    self.currentJob = ""
    #Keeps track of the massage to be displayed.
    self.message = 0
    #Messages to be displayed at each stage in the processing of a single query.
    self.messages = ["Searching for genes via genemark",
                     "Extending genes found via genemark",
                     "Searching for intergenic genes",
                     "Removing overlapping genes",
                     "Searching for promoters",
                     "Using transterm to find terminators",
                     "Removing transcription signals which conflict with genes",
                     "Using tRNAscan to find transfer RNAs",
                     "Writing Artemis file",
                     "Writing summary .xml, .html, and .xls files"]
    self.exception = None

  def initializeDisplay(self, queries, swing):
    """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """
  
    self.numJobs = len(queries)
    if swing:
      self.frame = JFrame("Neofelis")
      self.frame.addWindowListener(PipelineWindowAdapter(self))
      contentPane = JPanel(GridBagLayout())
      self.frame.setContentPane(contentPane)
      self.globalLabel = JLabel(max(queries, key = len))
      self.globalProgress = JProgressBar(0, self.numJobs)
      self.currentLabel = JLabel(max(self.messages, key = len))
      self.currentProgress = JProgressBar(0, len(self.messages))
      self.doneButton = JButton(DoneAction(self.frame))
      self.doneButton.setEnabled(False)

      constraints = GridBagConstraints()
      
      constraints.gridx, constraints.gridy = 0, 0
      constraints.gridwidth, constraints.gridheight = 1, 1
      constraints.weightx = 1
      constraints.fill = GridBagConstraints.HORIZONTAL
      contentPane.add(self.globalLabel, constraints)
      constraints.gridy = 1
      contentPane.add(self.globalProgress, constraints)
      constraints.gridy = 2
      contentPane.add(self.currentLabel, constraints)
      constraints.gridy = 3
      contentPane.add(self.currentProgress, constraints)
      constraints.gridy = 4
      constraints.weightx = 0
      constraints.fill = GridBagConstraints.NONE
      constraints.anchor = GridBagConstraints.LINE_END
      contentPane.add(self.doneButton, constraints)
    
      self.frame.pack()
      self.frame.setResizable(False)
      self.globalLabel.setText(" ")
      self.currentLabel.setText(" ")
      self.frame.setLocationRelativeTo(None)
      self.frame.setVisible(True)

  def updateProgress(self, job):
    """
    query: Name of the query currently being processed.
    
    This function use used for updating the progress shown in the interface.  If job is not equal to currentJob then
    global progress is incremented and shown and the currentProgress is reset and shown.  If job is equal to currentJob
    then the globalProgress does not change and currentProgress is increased.
    """
    if self.exception:
      raise self.exception
    
    if self.frame:
      if job != self.currentJob:
        self.currentProgress.setValue(self.currentProgress.getMaximum())
        self.globalLabel.setText(job)
        self.globalProgress.setValue(self.jobCount)
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))
      self.currentProgress.setValue(self.message)
      self.currentLabel.setText(self.messages[self.message])
    else:
      if job != self.currentJob:
        print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
        self.jobCount += 1
        self.currentJob = job
        self.message = -1
      self.message += 1
      print "    %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))

  def finished(self):
    """
    This function is to be called at the end of the pipeline.  Informs the user that the pipeline is finished
    and if a swing interface is being used the Done button is enabled.
    """
    print "Processing 100.00% done"
    if self.frame:
      self.globalLabel.setText("Finished")
      self.globalProgress.setValue(self.globalProgress.getMaximum())
      self.currentLabel.setText(" ")
      self.currentProgress.setValue(self.currentProgress.getMaximum())
      self.doneButton.setEnabled(True)
      while self.frame.isVisible():
        pass

  def run(self, blastLocation, genemarkLocation, transtermLocation, tRNAscanLocation, database, eValue, matrix, minLength, scaffoldingDistance, promoterScoreCutoff, queries, swing = False, email = ""):
    """
    blastLocation:       Directory blast was installed in.
    genemarkLocation:    Directory genemark was installed in.
    transtermLocation:   Directory transterm was installed in.
    tRNAscanLocation:    Directory tRNAscan was installed in.
    database:            Name of the blast database to use.
    eValue:              The e value used whenever a blast search is done.
    matrix:              The matrix to use when running genemark.  If None then genemark is run heuristically.
    minLength:           Minimum length of any genes included in the resulting annotation.
    scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified
    promoterScoreCutoff: Minimum score allowed for any promoters included in the resulting annotation
    queries:             A list of faster files to process.
    swing:               If true a swing window will be used to updated the user about the pipeline's progress.
    email:               If this is a non-empty string an email will be sent to the address in the string when the pipeline is done.  This will be attempted with the sendmail command on the local computer.
    
    The main pipeline function.  For every query genemark is used to predict genes, these genes are then extended to any preferable starts.  Then the pipeline searches
    for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes.  Then the genes are pruned to remove
    any undesirable genes found in the intergenic stage.  BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any
    signals which are inside or too far away from any genes.  Next, tRNAscan is used to find any transfer RNAs in the genome.  Finally, all the remaining genes,
    promoters, and terminators are written to an artemis file in the directory of the query with the same name but with a .art extension, and .xml, .html, and
    .xls files will be generating describing the blast results of the final genes.
    """
    self.initializeDisplay(queries, swing)

    try:
      for query in queries:
        name = os.path.splitext(query)[0]
        queryDirectory, name = os.path.split(name)
        
        genome = utils.loadGenome(query)
        swapFileName = "query" + str(id(self)) + ".fas"
        queryFile = open(swapFileName, "w")
        queryFile.write(">" + name + "\n")
        for i in range(0, len(genome), 50):
          queryFile.write(genome[i:min(i+50, len(genome))] + "\n")
        queryFile.close()

        self.updateProgress(query)
        initialGenes = genemark.findGenes(swapFileName, name, blastLocation, database, eValue, genemarkLocation, matrix, self)
      
        self.updateProgress(query)
        extendedGenes = extend.extendGenes(swapFileName, initialGenes, name, blastLocation, database, eValue, self)
    
        self.updateProgress(query)
        intergenicGenes = intergenic.findIntergenics(swapFileName, extendedGenes, name, minLength, blastLocation, database, eValue, self)

        genes = {}
        for k, v in extendedGenes.items() + intergenicGenes.items():
          genes[k] = v
        
        self.updateProgress(query)
        scaffolded = scaffolds.refineScaffolds(genes, scaffoldingDistance)
 
        self.updateProgress(query)
        initialPromoters = promoters.findPromoters(swapFileName, name, promoterScoreCutoff, self.frame)
    
        self.updateProgress(query)
        initialTerminators = terminators.findTerminators(swapFileName, name, genes.values(), transtermLocation)
      
        self.updateProgress(query)
        filteredSignals = signals.filterSignals(scaffolded.values(), initialPromoters + initialTerminators)
        filteredPromoters = filter(lambda x: isinstance(x, promoters.Promoter), filteredSignals)
        filteredTerminators = filter(lambda x: isinstance(x, terminators.Terminator), filteredSignals)

        self.updateProgress(query)
        transferRNAs = rna.findtRNAs(tRNAscanLocation, swapFileName)

        os.remove(swapFileName)

        self.updateProgress(query)
        artemis.writeArtemisFile(os.path.splitext(query)[0] + ".art", genome, scaffolded.values(), filteredPromoters, filteredTerminators, transferRNAs)

        self.updateProgress(query)
        report.report(name, scaffolded, os.path.splitext(query)[0])

      if email:
        if not os.path.isfile("EMAIL_MESSAGE"):
          message = open("EMAIL_MESSAGE", "w")
          message.write("Subject: Annotation Complete\nYour genome has been annotated.\n")
          message.close()
        
        sent = False
        while not sent:
          message = open("EMAIL_MESSAGE", "r")
          sendmailProcess = subprocess.Popen(["/usr/sbin/sendmail", "-F", "Neofelis", "-f", "*****@*****.**", email],
                                             stdin = message,
                                             stdout = subprocess.PIPE)
          result = ""
          nextRead = sendmailProcess.stdout.read()
          while nextRead:
            result += nextRead
            nextRead = sendmailProcess.stdout.read()
          sent = not result.strip()
          message.close()
    
      self.finished()
    except PipelineException:
      return
예제 #22
0
class Pipeline():
    def __init__(self):
        #If a swing interface is asked for this will be the JFrame.
        self.frame = None
        #Keeps track of the number of queries processed.
        self.jobCount = 0
        #Keeps track of the query currently being processed.
        self.currentJob = ""
        #Keeps track of the massage to be displayed.
        self.message = 0
        #Messages to be displayed at each stage in the processing of a single query.
        self.messages = [
            "Searching for genes via genemark",
            "Extending genes found via genemark",
            "Searching for intergenic genes", "Removing overlapping genes",
            "Searching for promoters", "Using transterm to find terminators",
            "Removing transcription signals which conflict with genes",
            "Writing Artemis file", "Writing summary file"
        ]
        self.exception = None

    def initializeDisplay(self, queries, swing):
        """
    queries: A list of the fasts files to be processed.
    swing:   If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
    
    Initializes the interface for telling the user about progress in the pipeline.  Queries is used to count the
    number of queries the pipeline will process and to size the swing display(if it is used) so that text
    isn't cutoff at the edge of the window.  The swing display is setup if swing is true.
    """

        self.numJobs = len(queries)
        if swing:
            self.frame = JFrame("Neofelis")
            self.frame.addWindowListener(PipelineWindowAdapter(self))
            contentPane = JPanel(GridBagLayout())
            self.frame.setContentPane(contentPane)
            self.globalLabel = JLabel(max(queries, key=len))
            self.globalProgress = JProgressBar(0, self.numJobs)
            self.currentLabel = JLabel(max(self.messages, key=len))
            self.currentProgress = JProgressBar(0, len(self.messages))
            self.doneButton = JButton(DoneAction(self.frame))
            self.doneButton.setEnabled(False)

            constraints = GridBagConstraints()

            constraints.gridx, constraints.gridy = 0, 0
            constraints.gridwidth, constraints.gridheight = 1, 1
            constraints.weightx = 1
            constraints.fill = GridBagConstraints.HORIZONTAL
            contentPane.add(self.globalLabel, constraints)
            constraints.gridy = 1
            contentPane.add(self.globalProgress, constraints)
            constraints.gridy = 2
            contentPane.add(self.currentLabel, constraints)
            constraints.gridy = 3
            contentPane.add(self.currentProgress, constraints)
            constraints.gridy = 4
            constraints.weightx = 0
            constraints.fill = GridBagConstraints.NONE
            constraints.anchor = GridBagConstraints.LINE_END
            contentPane.add(self.doneButton, constraints)

            self.frame.pack()
            self.frame.setResizable(False)
            self.globalLabel.setText(" ")
            self.currentLabel.setText(" ")
            self.frame.setLocationRelativeTo(None)
            self.frame.setVisible(True)

    def updateProgress(self, job):
        """
    query: Name of the query currently being processed.
    
    This function use used for updating the progress shown in the interface.  If job is not equal to currentJob then
    global progress is incremented and shown and the currentProgress is reset and shown.  If job is equal to currentJob
    then the globalProgress does not change and currentProgress is incremented.
    """
        if self.exception:
            raise self.exception

        if self.frame:
            if job != self.currentJob:
                self.currentProgress.setValue(
                    self.currentProgress.getMaximum())
                self.globalLabel.setText(job)
                self.globalProgress.setValue(self.jobCount)
                print "Processing %s, %.2f%% done" % (
                    job, 100.0 * self.jobCount / self.numJobs)
                self.jobCount += 1
                self.currentJob = job
                self.message = -1
            self.message += 1
            print "    %s, %.2f%% done" % (self.messages[self.message], 100.0 *
                                           self.message / len(self.messages))
            self.currentProgress.setValue(self.message)
            self.currentLabel.setText(self.messages[self.message])
        else:
            if job != self.currentJob:
                print "Processing %s, %.2f%% done" % (
                    job, 100.0 * self.jobCount / self.numJobs)
                self.jobCount += 1
                self.currentJob = job
                self.message = -1
            self.message += 1
            print "    %s, %.2f%% done" % (self.messages[self.message], 100.0 *
                                           self.message / len(self.messages))

    def finished(self):
        """
    This function is to be called at the end of the pipeline.  Informs the user that the pipeline is finished
    and if a swing interface is being used the Done button is enabled.
    """
        print "Processing 100.00% done"
        if self.frame:
            self.globalLabel.setText("Finished")
            self.globalProgress.setValue(self.globalProgress.getMaximum())
            self.currentLabel.setText(" ")
            self.currentProgress.setValue(self.currentProgress.getMaximum())
            self.doneButton.setEnabled(True)
            while self.frame.isVisible():
                pass

    def run(self,
            blastLocation,
            genemarkLocation,
            transtermLocation,
            database,
            eValue,
            matrix,
            minLength,
            scaffoldingDistance,
            ldfCutoff,
            queries,
            swing=False,
            email=""):
        """
    blastLocation:       Directory blast was installed in.
    genemarkLocation:    Directory genemark was installed in.
    transtermLocation:   Directory transterm was installed in.
    database:            Name of the blast database to use.
    eValue:              The e value used whenever a blast search is done.
    matrix:              The matrix to use when running genemark.  If None then genemark is run heuristically.
    minLength:           Minimum length of any genes included in the resulting annotation.
    scaffoldingDistance: The maximum length allowed between genes when contiguous regions of genes are being identified
    ldfCutoff:           Minimum LDF allowed for any promoters included in the resulting annotation
    queries:             A list of faster files to process.
    swing:               If true a swing window will be used to updated the user about the pipeline's progress.
    email:               If this is a non-empty string an email will be sent to the address in the string when the pipeline is done.  The local machine will be used as
                         an SMTP server and this will not work if it isn't.
    
    The main pipeline function.  For every query genemark is used to predict genes, these genes are then extended to any preferable starts.  Then the pipeline searches
    for any intergenic genes(genes between those found by genemark) and these are combined with the extended genemark genes.  Then the genes are pruned to remove
    any undesirable genes found in the intergenic stage.  BPROM and Transterm are used to find promoters and terminators, which are then pruned to remove any
    signals which are inside or too far away from any genes.  Finally, all the remaining genes, promoters, and terminators ar written to an artemis file in the directory
    of the query with the same name but with a .art extension, and .dat and .xls files will be generating describing the blast results of the final genes.
    """
        self.initializeDisplay(queries, swing)

        try:
            for query in queries:
                name = os.path.splitext(query)[0]
                queryDirectory, name = os.path.split(name)

                genome = utils.loadGenome(query)
                swapFileName = "query" + str(id(self)) + ".fas"
                queryFile = open(swapFileName, "w")
                queryFile.write(">" + name + "\n")
                for i in range(0, len(genome), 50):
                    queryFile.write(genome[i:min(i + 50, len(genome))] + "\n")
                queryFile.close()

                self.updateProgress(query)
                initialGenes = genemark.findGenes(swapFileName, name,
                                                  blastLocation, database,
                                                  eValue, genemarkLocation,
                                                  matrix, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".genemark.art", genome, initialGenes.values())

                self.updateProgress(query)
                extendedGenes = extend.extendGenes(swapFileName, initialGenes,
                                                   name, blastLocation,
                                                   database, eValue, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".extended.art", genome, extendedGenes.values())

                self.updateProgress(query)
                intergenicGenes = intergenic.findIntergenics(
                    swapFileName, extendedGenes, name, minLength,
                    blastLocation, database, eValue, self)
                #artemis.writeArtemisFile(os.path.splitext(query)[0] + ".intergenic.art", genome, intergenicGenes.values())
                genes = {}
                for k, v in extendedGenes.items() + intergenicGenes.items():
                    genes[k] = v

                self.updateProgress(query)
                scaffolded = scaffolds.refineScaffolds(genes,
                                                       scaffoldingDistance)

                self.updateProgress(query)
                initialPromoters = promoters.findPromoters(swapFileName, name)

                self.updateProgress(query)
                initialTerminators = terminators.findTerminators(
                    swapFileName, name, genes.values(), transtermLocation)

                self.updateProgress(query)
                filteredSignals = signals.filterSignals(
                    scaffolded.values(), initialPromoters + initialTerminators)
                filteredPromoters = filter(
                    lambda x: isinstance(x, promoters.Promoter),
                    filteredSignals)
                filteredTerminators = filter(
                    lambda x: isinstance(x, terminators.Terminator),
                    filteredSignals)

                self.updateProgress(query)
                artemis.writeArtemisFile(
                    os.path.splitext(query)[0] + ".art", genome,
                    scaffolded.values(), filteredPromoters,
                    filteredTerminators)

                self.updateProgress(query)
                report.report(name, scaffolded, os.path.splitext(query)[0])

            if email:
                message = MIMEText("Your genome has been annotated.")
                message["Subject"] = "Annotation complete"
                message["From"] = "Neofelis"
                message["To"] = email

                smtp = smtplib.SMTP("tmpl.arizona.edu", 587)
                smtp.ehlo()
                smtp.starttls()
                smtp.ehlo
                smtp.sendmail("Neofelis", [email], message.as_string())
                smtp.close()

            self.finished()
        except PipelineException:
            return
예제 #23
0
    def __init__(self):

        frame = JFrame("S1riu5 Spy")
        frame.setSize(700, 690)
        frame.setLocationRelativeTo(None)
        frame.setLayout(BorderLayout())

        tabPane = JTabbedPane(JTabbedPane.TOP)

        #第一个Tab用来做C段查询

        eachIp = self.getIp(HOSTDOMAIN)

        iList = eachIp.split(".")

        theIP = iList[0] + "." + iList[1] + "." + iList[2] + ".1/24"

        panel1 = JPanel()
        label = JLabel("IP CIDR:")
        self.textfield1 = JTextField(theIP, 15)
        button = JButton("SCAN", actionPerformed=self.cNmapScan)
        self.textArea = JTextArea(40, 65)
        self.textArea.append("IP: " + eachIp)
        self.textArea.setLineWrap(True)  #激活自动换行功能
        self.textArea.setWrapStyleWord(True)
        # 激活断行不断字功能

        panel1.add(label)
        panel1.add(self.textfield1)
        panel1.add(button)
        panel1.add(JScrollPane(self.textArea))  #设置自动滚动条
        tabPane.addTab("C segment query ", panel1)

        #第二个Tab用来做子域名查询

        theName = self.getDomain1(HOSTDOMAIN)

        self.textArea2 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea2.setLineWrap(True)  #激活自动换行功能
        self.textArea2.setWrapStyleWord(True)  # 激活断行不断字功能

        label2 = JLabel("Domain: ")
        self.textfield2 = JTextField(theName, 15)
        button2 = JButton("SCAN", actionPerformed=self.subDomain)
        self.panel2 = JPanel()
        self.panel2.add(label2)
        self.panel2.add(self.textfield2)
        self.panel2.add(button2)
        #self.panel2.add(scrollPane)
        self.panel2.add(JScrollPane(self.textArea2))
        tabPane.addTab("subDomains", self.panel2)

        #第三个Tab用来做敏感文件扫描

        self.tableData0 = [["1", "2"]]
        colNames2 = ('url', 'http code')
        dataModel3 = DefaultTableModel(self.tableData0, colNames2)
        self.table3 = JTable(dataModel3)
        ##

        label3 = JLabel("URL: ")
        self.textfield3 = JTextField(HOSTDOMAIN, 15)
        self.textArea3 = JTextArea(40, 65)
        #self.textArea.append("IP: " + eachIp)
        self.textArea3.setLineWrap(True)  #激活自动换行功能
        self.textArea3.setWrapStyleWord(True)  # 激活断行不断字功能
        a = 0
        b = 0
        self.label4 = JLabel(str(a) + "/" + str(b))
        #
        self.chkbox1 = JCheckBox('ASP')
        self.chkbox2 = JCheckBox('ASPX')
        self.chkbox3 = JCheckBox('JSP')
        self.chkbox4 = JCheckBox('PHP')
        self.chkbox5 = JCheckBox('MDB')
        self.chkbox6 = JCheckBox('DIR')
        button3 = JButton("SCAN", actionPerformed=self.senFileScan)
        panel3 = JPanel()

        panel3.add(label3)
        panel3.add(self.textfield3)
        panel3.add(self.chkbox1)
        panel3.add(self.chkbox2)
        panel3.add(self.chkbox3)
        panel3.add(self.chkbox4)
        panel3.add(self.chkbox5)
        panel3.add(self.chkbox6)
        panel3.add(button3)
        panel3.add(self.label4)
        panel3.add(JScrollPane(self.textArea3))

        #
        tabPane.addTab("Sebsitive File", panel3)
        #
        frame.add(tabPane)
        frame.setVisible(True)
예제 #24
0
class BurpExtender(IBurpExtender, IBurpExtenderCallbacks, IIntruderPayloadProcessor, ITab, IExtensionStateListener):
    def registerExtenderCallbacks( self, callbacks):
        self._helpers = callbacks.getHelpers()
        callbacks.setExtensionName("JWT FuzzHelper")
        callbacks.registerIntruderPayloadProcessor(self)
        callbacks.registerExtensionStateListener(self)
        
        self._stdout = PrintWriter(callbacks.getStdout(), True)
        self._stderr = PrintWriter(callbacks.getStderr(), True)

        # Holds values passed by user from Configuration panel
        self._fuzzoptions = { 
                                "target" : "Header", 
                                "selector" : None, 
                                "signature" : False,
                                "algorithm" : "HS256",
                                "key" : "",
                                "key_cmd" : ""
                            }

        self._isNone = lambda val: isinstance(val, type(None))

        # Configuration panel Layout
        self._configurationPanel = JPanel()
        gridBagLayout = GridBagLayout()
        gridBagLayout.columnWidths = [ 0, 0, 0]
        gridBagLayout.rowHeights = [ 10, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
        gridBagLayout.columnWeights = [ 0.0, 0.0, 0.0 ]
        gridBagLayout.rowWeights = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]
        self._configurationPanel.setLayout(gridBagLayout)

        # Setup tabs
        self._tabs = JTabbedPane()
        self._tabs.addTab('Configuration',self._configurationPanel)
        #self._tabs.addTab('Help',self._helpPanel)

        # Target Options
        targetLabel = JLabel("Target Selection (Required): ")
        targetLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 1
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(targetLabel,c)

        options = [ 'Header', 'Payload' ]
        self._targetComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 1
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._targetComboBox,c)

        # Help Button
        self._helpButton = JButton("Help", actionPerformed=self.helpMenu)
        c = GridBagConstraints()
        c.gridx = 2
        c.gridy = 1
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._helpButton,c)

        # Selector Options
        self._selectorLabel = JLabel("JSON Selector [Object Identifier-Index Syntax] (Required): ")
        self._selectorLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 2
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._selectorLabel, c)

        self._selectorTextField = JTextField('',50)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 2
        self._configurationPanel.add(self._selectorTextField, c)

        # Regex option

        self._regexLabel = JLabel("Use regex as JSON Selector? (Optional): ")
        self._regexLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 3
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._regexLabel,c)

        self._regexCheckBox = JCheckBox("", actionPerformed=self.regexSelector)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 3
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._regexCheckBox,c)

        # Signature Options
        generateSignatureLabel = JLabel("Generate signature? (Required): ")
        generateSignatureLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 4
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(generateSignatureLabel,c)

        options = ["False", "True"]
        self._generateSignatureComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 4
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._generateSignatureComboBox,c)

        signatureAlgorithmLabel = JLabel("Signature Algorithm (Optional): ")
        signatureAlgorithmLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 5
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(signatureAlgorithmLabel,c)

        options = ["None", "HS256","HS384","HS512","ES256","ES384","ES512","RS256","RS384","RS512","PS256","PS256","PS384","PS512"]
        self._algorithmSelectionComboBox = JComboBox(options)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 5
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._algorithmSelectionComboBox,c)

        # Signing key options
        self._signingKeyLabel = JLabel("Signing Key (Optional): ")
        self._signingKeyLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 6
        c.insets = Insets(0,10,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(self._signingKeyLabel,c)

        self.addSigningKeyTextArea()
        self._fromFileTextField = JTextField('',50) 

        fromFileLabel = JLabel("Signing key from file? (Optional): ")
        fromFileLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 7
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(fromFileLabel,c)

        self._fromFileCheckBox = JCheckBox("", actionPerformed=self.fromFile)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 7
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._fromFileCheckBox,c)

        self._fromCmdTextField = JTextField('',50)

        fromCmdLabel = JLabel("Signing key from command? (Optional): ")
        fromCmdLabel.setFont(Font("Tahoma",Font.BOLD, 12))
        c = GridBagConstraints()
        c.gridx = 0
        c.gridy = 8
        c.insets = Insets(0,0,0,0)
        c.anchor = GridBagConstraints.LINE_END
        self._configurationPanel.add(fromCmdLabel,c)

        self._fromCmdCheckBox = JCheckBox("", actionPerformed=self.fromCmd)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 8
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._fromCmdCheckBox,c)

        self._saveButton = JButton("Save Configuration", actionPerformed=self.saveOptions)
        self._saveButton.setText("Save Configuration")
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 9
        c.anchor = GridBagConstraints.FIRST_LINE_START
        self._configurationPanel.add(self._saveButton,c)

        
        callbacks.customizeUiComponent(self._configurationPanel)
        callbacks.customizeUiComponent(self._tabs)
        callbacks.addSuiteTab(self)

        self._stdout.println("[JWT FuzzHelper] Loaded successfully")
        return


    def getProcessorName(self):
        return "JWT Fuzzer"

    def extensionUnloaded(self):
        del self._configurationPanel
        return

    # Intruder logic function
    def processPayload(self, currentPayload, originalPayload, baseValue):
        dataParameter = self._helpers.bytesToString(
                         self._helpers.urlDecode(baseValue)
                       )

        # utf-8 encode
        header,payload,signature = [unicode(s).encode('utf-8') for s in dataParameter.split(".",3)]
        decoded_header = self._helpers.bytesToString(
                            self._helpers.base64Decode(header + "=" * (-len(header) % 4))
                        )
        decoded_payload = self._helpers.bytesToString(
                            self._helpers.base64Decode(payload+"=" * (-len(payload) % 4))
                        )

        # Decode header and payload, preserving order if they are JSON objects

        # Decode header
        try:
            header_dict = json.loads(decoded_header, object_pairs_hook=OrderedDict)
        except ValueError:
            raise RuntimeException("[JWT FuzzHelper] Error: ValueError. Failed to decode header!")
        except Exception as e:
            self._stderr.println("[ERROR] Encountered an unknown error when decoding header:\n{}\nCarrying on...".format(e))

        # Decode payload
        # Payload does not have to be a JSON object.
        #   Ref: https://github.com/auth0/node-jsonwebtoken#usage
        payload_is_string = False
        try:
            payload_dict = json.loads(decoded_payload, object_pairs_hook=OrderedDict)
        except ValueError:
            payload_is_string = True
            payload_dict = decoded_payload
        except Exception as e:
            self._stderr.println("[ERROR] Encountered an unknown error when decoding payload:\n{}\nCarrying on...".format(e))

        target = header_dict if self._fuzzoptions["target"] == "Header" else payload_dict
        selector = self._fuzzoptions["selector"]

        # If using Object Identifier-Index then retrieve the 
        # value specified by the selector, 
        # if this value does not exist, assume the user
        # wants to add the value that would have been specified
        # by the selector to the desired JWT segment (this behavior will 
        # be noted in the help docs)

        intruderPayload = self._helpers.bytesToString(currentPayload)
        if not self._fuzzoptions["regex"]:
            if selector != [""]:
                try:
                    value = self.getValue(target, selector)
                except Exception:
                    target = self.buildDict(target, selector)

            if not self._isNone(selector) and selector != [""]:
                target = self.setValue(target, selector, intruderPayload)
        
        # Simple match-replace for regex
        if self._fuzzoptions["regex"]:
            target_string = target if payload_is_string else json.dumps(target)
            target_string = re.sub(selector, intruderPayload, target_string)
            target = target_string if payload_is_string else json.loads(target_string, object_pairs_hook=OrderedDict)
            if self._fuzzoptions["target"] == "Payload":
                payload_dict = target
            else:
                header_dict = target
                

        algorithm = self._fuzzoptions["algorithm"]
        if self._fuzzoptions["signature"]: 
            # pyjwt requires lowercase 'none'. If user wants to try
            # "none", "NonE", "nOnE", etc... they should use .alg
            # as selector, delete sig from intruder and use those
            # permutations as their fuzz list (outlined in help docs)
            # and keep "Generate Signature" as False
            algorithm = "none" if algorithm.lower() == "none" else algorithm
            header_dict["alg"] = algorithm

        header = json.dumps(header_dict, separators=(",",":"))
        payload = payload_dict if payload_is_string else json.dumps(payload_dict, separators=(",",":"))
        header = self._helpers.base64Encode(header).strip("=")
        payload = self._helpers.base64Encode(payload).strip("=")

        contents = header + "." + payload
        
        key = self._fuzzoptions["key"]

        if len(self._fuzzoptions["key_cmd"]) > 0:
            # we provide 'contents' value as an only argument to key-generating command
            # it is expected that the command will print only the signature
            signature = check_output([self._fuzzoptions["key_cmd"], contents])
            modified_jwt = contents + "." + signature
        elif self._fuzzoptions["signature"]:
            # pyjwt throws error when using a public key in symmetric alg (for good reason of course),
            # must do natively to support algorithmic sub attacks
            if algorithm.startswith("HS"):
                if algorithm == "HS256":
                    hmac_algorithm = hashlib.sha256
                elif algorithm == "HS384":
                    hmac_algorithm = hashlib.sha384
                else:
                    hmac_algorithm = hashlib.sha512
            
                signature = self._helpers.base64Encode(
                            hmac.new(
                                    key, contents, hmac_algorithm
                                ).digest()
                    ).strip("=")

                modified_jwt = contents + "." +signature

            # JWT can't sign non-JSON payloads. WTF. This block is for non-JSON payloads.
            elif algorithm.startswith("RS") and payload_is_string:
                if algorithm == "RS256":
                    rsa_algorithm = "SHA-256"
                elif algorithm == "RS384":
                    rsa_algorithm = "SHA-384"
                else:
                    rsa_algorithm = "SHA-512"
                privkey = rsa.PrivateKey.load_pkcs1(key)
                signature = rsa.sign(contents,privkey,rsa_algorithm)
                signature = base64.b64encode(signature).encode('utf-8').replace("=", "")
                modified_jwt = contents + "." + signature
            else:
                # Use pyjwt when using asymmetric alg
                if algorithm == "none":
                    key = ""
                modified_jwt = jwt.encode(payload_dict,key,algorithm=algorithm,headers=header_dict)
        else:
            modified_jwt = contents + "." + signature

        return self._helpers.stringToBytes(modified_jwt)

    
    #-----------------------
    # getValue:
    #   @return: A value at arbitrary depth in dictionary
    #   @throws: TypeError
    #-----------------------
    def getValue(self, dictionary, values):
        return reduce(dict.__getitem__, values, dictionary)

    #-----------------------
    # buildDict:
    #   @note: Will build dictionary of arbitrary depth
    #-----------------------
    def buildDict(self, dictionary, keys):
        if self._isNone(keys):
            return dictionary

        root = current = dictionary
        for key in keys:
            if key not in current:
                current[key] = {}
            current = current[key]
        return root

    #----------------------
    # setValue:
    #   @note: Will set key of arbitrary depth
    #-----------------------
    def setValue(self, dictionary, keys, value):
        root = current = dictionary
        for i,key in enumerate(keys):
            if i == len(keys) - 1:
                current[key] = value
                break
            if key in current:
                current = current[key]
            else:
                # Should never happen
                current = self.buildDict(current, keys)
        return root
    
    #-----------------------
    # addSigningKeyTextArea:
    #   @note: Will toggle if fromFile selected. Be DRY.
    #----------------------
    def addSigningKeyTextArea(self):
        self._signingKeyTextArea = JTextArea()
        self._signingKeyTextArea.setColumns(50)
        self._signingKeyTextArea.setRows(10)
        self._signingKeyScrollPane = JScrollPane(self._signingKeyTextArea)
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 6
        c.anchor = GridBagConstraints.LINE_START
        self._configurationPanel.add(self._signingKeyScrollPane,c)

    def addSigningKeyFromFileTextField(self):
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 6
        self._configurationPanel.add(self._fromFileTextField, c)

    def addSigningKeyFromCmdTextField(self):
        c = GridBagConstraints()
        c.gridx = 1
        c.gridy = 6
        self._configurationPanel.add(self._fromCmdTextField, c)
    #-----------------------
    # End Helpers
    #-----------------------

    #-----------------------
    # Implement ITab
    #-----------------------

    def getTabCaption(self):
        return "JWT FuzzHelper"

    def getUiComponent(self):
        return self._tabs

    #---------------------------
    # Save configuration options
    #---------------------------

    def saveOptions(self,event):
        self._fuzzoptions["target"]     = self._targetComboBox.getSelectedItem()
        self._fuzzoptions["selector"]   = self._selectorTextField.getText()
        self._fuzzoptions["signature"]  = True if self._generateSignatureComboBox.getSelectedItem() == "True" else False
        self._fuzzoptions["algorithm"]  = self._algorithmSelectionComboBox.getSelectedItem()
        self._fuzzoptions["key_cmd"]    = ""
        
        if self._fromFileCheckBox.isSelected():
            filename = self._fromFileTextField.getText()
            if os.path.isdir(filename):
                self._stderr.println("{} is a directory".format(filename))
                return
            if os.path.exists(filename):
                with open(filename, 'rb') as f:
                    self._fuzzoptions["key"] = f.read()
        elif self._fromCmdCheckBox.isSelected():
            self._fuzzoptions["key_cmd"] = self._fromCmdTextField.getText()
        else:
            self._fuzzoptions["key"]    = unicode(self._signingKeyTextArea.getText()).encode("utf-8")
        # RSA keys need to end with a line break. Many headaches because of this.
        if not self._fuzzoptions["key"].endswith("\n") and self._fuzzoptions["algorithm"].startswith("RS"):
            self._fuzzoptions["key"] += "\n"
        self._stdout.println("[JWT FuzzHelper] Saved options:\n{}".format(self._fuzzoptions))


        # Sanity check selector if it's not a regular expression
        self._fuzzoptions["regex"] = self._regexCheckBox.isSelected()
        if not self._regexCheckBox.isSelected():
            m = re.search("(\.\w+)+",self._fuzzoptions["selector"])
            if self._fuzzoptions["selector"] != "." and (isinstance(m,type(None)) or m.group(0) != self._fuzzoptions["selector"]):
                self._saveButton.setText("Invalid JSON Selector!")
            else:
                self._fuzzoptions["selector"] = self._fuzzoptions["selector"].split(".")[1:]
                self._saveButton.setText("Saved!")
        # Sanity check the regular expression
        else:
            try:
                re.compile(self._fuzzoptions["selector"])
                self._saveButton.setText("Saved!")
            except re.error:
                self._saveButton.setText("Invalid Regex!")
        return

    #-------------------------
    # From file options
    #------------------------
    def fromFile(self,event):
        if self._fromFileCheckBox.isSelected():
            self._signingKeyLabel.setText("Path to Signing Key (Optional): ")
            self._configurationPanel.remove(self._signingKeyScrollPane)
            self.addSigningKeyFromFileTextField()
        else:
            self._signingKeyLabel.setText("Signing Key (Optional): ")
            self._configurationPanel.remove(self._fromFileTextField)
            self.addSigningKeyTextArea()
        self._configurationPanel.repaint()
        return

    def fromCmd(self,event):
        if self._fromCmdCheckBox.isSelected():
            self._signingKeyLabel.setText("Path to Signing Cmd (Optional): ")
            self._configurationPanel.remove(self._signingKeyScrollPane)
            self.addSigningKeyFromCmdTextField()
        else:
            self._signingKeyLabel.setText("Signing Key (Optional): ")
            self._configurationPanel.remove(self._fromCmdTextField)
            self.addSigningKeyTextArea()
        self._configurationPanel.repaint()
        return

    def regexSelector(self,event):
        if self._regexCheckBox.isSelected():
            self._selectorLabel.setText("Selector [Regex] (Required): ")
        else:
            self._selectorLabel.setText("JSON Selector [Object Identifier-Index Syntax] (Required): ")
        self._configurationPanel.repaint()
        return
    #-------------------------
    # Help popup
    #-------------------------
    def helpMenu(self,event):
        self._helpPopup = JFrame('JWT Fuzzer', size=(550, 450) );
        self._helpPopup.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
        helpPanel = JPanel()
        helpPanel.setPreferredSize(Dimension(550, 450))
        helpPanel.setBorder(EmptyBorder(10, 10, 10, 10))
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        self._helpPopup.setContentPane(helpPanel)
        helpHeadingText = JLabel("<html><h2>JWT Fuzzer</h2></html>")
        authorText = JLabel("<html><p>@author: &lt;pinnace&gt;</p></html>")
        aboutText = JLabel("<html><br /> <p>This extension adds an Intruder payload processor for JWTs.</p><br /></html>")
        repositoryText = JLabel("<html>Documentation and source code:</html>")
        repositoryLink = JLabel("<html>- <a href=\"https://github.com/pinnace/burp-jwt-fuzzhelper-extension\">https://github.com/pinnace/burp-jwt-fuzzhelper-extension</a></html>")
        licenseText = JLabel("<html><br/><p>JWT Fuzzer uses a GPL 3 license. This license does not apply to the dependency below:<p></html>") 
        dependencyLink = JLabel("<html>- <a href=\"https://github.com/jpadilla/pyjwt/blob/master/LICENSE\">pyjwt</a></html>")
        dependencyLink.addMouseListener(ClickListener())
        dependencyLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))
        repositoryLink.addMouseListener(ClickListener())
        repositoryLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR))
        
        helpPanel.add(helpHeadingText)
        helpPanel.add(authorText)
        helpPanel.add(aboutText)
        helpPanel.add(repositoryText)
        helpPanel.add(repositoryLink)
        helpPanel.add(licenseText)
        helpPanel.add(dependencyLink)

        self._helpPopup.setSize(Dimension(550, 450))
        self._helpPopup.pack()
        self._helpPopup.setLocationRelativeTo(None)
        self._helpPopup.setVisible(True)
        return
예제 #25
0
class StackOverlay:
    def __init__(self):
        self.frame = None
        self.overlayColorPreviewLabel = None
        self.showStackOverlayWindow()
        self.overlayColor = None

    def onQuit(self, e):
        print "Exiting..."
        self.frame.dispose()

    def showColorChooser(self, e):
        colorChooser = JColorChooser()
        self.overlayColor = colorChooser.showDialog(self.frame, "Choose color",
                                                    Color.red)
        self.overlayColorPreviewLabel.setBackground(self.overlayColor)

    def showStackOverlayWindow(self):
        all = JPanel()
        all.setLayout(MigLayout())

        self.imageIDs = WindowManager.getIDList()
        self.imageNames = []

        if self.imageIDs is None:
            IJ.error(
                "No open images",
                "Stack Overlay requires at least one image to be already open."
            )
            return

        for i in self.imageIDs:
            self.imageNames.append(WindowManager.getImage(i).getTitle())

        self.baseImageBox = JComboBox(self.imageNames)
        baseImageBoxLabel = JLabel("Base image")
        self.baseImageBox.setSelectedIndex(0)
        all.add(baseImageBoxLabel)
        all.add(self.baseImageBox, "wrap")

        self.overlayImageBox = JComboBox(self.imageNames)
        overlayImageBoxLabel = JLabel("Overlay image")
        if len(self.imageNames) > 1:
            self.overlayImageBox.setSelectedIndex(1)

        all.add(overlayImageBoxLabel)
        all.add(self.overlayImageBox, "wrap")

        all.add(JSeparator(SwingConstants.HORIZONTAL), "span, wrap")

        overlayStyleFrame = JPanel()
        overlayStyleFrame.setLayout(MigLayout())
        overlayStyleFrame.setBorder(
            BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Overlay Style"),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)))

        colorLabel = JLabel("Overlay color")
        self.overlayColorPreviewLabel = JLabel("           ")
        self.overlayColorPreviewLabel.setBorder(
            BorderFactory.createEmptyBorder(0, 0, 1, 0))
        self.overlayColorPreviewLabel.setOpaque(True)
        self.overlayColorPreviewLabel.setBackground(Color.red)
        self.overlayColor = Color.red
        colorPicker = JColorChooser()
        colorPicker.setPreviewPanel(self.overlayColorPreviewLabel)
        colorButton = JButton("Select color...",
                              actionPerformed=self.showColorChooser)

        opacityLabel = JLabel("Overlay opacity (%)")
        opacitySpinnerModel = SpinnerNumberModel(100, 0, 100, 1)
        self.opacitySpinner = JSpinner(opacitySpinnerModel)

        overlayStyleFrame.add(colorLabel)
        overlayStyleFrame.add(self.overlayColorPreviewLabel)
        overlayStyleFrame.add(colorButton, "wrap")

        overlayStyleFrame.add(opacityLabel)
        overlayStyleFrame.add(self.opacitySpinner, "wrap")

        all.add(overlayStyleFrame, "span, wrap")

        self.virtualStackCheckbox = JCheckBox("Use Virtual Stack", True)
        all.add(self.virtualStackCheckbox, "span, wrap")

        # TODO: add non-thermonuclear cancel button functionality
        overlayCancelButton = JButton("Cancel", actionPerformed=self.onQuit)
        overlayStartButton = JButton("Overlay images",
                                     actionPerformed=self.overlayImages)

        all.add(overlayCancelButton, "gapleft push")
        all.add(overlayStartButton, "gapleft push")

        self.frame = JFrame("Stack Overlay")
        self.frame.getContentPane().add(JScrollPane(all))
        self.frame.pack()
        self.frame.setLocationRelativeTo(None)
        self.frame.setVisible(True)

    def overlayImages(self, e):
        impBase = WindowManager.getImage(
            self.imageIDs[self.baseImageBox.getSelectedIndex()])
        refBase = impBase.getStack().getProcessor(1)

        impOverlay = WindowManager.getImage(
            self.imageIDs[self.overlayImageBox.getSelectedIndex()])
        refOverlay = impOverlay.getStack().getProcessor(1)

        print "Overlaying for stack sizes " + str(
            impBase.getStackSize()) + "/" + str(
                impOverlay.getStackSize()) + "..."

        stack = None

        if self.virtualStackCheckbox.isSelected():
            stack = OverlayVirtualStack()
            stack.overlayOpacity = float(
                self.opacitySpinner.getValue()) / 100.0
            stack.overlayColor = AWTColorToArray(
                self.overlayColorPreviewLabel.getBackground())
            stack.base = impBase
            stack.overlay = impOverlay

            ImagePlus(
                "Stack Overlay from " +
                self.imageNames[self.baseImageBox.getSelectedIndex()] +
                " and " +
                self.imageNames[self.overlayImageBox.getSelectedIndex()],
                stack).show()
        else:
            IJ.error(
                "Not implemented yet",
                "Using normal stacks is not implemented yet. Please use the Virtual Stack option."
            )
class JythonGui(ItemListener):
    def __init__(self, instructionsURI=''):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger('sasi_runner_gui')
        self.logger.addHandler(logging.StreamHandler())
        def log_fn(msg):
            self.log_msg(msg)
        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame(
            "SASI Runner",
            defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE,
        )
        self.frame.size = (650, 600,)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1
        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">'
             '<U>open instructions</U></FONT><HTML>'),
            actionPerformed=self.browseInstructions)
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT);
        instructionsButton.setBorderPainted(False);
        instructionsButton.setOpaque(False);
        instructionsButton.setBackground(Color.WHITE);
        instructionsButton.setToolTipText(self.instructionsURI);
        self.top_panel.add(instructionsButton)

        # 'Select input' elements.
        self.top_panel.add(getStageLabel(
            "Select a SASI .zip file or data folder:"))
        self.top_panel.add(
            JButton("Select input...", actionPerformed=self.openInputChooser))

        # 'Select output' elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(
            JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # 'Set result fields' elements.
        result_fields = [
            {'id': 'gear_id', 'label': 'Gear', 'selected': True, 
             'enabled': False}, 
            {'id': 'substrate_id', 'label': 'Substrate', 'selected': True}, 
            {'id': 'energy_id', 'label': 'Energy', 'selected': False},
            {'id': 'feature_id', 'label': 'Feature', 'selected': False}, 
            {'id': 'feature_category_id', 'label': 'Feature Category', 
             'selected': False}
        ]
        self.selected_result_fields = {}
        resolutionLabelPanel = JPanel(GridLayout(0,1))
        resolutionLabelPanel.add(getStageLabel("Set result resolution:"))
        resolutionLabelPanel.add(
            JLabel(("<html><i>This sets the specificity with which<br>"
                    "results will be grouped. Note that enabling<br>"
                    "more fields can *greatly* increase resulting<br>"
                    "output sizes and run times.</i>")))
        #self.top_panel.add(getStageLabel("Set result resolution:"))
        self.top_panel.add(resolutionLabelPanel)
        checkPanel = JPanel(GridLayout(0, 1))
        self.top_panel.add(checkPanel) 
        self.resultFieldCheckBoxes = {}
        for result_field in result_fields:
            self.selected_result_fields.setdefault(
                result_field['id'], result_field['selected'])
            checkBox = JCheckBox(
                result_field['label'], result_field['selected'])
            checkBox.setEnabled(result_field.get('enabled', True))
            checkBox.addItemListener(self)
            checkPanel.add(checkBox)
            self.resultFieldCheckBoxes[checkBox] = result_field

        # 'Run' elements.
        self.top_panel.add(getStageLabel("Run SASI: (this might take a while)"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASI)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(
            self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10,10,10,10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.logScrollBar = self.logScrollPane.getVerticalScrollBar()
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES

        self.outputChooser = JFileChooser()
        defaultOutputFile = os.path.join(System.getProperty("user.home"),
                                         "sasi_project.zip")

        self.outputChooser.setSelectedFile(File(defaultOutputFile));
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True

    def browseInstructions(self, event):
        """ Open a browser to the instructions page. """
        browseURI(self.instructionsURI)

    def itemStateChanged(self, event):
        """ Listen for checkbox changes. """
        checkBox = event.getItemSelectable()
        is_selected = (event.getStateChange() == ItemEvent.SELECTED)
        result_field = self.resultFieldCheckBoxes[checkBox]
        self.selected_result_fields[result_field['id']] = is_selected

    def log_msg(self, msg):
        """ Print message to log and scroll to bottom. """
        self.log.append(msg + "\n")
        self.log.setCaretPosition(self.log.getDocument().getLength())

    def openInputChooser(self, event):
        ret = self.inputChooser.showOpenDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_input_file = self.inputChooser.selectedFile
            self.log_msg("Selected '%s' as input." % self.selected_input_file.path)

    def openOutputChooser(self, event):
        ret = self.outputChooser.showSaveDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            selectedPath = self.outputChooser.selectedFile.path
            if not selectedPath.endswith('.zip'):
                zipPath = selectedPath + '.zip'
                self.outputChooser.setSelectedFile(File(zipPath))
            self.selected_output_file = self.outputChooser.selectedFile
            self.log_msg(
                "Selected '%s' as output." % self.selected_output_file.path)

    def runSASI(self, event):
        try:
            self.validateParameters()
        except Exception as e:
            self.log_msg("ERROR: '%s'" % e)

        # Run task in a separate thread, so that log
        # messages will be shown as task progresses.
        def run_task():
            self.tmp_dir = tempfile.mkdtemp(prefix="sasi_runner.")
            self.db_file = os.path.join(self.tmp_dir, "sasi_runner.db")

            self.progressBar.setValue(0)
            self.progressBar.setIndeterminate(True)

            def get_connection():
                engine = create_engine('h2+zxjdbc:////%s' % self.db_file)
                con = engine.connect()
                return con

            try:
                # Set result fields.
                result_fields = []
                for field_id, is_selected in self.selected_result_fields.items():
                    if is_selected: result_fields.append(field_id)

                task = RunSasiTask(
                    input_path=self.selected_input_file.path,
                    output_file=self.selected_output_file.path,
                    logger=self.logger,
                    get_connection=get_connection,
                    config={
                        'result_fields': result_fields,
                        'run_model': {
                            'run': {
                                'batch_size': 'auto',
                            }
                        },
                        'output': {
                            'batch_size': 'auto',
                        },
                    }
                )
                task.call()
            except Exception as e:
                self.logger.exception("Could not complete task")

            self.progressBar.setIndeterminate(False)
            self.progressBar.setValue(100)

            try:
                shutil.rmtree(self.tmp_dir)
            except:
                pass

        Thread(target=run_task).start()

    def validateParameters(self):
        return True
class JythonGui(object):
    def __init__(self, instructionsURI=""):
        self.instructionsURI = instructionsURI

        self.logger = logging.getLogger("sasi_gridder_gui")
        self.logger.addHandler(logging.StreamHandler())

        def log_fn(msg):
            self.log_msg(msg)

        self.logger.addHandler(FnLogHandler(log_fn))
        self.logger.setLevel(logging.DEBUG)

        self.selected_input_file = None
        self.selected_output_file = None

        self.frame = JFrame("SASI Gridder", defaultCloseOperation=WindowConstants.EXIT_ON_CLOSE)
        self.frame.size = (650, 600)

        self.main_panel = JPanel()
        self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
        self.frame.add(self.main_panel)

        self.top_panel = JPanel(SpringLayout())
        self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.main_panel.add(self.top_panel)

        self.stageCounter = 1

        def getStageLabel(txt):
            label = JLabel("%s. %s" % (self.stageCounter, txt))
            self.stageCounter += 1
            return label

        # Instructions link.
        self.top_panel.add(getStageLabel("Read the instructions:"))
        instructionsButton = JButton(
            ('<HTML><FONT color="#000099">' "<U>open instructions</U></FONT><HTML>"),
            actionPerformed=self.browseInstructions,
        )
        instructionsButton.setHorizontalAlignment(SwingConstants.LEFT)
        instructionsButton.setBorderPainted(False)
        instructionsButton.setOpaque(False)
        instructionsButton.setBackground(Color.WHITE)
        instructionsButton.setToolTipText(self.instructionsURI)
        self.top_panel.add(instructionsButton)

        # Select input elements.
        self.top_panel.add(getStageLabel("Select an input data folder:"))
        self.top_panel.add(JButton("Select input...", actionPerformed=self.openInputChooser))

        # Select output elements.
        self.top_panel.add(getStageLabel("Specify an output file:"))
        self.top_panel.add(JButton("Specify output...", actionPerformed=self.openOutputChooser))

        # Run elements.
        self.top_panel.add(getStageLabel("Run SASI Gridder: (this might take a hwile"))
        self.run_button = JButton("Run...", actionPerformed=self.runSASIGridder)
        self.top_panel.add(self.run_button)

        SpringUtilities.makeCompactGrid(self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)

        # Progress bar.
        self.progressBar = JProgressBar(0, 100)
        self.main_panel.add(self.progressBar)

        # Log panel.
        self.log_panel = JPanel()
        self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
        self.log_panel.setBorder(EmptyBorder(10, 10, 10, 10))
        self.main_panel.add(self.log_panel)
        self.log_panel.setLayout(BorderLayout())
        self.log = JTextArea()
        self.log.editable = False
        self.logScrollPane = JScrollPane(self.log)
        self.logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
        self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)

        # File selectors
        self.inputChooser = JFileChooser()
        self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
        self.outputChooser = JFileChooser()
        self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY
        defaultOutputFile = os.path.join(System.getProperty("user.home"), "gridded_efforts.csv")
        self.outputChooser.setSelectedFile(File(defaultOutputFile))

        self.frame.setLocationRelativeTo(None)
        self.frame.visible = True

    def browseInstructions(self, event):
        """ Open a browser to the instructions page. """
        browseURI(self.instructionsURI)
        return

    def log_msg(self, msg):
        self.log.append(msg + "\n")
        self.log.setCaretPosition(self.log.getDocument().getLength())

    def openInputChooser(self, event):
        ret = self.inputChooser.showOpenDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_input_file = self.inputChooser.selectedFile
            self.log_msg("Selected '%s' as input." % self.selected_input_file.path)

    def openOutputChooser(self, event):
        ret = self.outputChooser.showSaveDialog(self.frame)
        if ret == JFileChooser.APPROVE_OPTION:
            self.selected_output_file = self.outputChooser.selectedFile
            self.log_msg("Selected '%s' as output." % self.selected_output_file.path)

    def runSASIGridder(self, event):
        try:
            self.validateParameters()
        except Exception as e:
            self.log_msg("ERROR: '%s'" % e)

        # Run task in a separate thread, so that log
        # messages will be shown as task progresses.
        def run_task():

            self.progressBar.setValue(0)
            self.progressBar.setIndeterminate(True)

            try:
                input_dir = self.selected_input_file.path
                output_path = self.selected_output_file.path

                grid_path = os.path.join(input_dir, "grid", "grid.shp")

                stat_areas_path = os.path.join(input_dir, "stat_areas", "stat_areas.shp")

                raw_efforts_path = os.path.join(input_dir, "raw_efforts.csv")

                gear_mappings_path = os.path.join(input_dir, "gear_mappings.csv")

                gear_mappings = {}
                with open(gear_mappings_path, "rb") as f:
                    r = csv.DictReader(f)
                    for mapping in r:
                        gear_mappings[mapping["trip_type"]] = mapping["gear_code"]

                task = SASIGridderTask(
                    grid_path=grid_path,
                    raw_efforts_path=raw_efforts_path,
                    stat_areas_path=stat_areas_path,
                    output_path=output_path,
                    logger=self.logger,
                    gear_mappings=gear_mappings,
                    effort_limit=None,
                )
                task.call()
            except Exception as e:
                self.logger.exception("Could not complete task")

            self.progressBar.setIndeterminate(False)
            self.progressBar.setValue(100)

        Thread(target=run_task).start()

    def validateParameters(self):
        return True
class StackOverlay:
    def __init__(self):
        self.frame = None
        self.overlayColorPreviewLabel = None
        self.showStackOverlayWindow()
        self.overlayColor = None

    def onQuit(self, e):
        print "Exiting..."
        self.frame.dispose()
        
    def showColorChooser(self, e):
        colorChooser = JColorChooser()
        self.overlayColor = colorChooser.showDialog(self.frame, "Choose color", Color.red)
        self.overlayColorPreviewLabel.setBackground(self.overlayColor)

    def showStackOverlayWindow(self):
        all = JPanel()
        all.setLayout(MigLayout())

        self.imageIDs = WindowManager.getIDList()
        self.imageNames = []

        if self.imageIDs is None:
            IJ.error("No open images", "Stack Overlay requires at least one image to be already open.")
            return

        for i in self.imageIDs:
            self.imageNames.append(WindowManager.getImage(i).getTitle())

        self.baseImageBox = JComboBox(self.imageNames)
        baseImageBoxLabel = JLabel("Base image")
        self.baseImageBox.setSelectedIndex(0)
        all.add(baseImageBoxLabel)
        all.add(self.baseImageBox, "wrap")

        self.overlayImageBox = JComboBox(self.imageNames)
        overlayImageBoxLabel = JLabel("Overlay image")
        if len(self.imageNames) > 1:
            self.overlayImageBox.setSelectedIndex(1)

        all.add(overlayImageBoxLabel)
        all.add(self.overlayImageBox, "wrap")

        all.add(JSeparator(SwingConstants.HORIZONTAL), "span, wrap")

        overlayStyleFrame = JPanel()
        overlayStyleFrame.setLayout(MigLayout())
        overlayStyleFrame.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Overlay Style"), BorderFactory.createEmptyBorder(5,5,5,5)))

        colorLabel = JLabel("Overlay color")
        self.overlayColorPreviewLabel = JLabel("           ")
        self.overlayColorPreviewLabel.setBorder(BorderFactory.createEmptyBorder(0,0,1,0))
        self.overlayColorPreviewLabel.setOpaque(True)
        self.overlayColorPreviewLabel.setBackground(Color.red)
        self.overlayColor = Color.red
        colorPicker = JColorChooser()
        colorPicker.setPreviewPanel(self.overlayColorPreviewLabel)
        colorButton = JButton("Select color...", actionPerformed=self.showColorChooser)

        opacityLabel = JLabel("Overlay opacity (%)")
        opacitySpinnerModel = SpinnerNumberModel(100, 0, 100, 1)
        self.opacitySpinner = JSpinner(opacitySpinnerModel)

        overlayStyleFrame.add(colorLabel)
        overlayStyleFrame.add(self.overlayColorPreviewLabel)
        overlayStyleFrame.add(colorButton, "wrap")

        overlayStyleFrame.add(opacityLabel)
        overlayStyleFrame.add(self.opacitySpinner, "wrap")
        

        all.add(overlayStyleFrame, "span, wrap")
        
        self.virtualStackCheckbox = JCheckBox("Use Virtual Stack", True)
        all.add(self.virtualStackCheckbox, "span, wrap")

        # TODO: add non-thermonuclear cancel button functionality
        overlayCancelButton = JButton("Cancel", actionPerformed=self.onQuit)
        overlayStartButton = JButton("Overlay images", actionPerformed=self.overlayImages)
        
        all.add(overlayCancelButton, "gapleft push")
        all.add(overlayStartButton, "gapleft push")

        self.frame = JFrame("Stack Overlay")
        self.frame.getContentPane().add(JScrollPane(all))
        self.frame.pack()
        self.frame.setLocationRelativeTo(None)
        self.frame.setVisible(True)
        
    def overlayImages(self, e):
        impBase = WindowManager.getImage(self.imageIDs[self.baseImageBox.getSelectedIndex()])
        refBase = impBase.getStack().getProcessor(1)
        
        impOverlay = WindowManager.getImage(self.imageIDs[self.overlayImageBox.getSelectedIndex()])
        refOverlay = impOverlay.getStack().getProcessor(1)
        
        print "Overlaying for stack sizes " + str(impBase.getStackSize()) + "/" + str(impOverlay.getStackSize()) + "..."
        
        stack = None
        
        if self.virtualStackCheckbox.isSelected():
            stack = OverlayVirtualStack()
            stack.overlayOpacity = float(self.opacitySpinner.getValue())/100.0
            stack.overlayColor = AWTColorToArray(self.overlayColorPreviewLabel.getBackground())
            stack.base = impBase
            stack.overlay = impOverlay

            ImagePlus("Stack Overlay from " + self.imageNames[self.baseImageBox.getSelectedIndex()] + " and " + self.imageNames[self.overlayImageBox.getSelectedIndex()], stack).show()
        else:
            IJ.error("Not implemented yet", "Using normal stacks is not implemented yet. Please use the Virtual Stack option.")
예제 #29
0
def specifyRoiUI(roi=Roi(0, 0, 0, 0)):
    # A panel in which to place UI elements
    panel = JPanel()
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
    gb = GridBagLayout()
    panel.setLayout(gb)
    gc = GBC()

    bounds = roi.getBounds() if roi else Rectangle()
    textfields = []
    roimakers = []

    # Basic properties of most UI elements, will edit when needed
    gc.gridx = 0  # can be any natural number
    gc.gridy = 0  # idem.
    gc.gridwidth = 1  # when e.g. 2, the UI element will occupy two horizontally adjacent grid cells
    gc.gridheight = 1  # same but vertically
    gc.fill = GBC.NONE  # can also be BOTH, VERTICAL and HORIZONTAL

    for title in ["x", "y", "width", "height"]:
        # label
        gc.gridx = 0
        gc.anchor = GBC.EAST
        label = JLabel(title + ": ")
        gb.setConstraints(label, gc)  # copies the given constraints 'gc',
        # so we can modify and reuse gc later.
        panel.add(label)
        # text field, below the title
        gc.gridx = 1
        gc.anchor = GBC.WEST
        text = str(getattr(bounds,
                           title))  # same as e.g. bounds.x, bounds.width, ...
        textfield = JTextField(text,
                               10)  # 10 is the size of the field, in digits
        gb.setConstraints(textfield, gc)
        panel.add(textfield)
        textfields.append(
            textfield)  # collect all 4 created textfields for the listeners
        # setup ROI and text field listeners
        listener = RoiMaker(textfields,
                            len(textfields) -
                            1)  # second argument is the index of textfield
        # in the list of textfields.
        roimakers.append(listener)
        textfield.addKeyListener(listener)
        textfield.addMouseWheelListener(listener)
        # Position next ROI property in a new row by increasing the Y coordinate of the layout grid
        gc.gridy += 1

    # User documentation (uses HTML to define line breaks)
    doc = JLabel(
        "<html><body><br />Click on a field to activate it, then:<br />" +
        "Type in integer numbers<br />" +
        "or use arrow keys to increase by 1<br />" +
        "or use the scroll wheel on a field.</body></html>")
    gc.gridx = 0  # start at the first column
    gc.gridwidth = 2  # Spans both columns
    gb.setConstraints(doc, gc)
    panel.add(doc)

    # Listen to changes in the ROI of imp
    roilistener = TextFieldUpdater(textfields)
    Roi.addRoiListener(roilistener)

    # Show window
    frame = JFrame("Specify rectangular ROI")
    frame.getContentPane().add(panel)
    frame.pack()
    frame.setLocationRelativeTo(None)  # center in the screen
    frame.setDefaultCloseOperation(
        JFrame.DO_NOTHING_ON_CLOSE)  # prevent closing the window
    frame.addWindowListener(
        CloseControl(roilistener))  # handles closing the window
    frame.setVisible(True)
예제 #30
0
# C:\Users\simon\Documents\Programming_Challenge\3.2_JYTHON

from javax.swing import JFrame
from javax.swing import JButton
import requests


def doAGetRequest():
    re = requests.get('https://www.google.com')
    print("finished")


def onClick(event):
    print("clicked")
    executor = TaskExecutor()
    executor.runBackground(doAGetRequest)


frame = JFrame("Hello World!")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocationRelativeTo(None)
frame.setSize(300, 200)
frame.add(JButton("click", actionPerformed=onClick))
frame.setVisible(True)