Пример #1
0
class ListBoxDemo(SimplePanel):
    def __init__(self):
        SimplePanel.__init__(self)

        hPanel = HorizontalPanel()
        hPanel.setSpacing(10)

        self.list1 = ListBox()
        self.list1.setVisibleItemCount(10)
        self.list1.addItem("Item 1")
        self.list1.addItem("Item 2")
        self.list1.addItem("Item 3")
        self.list1.addChangeListener(getattr(self, "onList1ItemSelected"))

        self.list2 = ListBox()
        self.list2.setVisibleItemCount(1)
        self.list2.addItem("Item A")
        self.list2.addItem("Item B")
        self.list2.addItem("Item C")
        self.list2.addChangeListener(getattr(self, "onList2ItemSelected"))

        hPanel.add(self.list1)
        hPanel.add(self.list2)
        self.add(hPanel)


    def onList1ItemSelected(self, event):
        item = self.list1.getItemText(self.list1.getSelectedIndex())
        Window.alert("You selected " + item + " from list 1")


    def onList2ItemSelected(self, event):
        item = self.list2.getItemText(self.list2.getSelectedIndex())
        Window.alert("You selected " + item + " from list 2")
def makeFileChooser():
    l = ListBox()
    for i, tup in enumerate(files):
        name, content = tup
        l.addItem(name, i)
    l.addChangeListener(loadFile)
    return l
Пример #3
0
def makeFileChooser():
    l = ListBox()
    for i, tup in enumerate(files):
        name, content = tup
        l.addItem(name, i)
    l.addChangeListener(loadFile)
    return l
Пример #4
0
class TheoremPanel(ScrollPanel):
    def __init__(self, after):
        ScrollPanel.__init__(self, Size=("630px", "500px"))
        self.after = after
        self.pok = VerticalPanel()
        self.add(self.pok)
        self.images = list()

        def onItemSelected():
            item = self.list2.getItemText(self.list2.getSelectedIndex())
            self.refresh_theorems(item)

        self.list2 = ListBox()
        self.list2.setVisibleItemCount(1)
        for f in Theorem.get_all_folders():
            self.list2.addItem(f)
        self.pok.add(self.list2)
        self.list2.addChangeListener(onItemSelected)

        self.refresh_theorems(self.list2.getItemText(self.list2.getSelectedIndex()))

    def remove_images(self):
        for im in self.images:
            self.pok.remove(im)
        self.images = list()

    def refresh_theorems(self, folder):
        self.remove_images()

        def onClick(theorem):
            def name(n):
                return "var" + str(n + 1)

            def print_scheme(n):
                return ["\\alpha", "\\beta", "\\gamma", "\\delta", "\\epsilon"][n]

            def poas(sender):
                if len(theorem.operations) == 1:
                    constants = [Operation("const" + str(i + 1), 0, print_scheme(i), name(i), Operation.EXPRESSION)
                                 for i in range(theorem.operations[0].no_of_args)]

                    def after1(f):
                        self.after(
                            theorem.formula.substitute_definition(Formula([theorem.operations[0]] + constants), f),
                            predecessors=[], rule_name="insert")

                    request_formula([op for op in proof.get_operations()] + constants,
                                    after1, type=('rel' if theorem.operations[0].type == Operation.RELATION else 'exp'))
                else:
                    self.after(theorem.formula, predecessors=[], rule_name="insert")

            return poas

        for ax in [x for x in Theorem.theorems if x.folder == folder]:
            im = Image()
            im.addClickListener(onClick(ax))
            im.setUrl(latex_to_url(ax.formula.to_latex()))
            self.pok.add(im)
            self.images.append(im)
Пример #5
0
    def createColorList(self, caption):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem(caption)
        lb.addItem("White", "white")
        lb.addItem("Black", "black")
        lb.addItem("Red", "red")
        lb.addItem("Green", "green")
        lb.addItem("Yellow", "yellow")
        lb.addItem("Blue", "blue")
        return lb
Пример #6
0
    def createColorList(self, caption):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem(caption)
        lb.addItem("White", "white")
        lb.addItem("Black", "black")
        lb.addItem("Red", "red")
        lb.addItem("Green", "green")
        lb.addItem("Yellow", "yellow")
        lb.addItem("Blue", "blue")
        return lb
Пример #7
0
    def createHeadingStyleList(self, caption):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem(caption)
        lb.addItem("Heading1", "h1")
        lb.addItem("Heading2", "h2")
        lb.addItem("Heading3", "h3")
        lb.addItem("Heading4", "h4")
        lb.addItem("Heading5", "h5")

        return lb
Пример #8
0
    def createHeadingStyleList(self, caption):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem(caption)
        lb.addItem("Heading1", "h1")
        lb.addItem("Heading2", "h2")
        lb.addItem("Heading3", "h3")
        lb.addItem("Heading4", "h4")
        lb.addItem("Heading5", "h5")

        return lb
Пример #9
0
    def createFontSizes(self):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem("Size")
        lb.addItem("XXsmall")
        lb.addItem("Xsmall")
        lb.addItem("small")
        lb.addItem("medium")
        lb.addItem("large")
        lb.addItem("Xlarge")
        lb.addItem("XXlarge")
        return lb
Пример #10
0
    def createFontSizes(self):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem("Size")
        lb.addItem("XXsmall")
        lb.addItem("Xsmall")
        lb.addItem("small")
        lb.addItem("medium")
        lb.addItem("large")
        lb.addItem("Xlarge")
        lb.addItem("XXlarge")
        return lb
Пример #11
0
 def _create_add_dialog(self):
     contents = VerticalPanel(StyleName="Contents", Spacing=4)
     wtype = ListBox(Width="14em")
     wtype.addChangeListener(self)
     for wclass in self.WEIGHT_TYPES:
         wtype.addItem(wclass.NAME, value=wclass)
     panel = HorizontalPanel(Spacing=8)
     panel.add(HTML("Weight type: ", **captionstyle))
     panel.add(wtype)
     contents.add(panel)
     contents.add(Button("OK", getattr(self, '_close_add_dialog')))
     dialog = DialogBox(glass=True)
     dialog.setHTML('<b>Add a new type of weights</b>')
     dialog.setWidget(contents)
     return dialog, wtype
Пример #12
0
    def onModuleLoad(self):
        '''Create initial view of the panel.
        '''
        # Container that keeps everything
        self.panel = VerticalPanel()
        self.panel.setSpacing(10)

        # Create list of projects 
        proj_list = ListBox(Height='34px')
       
        proj_list.addItem('')
       
        proj_list.setVisibleItemCount(0)
        proj_list.addChangeListener(getattr(self, 'on_project_changed'))
        proj_list.setStyleName('form-control input-lg')
        
        self.proj_row = Form_Row('Select project',
                            proj_list,
                            help='project, status of which you want to report')
        
        # Project-specific container
        self.project_panel = VerticalPanel()

        # Submit report button
        self.submit_btn = Button('Submit report', getattr(self, 'send_data'))
        self.submit_btn.setStyleName('btn btn-primary btn-lg')
        self.submit_btn.setEnabled(False)

        self.msg_lbl = HTMLPanel('', Width='475px')

        # Add controls here
        self.panel.add(self.proj_row.panel())
        self.panel.add(self.project_panel)
        self.panel.add(Label(Height='20px'))
        self.panel.add(self.msg_lbl)
        btn_holder = HorizontalPanel()
        btn_holder.add(self.submit_btn)
        help_btn = HTMLPanel('')

        help_btn.setHTML(MODAL_PNL)
        btn_holder.add(Label(Width='10px'))
        btn_holder.add(help_btn)
        self.panel.add(btn_holder)
        
        self.root = RootPanel('report')
        self.root.add(self.panel)
Пример #13
0
    def createFontList(self):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem("Font", "")
        lb.addItem("Normal", "")
        lb.addItem("Times New Roman", "Times New Roman")
        lb.addItem("Arial", "Arial")
        lb.addItem("Aramanth", "Aramanth")
        lb.addItem("Calibri", "Calibri")
        lb.addItem("Courier New", "Courier New")
        lb.addItem("Georgia", "Georgia")
        lb.addItem("Helvetica", "Helvetica")
        lb.addItem("Symbol", "Symbol")
        lb.addItem("Trebuchet", "Trebuchet")
        lb.addItem("Verdana", "Verdana")
        return lb
Пример #14
0
    def createFontList(self):
        lb = ListBox()
        lb.addChangeListener(self)
        lb.setVisibleItemCount(1)

        lb.addItem("Font", "")
        lb.addItem("Normal", "")
        lb.addItem("Times New Roman", "Times New Roman")
        lb.addItem("Arial", "Arial")
        lb.addItem("Aramanth", "Aramanth")
        lb.addItem("Calibri", "Calibri")
        lb.addItem("Courier New", "Courier New")
        lb.addItem("Georgia", "Georgia")
        lb.addItem("Helvetica", "Helvetica")
        lb.addItem("Symbol", "Symbol")
        lb.addItem("Trebuchet", "Trebuchet")
        lb.addItem("Verdana", "Verdana")
        return lb
Пример #15
0
    def onModuleLoad(self):

        self.layout = HorizontalPanel()

        # Each demo will set their own dimensions, so it doesn't matter
        # what we initialize the canvas to.
        canvas = GWTCanvas(400,400)

        canvas.addStyleName("gwt-canvas")

        self.demos = []
        # Create demos
        self.demos.append(StaticDemo(canvas))
        self.demos.append(LogoDemo(canvas))
        self.demos.append(ParticleDemo(canvas))
        self.demos.append(GradientDemo(canvas))
        self.demos.append(SuiteDemo(canvas))

        # Add them to the selection list box
        lb = ListBox()
        lb.setStyleName("listBox")

        for i in range(len(self.demos)):
            lb.addItem(self.demos[i].getName())

        lb.addChangeListener(self)

        # start off with the first demo
        self.currentDemo = self.demos[0]

        # Add widgets to self.layout and RootPanel
        vp = VerticalPanel()
        vp.add(lb)
        vp.add(canvas)
        self.layout.add(vp)
        if self.currentDemo.getControls() is not None:
            self.layout.add(self.currentDemo.getControls())

        RootPanel().add(self.layout)
        self.currentDemo.drawDemo()
Пример #16
0
class TheoremPanel(ScrollPanel):
    def __init__(self, after):
        ScrollPanel.__init__(self, Size=("630px", "500px"))
        self.after = after
        self.pok = VerticalPanel()
        self.add(self.pok)
        self.images = list()

        def onItemSelected():
            item = self.list2.getItemText(self.list2.getSelectedIndex())
            self.refresh_theorems(item)

        self.list2 = ListBox()
        self.list2.setVisibleItemCount(1)
        for f in Theorem.get_all_folders():
            self.list2.addItem(f)
        self.pok.add(self.list2)
        self.list2.addChangeListener(onItemSelected)

        self.refresh_theorems(
            self.list2.getItemText(self.list2.getSelectedIndex()))

    def remove_images(self):
        for im in self.images:
            self.pok.remove(im)
        self.images = list()

    def refresh_theorems(self, folder):
        self.remove_images()

        def onClick(theorem):
            def name(n):
                return "var" + str(n + 1)

            def print_scheme(n):
                return [
                    "\\alpha", "\\beta", "\\gamma", "\\delta", "\\epsilon"
                ][n]

            def poas(sender):
                if len(theorem.operations) == 1:
                    constants = [
                        Operation("const" + str(i + 1), 0, print_scheme(i),
                                  name(i), Operation.EXPRESSION)
                        for i in range(theorem.operations[0].no_of_args)
                    ]

                    def after1(f):
                        self.after(theorem.formula.substitute_definition(
                            Formula([theorem.operations[0]] + constants), f),
                                   predecessors=[],
                                   rule_name="insert")

                    request_formula([op for op in proof.get_operations()] +
                                    constants,
                                    after1,
                                    type=('rel' if theorem.operations[0].type
                                          == Operation.RELATION else 'exp'))
                else:
                    self.after(theorem.formula,
                               predecessors=[],
                               rule_name="insert")

            return poas

        for ax in [x for x in Theorem.theorems if x.folder == folder]:
            im = Image()
            im.addClickListener(onClick(ax))
            im.setUrl(latex_to_url(ax.formula.to_latex()))
            self.pok.add(im)
            self.images.append(im)
Пример #17
0
class LatBuilderWeb:
    def setStyleSheet(self, sheet):
        e = DOM.createElement('link')
        e.setAttribute('rel', 'stylesheet')
        e.setAttribute('type', 'text/css')
        e.setAttribute('href', sheet)
        html = Window.getDocumentRoot().parentElement
        head = html.getElementsByTagName('head').item(0)
        head.appendChild(e)

    def includeMathJax(self, config):
        html = Window.getDocumentRoot().parentElement
        head = html.getElementsByTagName('head').item(0)

        e = DOM.createElement('script')
        e.setAttribute('type', 'text/javascript')
        e.setAttribute(
            'src', 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=' +
            config)
        head.appendChild(e)

        e = DOM.createElement('script')
        e.setAttribute('type', 'text/javascript')
        e.textContent = 'function Typeset() { MathJax.Hub.Queue(["Typeset",MathJax.Hub]); }'
        head.appendChild(e)

    def onModuleLoad(self):

        self.current_request = None

        Window.setTitle("Lattice Builder Web Interface")
        self.setStyleSheet("./LatBuilderWeb.css")
        self.includeMathJax('TeX-AMS-MML_HTMLorMML')

        self.TEXT_WAITING = "Lattice Builder is working..."
        self.TEXT_ERROR = "Server Error"
        self.FIGURES_OF_MERIT = [
            # (key, name)
            ('{cs}P2', 'P2'),
            ('{cs}P4', 'P4'),
            ('{cs}P6', 'P6'),
            ('{cs}R{alpha}', 'R_alpha'),
            ('spectral', 'spectral'),
        ]
        self.CONSTRUCTION_METHODS = [
            ('explicit:{genvec}', "Explicit (Evaluation)",
             "Evaluates the figure of merit for a given generating vector.<br/>"
             "<strong>Please specify the generating vector in the Lattice "
             "Properties panel above.</strong>"),
            ('exhaustive', "Exhaustive",
             "Examines all generating vectors and retains the best one."),
            ('random:{samples}', "Random",
             "Examines a number of randomly selected generating vectors and "
             "retains the best one."),
            ('Korobov', "Korobov",
             "Examines all generating vectors of the form (1, a, a^2 mod n, "
             "..., a^s mod n) and retains the best one."),
            ('random-Korobov:{samples}', "Random Korobov",
             "Examines a number of randomly selected generating vectors of "
             "the form (1, a, a^2 mod n, ..., a^s mod n) and retains the "
             "best one."),
            ('CBC', "Component-by-Component",
             "Examines all possible values of the components of the "
             "generating vector and selects the best ones, one coordinate "
             "at a time."),
            ('random-CBC:{samples}', "Random Component-by-Component",
             "Examines a number of randomly selected values of the "
             "components of the generating vector and selects the best "
             "ones, one coordinate at a time."),
            ('fast-CBC', "Fast Component-by-Component",
             "Examines all possible values of the components of the "
             "generating vector and selects the best ones, one coordinate "
             "at a time.  Computation is accelerated by using fast "
             "Fourier transforms."),
        ]
        self.COMBINER_TYPES = [
            ('level:max', 'highest level'),
            ('sum', 'weighted sum'),
            ('max', 'maximum weighted value'),
        ]
        self.NORMALIZATION_TYPES = [
            ('norm:P{alpha}-SL10', 'SL10 P-alpha'),
            ('norm:P{alpha}-DPW08', 'DPW08 P-alpha'),
        ]

        captionstyle = {
            'Width': '10em',
            'HorizontalAlignment': 'right',
        }

        self.remote = LatBuilderService()
        WeightValuesArray.REMOTE = self.remote

        main_panel = VerticalPanel(Spacing=30)

        # information

        info = """<h2>Lattice Builder Web Interface</h2>
        <p>This Web interface allows
        <a href="https://github.com/mungerd/latbuilder#readme">Lattice Builder</a>
        users to call the executable program without having to construct the
        command line explicitly.
        </p>
        <p>Enter the construction parameters below, and press the <em>Search for
        Good Lattices</em> button.  The results will show at the bottom.
        </p>"""

        main_panel.add(HTML(info))

        self.version_label = HTML()
        main_panel.add(self.version_label)
        self.remote.backend_version(self)

        params_panel = VerticalPanel(Spacing=15)
        main_panel.add(params_panel)

        # lattice type and size and dimension

        lat_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Lattice Properties", lat_panel))
        lat_panel.add(
            HTML(
                r'\[ P_n = \left\{ (i \boldsymbol a \bmod n) / n \::\: i = 0, \dots, n \right\} \qquad (\boldsymbol a \in \mathbb Z^s) \]',
                StyleName='DisplayMath'))

        self.size = TextBox(Text="2^10")
        self.size.addChangeListener(self)

        self.embedded = CheckBox("embedded")
        self.embedded.addClickListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Size (\(n\)): ", StyleName="CaptionLabel"))
        panel.add(self.size)
        panel.add(self.embedded)
        lat_panel.add(panel)

        self.dimension = TextBox(Text="3")
        self.dimension.addChangeListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Dimension (\(s\)): ", StyleName="CaptionLabel"))
        panel.add(self.dimension)
        lat_panel.add(panel)

        self.generating_vector = GeneratingVector(self.size)
        self.generating_vector.panel.setVisible(False)
        lat_panel.add(self.generating_vector.panel)

        # figure of merit

        merit_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Figure of Merit", merit_panel))
        merit_panel.add(
            HTML(
                r"\[ \left[ \mathcal D_q(P_n) \right]^q = "
                r"\sum_{\emptyset \neq u \subseteq \{1,\dots,s\}}"
                r"\gamma_u^q \, \left[\mathcal D_u(P_n)\right]^q"
                r"\qquad (q > 0) \]",
                StyleName='DisplayMath'))

        self.norm_type = TextBox(Text="2")
        self.norm_type.addChangeListener(self)

        panel = HorizontalPanel(Spacing=8)
        panel.add(
            HTML(r"Norm type (\(q\) or <b>inf</b>): ",
                 StyleName="CaptionLabel"))
        panel.add(self.norm_type)
        merit_panel.add(panel)

        self.merit = ListBox()
        self.merit.addChangeListener(self)
        for key, name in self.FIGURES_OF_MERIT:
            self.merit.addItem(name)

        self.merit_cs = CheckBox("Use coordinate-symmetric implementation",
                                 Checked=True)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Figure of merit: ", StyleName="CaptionLabel"))
        panel.add(self.merit)
        panel.add(self.merit_cs)
        merit_panel.add(panel)

        self.merit_alpha_panel = HorizontalPanel(Spacing=8)
        self.merit_alpha = TextBox(Text="2")
        self.merit_alpha_panel.add(
            HTML("Value of alpha: ", StyleName="CaptionLabel"))
        self.merit_alpha_panel.add(self.merit_alpha)
        merit_panel.add(self.merit_alpha_panel)

        # filters and combiner

        multilevel_panel = VerticalPanel(Spacing=8)
        self.multilevel_panel = CaptionPanel("Multilevel Filters and Combiner",
                                             multilevel_panel,
                                             Visible=False)
        params_panel.add(self.multilevel_panel)

        self.ml_normalization_enable = CheckBox("Normalization")
        self.ml_normalization_enable.addClickListener(self)
        multilevel_panel.add(self.ml_normalization_enable)

        self.ml_normalization_panel = VerticalPanel(Spacing=4,
                                                    Visible=False,
                                                    StyleName='SubPanel')
        multilevel_panel.add(self.ml_normalization_panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Normalization type: ", StyleName="CaptionLabel"))
        self.ml_normalization_type = ListBox()
        for key, name in self.NORMALIZATION_TYPES:
            self.ml_normalization_type.addItem(name, value=key)
        panel.add(self.ml_normalization_type)
        self.ml_normalization_panel.add(panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Minimum level: ", StyleName="CaptionLabel"))
        self.ml_min_level = TextBox(Text="1")
        panel.add(self.ml_min_level)
        self.ml_normalization_panel.add(panel)

        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Maximum level: ", StyleName="CaptionLabel"))
        self.ml_max_level = TextBox(Text="1")
        panel.add(self.ml_max_level)
        self.ml_normalization_panel.add(panel)

        self.ml_lowpass_enable = CheckBox("Low-pass filter")
        self.ml_lowpass_enable.addClickListener(self)
        multilevel_panel.add(self.ml_lowpass_enable)

        self.ml_lowpass_panel = VerticalPanel(Spacing=4,
                                              Visible=False,
                                              StyleName='SubPanel')
        multilevel_panel.add(self.ml_lowpass_panel)

        self.ml_lowpass = TextBox(Text="1.0")
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Low-pass threshold: ", StyleName="CaptionLabel"))
        panel.add(self.ml_lowpass)
        self.ml_lowpass_panel.add(panel)

        self.combiner_type = ListBox()
        for key, name in self.COMBINER_TYPES:
            self.combiner_type.addItem(name, value=key)
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Combiner: ", StyleName="CaptionLabel"))
        panel.add(self.combiner_type)
        multilevel_panel.add(panel)

        # weights

        self.weights = CompoundWeights()
        weights_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Weights", weights_panel))
        weights_panel.add(
            HTML(r"\[ \gamma_u^p \qquad (u \subseteq \{1, \dots, s\}) \]",
                 StyleName='DisplayMath'))

        self.weights_power = TextBox(Text="2")
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML(r"Weights power (\(p\)): ", StyleName="CaptionLabel"))
        panel.add(self.weights_power)

        weights_panel.add(panel)
        weights_panel.add(self.weights.panel)
        self.weights.add_weights(ProductWeights)

        # construction method

        cons_panel = VerticalPanel()
        params_panel.add(CaptionPanel("Construction Method", cons_panel))

        self.construction = ListBox()
        self.construction.addChangeListener(self)
        for key, name, desc in self.CONSTRUCTION_METHODS:
            self.construction.addItem(name, value=key)
        self.construction_desc = HTML()

        panel = HorizontalPanel(Spacing=8)
        panel.add(self.construction)
        panel.add(self.construction_desc)
        cons_panel.add(panel)

        self.construction_samples_panel = HorizontalPanel(Spacing=8)
        self.construction_samples = TextBox(Text="30")
        self.construction_samples_panel.add(
            HTML("Random samples: ", StyleName="CaptionLabel"))
        self.construction_samples_panel.add(self.construction_samples)
        cons_panel.add(self.construction_samples_panel)

        # execute button

        panel = VerticalPanel(Spacing=8,
                              Width="100%",
                              HorizontalAlignment='center')
        main_panel.add(panel)

        button_panel = HorizontalPanel()
        panel.add(button_panel)
        self.button_search = Button("Search", self)
        button_panel.add(self.button_search)
        self.button_abort = Button("Abort", self, Visible=False)
        button_panel.add(self.button_abort)

        self.status = Label()
        panel.add(self.status)

        # results

        results_panel = VerticalPanel()
        self.results_panel = CaptionPanel("Results",
                                          results_panel,
                                          Visible=False)
        main_panel.add(self.results_panel)

        self.results_size = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Lattice size: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_size)
        results_panel.add(panel)

        self.results_gen = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Generating vector: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_gen)
        results_panel.add(panel)

        self.results_merit = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("Merit value: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_merit)
        results_panel.add(panel)

        self.results_cpu_time = Label()
        panel = HorizontalPanel(Spacing=8)
        panel.add(HTML("CPU time: ", StyleName="ResultsCaptionLabel"))
        panel.add(self.results_cpu_time)
        results_panel.add(panel)

        self.results_cmd = Label(StyleName='Command', Visible=False)
        panel = HorizontalPanel(Spacing=8)

        self.results_cmd_link = Hyperlink("Command line: ",
                                          StyleName="ResultsCaptionLabel")
        self.results_cmd_link.addClickListener(self)
        panel.add(self.results_cmd_link)
        panel.add(self.results_cmd)
        results_panel.add(panel)

        # update selections

        self.construction.selectValue('CBC')

        self.onChange(self.size)
        self.onChange(self.construction)
        self.onChange(self.merit)
        self.onChange(self.dimension)
        self.onClick(self.embedded)
        self.onChange(self.ml_normalization_enable)
        self.onChange(self.ml_lowpass_enable)

        RootPanel().add(main_panel)

    def onChange(self, sender):

        if sender == self.construction:
            key, name, desc = \
                    self.CONSTRUCTION_METHODS[self.construction.getSelectedIndex()]
            self.construction_desc.setHTML(desc)
            self.construction_samples_panel.setVisible('{samples}' in key)
            if key.startswith('explicit'):
                self.generating_vector.panel.setVisible(True)
                self.button_search.setText("Evaluate Figure of Merit")
            else:
                self.generating_vector.panel.setVisible(False)
                self.button_search.setText("Search for Good Lattices")

        elif sender == self.merit:
            key, name = \
                    self.FIGURES_OF_MERIT[self.merit.getSelectedIndex()]
            self.merit_alpha_panel.setVisible('{alpha}' in key)
            self.merit_cs.setVisible('{cs}' in key)

        elif sender == self.size:
            max_level = LatSize(self.size.getText()).max_level
            if int(self.ml_min_level.getText()) > max_level:
                self.ml_min_level.setText(max_level)
            self.ml_max_level.setText(max_level)

        elif sender == self.dimension:
            # resize weights
            dimension = int(self.dimension.getText())
            self.generating_vector.dimension = dimension
            self.weights.dimension = dimension

        elif sender == self.norm_type:
            q = self.norm_type.getText().strip()
            self.merit_cs.setVisible(q == '2')
            if q == 'inf':
                self.weights_power.setText('1')
            else:
                self.weights_power.setText(q)

    def onClick(self, sender):
        if sender == self.embedded:
            self.multilevel_panel.setVisible(self.embedded.getChecked())

        elif sender == self.ml_normalization_enable:
            self.ml_normalization_panel.setVisible(
                self.ml_normalization_enable.getChecked())

        elif sender == self.ml_lowpass_enable:
            self.ml_lowpass_panel.setVisible(
                self.ml_lowpass_enable.getChecked())

        elif sender == self.results_cmd_link:
            self.results_cmd.setVisible(not self.results_cmd.getVisible())

        elif sender == self.button_search:

            self.results_panel.setVisible(False)
            self.button_search.setVisible(False)
            self.button_abort.setVisible(True)

            lattype = self.embedded.getChecked() and 'embedded' or 'ordinary'
            size = self.size.getText()
            dimension = self.dimension.getText()

            norm_type = self.norm_type.getText()
            merit, merit_name = \
                    self.FIGURES_OF_MERIT[self.merit.getSelectedIndex()]
            alpha = self.merit_alpha.getText()
            cs = norm_type == 2 and self.merit_cs.getChecked() and 'CS:' or ''

            weights_power = self.weights_power.getText()
            weights = [w.as_arg() for w in self.weights.weights]

            construction, construction_name, desc = \
                    self.CONSTRUCTION_METHODS[self.construction.getSelectedIndex()]
            samples = self.construction_samples.getText()
            genvec = ','.join(self.generating_vector.values)

            mlfilters = []
            combiner_type = None

            if self.embedded.getChecked():
                if self.ml_normalization_enable.getChecked():
                    ml_normalization_type, ml_normalization_name = \
                            self.NORMALIZATION_TYPES[self.ml_normalization_type.getSelectedIndex()]
                    ml_normalization_type += ':even:{},{}'.format(
                        self.ml_min_level.getText(),
                        self.ml_max_level.getText())
                    mlfilters.append(ml_normalization_type.format(alpha=alpha))
                if self.ml_lowpass_enable.getChecked():
                    mlfilters.append('low-pass:{}'.format(
                        self.ml_lowpass.getText()))

                combiner_type, combiner_name = \
                        self.COMBINER_TYPES[self.combiner_type.getSelectedIndex()]

            self.status.setText(self.TEXT_WAITING)

            self.current_request = self.remote.latbuilder_exec(
                lattype, size, dimension, norm_type,
                merit.format(alpha=alpha, cs=cs),
                construction.format(samples=samples, genvec=genvec), weights,
                weights_power, None, mlfilters, combiner_type, self)

        elif sender == self.button_abort:
            # Need to patch JSONService.sendRequest():
            #
            # return HTTPRequest().asyncPost(self.url, msg_data,
            #                                JSONResponseTextHandler(request_info)
            #                                False, self.content_type,
            #                                self.headers)
            if self.current_request:
                self.current_request.abort()
                self.current_request = None
            self.button_abort.setVisible(False)
            self.button_search.setVisible(True)

        elif sender == self.product_weights_expr_link:
            self.showDialog(self._product_weights_expr_dialog)

        elif sender == self.order_weights_expr_link:
            self.showDialog(self._order_weights_expr_dialog)

    def onRemoteResponse(self, response, request_info):
        try:
            if request_info.method == 'latbuilder_exec':
                self.button_search.setVisible(True)
                self.button_abort.setVisible(False)
                cmd, points, gen, merit, seconds = eval(response)
                self.results_size.setText(points)
                self.results_gen.setText(', '.join(gen))
                self.results_merit.setText(merit)
                self.results_cpu_time.setText(format_time(seconds=seconds))
                self.results_cmd.setText(cmd)
                self.results_panel.setVisible(True)
                self.status.setText("")
            elif request_info.method == 'backend_version':
                version = response
                self.version_label.setHTML(
                    "<b>Backend:</b> {}".format(version))
        except:
            self.status.setText(response.replace('\n', '  |  '))

    def onRemoteError(self, code, errobj, request_info):
        if request_info.method == 'latbuilder_exec':
            self.button_search.setVisible(True)
            self.button_abort.setVisible(False)
        message = errobj['message']
        if code != 0:
            self.status.setText("HTTP error %d: %s" % (code, message['name']))
        else:
            code = errobj['code']
            if code == -32603:
                self.status.setText("Aborted.")
            else:
                self.status.setText("JSONRPC Error %s: %s" % (code, message))
Пример #18
0
class SongFrequency:

    def __init__(self):
        self.artist =''
        self.start_date = ''
        self.end_date = ''
        self.period_search =''
        self.search_option = 1
        #declare the general interface widgets
        self.panel = DockPanel(StyleName = 'background')
        self.ret_area = TextArea()
        self.ret_area.setWidth("350px")
        self.ret_area.setHeight("90px")
        self.options = ListBox()

        self.search_button = Button("Search", getattr(self, "get_result"), StyleName = 'button')

        #set up the date search panel; it has different text boxes for
        #to and from search dates
        self.date_search_panel = VerticalPanel()
        self.date_search_start = TextBox()
        self.date_search_start.addInputListener(self)
        self.date_search_end = TextBox()
        self.date_search_end.addInputListener(self)
        
        self.date_search_panel.add(HTML("Enter as month/day/year", True, StyleName = 'text'))
        self.date_search_panel.add(HTML("From:", True, StyleName = 'text'))
        self.date_search_panel.add(self.date_search_start)
        self.date_search_panel.add(HTML("To:", True, StyleName = 'text'))
        self.date_search_panel.add(self.date_search_end)
        #set up the artist search panel
        self.artist_search = TextBox()
        self.artist_search.addInputListener(self)
        self.artist_search_panel = VerticalPanel()
        self.artist_search_panel.add(HTML("Enter artist's name:",True,
                                          StyleName = 'text'))
        self.artist_search_panel.add(self.artist_search)

        #Put together the list timespan search options
        self.period_search_panel = VerticalPanel()
        self.period_search_panel.add(HTML("Select a seach period:",True,
                                          StyleName = 'text'))
        self.period_search = ListBox()
        self.period_search.setVisibleItemCount(1)
        self.period_search.addItem("last week")
        self.period_search.addItem("last month")
        self.period_search.addItem("last year")
        self.period_search.addItem("all time")
        self.period_search_panel.add(self.period_search)
        #add the listeners to the appropriate widgets
        self.options.addChangeListener(self)
        self.period_search.addChangeListener(self)
        self.ret_area_scroll = ScrollPanel()
        self.search_panel = HorizontalPanel()
        self.options_panel = VerticalPanel()

    # A change listener for the boxes
    def onChange(self, sender):
        #switch the list box options
        if sender == self.options:
            self.search_panel.remove(self.period_search_panel)
            self.search_panel.remove(self.date_search_panel)
            self.search_panel.remove(self.artist_search_panel)

            index = self.options.getSelectedIndex()

            if index == 0:
                self.search_panel.add(self.artist_search_panel)
                self.search_option = 1
            elif index == 1:
                self.search_panel.add(self.date_search_panel)
                self.search_option = 2
            elif index == 2:
                self.search_panel.add(self.period_search_panel)
                self.search_option = 3

        elif sender == self.period_search:
            index = self.period_search.getSelectedIndex()
            if index == 0:
                self.period_search = "last week"
            elif index == 1:
                self.period_search = "last month"
            elif index == 2:
                self.period_search = "last year"
            elif index == 3:
                self.period_search = "all time"

    #A listener for the text boxes            
    def onInput(self, sender):
        if sender == self.artist_search:
            self.artist = sender.getText()
        elif sender == self.date_search_end:
            self.end_date = sender.getText()
        elif sender == self.date_search_start:
            self.start_date = sender.getText()

    #A listener for the buttons that, when the button is clicked, looks up the results and outputs them
    def get_result(self):
        return_str = " "
        if self.search_option == 1:
            return_str = self.artist
        elif self.search_option == 2:
            return_str = self.start_date
        elif self.search_option ==3:
            return_str = self.period_search
        else:
            return_str = "Find the most played artist, album, or song for a time period, or the number of songs played by a certain artist"
        self.ret_area.setText(return_str)

   
    def onModuleLoad(self):
        #Put together the list of options
        self.options.addItem("Artist")
        self.options.addItem("Date")
        self.options.addItem("Time Span")
        self.options.setVisibleItemCount(3)

        #put the text area together
        self.ret_area_scroll.add(self.ret_area)
        self.ret_area.setText("Find the most played artist, album, or song for a time period, or the number of songs played by a certain artist")
        #put the search items together
        self.search_panel.add(self.artist_search_panel)
        #Put together the options panel
        self.options_panel.add(HTML("Search By:", True, StyleName = 'text'))
        self.options_panel.add(self.options)
        #Add everything to the main panel
        self.panel.add(HTML("WQHS Song Search",True, StyleName = 'header'),
                       DockPanel.NORTH)

        self.panel.add(self.options_panel, DockPanel.WEST)
        
        self.panel.add(self.ret_area_scroll, DockPanel.SOUTH)
        self.panel.setCellHeight(self.ret_area_scroll, "100px")
        self.panel.setCellWidth(self.ret_area_scroll, "300px")

        self.panel.add(self.search_button, DockPanel.EAST)
        
        self.panel.add(self.search_panel, DockPanel.CENTER)
    
        #Associate panel with the HTML host page
        RootPanel().add(self.panel)
Пример #19
0
class RolePanel(AbsolutePanel):

    user = None
    selectedRole = None

    roleList = None
    roleCombo = None
    addBtn = None
    removeBtn = None

    def __init__(self,parent):
        AbsolutePanel.__init__(self)

        self.roleList = ListBox()
        self.roleList.setWidth('300px')
        self.roleList.setVisibleItemCount(6)
        self.roleList.addChangeListener(self.onListChange)
        #self.roleList.addKeyboardListener(self)
        self.roleCombo = ListBox()
        self.roleCombo.addKeyboardListener(self)
        self.roleCombo.addChangeListener(self.onComboChange)
        self.addBtn = Button("Add")
        self.addBtn.setEnabled(False)
        self.removeBtn = Button("Remove")
        self.removeBtn.setEnabled(False)

        vpanel = VerticalPanel()
        vpanel.add(self.roleList)
        hpanel = HorizontalPanel()
        hpanel.add(self.roleCombo)
        hpanel.add(self.addBtn)
        hpanel.add(self.removeBtn)
        vpanel.add(hpanel)

        self.add(vpanel)
        self.clearForm()
        return

    def clearForm(self):
        self.user = None
        self.updateRoleList([])
        self.roleCombo.setItemTextSelection(None)

    def updateRoleList(self,items):
        self.roleList.clear()
        for item in items:
            self.roleList.addItem(item)
        #self.roleList.addItem('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
        #self.roleList.addItem('- - - - - - - -')

    def updateRoleCombo(self,choices, default_):
        self.roleCombo.clear()
        for choice in choices:
            self.roleCombo.addItem(choice)
        self.roleCombo.selectValue(default_)

    def onComboChange(self, sender, keyCode=None, modifiers=None):
        selected = self.roleCombo.getSelectedItemText()
        if  not selected \
            or selected[0] == ApplicationConstants.ROLE_NONE_SELECTED \
            or not self.user:
            self.addBtn.setEnabled(False)
            self.selectedRole=None
        else:
            self.addBtn.setEnabled(True)
            self.selectedRole=selected[0]
        self.removeBtn.setEnabled(False)
        self.roleList.setItemTextSelection(None)

    def onListChange(self, sender):
        selected = self.roleList.getSelectedItemText()
        if selected:
            self.removeBtn.setEnabled(True)
            self.selectedRole=selected[0]
        else:
            self.removeBtn.setEnabled(False)
            self.selectedRole=None
        self.addBtn.setEnabled(False)
        self.roleCombo.setItemTextSelection(None)

    def onClick(self, sender):
        pass

    def onKeyUp(self, sender, keyCode, modifiers):
        if sender == self.roleCombo:
            self.onComboChange(sender)
        elif sender == self.roleList:
            self.onListChange(sender)

    def onKeyDown(self, sender, keyCode, modifiers):
        pass

    def onKeyPress(self, sender, keyCode, modifiers):
        pass
Пример #20
0
class RolePanel(AbsolutePanel):

    user = None
    selectedRole = None

    roleList = None
    roleCombo = None
    addBtn = None
    removeBtn = None

    def __init__(self, parent):
        AbsolutePanel.__init__(self)

        self.roleList = ListBox()
        self.roleList.setWidth('300px')
        self.roleList.setVisibleItemCount(6)
        self.roleList.addChangeListener(self.onListChange)
        #self.roleList.addKeyboardListener(self)
        self.roleCombo = ListBox()
        self.roleCombo.addKeyboardListener(self)
        self.roleCombo.addChangeListener(self.onComboChange)
        self.addBtn = Button("Add")
        self.addBtn.setEnabled(False)
        self.removeBtn = Button("Remove")
        self.removeBtn.setEnabled(False)

        vpanel = VerticalPanel()
        vpanel.add(self.roleList)
        hpanel = HorizontalPanel()
        hpanel.add(self.roleCombo)
        hpanel.add(self.addBtn)
        hpanel.add(self.removeBtn)
        vpanel.add(hpanel)

        self.add(vpanel)
        self.clearForm()
        return

    def clearForm(self):
        self.user = None
        self.updateRoleList([])
        self.roleCombo.setItemTextSelection(None)

    def updateRoleList(self, items):
        self.roleList.clear()
        for item in items:
            self.roleList.addItem(item)
        #self.roleList.addItem('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
        #self.roleList.addItem('- - - - - - - -')

    def updateRoleCombo(self, choices, default_):
        self.roleCombo.clear()
        for choice in choices:
            self.roleCombo.addItem(choice)
        self.roleCombo.selectValue(default_)

    def onComboChange(self, sender, keyCode=None, modifiers=None):
        selected = self.roleCombo.getSelectedItemText()
        if  not selected \
            or selected[0] == ApplicationConstants.ROLE_NONE_SELECTED \
            or not self.user:
            self.addBtn.setEnabled(False)
            self.selectedRole = None
        else:
            self.addBtn.setEnabled(True)
            self.selectedRole = selected[0]
        self.removeBtn.setEnabled(False)
        self.roleList.setItemTextSelection(None)

    def onListChange(self, sender):
        selected = self.roleList.getSelectedItemText()
        if selected:
            self.removeBtn.setEnabled(True)
            self.selectedRole = selected[0]
        else:
            self.removeBtn.setEnabled(False)
            self.selectedRole = None
        self.addBtn.setEnabled(False)
        self.roleCombo.setItemTextSelection(None)

    def onClick(self, sender):
        pass

    def onKeyUp(self, sender, keyCode, modifiers):
        if sender == self.roleCombo:
            self.onComboChange(sender)
        elif sender == self.roleList:
            self.onListChange(sender)

    def onKeyDown(self, sender, keyCode, modifiers):
        pass

    def onKeyPress(self, sender, keyCode, modifiers):
        pass
Пример #21
0
class AutoCompleteByURLTextBox(AutoCompleteTextBox):
	def __init__(self, url):
		self.choicesPopup = PopupPanel(True)
		self.choices = ListBox()
		self.items = AutoCompleteURL(url)
		self.popupAdded = False
		self.visible = False
		
		TextBox.__init__(self)
		self.addKeyboardListener(self)
		self.choices.addChangeListener(self)
		self.setStyleName("AutoCompleteTextBox")
		
		self.choicesPopup.add(self.choices)
		self.choicesPopup.addStyleName("AutoCompleteChoices")
		
		self.choices.setStyleName("list")
		self.url = url
	
	"""
	def setCompletionItems(self, items):
		if not items.getCompletionItems:
			items = AutoCompletionURL(self.url)
		
		self.items = items

	def getCompletionItems(self):
		return self.items
	"""
	
	def onKeyUp(self, arg0, arg1, arg2):
		if arg1 == KeyboardListener.KEY_DOWN:
			selectedIndex = self.choices.getSelectedIndex()
			selectedIndex += 1
			if selectedIndex > self.choices.getItemCount():
				selectedIndex = 0
		
			self.choices.setSelectedIndex(selectedIndex)		   
			return

		if arg1 == KeyboardListener.KEY_UP:
			selectedIndex = self.choices.getSelectedIndex()
			selectedIndex -= 1
			if selectedIndex < 0:
				selectedIndex = self.choices.getItemCount()
			self.choices.setSelectedIndex(selectedIndex)
			return

		if arg1 == KeyboardListener.KEY_ENTER:
			if self.visible:
				self.complete()	  
			return

		if arg1 == KeyboardListener.KEY_ESCAPE:
			self.choices.clear()
			self.choicesPopup.hide()
			self.visible = False
			return

		text = self.getText()
		matches = []
		if len(text) > 0:
			matches = self.items.getCompletionItems(text)

		if len(matches) > 0:
			self.choices.clear()

			for i in range(len(matches)):
				self.choices.addItem(matches[i])
				
			if len(matches) == 1 and matches[0] == text:
				self.choicesPopup.hide()
			else:
				self.choices.setSelectedIndex(0)
				self.choices.setVisibleItemCount(len(matches) + 1)
					
				if not self.popupAdded:
					RootPanel().add(self.choicesPopup)
					self.popupAdded = True

				self.choicesPopup.show()
				self.visible = True
				self.choicesPopup.setPopupPosition(self.getAbsoluteLeft(), self.getAbsoluteTop() + self.getOffsetHeight())
				self.choices.setWidth(self.getOffsetWidth() + "px")
		else:
			self.visible = False
			self.choicesPopup.hide()
Пример #22
0
class AutoCompleteTextBox(TextBox):
    def __init__(self, **kwargs):
        self.choicesPopup = PopupPanel(True, False)
        self.choices = ListBox()
        self.items = SimpleAutoCompletionItems()
        self.popupAdded = False
        self.visible = False

        self.choices.addClickListener(self)
        self.choices.addChangeListener(self)

        self.choicesPopup.add(self.choices)
        self.choicesPopup.addStyleName("AutoCompleteChoices")
            
        self.choices.setStyleName("list")

        if not kwargs.has_key('StyleName'): kwargs['StyleName']="gwt-AutoCompleteTextBox"

        TextBox.__init__(self, **kwargs)
        self.addKeyboardListener(self)

    def setCompletionItems(self, items):
        if not hasattr(items, 'getCompletionItems'):
            items = SimpleAutoCompletionItems(items)
        
        self.items = items

    def getCompletionItems(self):
        return self.items

    def onKeyDown(self, arg0, arg1, arg2):
        pass

    def onKeyPress(self, arg0, arg1, arg2):
        pass

    def onKeyUp(self, arg0, arg1, arg2):
        if arg1 == KeyboardListener.KEY_DOWN:
            selectedIndex = self.choices.getSelectedIndex()
            selectedIndex += 1
            if selectedIndex >= self.choices.getItemCount():
                selectedIndex = 0
            self.choices.setSelectedIndex(selectedIndex)           
            return

        if arg1 == KeyboardListener.KEY_UP:
            selectedIndex = self.choices.getSelectedIndex()
            selectedIndex -= 1
            if selectedIndex < 0:
                selectedIndex = self.choices.getItemCount() - 1
            self.choices.setSelectedIndex(selectedIndex)
            return

        if arg1 == KeyboardListener.KEY_ENTER:
            if self.visible:
                self.complete()      
            return

        if arg1 == KeyboardListener.KEY_ESCAPE:
            self.choices.clear()
            self.choicesPopup.hide()
            self.visible = False
            return

        text = self.getText()
        matches = []
        if len(text) > 0:
            matches = self.items.getCompletionItems(text)

        if len(matches) > 0:
            self.choices.clear()

            for i in range(len(matches)):
                self.choices.addItem(matches[i])
                
            if len(matches) == 1 and matches[0] == text:
                self.choicesPopup.hide()
            else:
                self.choices.setSelectedIndex(0)
                self.choices.setVisibleItemCount(len(matches) + 1)
                    
                if not self.popupAdded:
                    RootPanel().add(self.choicesPopup)
                    self.popupAdded = True

                self.choicesPopup.show()
                self.visible = True
                self.choicesPopup.setPopupPosition(self.getAbsoluteLeft(), self.getAbsoluteTop() + self.getOffsetHeight())
                self.choices.setWidth("%dpx" % self.getOffsetWidth())
        else:
            self.visible = False
            self.choicesPopup.hide()

    def onChange(self, arg0):
        self.complete()

    def onClick(self, arg0):
        self.complete()

    def complete(self):
        if self.choices.getItemCount() > 0:
            self.setText(self.choices.getItemText(self.choices.getSelectedIndex()))
            
        self.choices.clear()
        self.choicesPopup.hide()
        self.setFocus(True)
        self.visible = False
Пример #23
0
    def onRemoteResponse(self, response, request_info):
        mname = request_info.method
        if mname == "customize_message":
            showCustomizationResult(self, response, request_info)
            return

        if mname == "get_messagesdata_for_cust":
            locations_data = response["locations"]
            selectionbox = VerticalPanel(Padding=3)
            locations = ListBox()
            for (loc_name, loc_id) in locations_data:
                locations.addItem(loc_id, loc_name)
            messages = ListBox()
            messages.setName("locations")
            messages.addItem(location_select_label)
            for (name, d) in response["messages"].items():
                messages.addItem(d['label'], name)

            locations.addChangeListener(self)
            messages.addChangeListener(self)
            self.locations = locations
            self.messages = messages

            locationbox = HorizontalPanel()
            locationbox.add(Label("Location: ", StyleName="text", Width=80))
            locationbox.add(locations)

            msgnamebox = HorizontalPanel()
            msgnamebox.add(Label("Message: ", StyleName="text", Width=80))
            msgnamebox.add(messages)

            selectionbox.add(locationbox)
            selectionbox.add(msgnamebox)

            mainpanel = VerticalPanel(StyleName="dataBoxContent")
            mainpanel.add(selectionbox)
            self.mainpanel = mainpanel
            root = RootPanel()
            root.add(mainpanel)

        if mname == "get_messagecustdata":
            self.messages_data = response
            buttonspanel = FlowPanel(Spacing=1, Padding=1, Width=600)
            #buttonspanel.add(Label("Macros:", StyleName="text"))
            for macro_d in self.messages_data['macros']:
                macrobutton = Button(macro_d['label'], self, StyleName="buttonlikelink")#"nicebutton small")
                macrobutton.name = macro_d['name']
                buttonspanel.add(macrobutton)

            msgpanel = VerticalPanel(Padding=1, Spacing=1)
            messagebox = TextArea()
            messagebox.setCharacterWidth(70)
            height = len(self.messages_data["text"].split('\n')) + 1
            messagebox.setVisibleLines(height)
            messagebox.setText(self.messages_data["text"])
            messagebox.setName("textBoxFormElement")
            self.messagebox = messagebox
            msgpanel.add(messagebox)
            self.statusbar = Label(StyleName="errorMessage")
            msgpanel.add(self.statusbar)
            actionbuttons = HorizontalPanel(Spacing=2)
            updatebutton = Button("Update", self, StyleName="nicebutton small yellow")
            updatebutton.name = "update"
            actionbuttons.add(updatebutton)
            #actionbuttons.add(Button("Send me a preview mail"))
            msgpanel.add(actionbuttons)

            editorbox = VerticalPanel(Padding=1)
            editorbox.add(buttonspanel)
            editorbox.add(msgpanel)
            editorpanel = CaptionPanel("Message editor", editorbox, Padding=1, StyleName="text")
            editorpanel.name = "editorpanel"
            self.editorpanel = editorpanel

            self.mainpanel.add(editorpanel)
Пример #24
0
class ReducePanelIFACE(PanelIFACE):
    def __init__(self, parent = None):
        
        PanelIFACE.__init__(self, parent)
        self.panel = VerticalPanel()
        self.panel.setBorderWidth(1)
        self.panel.setWidth("100%")
        # prepare panel
        self.prepareReduce = HTML("<tt> .. none yet .. </tt>", True, )

        self.recipeList = ListBox()
        self.recipeList.addChangeListener(getattr(self, "onRecipeSelected"))
        self.recipeList.addItem("None")
        HTTPRequest().asyncGet("recipes.xml",
                                RecipeListLoader(self))

        #EO prepare panel
        self.reduceCLPanel = DockPanel(Spacing = 5)
        self.reduceCLPanel.add(HTML("<i>Reduce Command Line</i>:"), DockPanel.NORTH)                        
        self.reduceCLPanel.add(self.prepareReduce, DockPanel.NORTH)

        self.reduceFilesPanel = DockPanel(Spacing = 5)
        self.reduceFilesPanel.add(HTML("<b>Datasets</b>:"), DockPanel.WEST)

        self.reduceFiles = ListBox()
        self.reduceFiles.setVisibleItemCount(5)
        self.reduceFilesPanel.add(self.reduceFiles, DockPanel.WEST)
        self.clearReduceFilesButton = Button("<b>Clear List</b>", listener = getattr(self, "onClearReduceFiles"))
        self.reduceFilesPanel.add(self.clearReduceFilesButton, DockPanel.SOUTH)

        self.recipeListPanel = DockPanel(Spacing = 5)
        self.recipeListPanel.add(HTML("<b>Recipes List</b>:"),DockPanel.WEST)
        self.recipeListPanel.add(self.recipeList, DockPanel.WEST)

        self.runReduceButton = Button("<b>RUN REDUCE</b>", listener = getattr(self, "onRunReduce"))

        self.adInfo = HTML("file info...")
        # major sub panels
        self.panel.add(self.reduceCLPanel)
        self.panel.add(self.reduceFilesPanel)
        self.panel.add(self.recipeListPanel)
        self.panel.add(self.runReduceButton)
        self.panel.add(self.adInfo)
    def onRecipeSelected(self, event):
        self.updateReduceCL()
    
    def onClearReduceFiles(self, event):
        self.reduceFiles.clear() 
        self.adInfo.setHTML("file info...") 
        self.updateReduceCL()
        
    def updateReduceCL(self):
        recipe = self.recipeList.getItemText(self.recipeList.getSelectedIndex())
        
        if recipe=="None":
            rstr = ""
        else:
            rstr = "-r "+recipe

        rfiles = []            
        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            rfiles.append(fname)
        filesstr = " ".join(rfiles)
        
                
        self.prepareReduce.setHTML('<b>reduce</b> %(recipe)s %(files)s' % 
                                        { "recipe":rstr, 
                                          "files":filesstr})
    def onRunReduce(self):
        recipe = self.recipeList.getItemText(self.recipeList.getSelectedIndex())
        
        if recipe=="None":
            rstr = ""
        else:
            rstr = "p=-r"+recipe

        rfiles = []            
        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            rfiles.append(quote(self.pathdict[fname]["path"]))
        filesstr = "&p=".join(rfiles)
                
        cl = "/runreduce?%s&p=%s" % (rstr, filesstr)
        # @@TEST
        # cl = "/recipes.xml"
        if False:
            msg = repr(self.parent)+repr(dir(self.parent))
            JS("alert(msg)")
        if hasattr(self.parent, "roFrame"):
            self.parent.roFrame.setUrl(cl)
            self.parent.tabPanel.selectTab(self.parent.tabIFACEdict["rogui"])
        else:
            JS("window.open(cl)")

    def onTreeItemSelected(self, item):
        pathdict = self.pathdict
        
        tfile = item.getText()
        #check if already in

        self.reduceFiles.addItem(tfile)
        self.updateReduceCL()
        
        filename = tfile
        if filename in pathdict:
            if pathdict[filename]["filetype"] == "fileEntry":
                url = "adinfo?filename=%s" % self.pathdict[item.getText()]["path"]
                HTTPRequest().asyncGet(url, 
                               ADInfoLoader(self),
                              )
            else:
                self.adInfo.setHTML("""
                    <b style="font-size:200%%">%s</b>""" % pathdict[filename]["filetype"])
        else:
            self.adInfo.setHTML("unknown node")
        return
Пример #25
0
class UserListPanel(VerticalPanel):
    def __init__(self, tabPanel, topPanel, **kwargs):
        VerticalPanel.__init__(self, StyleName='user-list-panel', **kwargs)
        self.tabPanel = tabPanel
        self.topPanel = topPanel
        self.iconAdder = None
        self.iconPanel = None
        self.nSelected = 0
        self.leftPanelWidth = 340
        self.widthFudgeFactor = 25

    def clear(self):
        VerticalPanel.clear(self)
        self.nSelected = 0

    def updateResultLink(self):
        self.resultLink.setHTML('Results:&nbsp;<a href="%s">link</a>' %
                                self.tabPanel.resultsLink())
    
    def setUsers(self, title, users, kwargs):
        self.users = users
        self.nUsers = len(users)
        self.title = title
        self.resultPanel = HorizontalPanel(StyleName='result-panel')
        self.add(self.resultPanel)
        self.leftPanel = VerticalPanel(StyleName='results-left-panel',
                                       Width=self.leftPanelWidth)
        self.resultPanel.add(self.leftPanel)
        if not users:
            self.iconPanel = None
            self.leftPanel.add(HTML(title, StyleName='result-title'))
        else:
            # Set a display order that will show everything for now.
            self.displayOrder = range(self.nUsers)
            self.largeAvatar = LargeAvatar(self, self.tabPanel, self.topPanel)
            self.leftPanel.add(self.largeAvatar)

            resultPanelBottomLeft = VerticalPanel(
                StyleName='results-left-panel-bottom-left')

            self.resultLink = HTML(StyleName='result-detail')
            self.updateResultLink()
            resultPanelBottomLeft.add(self.resultLink)
            
            self.iconSizePanel = HorizontalPanel()
            self.iconSizePanel.add(
                HTML('Icons:&nbsp;', StyleName='result-detail'))

            self.iconSizeLb = lb = ListBox()
            i = 0
            for text, key in _iconData:
                lb.addItem(text, key)
                if key == _iconSize:
                    lb.setSelectedIndex(i)
                i += 1
            lb.addChangeListener(IconSizeChanger(self))
            self.iconSizePanel.add(lb)
            resultPanelBottomLeft.add(self.iconSizePanel)

            if self.nUsers > 1:
                self.sortPanel = HorizontalPanel()
                self.sortPanel.add(
                    HTML('Sort:&nbsp;', StyleName='result-detail'))

                self.lb = lb = ListBox()
                i = 0
                for text, key in _sortKeyData:
                    lb.addItem(text, key)
                    if key == _sortKey:
                        lb.setSelectedIndex(i)
                    i += 1
                lb.addChangeListener(self)
                self.sortPanel.add(lb)
                resultPanelBottomLeft.add(self.sortPanel)
                
            self.filterPanel = HorizontalPanel()
            resultPanelBottomLeft.add(self.filterPanel)
            self.addFilterWidgets()
            
            if self.topPanel.loggedIn():
                if 'screennames' in kwargs:
                    resultPanelBottomLeft.add(tweet.SimpleTweetPanel(
                        kwargs['screennames'], len(self.users), self.topPanel))
                elif 'query' in kwargs:
                    resultPanelBottomLeft.add(tweet.PrepareTweetButton(
                        kwargs['query'], len(self.users),
                        self.tabPanel.tabName, self.topPanel))

            self.leftPanel.add(resultPanelBottomLeft)

            self.iconPanel = VerticalPanel(StyleName='icon-outer-panel')
            self.resultPanel.add(self.iconPanel)
            self.images = []
            for u in users:
                url = u['profile_image_url']
                i = Image(url, StyleName='avatar-' + _iconSize)
                # Does calling prefetch actually help?
                i.prefetch(url)
                i._user = u
                i._selected = False
                i.addMouseListener(self)
                self.images.append(i)
            self.showUsers()

    def addFilterWidgets(self):
        """If we're logged in (and hence the friends list is available),
        create a filter listbox. If not, tell the loginPanel that we exist
        so it can call us when the login is complete."""
        if self.topPanel.loggedIn():
            # Window.alert('Logged in')
            self.filterPanel.add(
                HTML('Filter:&nbsp;', StyleName='result-detail'))
            self.filterChanger = FilterChanger(self, self.topPanel)
            self.filterBox = ListBox()
            self.filterBox.addItem('None', 0)
            self.filterBox.addItem(
                'Following (%d of %d)' %
                (self.filterChanger.nFriends, self.nUsers), 1)
            self.filterBox.addItem(
                "Not following (%d of %d)" %
                (self.nUsers - self.filterChanger.nFriends, self.nUsers), 2)
            self.filterBox.addChangeListener(self.filterChanger)
            self.filterPanel.add(self.filterBox)
        else:
            # Not yet logged in. Add ourselves to the list of UserListPanels
            # that the loginPanel will call when it's ready.
            self.topPanel.loginPanel.addUserListPanel(self)
                    
    def onChange(self, sender):
        global _sortKey
        _sortKey = self.lb.getValue(self.lb.getSelectedIndex())
        self.updateResultLink()
        self.showUsers()

    def showUsers(self):
        # Cancel any existing timed icon additions before changing
        # self.displayOrder.
        if self.iconAdder is not None:
            self.iconAdder.cancel()
            self.iconAdder = None
            
        self.iconPanel.clear()

        # Set a title above the icons.
        if hasattr(self, 'filterChanger'):
            order = self.filterChanger.currentOrder
            if order == 0:
                title = self.title
            else:
                if order == 1:
                    n = self.filterChanger.nFriends
                    detail = 'follow'
                else:
                    n = self.nUsers - self.filterChanger.nFriends
                    detail = "don't follow"
                if n == 0:
                    if detail == 'follow':
                        title = "You don't follow any of them!"
                    else:
                        title = "You already follow them all!"
                else:
                    if n > 1:
                        plural = 's'
                    else:
                        plural = ''
                    title = 'The %d user%s you %s:' % (n, plural, detail)
        else:
            title = self.title
        self.iconPanel.add(HTML(title, StyleName='result-title'))
        
        if not self.displayOrder:
            # There are no users to show.
            return
            
        decreasing = _sortKey in (
            'friends_count', 'followers_count', 'statuses_count')
        alpha = _sortKey in ('screen_name', 'name', 'location')
        def _keyFunc(n):
            value = self.users[n][_sortKey]
            if decreasing:
                return -1 * value
            elif alpha:
                if value:
                    return value.lower().strip()
                else:
                    # Uh, put this towards the end (of ASCII at least)
                    return '~~~'
            else:
                return value

        # Don't use sorted here, as it replaces the display order list
        # (which is actually being maintained for us by our FilterChanger
        # instance).
        self.displayOrder.sort(key=_keyFunc)
        self.icons = FlowPanel(StyleName='icon-panel')
        self.adjustWidths()
        self.iconPanel.add(self.icons)
        self.iconAdder = IconAdder(self)
        Timer.Timer(1, self.iconAdder)
        if self.nSelected == 0:
            self.largeAvatar.setUser(self.users[self.displayOrder[0]])

    def onMouseEnter(self, img):
        if not self.nSelected:
            self.largeAvatar.setUser(img._user)

    def onMouseMove(self, img, x, y):
        pass

    def onMouseLeave(self, img):
        pass

    def onMouseDown(self, img, x, y):
        self.largeAvatar.setUser(img._user)
        if not img._selected and self.nSelected:
            self._unselectAll()
        self._toggleSelect(img)

    def onMouseUp(self, img, x, y):
        pass

    def _toggleSelect(self, img):
        if img._selected:
            self._unselect(img)
        else:
            self._select(img)
        
    def _unselect(self, img):
        if img._selected:
            img.removeStyleDependentName('selected')
            self.nSelected -= 1
            img._selected = False

    def _select(self, img):
        if not img._selected:
            img.addStyleDependentName('selected')
            self.nSelected += 1
            img._selected = True

    def _unselectAll(self):
        for img in self.images:
            self._unselect(img)

    def unselectNotFollowed(self):
        for img in self.images:
            if not img._user['following'] and img._selected:
                self._unselect(img)

    def unselectFollowed(self):
        for img in self.images:
            if img._user['following'] and img._selected:
                self._unselect(img)

    def setIconSizes(self):
        for img in self.images:
            selected = img._selected
            if selected:
                self._unselect(img)
            img.setStyleName('avatar-' + _iconSize)
            if selected:
                self._select(img)

    def adjustWidths(self, windowWidth=None):
        if windowWidth is None:
            windowWidth = Window.getClientWidth()
        width = windowWidth - self.leftPanelWidth - self.widthFudgeFactor
        if self.iconPanel is not None:
            self.icons.setWidth(width)

    def adjustSize(self, width, height):
        self.adjustWidths(width)
Пример #26
0
class AutoCompleteTextBox(TextBox):
    def __init__(self, **kwargs):
        self.choicesPopup = PopupPanel(True, False)
        self.choices = ListBox()
        self.items = SimpleAutoCompletionItems()
        self.popupAdded = False
        self.visible = False

        self.choices.addClickListener(self)
        self.choices.addChangeListener(self)

        self.choicesPopup.add(self.choices)
        self.choicesPopup.addStyleName("AutoCompleteChoices")

        self.choices.setStyleName("list")

        if not kwargs.has_key('StyleName'):
            kwargs['StyleName'] = "gwt-AutoCompleteTextBox"

        TextBox.__init__(self, **kwargs)
        self.addKeyboardListener(self)

    def setCompletionItems(self, items):
        if not hasattr(items, 'getCompletionItems'):
            items = SimpleAutoCompletionItems(items)

        self.items = items

    def getCompletionItems(self):
        return self.items

    def onKeyDown(self, arg0, arg1, arg2):
        pass

    def onKeyPress(self, arg0, arg1, arg2):
        pass

    def onKeyUp(self, arg0, arg1, arg2):
        if arg1 == KeyboardListener.KEY_DOWN:
            selectedIndex = self.choices.getSelectedIndex()
            selectedIndex += 1
            if selectedIndex >= self.choices.getItemCount():
                selectedIndex = 0
            self.choices.setSelectedIndex(selectedIndex)
            return

        if arg1 == KeyboardListener.KEY_UP:
            selectedIndex = self.choices.getSelectedIndex()
            selectedIndex -= 1
            if selectedIndex < 0:
                selectedIndex = self.choices.getItemCount() - 1
            self.choices.setSelectedIndex(selectedIndex)
            return

        if arg1 == KeyboardListener.KEY_ENTER:
            if self.visible:
                self.complete()
            return

        if arg1 == KeyboardListener.KEY_ESCAPE:
            self.choices.clear()
            self.choicesPopup.hide()
            self.visible = False
            return

        text = self.getText()
        matches = []
        if len(text) > 0:
            matches = self.items.getCompletionItems(text)

        if len(matches) > 0:
            self.choices.clear()

            for i in range(len(matches)):
                self.choices.addItem(matches[i])

            if len(matches) == 1 and matches[0] == text:
                self.choicesPopup.hide()
            else:
                self.choices.setSelectedIndex(0)
                self.choices.setVisibleItemCount(len(matches) + 1)

                if not self.popupAdded:
                    RootPanel().add(self.choicesPopup)
                    self.popupAdded = True

                self.choicesPopup.show()
                self.visible = True
                self.choicesPopup.setPopupPosition(
                    self.getAbsoluteLeft(),
                    self.getAbsoluteTop() + self.getOffsetHeight())
                self.choices.setWidth("%dpx" % self.getOffsetWidth())
        else:
            self.visible = False
            self.choicesPopup.hide()

    def onChange(self, arg0):
        self.complete()

    def onClick(self, arg0):
        self.complete()

    def complete(self):
        if self.choices.getItemCount() > 0:
            self.setText(
                self.choices.getItemText(self.choices.getSelectedIndex()))

        self.choices.clear()
        self.choicesPopup.hide()
        self.setFocus(True)
        self.visible = False
Пример #27
0
class Milestones_Row(SimplePanel):
    '''
    Create and edit projects
    '''
    def __init__(self, milestone_names, milestone_dates):
        # We need to use old form of inheritance because of pyjamas
        SimplePanel.__init__(self)
        self.milestone_dates = milestone_dates
       
        self.hpanel = HorizontalPanel()
        self.hpanel.setVerticalAlignment(HasAlignment.ALIGN_TOP)
        self.name = ListBox(Height='34px', Width='208px')
        self.name.setStyleName('form-control input-lg')
        self.name.addChangeListener(getattr(self, 'on_milestone_changed'))
       
        for m in milestone_names:
            self.name.addItem(m) 
        if len(self.milestone_dates) > 0:
            self.planned_completion = Label(self.milestone_dates[0])
        else:
            self.planned_completion = Label('Undefined')
            
        self.planned_completion.setStyleName('form-control text-normal')

        self.expected_completion = Report_Date_Field(cal_ID='end')
        self.expected_completion.getTextBox().setStyleName('form-control')
        self.expected_completion.setRegex(DATE_MATCHER)
        self.expected_completion.appendValidListener(self._display_ok)
        self.expected_completion.appendInvalidListener(self._display_error)
        self.expected_completion.validate(None)

        self.hpanel.add(self.name)
        self.hpanel.add(Label(Width='10px'))
        self.hpanel.add(self.planned_completion)
        self.hpanel.add(Label(Width='10px'))
        self.hpanel.add(self.expected_completion)
        
    def get_name_txt(self):
        '''Return project name.
        '''
        return self.name.getText()


    def get_milestone_data(self):
        '''Get milestone data and return in the form suitable for passing to
        the model.
        '''
        name = self.name.getItemText(self.name.getSelectedIndex())
        planned_completion = self.planned_completion.getText()
        expected_completion = self.expected_completion.getTextBox().getText()
        return (name, planned_completion, expected_completion)

    def _display_ok(self, obj):
        obj.setStyleName('form-input')

    def _display_error(self, obj):
        if len(obj.getTextBox().getText()) > 0:
            obj.setStyleName('form-group has-error')
        
    def on_milestone_changed(self, event):
        '''
        Change completion date if milestone changed
        '''
        ind = self.name.getSelectedIndex()
        self.planned_completion.setText(self.milestone_dates[ind])
Пример #28
0
class I2CPanel :
	
	class saveStateListener :
		def __init__(self, panel) :
			self._saveStatePanel=panel	
			
		def onRemoteResponse(self, response, request_info):
			self._saveStatePanel.returnStatement.setText("File saved:" + response)
			
		def onRemoteError(self, code, message, request_info):
			ErrorMessage( "Unable to contact server" )
			
	
	class loadStateListener :
		def __init__(self, panel) :
			self._saveStatePanel=panel	
			
		def onRemoteResponse(self, response, request_info):
			self._saveStatePanel.returnStatement.setText("File loaded:" + response)
			self._saveStatePanel.rpcService.I2CRegisterValues( self._saveStatePanel.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self._saveStatePanel) ) #refresh of text boxes

		def onRemoteError(self, code, message, request_info):
			ErrorMessage( "Unable to contact server" )
	
	class ConnectedCBCListener :
		"""
		A class to listen for the response to the connectedCBCNames call
		"""
		def __init__(self, listBox) :
			self.listBox=listBox
			
		def onRemoteResponse(self, response, request_info):
			self.listBox.clear()
			if response == None:
				self.listBox.addItem("<none>")
				self.listBox.setEnabled( False )
			else :
				for name in response :
					self.listBox.addItem(name) #e.g FE0CBC0
				self.listBox.setEnabled(True)

		def onRemoteError(self, code, message, request_info):
			ErrorMessage( "Unable to contact server" )

	class ReadRegisterValueListener :
		"""
		A class to listen for the response to the call to get the register values
		"""
		def __init__(self, panel) :
			self._I2Cpanel=panel
			self.textBoxes=self._I2Cpanel.i2cValueEntries
			
		def onRemoteResponse(self, response, request_info):
			#Call is now made for all connected CBCs for better stability of status box- fb
			for cbcName in self._I2Cpanel.getActiveCBCs():
				if cbcName=='FE0CBC0':
					valuesTuple = response[response.keys()[0]]
				elif cbcName=='FE0CBC1':
					valuesTuple = response[response.keys()[1]]
			# For this chip loop over all the register and set the text box values
			for registerName in valuesTuple :
				box=self.textBoxes[registerName]
				status=self._I2Cpanel.statusValueEntries[registerName]
				box.setText( "0x%02x"%valuesTuple[registerName] )
				box.setStyleAttribute( "background-color", "#FFFFFF" )
				box.setEnabled( True )
			#for some reason pyjas likes these separated - fb	
			for registerName in valuesTuple:
				if response['FE0CBC0'][registerName]==response['FE0CBC1'][registerName]:
					self._I2Cpanel.statusValueEntries[registerName].setText("==")
				else:
					self._I2Cpanel.statusValueEntries[registerName].setText(" //")
		def onRemoteError(self, code, message, request_info):
			ErrorMessage( "Unable to contact server" )

	class RefreshListener :
		"""
		A class that will wait for a response before refreshing the status box
		"""
		def __init__(self, panel) :
			self._Refresh = panel
		
		def onRemoteResponse(self, response, request_info):
			self._Refresh.rpcService.I2CRegisterValues( self._Refresh.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self._Refresh) )	 #Live refresh of the status box
			

		def onRemoteError(self, code, message, request_info):
			ErrorMessage( "Unable to contact server" )

	def __init__( self ) :
		# This is the service that will be used to communicate with the DAQ software
		self.rpcService = GlibRPCService.instance()
		# The main panel that everythings will be insided
		self.mainPanel = HorizontalPanel()
		self.mainPanel.setSpacing(10)
		self.i2cValueEntries = {} # The input boxes for all the registers
		self.statusValueEntries = {} # Displays the status of the i2cValueEntries
		
		self.stateValueEntries = {} # For load/save state
		self.fileName = {} # File name of the i2c registers
		
		# This is the list of available CBC chips. It will be populated by a call to the
		# server later.
		self.cbcList=ListBox(MultipleSelect=True, VisibleItemCount=10)
		self.cbcList.addItem( "waiting..." ) # Default text until I hear from the server what's connected
		self.cbcList.setEnabled( False )
		self.cbcList.addChangeListener(self)
		self.rpcService.connectedCBCNames( None, I2CPanel.ConnectedCBCListener(self.cbcList) ) # Ask the server what's connected
		
		
		# This is the panel that will have the list of I2C registers. I'll split up the
		# registers into subjects to make them more manageable.
		self.mainSettings = DisclosurePanel("Main Control Registers")
		self.channelMasks = DisclosurePanel("Channel Masks")
		self.channelTrims = DisclosurePanel("Channel Trims")
		self.callSettings = VerticalPanel("Load/Save States")
		self.callSettings.setBorderWidth(1)

		self.callSettings.add(HTML("<center>Load/Save State</center>"))
		
		cbcListAndCallSettings=VerticalPanel()
		cbcListAndCallSettings.add(self.cbcList)
		cbcListAndCallSettings.add(self.callSettings)
		self.mainPanel.add(cbcListAndCallSettings)
		self.mainPanel.add(self.mainSettings)
		self.mainPanel.add(self.channelMasks)
		self.mainPanel.add(self.channelTrims)
		
		self.callSettings.add( self.createStatesPanel())
		self.mainSettings.add( self.createRegisterPanel(["FrontEndControl","TriggerLatency","HitDetectSLVS","Ipre1","Ipre2","Ipsf","Ipa","Ipaos","Vpafb","Icomp","Vpc","Vplus","VCth","TestPulsePot","SelTestPulseDel&ChanGroup","MiscTestPulseCtrl&AnalogMux","TestPulseChargePumpCurrent","TestPulseChargeMirrCascodeVolt","CwdWindow&Coincid","MiscStubLogic"]) )
		self.channelMasks.add( self.createRegisterPanel(["MaskChannelFrom008downto001","MaskChannelFrom016downto009","MaskChannelFrom024downto017","MaskChannelFrom032downto025","MaskChannelFrom040downto033","MaskChannelFrom048downto041","MaskChannelFrom056downto049","MaskChannelFrom064downto057","MaskChannelFrom072downto065","MaskChannelFrom080downto073","MaskChannelFrom088downto081","MaskChannelFrom096downto089","MaskChannelFrom104downto097","MaskChannelFrom112downto105","MaskChannelFrom120downto113","MaskChannelFrom128downto121","MaskChannelFrom136downto129","MaskChannelFrom144downto137","MaskChannelFrom152downto145","MaskChannelFrom160downto153","MaskChannelFrom168downto161","MaskChannelFrom176downto169","MaskChannelFrom184downto177","MaskChannelFrom192downto185","MaskChannelFrom200downto193","MaskChannelFrom208downto201","MaskChannelFrom216downto209","MaskChannelFrom224downto217","MaskChannelFrom232downto225","MaskChannelFrom240downto233","MaskChannelFrom248downto241","MaskChannelFrom254downto249"]) )
		self.channelTrims.add( self.createRegisterPanel(["Channel001","Channel002","Channel003","Channel004","Channel005","Channel006","Channel007","Channel008","Channel009","Channel010","Channel011","Channel012","Channel013","Channel014","Channel015","Channel016","Channel017","Channel018","Channel019","Channel020","Channel021","Channel022","Channel023","Channel024","Channel025","Channel026","Channel027","Channel028","Channel029","Channel030","Channel031","Channel032","Channel033","Channel034","Channel035","Channel036","Channel037","Channel038","Channel039","Channel040","Channel041","Channel042","Channel043","Channel044","Channel045","Channel046","Channel047","Channel048","Channel049","Channel050","Channel051","Channel052","Channel053","Channel054","Channel055","Channel056","Channel057","Channel058","Channel059","Channel060","Channel061","Channel062","Channel063","Channel064","Channel065","Channel066","Channel067","Channel068","Channel069","Channel070","Channel071","Channel072","Channel073","Channel074","Channel075","Channel076","Channel077","Channel078","Channel079","Channel080","Channel081","Channel082","Channel083","Channel084","Channel085","Channel086","Channel087","Channel088","Channel089","Channel090","Channel091","Channel092","Channel093","Channel094","Channel095","Channel096","Channel097","Channel098","Channel099","Channel100","Channel101","Channel102","Channel103","Channel104","Channel105","Channel106","Channel107","Channel108","Channel109","Channel110","Channel111","Channel112","Channel113","Channel114","Channel115","Channel116","Channel117","Channel118","Channel119","Channel120","Channel121","Channel122","Channel123","Channel124","Channel125","Channel126","Channel127","Channel128","Channel129","Channel130","Channel131","Channel132","Channel133","Channel134","Channel135","Channel136","Channel137","Channel138","Channel139","Channel140","Channel141","Channel142","Channel143","Channel144","Channel145","Channel146","Channel147","Channel148","Channel149","Channel150","Channel151","Channel152","Channel153","Channel154","Channel155","Channel156","Channel157","Channel158","Channel159","Channel160","Channel161","Channel162","Channel163","Channel164","Channel165","Channel166","Channel167","Channel168","Channel169","Channel170","Channel171","Channel172","Channel173","Channel174","Channel175","Channel176","Channel177","Channel178","Channel179","Channel180","Channel181","Channel182","Channel183","Channel184","Channel185","Channel186","Channel187","Channel188","Channel189","Channel190","Channel191","Channel192","Channel193","Channel194","Channel195","Channel196","Channel197","Channel198","Channel199","Channel200","Channel201","Channel202","Channel203","Channel204","Channel205","Channel206","Channel207","Channel208","Channel209","Channel210","Channel211","Channel212","Channel213","Channel214","Channel215","Channel216","Channel217","Channel218","Channel219","Channel220","Channel221","Channel222","Channel223","Channel224","Channel225","Channel226","Channel227","Channel228","Channel229","Channel230","Channel231","Channel232","Channel233","Channel234","Channel235","Channel236","Channel237","Channel238","Channel239","Channel240","Channel241","Channel242","Channel243","Channel244","Channel245","Channel246","Channel247","Channel248","Channel249","Channel250","Channel251","Channel252","Channel253","Channel254","ChannelDummy"]) )
		
		self.mainSettings.add()
		self.echo=Label()
		self.mainPanel.add(self.echo)

	def getPanel( self ) :
		return self.mainPanel
	
	def onChange( self, sender ) :
		
		if sender == self.cbcList :
			# Make a call to the RPC service to get the register values
			self.rpcService.I2CRegisterValues( self.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self) )#fb - sends all CBCs
			self.load.setEnabled(True)
			self.save.setEnabled(True)
		elif sender == self.save:
			msg = self.saveFileName.getText()
			self.rpcService.saveI2cRegisterValues(msg, I2CPanel.saveStateListener(self) )
		elif sender == self.load:
			msg = self.loadFileName.getText()
			self.rpcService.loadI2cRegisterValues(msg, I2CPanel.loadStateListener(self) )	
			self.rpcService.I2CRegisterValues( self.getTotalCBCs(), I2CPanel.ReadRegisterValueListener(self) )#
				
		# Sender must be a text box. Need to format the input.
		else : 
			try:
			# For some reason the '0x' at the start of the string is causing exceptions,
			# even though it works fine with interactive python. I'll take it off anyway.
				string=sender.getText()
				if( len(string)>=2 ) :
					if string[0]=='0' and string[1]=='x' : string=string[2:]
					value=int( string, 16 ) # convert as hex
					# Cap values at 255
					if value<0 : value=0
					if value>255 : value=255
					sender.setStyleAttribute( "background-color", "#FFFFFF" )
			# Convert to the same format as everything else
				sender.setText( "0x%02x"%value )
			# Send the change to the RPC service
				messageParameters = {}
				for cbcName in self.getActiveCBCs() :
					messageParameters[cbcName]={ sender.getTitle():value }
					self.rpcService.setI2CRegisterValues( messageParameters, I2CPanel.RefreshListener(self) )
			
			except ValueError:
				sender.setStyleAttribute( "background-color", "#FF3333" )		
		
		#self.echoSelection()
	
	def echoSelection(self): #fb - a good "print screen" method
		msg = " File saved: "
		for names in self.getCheckedStates():
			msg += names
		self.echo.setText(msg)	
			
	def getList(self):
		selectCBCs = []
		for i in range(self.cbcList.getItemCount()) :
			if self.cbcList.isItemSelected(i):
				selectedCBCs.append(self.cbcList.getItemText(i))
				
	def getTotalCBCs(self) : #fb
		totalCBCs = []
		for i in range(self.cbcList.getItemCount()) :
			totalCBCs.append(self.cbcList.getItemText(i))
		return totalCBCs
	
	def getSpecificCBC(self, i): #fb
		specificCBC = []
		specificCBC.append(self.cbcList.getItemText(i))
		return specificCBC
		

	def getActiveCBCs(self) :
		selectedCBCs = []
		for i in range(self.cbcList.getItemCount()) :
			if self.cbcList.isItemSelected(i):
				selectedCBCs.append(self.cbcList.getItemText(i))
		return selectedCBCs
	
	def getCheckedStates(self): # returns the checked boxes + filename
		selectedStates = []
		#for names in self.stateValueEntries:
			#if str(self.stateValueEntries[names].isChecked())=="True":
			#	selectedStates.append(names)
		selectedStates.append(self.saveFileName.getText())
		return selectedStates
		
	def createRegisterPanel( self, registerNames ) :
		"""
		Creates panels and buttons for everything given in registerNames, and returns the main panel.
		"""
		flowPanel=FlowPanel()
		for buttonName in registerNames :
			newPanel=HorizontalPanel()
			label=Label(buttonName)
			newPanel.add( label )
			newTextBox=TextBox()
			newTextBox.setEnabled(False)
			newTextBox.setWidth(80)
			statusBox=TextBox()
			statusBox.setEnabled(False)
			statusBox.setWidth(30)
			newPanel.add(newTextBox)
			newPanel.add(statusBox)
			newPanel.setCellHorizontalAlignment( newTextBox, HasHorizontalAlignment.ALIGN_RIGHT )
			newPanel.setCellHorizontalAlignment( statusBox, HasHorizontalAlignment.ALIGN_RIGHT )
			newPanel.setCellWidth( statusBox, "20px" )
			newPanel.setWidth("100%")
			#newPanel.setStyleName("areaStyle");
			#newPanel.setBorderWidth(5);
			
			newTextBox.setText("select chip...")
			newTextBox.addChangeListener(self)
			newTextBox.setTitle(buttonName) # This isn't displayed, but it's useful to have stored
			
			self.i2cValueEntries[buttonName]=newTextBox	
			
			self.statusValueEntries[buttonName]=statusBox
			statusBox.setTitle(buttonName)
			statusBox.setText("...")
			
			flowPanel.add(newPanel)


		return flowPanel
	
	def createStatesPanel(self):
		vertPanel=VerticalPanel()
		vertPanel.setSpacing(10)
		
		selectionNames = (["Main Control", "Masks", "Trims"])	
		registerSelection = VerticalPanel()
		
		for name in selectionNames :
			checkBox = CheckBox(name)
			checkBox.setTitle(name)
			self.stateValueEntries[name]=checkBox
			registerSelection.add(checkBox)
		
		#Tidy up 
		loadPanel = HorizontalPanel()
		loadFileTextBox = TextBox()
		loadFileTextBox.setText("MyI2cCfg")
		loadFileTextBox.setWidth(80)
		self.loadFileName = loadFileTextBox
		loadPanel.add(loadFileTextBox)
		self.load = Button("Load",getattr(self,"onChange")) #overrides default and sends it to onChange
		loadPanel.add(self.load)
		self.load.setEnabled(False)
		
		savePanel = HorizontalPanel()
		saveFileTextBox = TextBox()
		saveFileTextBox.setText("MyI2cCfg")
		saveFileTextBox.setWidth(80)
		self.saveFileName = saveFileTextBox
		savePanel.add(saveFileTextBox)
		self.save = Button("Save", getattr(self,"onChange"))
		savePanel.add(self.save)
		self.save.setEnabled(False)
		
		self.returnStatement = Label()
		
		vertPanel.add(registerSelection)
		vertPanel.add(loadPanel)
		vertPanel.add(savePanel)
		vertPanel.add(self.returnStatement)
		
		return vertPanel
Пример #29
0
class Lists(Sink):
    def __init__(self):
        Sink.__init__(self)

        self.sStrings=[["foo0", "bar0", "baz0", "toto0", "tintin0"],
            ["foo1", "bar1", "baz1", "toto1", "tintin1"],
            ["foo2", "bar2", "baz2", "toto2", "tintin2"],
            ["foo3", "bar3", "baz3", "toto3", "tintin3"],
            ["foo4", "bar4", "baz4", "toto4", "tintin4"]]

        self.combo=ListBox(VisibleItemCount=1)
        self.list=ListBox(MultipleSelect=True, VisibleItemCount=10)
        self.echo=Label()

        self.combo.addChangeListener(self)
        
        for i in range(len(self.sStrings)):
            txt = "List %d" % i
            self.combo.addItem(txt)
            # test setItemText
            self.combo.setItemText(i, txt + " using set text")
        self.combo.setSelectedIndex(0)
        self.fillList(0)
        
        self.list.addChangeListener(self)
        
        horz = HorizontalPanel(VerticalAlignment=HasAlignment.ALIGN_TOP,
                               Spacing=8)
        horz.add(self.combo)
        horz.add(self.list)
        
        panel = VerticalPanel(HorizontalAlignment=HasAlignment.ALIGN_LEFT)
        panel.add(horz)
        panel.add(self.echo)
        self.initWidget(panel)
        
        self.echoSelection()

    def onChange(self, sender):
        if sender == self.combo:
            self.fillList(self.combo.getSelectedIndex())
        elif sender == self.list:
            self.echoSelection()

    def onShow(self):
        pass
    
    def fillList(self, idx):
        self.list.clear()
        strings = self.sStrings[idx]
        for i in range(len(strings)):
            self.list.addItem(strings[i])

        self.echoSelection()

    def echoSelection(self):
        msg = "Selected items: "
        for i in range(self.list.getItemCount()):
            if self.list.isItemSelected(i):
                msg += self.list.getItemText(i) + " "
        self.echo.setText(msg)
Пример #30
0
class MechOptionPanel(HorizontalPanel):
    def __init__(self, handle, idx, checkOptions = [False, True]):
        HorizontalPanel.__init__(self)
        self.log = logging.getConsoleLogger(type(self).__name__, lev)
        self.log.disabled = False
        self.log.debug('__init__: Instantiation')
        self.idx = idx
        self._handle = handle
        self._checkOptions = checkOptions
        self.setStyleName('os-mech-checkbox-options')
        #checkbox = CheckBox('symbol')
        #checkbox.setChecked(checkOptions[0])
        #checkbox.addClickListener(self.onClickOption)
        #checkbox.setID('CBSY%d'%idx)
        #self.append(checkbox)
        #checkbox = CheckBox('value')
        #checkbox.setChecked(checkOptions[1])
        #checkbox.addClickListener(self.onClickOption)
        #checkbox.setID('CBVA%d'%idx)
        #self.append(checkbox)
        
        self._textBoxRatio = TextBox('1:1')
        self._ratioCache = self._textBoxRatio.getText()
        self._textBoxRatio.setTitle('Ratio')
        self._ratioCache = self._textBoxRatio.getText()
        
        self._textBoxRatio.addChangeListener(self.onRatioChange) 
        self._textBoxRatio.setID('TXRT%d'%idx)
        self._textBoxRatio.setStyleName('os-mech-textbox-ratio')
        
        self._listBoxSize = ListBox()
        self._listBoxSize.addChangeListener(self.onSizeSet)
        self._listBoxSize.setVisibleItemCount(1)
        self._listBoxSize.setStyleName('os-mech-listbox-size')

        self._listBoxUnit = ListBox()
        self._listBoxUnit.addChangeListener(self.onUnitSet)
        self._listBoxUnit.setVisibleItemCount(1)
        self._listBoxUnit.setStyleName('os-mech-listbox-unit')

        self.append(Label('Ratio'))
        self.append(self._textBoxRatio)
        self.append(Label('Size'))
        self.append(self._listBoxSize)
        self.append(Label('Unit'))
        self.append(self._listBoxUnit)
    def onSizeSet(self, sender, event):
        value = sender.getSelectedItemText()[0]
        self.log.debug('Change size to %s'%value)
        self._handle.remoteService.mech_options_set(self._handle._handle, self.idx, 'size', value)
    def onUnitSet(self, sender, event):
        value = sender.getSelectedValues()[0]
        self._handle.remoteService.mech_options_set(self._handle._handle, self.idx, 'unit',int(value))
    def onRatioChange(self, sender, event):
        #validate ratio change
        matches = re.findall(r'^\d{1,4}:\d{1,4}$', self._textBoxRatio.getText())
        if len(matches) == 1: # correct
            self._ratioCache = self._textBoxRatio.getText()
            self._handle.remoteService.mech_options_set(self._handle._handle, self.idx, 'ratio', self._ratioCache)
        else: # invalid
            self._textBoxRatio.setText(self._ratioCache)
    def actSizeFill(self, options, value = 0):
        for idx, option in enumerate(options, idx):
            self._listBoxSize.addItem(option, idx)
        self._listBoxSize.setSelectedIndex(value)
    def actUnitFill(self, options, value = 0):
        for number, name in options.items():
            self._listBoxUnit.addItem(name, number)
        if value < 100000:
            self._listBoxUnit.setSelectedIndex(value)
        else:
            self._listBoxUnit.selectValue(value)
    def actSizeSet(self, value):
        self.log.debug('actSizeSet, setting value %s'%value)
        self._listBoxSize.selectValue(value)
    def actRatioChange(self, ratio):
        self._textBoxRatio.setText(ratio)
        self._ratioCache = ratio
    def onClickOption(self, sender, event):
        sendId = int(sender.getID()[4:])
        if sendId == 0:
            self._checkOptions[0] = sender.isChecked()
            self._checkOptions[1] = not(sender.isChecked())
        else:
            self._checkOptions[0] = not(sender.isChecked())
            self._checkOptions[1] = sender.isChecked()
        checkbox = self.getWidget(0)
        checkbox.setChecked(self._checkOptions[0])
        checkbox = self.getWidget(1)
        checkbox.setChecked(self._checkOptions[1])
        self._handle.remoteService.mech_options_set(self._handle._handle, self.idx,  'checkOptions', self._checkOptions)
Пример #31
0
Файл: Lists.py Проект: Afey/pyjs
class Lists(Sink):
    def __init__(self):
        Sink.__init__(self)

        self.sStrings=[["foo0", "bar0", "baz0", "toto0", "tintin0"],
            ["foo1", "bar1", "baz1", "toto1", "tintin1"],
            ["foo2", "bar2", "baz2", "toto2", "tintin2"],
            ["foo3", "bar3", "baz3", "toto3", "tintin3"],
            ["foo4", "bar4", "baz4", "toto4", "tintin4"]]

        self.combo=ListBox(VisibleItemCount=1)
        self.list=ListBox(MultipleSelect=True, VisibleItemCount=10)
        self.echo=Label()

        self.combo.addChangeListener(self)

        for i in range(len(self.sStrings)):
            txt = "List %d" % i
            self.combo.addItem(txt)
            # test setItemText
            self.combo.setItemText(i, txt + " using set text")
        self.combo.setSelectedIndex(0)
        self.fillList(0)
        self.list.setItemSelected(0, False)
        self.list.setItemSelected(1, True)

        self.list.addChangeListener(self)

        horz = HorizontalPanel(VerticalAlignment=HasAlignment.ALIGN_TOP,
                               Spacing=8)
        horz.add(self.combo)
        horz.add(self.list)

        panel = VerticalPanel(HorizontalAlignment=HasAlignment.ALIGN_LEFT)
        panel.add(horz)
        panel.add(self.echo)
        self.initWidget(panel)

        self.echoSelection()

    def onChange(self, sender):
        if sender == self.combo:
            self.fillList(self.combo.getSelectedIndex())
        elif sender == self.list:
            self.echoSelection()

    def onShow(self):
        pass

    def fillList(self, idx):
        self.list.clear()
        strings = self.sStrings[idx]
        for i in range(len(strings)):
            self.list.addItem(strings[i])

        self.echoSelection()

    def echoSelection(self):
        msg = "Selected items: "
        for i in range(self.list.getItemCount()):
            if self.list.isItemSelected(i):
                msg += self.list.getItemText(i) + " "
        self.echo.setText(msg)
Пример #32
0
class DirectionsSimple(DockPanel):
    def __init__(self):
        DockPanel.__init__(self)
        self.setSize('100%', '100%')

        # widgets

        topPanel = HorizontalPanel()
        self.add(topPanel, DockPanel.NORTH)

        places = {
            "chicago, il": "Chicago",
            "st louis, mo": "St Louis",
            "joplin, mo": "Joplin, MO",
            "oklahoma city, ok": "Oklahoma City",
            "amarillo, tx": "Amarillo",
            "gallup, nm": "Gallup, NM",
            "flagstaff, az": "Flagstaff, AZ",
            "winona, az": "Winona",
            "kingman, az": "Kingman",
            "barstow, ca": "Barstow",
            "san bernardino, ca": "San Bernardino",
            "los angeles, ca": "Los Angeles"
        }

        self.start = ListBox()
        self.end = ListBox()

        for value in places:
            self.start.addItem(places[value], value)
            self.end.addItem(places[value], value)

        self.start.addChangeListener(self.calcRoute)
        self.end.addChangeListener(self.calcRoute)

        topPanel.add(self.start)
        topPanel.add(self.end)

        # now, the map

        mapPanel = SimplePanel()
        mapPanel.setSize('800', '500')
        self.add(mapPanel, DockPanel.CENTER)

        chigado = LatLng(41.850033, -87.6500523)
        options = MapOptions(zoom=7,
                             center=chigado,
                             mapTypeId=MapTypeId.ROADMAP)

        self.map = Map(mapPanel.getElement(), options)

        # initialize the renderer
        self.directionsDisplay = DirectionsRenderer()
        self.directionsDisplay.setMap(self.map)

        self.directionsService = DirectionsService()

    def calcRoute(self):
        start = self.start.getValue(self.start.getSelectedIndex())
        end = self.end.getValue(self.end.getSelectedIndex())

        print "calcRoute start:", start, "end:", end

        request = DirectionsRequest(origin=start, destination=end, \
            travelMode=DirectionsTravelMode.DRIVING)

        self.directionsService.route(request, self.directionsResult)

    def directionsResult(self, response, status):
        print "directionsResult:"

        if status == DirectionsStatus.OK:

            for trip in response.trips:
                print "copyrights:", trip.copyrights

                for route in trip.routes:
                    print route.start_geocode.formatted_address
                    print route.end_geocode.formatted_address
                    print route.steps[0].start_point
                    print route.steps[0].end_point

                print "\n"

            self.directionsDisplay.setDirections(response)
Пример #33
0
class DirectionsSimple(DockPanel):

    def __init__(self):
        DockPanel.__init__(self)
        self.setSize('100%', '100%')

        # widgets

        topPanel = HorizontalPanel()
        self.add(topPanel, DockPanel.NORTH)

        places = {
            "chicago, il": "Chicago",

            "st louis, mo": "St Louis",
            "joplin, mo": "Joplin, MO",
            "oklahoma city, ok": "Oklahoma City",
            "amarillo, tx": "Amarillo",
            "gallup, nm": "Gallup, NM",
            "flagstaff, az": "Flagstaff, AZ",

            "winona, az": "Winona",
            "kingman, az": "Kingman",
            "barstow, ca": "Barstow",
            "san bernardino, ca": "San Bernardino",
            "los angeles, ca": "Los Angeles"}

        self.start = ListBox()
        self.end = ListBox()

        for value in places:
            self.start.addItem(places[value], value)
            self.end.addItem(places[value], value)

        self.start.addChangeListener(self.calcRoute)
        self.end.addChangeListener(self.calcRoute)

        topPanel.add(self.start)
        topPanel.add(self.end)

        # now, the map

        mapPanel = SimplePanel()
        mapPanel.setSize('800', '500')
        self.add(mapPanel, DockPanel.CENTER)

        chigado = LatLng(41.850033, -87.6500523)
        options = MapOptions(zoom=7, center=chigado,
                           mapTypeId=MapTypeId.ROADMAP)

        self.map = Map(mapPanel.getElement(), options)

        # initialize the renderer
        self.directionsDisplay = DirectionsRenderer()
        self.directionsDisplay.setMap(self.map)

        self.directionsService = DirectionsService()

    def calcRoute(self):
        start = self.start.getValue(self.start.getSelectedIndex())
        end = self.end.getValue(self.end.getSelectedIndex())

        print "calcRoute start:", start, "end:", end

        request = DirectionsRequest(origin=start, destination=end, \
            travelMode=DirectionsTravelMode.DRIVING)

        self.directionsService.route(request, self.directionsResult)

    def directionsResult(self, response, status):
        print "directionsResult:"

        if status == DirectionsStatus.OK:

            for trip in response.trips:
                print "copyrights:", trip.copyrights

                for route in trip.routes:
                    print route.start_geocode.formatted_address
                    print route.end_geocode.formatted_address
                    print route.steps[0].start_point
                    print route.steps[0].end_point

                print "\n"

            self.directionsDisplay.setDirections(response)
Пример #34
0
class UserForm(AbsolutePanel):

    MODE_ADD    = "modeAdd";
    MODE_EDIT   = "modeEdit";

    user = None
    mode = None

    usernameInput = None
    firstInput = None
    lastInput = None
    emailInput = None
    passwordInput = None
    confirmInput = None
    departmentCombo = None
    addBtn = None
    cancelBtn = None

    def __init__(self,parent):
        AbsolutePanel.__init__(self)
        ftable = FlexTable()

        ftable.setWidget(0, 0, Label("First Name", wordWrap=False))
        ftableFormatter = ftable.getFlexCellFormatter()
        self.firstInput = TextBox()
        self.firstInput.addChangeListener(self.checkValid)
        self.firstInput.addKeyboardListener(self)
        ftable.setWidget(0, 1, self.firstInput)

        ftable.setWidget(1, 0, Label("Last Name", wordWrap=False))
        self.lastInput = TextBox()
        self.lastInput.addChangeListener(self.checkValid)
        self.lastInput.addKeyboardListener(self)
        ftable.setWidget(1, 1, self.lastInput)

        ftable.setWidget(2, 0, Label("Email", wordWrap=False))
        self.emailInput = TextBox()
        self.emailInput.addChangeListener(self.checkValid)
        self.emailInput.addKeyboardListener(self)
        ftable.setWidget(2, 1, self.emailInput)

        w = Label("* Username", wordWrap=False)
        w.addMouseListener(TooltipListener("Required, not changable"))
        ftable.setWidget(3, 0, w)
        self.usernameInput = TextBox()
        self.usernameInput.addChangeListener(self.checkValid)
        self.usernameInput.addKeyboardListener(self)
        ftable.setWidget(3, 1, self.usernameInput)

        w = Label("* Password", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(4, 0, w)
        self.passwordInput = PasswordTextBox()
        self.passwordInput.addChangeListener(self.checkValid)
        self.passwordInput.addKeyboardListener(self)
        ftable.setWidget(4, 1, self.passwordInput)

        w = Label("* Confirm", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(5, 0, w)
        self.confirmInput = PasswordTextBox()
        self.confirmInput.addChangeListener(self.checkValid)
        self.confirmInput.addKeyboardListener(self)
        ftable.setWidget(5, 1, self.confirmInput)

        w = Label("* Department", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(6, 0, w)
        self.departmentCombo = ListBox()
        self.departmentCombo.addChangeListener(self.checkValid)
        self.departmentCombo.addKeyboardListener(self)
        ftable.setWidget(6, 1, self.departmentCombo)

        hpanel = HorizontalPanel()
        self.addBtn = Button("Add User")
        self.addBtn.setEnabled(False)
        hpanel.add(self.addBtn)
        self.cancelBtn = Button("Cancel")
        hpanel.add(self.cancelBtn)
        ftable.setWidget(7, 0, hpanel)
        ftableFormatter.setColSpan(7, 0, 2)

        self.add(ftable)
        self.clearForm()
        return

    def clearForm(self):
        self.user = None
        self.usernameInput.setText('')
        self.firstInput.setText('')
        self.lastInput.setText('')
        self.emailInput.setText('')
        self.passwordInput.setText('')
        self.confirmInput.setText('')
        self.departmentCombo.setItemTextSelection(None)
        self.updateMode(self.MODE_ADD)
        self.checkValid()

    def updateUser(self, user):
        def setText(elem, value):
            if value:
                elem.setText(value)
            else:
                elem.setText("")
        self.user = user
        setText(self.usernameInput, self.user.username)
        setText(self.firstInput, self.user.fname)
        setText(self.lastInput, self.user.lname)
        setText(self.emailInput, self.user.email)
        setText(self.passwordInput, self.user.password)
        setText(self.confirmInput, self.user.password)
        self.departmentCombo.setItemTextSelection([self.user.department])
        self.checkValid()

    def updateDepartmentCombo(self,choices, default_):
        self.departmentCombo.clear()
        for choice in choices:
            self.departmentCombo.addItem(choice)
        self.departmentCombo.selectValue(default_)

    def updateMode(self, mode):
        self.mode = mode
        if self.mode == self.MODE_ADD:
            self.addBtn.setText("Add User")
        else:
            self.addBtn.setText("Update User")

    def checkValid(self, evt=None):
        if self.enableSubmit(self.usernameInput.getText(),self.passwordInput.getText(),self.confirmInput.getText(), self.departmentCombo.getSelectedItemText(True)):
            self.addBtn.setEnabled(True)
        else:
            self.addBtn.setEnabled(False)

    def enableSubmit(self, u, p, c, d):
        return (len(u) > 0 and len(p) >0 and p == c and len(d) > 0)

    def onClick(self, sender):
        pass

    def onKeyUp(self, sender, keyCode, modifiers):
        self.checkValid()

    def onKeyDown(self, sender, keyCode, modifiers):
        pass

    def onKeyPress(self, sender, keyCode, modifiers):
        pass
Пример #35
0
class Trees(Sink):
    pathdict = {}
    reduceFiles = None
    def __init__(self, parent = None):
        Sink.__init__(self, parent)
        self.reduceFiles = []
        if True:
            HTTPRequest().asyncGet("datadir.xml", 
                                    DirDictLoader(self),
                                )
        dock = DockPanel(HorizontalAlignment=HasAlignment.ALIGN_LEFT, 
                            Spacing=10,
                             Size=("100%","100%"))
        self.dock = dock
        self.fProto = []

        self.fTree = Tree()
        self.prPanel = VerticalPanel(Size=("50%", ""))
        self.treePanel = HorizontalPanel(Size=("50%", "100%"))
        self.treePanel.add(self.fTree)
        dock.add(self.treePanel, DockPanel.WEST)
        
        self.treePanel.setBorderWidth(1)
        self.treePanel.setWidth("100%")
        self.prPanel.setBorderWidth(1)
        self.prPanel.setWidth("100%")
        # prepare panel
        self.prepareReduce = HTML("<tt> .. none yet .. </tt>", True, )
        
        self.recipeList = ListBox()
        self.recipeList.addChangeListener(getattr(self, "onRecipeSelected"))
        self.recipeList.addItem("None")
        HTTPRequest().asyncGet("recipes.xml",
                                RecipeListLoader(self))

        #EO prepare panel
        self.reduceCLPanel = DockPanel(Spacing = 5)
        self.reduceCLPanel.add(HTML("<i>Reduce Command Line</i>:"), DockPanel.NORTH)                        
        self.reduceCLPanel.add(self.prepareReduce, DockPanel.NORTH)

        self.reduceFilesPanel = DockPanel(Spacing = 5)
        self.reduceFilesPanel.add(HTML("<b>Datasets</b>:"), DockPanel.WEST)
        
        self.reduceFiles = ListBox()
        self.reduceFiles.setVisibleItemCount(5)
        self.reduceFilesPanel.add(self.reduceFiles, DockPanel.WEST)
        self.clearReduceFilesButton = Button("<b>Clear List</b>", listener = getattr(self, "onClearReduceFiles"))
        self.reduceFilesPanel.add(self.clearReduceFilesButton, DockPanel.SOUTH)

        self.recipeListPanel = DockPanel(Spacing = 5)
        self.recipeListPanel.add(HTML("<b>Recipes List</b>:"),DockPanel.WEST)
        self.recipeListPanel.add(self.recipeList, DockPanel.WEST)
        
        self.runReduceButton = Button("<b>RUN REDUCE</b>", listener = getattr(self, "onRunReduce"))
        
        self.adInfo = HTML("file info...")
        # major sub panels
        self.prPanel.add(self.reduceCLPanel)
        self.prPanel.add(self.reduceFilesPanel)
        self.prPanel.add(self.recipeListPanel)
        self.prPanel.add(self.runReduceButton)
        self.prPanel.add(self.adInfo)
       
        
        dock.add(self.prPanel,DockPanel.EAST)
        
        dock.setCellWidth(self.treePanel, "50%")
        dock.setCellWidth(self.prPanel, "50%")
        for i in range(len(self.fProto)):
            self.createItem(self.fProto[i])
            self.fTree.addItem(self.fProto[i].item)

        self.fTree.addTreeListener(self)
        self.initWidget(self.dock)
        
        if False: #self.parent.filexml != None:
            DirDictLoader(self).onCompletion(self.parent.filexml)

    def onTreeItemSelected(self, item):
        pathdict = self.pathdict
        
        tfile = item.getText()
        #check if already in

        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            if fname == tfile:
                return
        self.reduceFiles.addItem(tfile)
        self.updateReduceCL()
        
        filename = tfile
        if filename in pathdict:
            if pathdict[filename]["filetype"] == "fileEntry":
                HTTPRequest().asyncGet("adinfo?filename=%s" % self.pathdict[item.getText()]["path"], 
                               ADInfoLoader(self),
                              )
            else:
                self.adInfo.setHTML("""
                    <b style="font-size:200%%">%s</b>""" % pathdict[filename]["filetype"])
        else:
            self.adInfo.setHTML("unknown node")
        return
        
        # self.prepareReduce.setHTML('<a href="runreduce?p=-r&p=callen&p=%(fname)s">reduce -r callen %(fname)s</a>' %
        #                            {"fname":item.getText()})
        pass
 
    def onRecipeSelected(self, event):
        self.updateReduceCL()
    
    def onClearReduceFiles(self, event):
        self.reduceFiles.clear() 
        self.adInfo.setHTML("file info...") 
        self.updateReduceCL()
        
    def updateReduceCL(self):
        recipe = self.recipeList.getItemText(self.recipeList.getSelectedIndex())
        
        if recipe=="None":
            rstr = ""
        else:
            rstr = "-r "+recipe

        rfiles = []            
        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            rfiles.append(fname)
        filesstr = " ".join(rfiles)
        
                
        self.prepareReduce.setHTML('<b>reduce</b> %(recipe)s %(files)s' % 
                                        { "recipe":rstr, 
                                          "files":filesstr})
    def onRunReduce(self):
        recipe = self.recipeList.getItemText(self.recipeList.getSelectedIndex())
        
        if recipe=="None":
            rstr = ""
        else:
            rstr = "p=-r"+recipe

        rfiles = []            
        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            rfiles.append(quote(self.pathdict[fname]["path"]))
        filesstr = "&p=".join(rfiles)
                
        cl = "/runreduce?%s&p=%s" % (rstr, filesstr)
        JS("window.open(cl)")

        
    def onTreeItemSelected(self, item):
        pathdict = self.pathdict
        
        tfile = item.getText()
        #check if already in
        if tfile in pathdict:
            ftype = pathdict[tfile]["filetype"]
            if ftype != "fileEntry":
                item.setState(True)
                return
        else:
            return
        for i in range(0, self.reduceFiles.getItemCount()):
            fname = self.reduceFiles.getItemText(i)
            if fname == tfile:
                return
        self.reduceFiles.addItem(tfile)
        self.updateReduceCL()
        
        filename = tfile
        if filename in pathdict:
            if pathdict[filename]["filetype"] == "fileEntry":
                HTTPRequest().asyncGet("adinfo?filename=%s" % self.pathdict[item.getText()]["path"], 
                               ADInfoLoader(self),
                              )
            else:
                self.adInfo.setHTML("""
                    <b style="font-size:200%%">%s</b>""" % pathdict[filename]["filetype"])
        else:
            self.adInfo.setHTML("unknown node")
        return
        
        # self.prepareReduce.setHTML('<a href="runreduce?p=-r&p=callen&p=%(fname)s">reduce -r callen %(fname)s</a>' %
        #                            {"fname":item.getText()})
        pass
    
    def onTreeItemStateChanged(self, item):
        child = item.getChild(0)
        if hasattr(child, "isPendingItem"):
            item.removeItem(child)
        
            proto = item.getUserObject()
            for i in range(len(proto.children)):
                self.createItem(proto.children[i])
                index = self.getSortIndex(item, proto.children[i].text)
                # demonstrate insertItem.  addItem is easy.
                item.insertItem(proto.children[i].item, index)
                item.setState(True)

    def getSortIndex(self, parent, text):
        nodes = parent.getChildCount()
        node = 0
        text = text.lower()

        while node < nodes:
            item = parent.getChild(node)
            if cmp(text, item.getText().lower()) < 0:
                break;
            else:
                node += 1
        
        return node
    
    def createProto(self, node):
            #if node.nodeType != node.ELEMENT_NODE:
            #    return
            pathdict = self.pathdict
            if not node.hasChildNodes():
                if node.nodeType != 1:
                    return None
                newproto = Proto(str(node.getAttribute("name")))
                if node.tagName == "fileEntry":
                    pathdict.update({node.getAttribute("name"):
                                        { "path":node.getAttribute("fullpath"),
                                          "filetype": node.tagName }})
                elif node.tagName == "dirEntry":
                    pathdict.update({node.getAttribute("name"):
                                        { "path":node.getAttribute("name"),
                                          "filetype": node.tagName}})
                else:
                    pathdict.update({node.getAttribute("name"):
                                        { "path": "NOPATH",
                                          "filetype": node.tagName}})
                self.createItem(newproto)
                return newproto
            else:
                cprotos = []
                for i in range(0, node.childNodes.length):
                    childnode = node.childNodes.item(i)
                    ncproto = self.createProto(childnode)
                    if ncproto != None:
                        ncitem  = self.createItem(ncproto)
                        cprotos.append(ncproto)
                if len(cprotos)>0:
                    newproto = Proto(str(node.getAttribute("name")),cprotos)
                else:
                    newproto = Proto(str(node.getAttribute("name")))
                if node.tagName == "fileEntry":
                    pathdict.update({node.getAttribute("name"):
                                        { "path":node.getAttribute("fullpath"),
                                          "filetype": node.tagName }})
                elif node.tagName == "dirEntry":
                    pathdict.update({node.getAttribute("name"):
                                        { "path":node.getAttribute("name"),
                                          "filetype": node.tagName}})
                else:
                    pathdict.update({node.getAttribute("name"):
                                        { "path": "NOPATH",
                                          "filetype": node.tagName}})

                self.createItem(newproto)
            return newproto
    
    def fromXML(self,text):
        doc = create_xml_doc(text)
        #node = doc.firstChild
        
        #node = doc.getElementById("topDirectory")
        nodes = doc.getElementsByTagName("dirEntry")
        node = nodes.item(0)
        s = repr(node)
        
        newproto = self.createProto(node)    
        plist = [newproto]
        #plist = [Proto(node.tagName)]

        for i in range(len(plist)):
            num = str(len(plist))
            # self.createItem(plist[i])
            self.fTree.addItem(plist[i].item)
            plist[i].item.setState(True)

        
    def onShow(self):
        if False:
            for item in self.fTree.treeItemIterator():
                key = repr(item.tree)
                if key != "null":
                    item.setState(True)
                else:
                    JS("alert(item.getText())")

        pass

    def createItem(self, proto):
        proto.item = TreeItem(proto.text)
        proto.item.setUserObject(proto)
        if len(proto.children) > 0:
            proto.item.addItem(PendingItem())
Пример #36
0
class UserForm(AbsolutePanel):

    MODE_ADD = "modeAdd"
    MODE_EDIT = "modeEdit"

    user = None
    mode = None

    usernameInput = None
    firstInput = None
    lastInput = None
    emailInput = None
    passwordInput = None
    confirmInput = None
    departmentCombo = None
    addBtn = None
    cancelBtn = None

    def __init__(self, parent):
        AbsolutePanel.__init__(self)
        ftable = FlexTable()

        ftable.setWidget(0, 0, Label("First Name", wordWrap=False))
        ftableFormatter = ftable.getFlexCellFormatter()
        self.firstInput = TextBox()
        self.firstInput.addChangeListener(self.checkValid)
        self.firstInput.addKeyboardListener(self)
        ftable.setWidget(0, 1, self.firstInput)

        ftable.setWidget(1, 0, Label("Last Name", wordWrap=False))
        self.lastInput = TextBox()
        self.lastInput.addChangeListener(self.checkValid)
        self.lastInput.addKeyboardListener(self)
        ftable.setWidget(1, 1, self.lastInput)

        ftable.setWidget(2, 0, Label("Email", wordWrap=False))
        self.emailInput = TextBox()
        self.emailInput.addChangeListener(self.checkValid)
        self.emailInput.addKeyboardListener(self)
        ftable.setWidget(2, 1, self.emailInput)

        w = Label("* Username", wordWrap=False)
        w.addMouseListener(TooltipListener("Required, not changable"))
        ftable.setWidget(3, 0, w)
        self.usernameInput = TextBox()
        self.usernameInput.addChangeListener(self.checkValid)
        self.usernameInput.addKeyboardListener(self)
        ftable.setWidget(3, 1, self.usernameInput)

        w = Label("* Password", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(4, 0, w)
        self.passwordInput = PasswordTextBox()
        self.passwordInput.addChangeListener(self.checkValid)
        self.passwordInput.addKeyboardListener(self)
        ftable.setWidget(4, 1, self.passwordInput)

        w = Label("* Confirm", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(5, 0, w)
        self.confirmInput = PasswordTextBox()
        self.confirmInput.addChangeListener(self.checkValid)
        self.confirmInput.addKeyboardListener(self)
        ftable.setWidget(5, 1, self.confirmInput)

        w = Label("* Department", wordWrap=False)
        w.addMouseListener(TooltipListener("Required"))
        ftable.setWidget(6, 0, w)
        self.departmentCombo = ListBox()
        self.departmentCombo.addChangeListener(self.checkValid)
        self.departmentCombo.addKeyboardListener(self)
        ftable.setWidget(6, 1, self.departmentCombo)

        hpanel = HorizontalPanel()
        self.addBtn = Button("Add User")
        self.addBtn.setEnabled(False)
        hpanel.add(self.addBtn)
        self.cancelBtn = Button("Cancel")
        hpanel.add(self.cancelBtn)
        ftable.setWidget(7, 0, hpanel)
        ftableFormatter.setColSpan(7, 0, 2)

        self.add(ftable)
        self.clearForm()
        return

    def clearForm(self):
        self.user = None
        self.usernameInput.setText('')
        self.firstInput.setText('')
        self.lastInput.setText('')
        self.emailInput.setText('')
        self.passwordInput.setText('')
        self.confirmInput.setText('')
        self.departmentCombo.setItemTextSelection(None)
        self.updateMode(self.MODE_ADD)
        self.checkValid()

    def updateUser(self, user):
        def setText(elem, value):
            if value:
                elem.setText(value)
            else:
                elem.setText("")

        self.user = user
        setText(self.usernameInput, self.user.username)
        setText(self.firstInput, self.user.fname)
        setText(self.lastInput, self.user.lname)
        setText(self.emailInput, self.user.email)
        setText(self.passwordInput, self.user.password)
        setText(self.confirmInput, self.user.password)
        self.departmentCombo.setItemTextSelection([self.user.department])
        self.checkValid()

    def updateDepartmentCombo(self, choices, default_):
        self.departmentCombo.clear()
        for choice in choices:
            self.departmentCombo.addItem(choice)
        self.departmentCombo.selectValue(default_)

    def updateMode(self, mode):
        self.mode = mode
        if self.mode == self.MODE_ADD:
            self.addBtn.setText("Add User")
        else:
            self.addBtn.setText("Update User")

    def checkValid(self, evt=None):
        if self.enableSubmit(self.usernameInput.getText(),
                             self.passwordInput.getText(),
                             self.confirmInput.getText(),
                             self.departmentCombo.getSelectedItemText(True)):
            self.addBtn.setEnabled(True)
        else:
            self.addBtn.setEnabled(False)

    def enableSubmit(self, u, p, c, d):
        return (len(u) > 0 and len(p) > 0 and p == c and len(d) > 0)

    def onClick(self, sender):
        pass

    def onKeyUp(self, sender, keyCode, modifiers):
        self.checkValid()

    def onKeyDown(self, sender, keyCode, modifiers):
        pass

    def onKeyPress(self, sender, keyCode, modifiers):
        pass