def __init__(self, label='', **kwargs):

        self.class_ = 'd-flex align-center mb-2'
        self.disabled = True
        self.row = True
        self.label = label

        super().__init__(**kwargs)

        self.w_prev = v.Btn(_metadata={'name': 'previous'},
                            x_small=True,
                            children=[
                                v.Icon(left=True,
                                       children=['mdi-chevron-left']), 'prev'
                            ])

        self.w_next = v.Btn(
            _metadata={'name': 'next'},
            x_small=True,
            children=[v.Icon(children=['mdi-chevron-right']), 'nxt'])

        self.w_list = v.Select(class_='ma-2',
                               label=self.label,
                               items=self.items,
                               v_model='')

        self.children = [self.w_prev, self.w_list, self.w_next]

        link((self.w_list, 'items'), (self, 'items'))
        link((self.w_list, 'v_model'), (self, 'v_model'))
        self.w_prev.on_event('click', self.prev_next_event)
        self.w_next.on_event('click', self.prev_next_event)
Example #2
0
    def __init__(self):

        self.prev = v.Btn(_metadata={'increm': -1},
                          x_small=True,
                          class_='ml-2 mr-2',
                          color=sc.secondary,
                          children=[
                              v.Icon(children=['mdi-chevron-left']),
                              cm.dynamic_select.prev
                          ])

        self.next = v.Btn(_metadata={'increm': 1},
                          x_small=True,
                          class_='ml-2 mr-2',
                          color=sc.secondary,
                          children=[
                              cm.dynamic_select.next,
                              v.Icon(children=['mdi-chevron-right'])
                          ])

        self.select = v.Select(dense=True,
                               label=cm.dynamic_select.label,
                               v_model=None)

        super().__init__(v_model=None,
                         align_center=True,
                         row=True,
                         class_='ma-1',
                         children=[self.prev, self.select, self.next])

        # js behaviour
        jslink((self, 'v_model'), (self.select, 'v_model'))
        self.prev.on_event('click', self._on_click)
        self.next.on_event('click', self._on_click)
Example #3
0
    def get_items(self):
        """return the list of items inside the folder"""

        list_dir = glob(os.path.join(self.folder, '*/'))

        for extention in self.extentions:
            list_dir.extend(glob(os.path.join(self.folder, '*' + extention)))

        folder_list = []
        file_list = []

        for el in list_dir:
            extention = Path(el).suffix
            if extention == '':
                icon = 'mdi-folder-outline'
                color = 'amber'
            elif extention in ['.csv', '.txt']:
                icon = 'mdi-border-all'
                color = 'green accent-4'
            elif extention in ['.tiff', '.tif']:
                icon = "mdi-image-outline"
                color = "deep-purple"
            else:
                icon = 'mdi-file-outline'
                color = 'light-blue'

            children = [
                v.ListItemAction(
                    children=[v.Icon(color=color, children=[icon])]),
                v.ListItemContent(children=[
                    v.ListItemTitle(children=[Path(el).stem + Path(el).suffix])
                ])
            ]

            if os.path.isdir(el):
                folder_list.append(v.ListItem(value=el, children=children))
            else:
                file_list.append(v.ListItem(value=el, children=children))

        folder_list = sorted(folder_list, key=lambda x: x.value)
        file_list = sorted(file_list, key=lambda x: x.value)

        parent_path = str(Path(self.folder).parent)
        parent_item = v.ListItem(
            value=parent_path,
            children=[
                v.ListItemAction(children=[
                    v.Icon(color='black',
                           children=['mdi-folder-upload-outline'])
                ]),
                v.ListItemContent(
                    children=[v.ListItemTitle(children=[f'..{parent_path}'])])
            ])

        folder_list.extend(file_list)
        folder_list.insert(0, parent_item)

        return folder_list
Example #4
0
 def create_link_button(self, target, text, icon):
     return v.Btn(
         class_="mx-2",
         href=target,
         target="_blank",
         children=[v.Icon(children=[icon]), text],
     )
Example #5
0
    def __init__(self, title='SEPAL module', **kwargs):

        self.toggle_button = v.Btn(icon=True,
                                   children=[
                                       v.Icon(class_="white--text",
                                              children=['mdi-dots-vertical'])
                                   ])

        super().__init__(
            color=sepal_main,
            class_="white--text",
            dense=True,
            app=True,
            children=[self.toggle_button,
                      v.ToolbarTitle(children=[title])],
            **kwargs)

        def setTitle(self, title):
            """set the title in the appbar"""

            self.children = [
                self.toolBarButton,
                v.ToolbarTitle(children=[title])
            ]

            return self
Example #6
0
def AppBar(title='SEPAL module'):
    """
    create an appBar widget with the provided title using the sepal color framework
    
    Returns: 
        app (v.AppBar) : The created appbar
        toolbarButton (v.Btn) : The button to display the side drawer
    """

    toolBarButton = v.Btn(
        icon = True, 
        children=[
            v.Icon(class_="white--text", children=['mdi-dots-vertical'])
        ]
    )
    
    appBar = v.AppBar(
        color=sepal_main,
        class_="white--text",
        dense=True,
        app = True,
        children = [
            toolBarButton, 
            v.ToolbarTitle(children=[title]),
        ]
    )
    
    return (appBar, toolBarButton)
Example #7
0
    def __init__(self, model):
        self.model = model

        self.panels = v.ExpansionPanels(accordion=True, multiple=True, v_model=[])
        up = 'keyboard_arrow_up'
        down = 'keyboard_arrow_down'
        legend_icon = v.Icon(children=[down])
        self.legend_button = v.Btn(icon=True, children=[legend_icon])
        # Style to remove gray background in panels, and remove padding in panel contents
        panel_style = v.Html(tag='style', children=[(
            ".v-application--wrap{background-color: white!important}"
            ".v-expansion-panel-content__wrap{padding:0!important}"
            ".v-input__slot .v-label{color: black!important}"
        )])

        def a(): self.widgets = VBox([self.panels, panel_style], layout=Layout(padding='0px', border='1px solid black', width='400px'))
        def b(): self.accesses = Accesses(model, self.update_selection)
        def c(): self.stats = PlotStats(model)
        def d(): self.tags = Tags(model, self.update_selection, tag_type=TAG_TYPE_SPACETIME)
        def e(): self.threads = Tags(model, self.update_selection, tag_type=TAG_TYPE_THREAD)
        def m(): self.mearsurement = PlotMeasure(model)
        def f(): self.add_panel(LEGEND_MEM_ACCESS_TITLE, self.accesses.widgets)
        def g(): self.add_panel(LEGEND_TAGS_TITLE, self.tags.widgets)
        def h(): self.add_panel(LEGEND_THREADS_TITLE, self.threads.widgets)
        #def i(): self.add_panel(LEGEND_STATS_TITLE, self.stats.widgets)
        def n(): self.add_panel(LEGEND_MEASUREMENT_TITLE, self.mearsurement.widgets)

        self.progress_bar([
            a,
            b,
            c,
            d,
            e,
            m,
            f,
            g,
            h,
            #i,
            n
            ])

        # give accesses nformation about tags and threads for layers



        def update_legend_icon(_panels, _, selected):
            if len(selected) == len(self.panels.children):
                legend_icon.children = [up]
            elif selected == []:
                legend_icon.children = [down]
        self.panels.on_event('change', update_legend_icon)

        def update_panels(*args):
            if legend_icon.children[0] == up:
                legend_icon.children = [down]
                self.panels.v_model = []
            else:
                legend_icon.children = [up]
                self.panels.v_model = list(range(len(self.panels.children)))
        self.legend_button.on_event('click', update_panels)
Example #8
0
    def __init__(self,
                 widget,
                 name="name",
                 header="header",
                 id_="id",
                 **kwargs):

        # default
        self.id = id_
        self.header = header
        self.name = name
        self.class_ = "ma-5"
        self.widget = widget
        self.align_center = True

        # creat a pencil btn
        self.btn = v.Icon(children=["mdi-pencil"], _metadata={"layer": id_})

        # create the row
        super().__init__(**kwargs)

        self.children = [
            v.Flex(align_center=True, xs1=True, children=[self.btn]),
            v.Flex(align_center=True, xs11=True, children=[self.widget]),
        ]

        # js behaviour
        self.widget.observe(self._on_change, "v_model")
Example #9
0
    def _initialize_widgets(self):
        """
        Initialize all widgets to display them
        """

        self.btn = v.Btn(
            color="blue",
            elevation=4,
            style_="width:150px;margin:auto;",
            outlined=True,
            children=[v.Icon(children=["get_app"]), "Save"],
        )

        self.reset = v.Btn(
            color="red",
            elevation=4,
            style_="width:150px;margin:auto;",
            outlined=True,
            children=["Reset"],
        )

        def resetwidgets(widget, event, data):

            clear_output(wait=True)
            self.display()

        self.btn.on_event("click", self.save)

        self.reset.on_event("click", resetwidgets)

        self.title_and_files = TitleAndFiles()
        self.driver = Driver()
        self.model = Model("model")
Example #10
0
def DrawerItem(title, icon=None, card='', href=''):
    """ 
    create a drawer item using the user input
    
    Args:
        title (str): the title to display in the drawer,
        icon (str, optional): the icon id following the mdi code. folder icon if None
        card (str), optional): the tile metadata linked to the drawer
        href(str, optional): the link targeted by the button
    
    Returns:
        item (v.ListItem): the item to display
    """

    if not icon:
        icon = 'mdi-folder-outline'

    item = v.ListItem(
        link=True,
        children=[
            v.ListItemAction(
                children=[v.Icon(class_="white--text", children=[icon])]),
            v.ListItemContent(children=[
                v.ListItemTitle(class_="white--text", children=[title])
            ])
        ])

    if not href == '':
        item.href = href
        item.target = "_blank"

    if not card == '':
        item._metadata = {'card_id': card}

    return item
Example #11
0
    def set_icon(self, icon):

        common_icons = {'default': 'mdi-adjust', 'download': 'mdi-download'}

        if icon in common_icons.keys():
            icon = common_icons[icon]

        return v.Icon(left=True, children=[icon])
Example #12
0
def DownloadBtn(text, path="#"):
    btn = v.Btn(class_='ma-2',
                xs5=True,
                color='success',
                href=utils.create_download_link(path),
                children=[v.Icon(left=True, children=['mdi-download']), text])

    return btn
Example #13
0
    def set_icon(self, icon):

        if self.v_icon:
            self.v_icon.children = [icon]
        else:
            self.v_icon = v.Icon(left=True, children=[icon])
            self.children = [self.v_icon] + self.children

        return self
Example #14
0
    def __init__(self, text, path='#', **kwargs):

        self.class_ = 'ma-2'
        self.xs5 = True
        self.color = 'success'
        self.children = [v.Icon(left=True, children=['mdi-download']), text]
        super().__init__(**kwargs)

        # create the URL
        self.set_url(path)
Example #15
0
    def __init__(self, planet_key, w_state=None, *args, **kwargs):

        self.class_ = 'align-center mb-2'
        self.row = True

        super().__init__(*args, **kwargs)

        self.api_key = ''
        self.valid_planet = False
        self.client = None
        self.planet_key = planet_key

        #         self.w_state = StateBar(done=True) if not w_state else w_state

        self.not_connected = Tooltip(widget=v.Icon(children=['mdi-circle'],
                                                   color='red',
                                                   x_small=True),
                                     tooltip='Not connected to Planet')

        self.connected = Tooltip(widget=v.Icon(children=['mdi-circle'],
                                               color='green',
                                               x_small=True),
                                 tooltip='Connected to Planet')

        self.w_api_key = sw.PasswordField(label='Planet API key',
                                          v_model=self.api_key)
        w_api_btn = sw.Btn(
            'Validate ',
            small=True,
        )

        w_api_key = v.Flex(class_='d-flex align-center mb-2',
                           row=True,
                           children=[self.w_api_key, w_api_btn])

        self.children = [
            self.not_connected,
            w_api_key,
        ]
        # Events
        w_api_btn.on_event('click', self._validate_api_event)
Example #16
0
def ProcessBtn(text="Launch process"):
    """
    create a process button filled with the provided text
    
    Returns: 
        btn (v.Btn) : the btn
    """
    btn = v.Btn(
        color='primary',
        children=[v.Icon(left=True, children=['mdi-map-marker-check']), text])

    return btn
Example #17
0
    def __init__(self, text, path='#', **kwargs):

        #create the url
        if utils.is_absolute(path):
            url = path
        else:
            url = utils.create_download_link(path)

        super().__init__(
            class_='ma-2',
            xs5=True,
            color='success',
            href=url,
            children=[v.Icon(left=True, children=['mdi-download']), text],
            **kwargs)
Example #18
0
def exception_widget(exc):
    """Create an exception notification widget and raises
    sys.exit() silently.

    Parameters:
        exc (Exception): Input exception.

    Raises:
        SilentExit: Exits silently.
    """
    tback = traceback.TracebackException.from_exception(exc).format()
    trace_list = [string for string in tback if 'File' in string]
    if any(trace_list):
        tback = trace_list[-1].split('\n')[0]
    else:
        tback = ''
    exc_type = exc.__class__.__name__
    exc_msg = exc.args[0]

    title = vue.CardTitle(class_='headline body-1 font-weight-medium',
                          primary_title=True,
                          children=[
                              vue.Icon(children=['warning'],
                                       style_='color:#ffffff;'
                                       'margin: 0px 5px'), exc_type
                          ],
                          style_='height:35px;'
                          'background-color:#AA0114;'
                          'color:#ffffff;'
                          'padding: 0px 10px')
    subtitle = vue.CardSubtitle(
        children=[exc_msg],
        class_='text--primary body-1 fontweight-medium',
        style_="margin: 0px 0px; color:#212121")
    children = [title, subtitle]

    if tback:
        text = vue.CardText(children=[tback],
                            class_='font-weight-medium',
                            style_="margin: -15px 0px")
        children.append(text)

    exc_card = vue.Card(
        children=children,
        style_='height: auto; min-height: 100px;',
    )
    display(exc_card)
    raise SilentExit
Example #19
0
    def __init__(self, title='SEPAL module', **kwargs):

        self.toggle_button = v.Btn(icon=True,
                                   children=[
                                       v.Icon(class_="white--text",
                                              children=['mdi-dots-vertical'])
                                   ])

        self.title = v.ToolbarTitle(children=[title])

        super().__init__(color=sepal_main,
                         class_="white--text",
                         dense=True,
                         app=True,
                         children=[self.toggle_button, self.title],
                         **kwargs)
Example #20
0
    def add_element(self, icon, controller):
        link = v.ListItem(
            href="#",
            children=[
                v.ListItemAction(children=[v.Icon(children=[icon])]),
                v.ListItemContent(
                    children=[v.ListItemTitle(children=[controller.name])])
            ])

        def on_click(*change):
            self.trigger("change_view", controller)

        link.on_event("click", on_click)

        self.__elements.append(link)
        self.__controllers.append(controller)
Example #21
0
    def set_icon(self, icon):
        """
        set a new icon
        
        Args:
            icon (str): the full name of a mdi-icon
            
        Return:
            self
        """
        if self.v_icon:
            self.v_icon.children = [icon]
        else:
            self.v_icon = v.Icon(left=True, children=[icon])
            self.children = [self.v_icon] + self.children

        return self
Example #22
0
    def __init__(self, model):
        self.model = model

        self.panels = v.ExpansionPanels(accordion=True,
                                        multiple=True,
                                        v_model=[])
        up = 'keyboard_arrow_up'
        down = 'keyboard_arrow_down'
        legend_icon = v.Icon(children=[down])
        self.legend_button = v.Btn(icon=True, children=[legend_icon])
        # Style to remove gray background in panels, and remove padding in panel contents
        panel_style = v.Html(
            tag='style',
            children=[
                ".v-application--wrap{background-color: white!important} .v-expansion-panel-content__wrap{padding:0!important}"
            ])
        self.widgets = VBox([self.panels, panel_style],
                            layout=Layout(padding='0px',
                                          border='1px solid black',
                                          width='400px'))
        self.accesses = Accesses(model, self.update_selection)
        self.stats = PlotStats(model)
        self.tags = Tags(model, self.update_selection)
        self.add_panel(LEGEND_MEM_ACCESS_TITLE, self.accesses.widgets)
        self.add_panel(LEGEND_TAGS_TITLE, self.tags.widgets)
        self.add_panel(LEGEND_STATS_TITLE, self.stats.widgets)

        def update_legend_icon(_panels, _, selected):
            if len(selected) == len(self.panels.children):
                legend_icon.children = [up]
            elif selected == []:
                legend_icon.children = [down]

        self.panels.on_event('change', update_legend_icon)

        def update_panels(*args):
            if legend_icon.children[0] == up:
                legend_icon.children = [down]
                self.panels.v_model = []
            else:
                legend_icon.children = [up]
                self.panels.v_model = list(range(len(self.panels.children)))

        self.legend_button.on_event('click', update_panels)
Example #23
0
    def __init__(self, *args, **kwargs):
        self.form = self.form_class(*args, **kwargs)

        update_btn = v.Btn(children=['update'], color='success')
        close_btn = v.Btn(children=['close'], color='error')

        self.update_dialog = v.Dialog(
            width='500',
            v_model=False,
            children=[
                v.Card(children=[
                    v.CardTitle(class_='headline gray lighten-2',
                                primary_title=True,
                                children=[self.update_text]),
                    v.CardText(children=[self.form]),
                    v.CardActions(children=[v.Spacer(), update_btn, close_btn])
                ]),
            ])

        update_btn.on_event('click', self.update_click)
        close_btn.on_event('click', self.close_click)

        self.content = v.CardText(children=[f'{self}'])

        self.btn = v.Btn(
            children=[v.Icon(children=['mdi-close'])],
            fab=True,
            color='error',
            dark=True,
            x_small=True,
        )

        super().__init__(children=[
            v.ListItemAction(children=[self.btn]),
            v.ListItemContent(children=[
                v.Card(
                    children=[self.content],
                    flat=True,
                    color='transparent',
                    light=True,
                ), self.update_dialog
            ]),
        ],
                         **kwargs)
Example #24
0
    def __init__(self, title, icon=None, card=None, href=None, **kwargs):

        icon = icon if icon else 'mdi-folder-outline'

        children = [
            v.ListItemAction(
                children=[v.Icon(class_="white--text", children=[icon])]),
            v.ListItemContent(children=[
                v.ListItemTitle(class_="white--text", children=[title])
            ])
        ]

        super().__init__(link=True, children=children, **kwargs)

        if href:
            self.href = href
            self.target = "_blank"
        elif card:
            self._metadata = {'card_id': card}
Example #25
0
    def __init__(self):

        # init the downloadable informations
        self.geometry = None
        self.dataset = None
        self.name = None
        self.aoi_name = None

        # create the useful widgets
        self.w_scale = v.Slider(
            v_model=30,  # align on the landsat images
            min=10,
            max=300,
            thumb_label=True,
            step=10,
        )

        self.w_method = v.RadioGroup(
            v_model="gee",
            row=True,
            children=[
                v.Radio(label=cm.export.radio.sepal, value="sepal"),
                v.Radio(label=cm.export.radio.gee, value="gee"),
            ],
        )

        self.alert = sw.Alert()

        self.btn = sw.Btn(cm.export.apply, small=True)

        export_data = v.Card(children=[
            v.CardTitle(
                children=[v.Html(tag="h4", children=[cm.export.title])]),
            v.CardText(children=[
                v.Html(tag="h4", children=[cm.export.scale]),
                self.w_scale,
                v.Html(tag="h4", children=[cm.export.radio.label]),
                self.w_method,
                self.alert,
            ]),
            v.CardActions(children=[self.btn]),
        ])

        # the clickable icon
        self.download_btn = v.Btn(
            v_on="menu.on",
            color="primary",
            icon=True,
            children=[v.Icon(children=["mdi-cloud-download"])],
        )

        super().__init__(
            value=False,
            close_on_content_click=False,
            nudge_width=200,
            offset_x=True,
            children=[export_data],
            v_slots=[{
                "name": "activator",
                "variable": "menu",
                "children": self.download_btn
            }],
        )

        # add js behaviour
        self.btn.on_event("click", self._apply)
Example #26
0
    def create_tools(self):
        self.tools = []
        tool_actions = []
        self.tool_actions_map = tool_actions_map = {u"pan/zoom": self.panzoom}
        tool_actions.append(u"pan/zoom")

        # self.control_widget.set_title(0, "Main")
        self._main_widget = widgets.VBox()
        self._main_widget_1 = widgets.HBox()
        self._main_widget_2 = widgets.HBox()
        if 1:  # tool_select:
            self.brush = bqplot.interacts.BrushSelector(x_scale=self.scale_x,
                                                        y_scale=self.scale_y,
                                                        color="green")
            tool_actions_map["select"] = self.brush
            tool_actions.append("select")

            self.brush.observe(self.update_brush, ["selected", "selected_x"])
            # fig.interaction = brush
            # callback = self.dataset.signal_selection_changed.connect(lambda dataset: update_image())
            # callback = self.dataset.signal_selection_changed.connect(lambda *x: self.update_grid())

            # def cleanup(callback=callback):
            #    self.dataset.signal_selection_changed.disconnect(callback=callback)
            # self._cleanups.append(cleanup)

            self.button_select_nothing = v.Btn(
                icon=True,
                v_on='tooltip.on',
                children=[v.Icon(children=['delete'])])
            self.widget_select_nothing = v.Tooltip(
                bottom=True,
                v_slots=[{
                    'name': 'activator',
                    'variable': 'tooltip',
                    'children': self.button_select_nothing
                }],
                children=["Delete selection"])
            self.button_reset = widgets.Button(description="", icon="refresh")
            import copy
            self.start_limits = copy.deepcopy(self.limits)

            def reset(*args):
                self.limits = copy.deepcopy(self.start_limits)
                with self.scale_y.hold_trait_notifications():
                    self.scale_y.min, self.scale_y.max = self.limits[1]
                with self.scale_x.hold_trait_notifications():
                    self.scale_x.min, self.scale_x.max = self.limits[0]
                self.plot.update_grid()

            self.button_reset.on_click(reset)

            self.button_select_nothing.on_event(
                'click', lambda *ignore: self.plot.select_nothing())
            self.tools.append(self.button_select_nothing)
            self.modes_names = "replace and or xor subtract".split()
            self.modes_labels = "replace and or xor subtract".split()
            self.button_selection_mode = widgets.Dropdown(
                description='select', options=self.modes_labels)
            self.tools.append(self.button_selection_mode)

            def change_interact(*args):
                with self.output:
                    # print "change", args
                    name = tool_actions[self.button_action.v_model]
                    self.figure.interaction = tool_actions_map[name]

            tool_actions = ["pan/zoom", "select"]
            # tool_actions = [("m", "m"), ("b", "b")]
            self.button_action = \
                v.BtnToggle(v_model=0, mandatory=True, multiple=False, children=[
                                v.Tooltip(bottom=True, v_slots=[{
                                    'name': 'activator',
                                    'variable': 'tooltip',
                                    'children': v.Btn(v_on='tooltip.on', children=[
                                        v.Icon(children=['pan_tool'])
                                    ])
                                }], children=[
                                    "Pan & zoom"
                                ]),
                                v.Tooltip(bottom=True, v_slots=[{
                                    'name': 'activator',
                                    'variable': 'tooltip',
                                    'children': v.Btn(v_on='tooltip.on', children=[
                                        v.Icon(children=['crop_free'])
                                    ])
                                }], children=[
                                    "Square selection"
                                ]),
                        ])
            self.widget_tool_basic = v.Layout(children=[
                v.Layout(
                    pa_1=True,
                    column=False,
                    align_center=True,
                    children=[self.button_action, self.widget_select_nothing])
            ])
            self.plot.add_control_widget(self.widget_tool_basic)

            self.button_action.observe(change_interact, "v_model")
            self.tools.insert(0, self.button_action)
            self.button_action.value = "pan/zoom"  # tool_actions[-1]
            if len(self.tools) == 1:
                tools = []
            # self._main_widget_1.children += (self.button_reset,)
            self._main_widget_1.children += (self.button_action, )
            self._main_widget_1.children += (self.button_select_nothing, )
            # self._main_widget_2.children += (self.button_selection_mode,)
        self._main_widget.children = [self._main_widget_1, self._main_widget_2]
        self.control_widget.children += (self._main_widget, )
        self._update_grid_counter = 0  # keep track of t
        self._update_grid_counter_scheduled = 0  # keep track of t
Example #27
0
    def __init__(self):

        # init the downloadable informations
        self.geometry = None
        self.names = []
        self.datasets = {}

        # create the useful widgets
        self.w_scale = v.Slider(
            class_="mt-5",
            v_model=30,  # align on the landsat images,
            ticks="always",
            tick_labels=[
                str(i) if i in self.TICKS_TO_SHOW else ""
                for i in range(10, 301, 10)
            ],
            min=10,
            max=300,
            thumb_label=True,
            step=10,
        )

        self.w_prefix = v.TextField(
            label=cm.export.name,
            small=True,
            dense=True,
            v_model=None,
        )

        self.w_datasets = v.Select(
            dense=True,
            small=True,
            label=cm.export.datasets,
            v_model=None,
            items=[*self.datasets],
            multiple=True,
            chips=True,
        )

        self.w_method = v.RadioGroup(
            v_model="gee",
            row=True,
            children=[
                v.Radio(label=cm.export.radio.sepal, value="sepal"),
                v.Radio(label=cm.export.radio.gee, value="gee"),
            ],
        )

        self.alert = sw.Alert()

        self.btn = sw.Btn(cm.export.apply, small=True)

        export_data = v.Card(children=[
            v.CardTitle(
                children=[v.Html(tag="h4", children=[cm.export.title])]),
            v.CardText(children=[
                self.w_prefix,
                self.w_datasets,
                v.Html(tag="h4", children=[cm.export.scale]),
                self.w_scale,
                v.Html(tag="h4", children=[cm.export.radio.label]),
                self.w_method,
                self.alert,
            ]),
            v.CardActions(children=[self.btn]),
        ])

        # the clickable icon
        self.w_down = v.Btn(
            v_on="menu.on",
            color="primary",
            icon=True,
            children=[v.Icon(children=["mdi-cloud-download"])],
        )

        super().__init__(
            value=False,
            close_on_content_click=False,
            nudge_width=200,
            offset_x=True,
            children=[export_data],
            v_slots=[{
                "name": "activator",
                "variable": "menu",
                "children": self.w_down
            }],
        )

        # add js behaviour
        self.btn.on_event("click", self._apply)
Example #28
0
    def create_tools(self):
        self.tools = []
        self.tool_actions = []
        tool_actions_map = dict()

        if 1:  # tool_select:
            #### initiaite the 4 types of zoom brushes, which should only highlight axis that are not locked ###
            self.zoom_brush_full = bqplot.interacts.BrushSelector(
                x_scale=self.scale_x, y_scale=self.scale_y, color="blue")
            self.zoom_brush_full.observe(self.update_zoom_brush_full,
                                         ["brushing"])

            self.zoom_brush_vertical = bqplot.interacts.BrushIntervalSelector(
                scale=self.scale_y, orientation='vertical', color="blue")
            self.zoom_brush_vertical.observe(self.update_zoom_brush_vertical,
                                             ["brushing"])

            self.zoom_brush_horizontal = bqplot.interacts.BrushIntervalSelector(
                scale=self.scale_x, orientation='horizontal', color="blue")
            self.zoom_brush_horizontal.observe(
                self.update_zoom_brush_horizontal, ["brushing"])

            self.zoom_brush_none = bqplot.interacts.BrushSelector(
                x_scale=self.scale_x, y_scale=self.scale_y, color="gray")
            self.zoom_brush_none.observe(self.update_zoom_brush_none,
                                         ["brushing"])

            # initiaite measurement tool
            self.ruler = bqplot.interacts.BrushSelector(x_scale=self.scale_x,
                                                        y_scale=self.scale_y,
                                                        color="blue")
            self.ruler.observe(self.measure_selected_area, ["brushing"])
            #### Set the default initial tools ####
            self.zoom_brush = self.zoom_brush_full
            self.click_brush = None  # use regular mouse
            self.click_brush_in = None
            self.click_brush_out = None

            tool_actions_map[ZOOM_SELECT] = self.zoom_brush
            tool_actions_map[PAN_ZOOM] = self.panzoom
            tool_actions_map[CLICK_ZOOM_IN] = self.click_brush_in
            tool_actions_map[CLICK_ZOOM_OUT] = self.click_brush_out
            tool_actions_map[RULER] = self.ruler
            self.tool_actions = [
                PAN_ZOOM, ZOOM_SELECT, CLICK_ZOOM_IN, CLICK_ZOOM_OUT, RULER
            ]

            self.start_limits = copy.deepcopy(self.limits)

            def change_interact(*args):
                with self.output:
                    name = self.tool_actions[self.interaction_tooltips.v_model]
                    self.figure.interaction = tool_actions_map[name]
                    if name == RULER:
                        self.plot.model.legend.openMeasurementPanel()

            self.interaction_tooltips = \
                v.BtnToggle(v_model=0, mandatory=True, multiple=False, children=[
                                v.Tooltip(bottom=True, v_slots=[{
                                    'name': 'activator',
                                    'variable': 'tooltip',
                                    'children': v.Btn(v_on='tooltip.on', children=[
                                        v.Icon(children=['pan_tool'])
                                    ])
                                }], children=[PAN_ZOOM]),
                                v.Tooltip(bottom=True, v_slots=[{
                                    'name': 'activator',
                                    'variable': 'tooltip',
                                    'children': v.Btn(v_on='tooltip.on', children=[
                                        v.Icon(children=['crop'])
                                    ])
                                }], children=[ZOOM_SELECT]),
                                v.Tooltip(bottom=True, v_slots=[{
                                    'name': 'activator',
                                    'variable': 'tooltip',
                                    'children': v.Btn(v_on='tooltip.on', children=[
                                        v.Icon(
                                            children=['mdi-magnify-plus-cursor'])
                                    ])
                                }], children=[CLICK_ZOOM_IN]),
                                v.Tooltip(bottom=True, v_slots=[{
                                    'name': 'activator',
                                    'variable': 'tooltip',
                                                'children': v.Btn(v_on='tooltip.on', children=[
                                                    v.Icon(
                                                        children=['mdi-magnify-minus-cursor'])
                                                ])
                                }], children=[CLICK_ZOOM_OUT]),
                                v.Tooltip(bottom=True, v_slots=[{
                                    'name': 'activator',
                                    'variable': 'tooltip',
                                    'children': v.Btn(v_on='tooltip.on', children=[
                                        v.Icon(children=['mdi-ruler'])
                                    ])
                                }], children=[RULER])      # ruler
                            ])
            self.interaction_tooltips.observe(change_interact, "v_model")

            def reset(*args):
                (x1, x2), (y1, y2) = self.start_limits
                self.zoom_sel(x1, x2, y1, y2, smart_zoom=True)
                with self.zoom_brush.hold_trait_notifications():
                    self.zoom_brush.selected_x = None
                    self.zoom_brush.selected_y = None
                    self.zoom_brush.selected = None

            self.screenshot_btn = v.Btn(
                v_on='tooltip.on',
                icon=True,
                children=[v.Icon(children=['mdi-camera'])])
            self.screenshot_tooltip = v.Tooltip(bottom=True,
                                                v_slots=[{
                                                    'name':
                                                    'activator',
                                                    'variable':
                                                    'tooltip',
                                                    'children':
                                                    self.screenshot_btn
                                                }],
                                                children=[SCREENSHOT])

            @debounced(0.5)
            def screenshot():
                def peer(a):
                    print(type(a).__name__)
                    print(type(a).__module__)
                    print(dir(a))

                #display(self.pil_image_test)
                # print(self.core_image.value)
                #peer(self.figure)
                #self.figure.save_png("test.png")
                #display(IPyImage("test.png"))
                #display(self.core.image)
                clear_output(wait=True)
                self.plot.model.plot.show()
                display(IPyImage(self.core_image.value))

            self.screenshot_btn.on_event('click', lambda *ignore: screenshot())
            self.reset_btn = v.Btn(v_on='tooltip.on',
                                   icon=True,
                                   children=[v.Icon(children=['refresh'])])
            self.reset_btn.on_event('click', lambda *ignore: reset())
            self.reset_tooltip = v.Tooltip(bottom=True,
                                           v_slots=[{
                                               'name': 'activator',
                                               'variable': 'tooltip',
                                               'children': self.reset_btn
                                           }],
                                           children=[RESET_ZOOM])

            self.undo_btn = v.Btn(v_on='tooltip.on',
                                  icon=True,
                                  disabled=True,
                                  children=[v.Icon(children=['undo'])])
            self.undo_tooltip = v.Tooltip(bottom=True,
                                          v_slots=[{
                                              'name': 'activator',
                                              'variable': 'tooltip',
                                              'children': self.undo_btn
                                          }],
                                          children=[UNDO])

            self.redo_btn = v.Btn(v_on='tooltip.on',
                                  icon=True,
                                  disabled=True,
                                  children=[v.Icon(children=['redo'])])
            self.redo_tooltip = v.Tooltip(bottom=True,
                                          v_slots=[{
                                              'name': 'activator',
                                              'variable': 'tooltip',
                                              'children': self.redo_btn
                                          }],
                                          children=[REDO])

            @debounced(0.5)
            def undo_redo(*args):
                self.curr_action = args[0]
                (x1, x2), (y1, y2) = args[1][-1]
                with self.scale_x.hold_trait_notifications():
                    with self.scale_y.hold_trait_notifications():
                        self.scale_x.min, self.scale_x.max = x1, x2
                        self.scale_y.min, self.scale_y.max = y1, y2

            self.undo_btn.on_event(
                'click',
                lambda *ignore: undo_redo(Action.undo, self.undo_actions))
            self.redo_btn.on_event(
                'click',
                lambda *ignore: undo_redo(Action.redo, self.redo_actions))

            control_lyt = widgets.Layout(width='100px')
            self.control_x = widgets.Checkbox(value=False,
                                              description='Lock X Axis',
                                              indent=False,
                                              layout=control_lyt)
            self.control_y = widgets.Checkbox(value=False,
                                              description='Lock Y Axis',
                                              indent=False,
                                              layout=control_lyt)

            def axis_lock_update(checkbox):
                ####### Only allows one checkbox to be locked at a time ######
                if checkbox['owner'].description == self.control_x.description:
                    if self.control_y.value:
                        self.control_y.value = False

                if checkbox['owner'].description == self.control_y.description:
                    if self.control_x.value:
                        self.control_x.value = False
                ##############################################################
                # When a axis checkbox is locked.
                # Updates the panzoom tool to lock eithier the x or y axis.
                # Also updates the zoombrush tool to use relevant zoom brush
                if self.control_x.value:
                    if self.control_y.value:
                        self.panzoom = bqplot.PanZoom()
                        self.zoom_brush = self.zoom_brush_none
                    else:
                        self.panzoom = bqplot.PanZoom(
                            scales={'y': [self.scale_y]})
                        self.zoom_brush = self.zoom_brush_vertical
                else:
                    if self.control_y.value:
                        self.panzoom = bqplot.PanZoom(
                            scales={'x': [self.scale_x]})
                        self.zoom_brush = self.zoom_brush_horizontal
                    else:
                        self.panzoom = bqplot.PanZoom(scales={
                            'x': [self.scale_x],
                            'y': [self.scale_y]
                        })
                        self.zoom_brush = self.zoom_brush_full

                tool_actions_map[PAN_ZOOM] = self.panzoom
                tool_actions_map[ZOOM_SELECT] = self.zoom_brush

                # Update immediately if in PAN_ZOOM mode
                name = self.tool_actions[self.interaction_tooltips.v_model]
                if name == PAN_ZOOM:
                    self.figure.interaction = self.panzoom
                elif name == ZOOM_SELECT:
                    self.figure.interaction = self.zoom_brush

            self.control_x.observe(axis_lock_update)
            self.control_y.observe(axis_lock_update)
            self.axis_controls = widgets.VBox([self.control_x, self.control_y])

            self.tooltips = v.Row(children=[
                self.axis_controls, self.interaction_tooltips,
                self.reset_tooltip, self.undo_tooltip, self.redo_tooltip,
                self.screenshot_tooltip
            ],
                                  align='center',
                                  justify='center')
            self.plot.add_to_toolbar(self.tooltips)
Example #29
0
    def play(self):

        #labels = widgets.HBox([widgets.Label(value="Option"), widgets.Label(value="Topics")])
        #options = widgets.SelectMultiple(options=['--clock', '--loop', '--keep-alive', '--wait-for-subscribers'])
        #topics = widgets.SelectMultiple(options=self.topics.keys(), value=self.topics.keys())

        options = [
            vue.Checkbox(label='--clock',
                         value='--clock',
                         v_model=None,
                         class_='mx-0 px-0'),
            vue.Checkbox(label='--loop',
                         value='--loop',
                         v_model=None,
                         class_='mx-0 px-0'),
            vue.Checkbox(label='--keep-alive',
                         value='--keep-alive',
                         v_model=None,
                         class_='mx-0 px-0'),
            vue.Checkbox(label='--wait-for-subscribers',
                         value='--wait-for-subscribers',
                         v_model=None,
                         class_='mx-0 px-0')
        ]

        topics = [
            vue.Checkbox(label=t, value=t, v_model=t, class_='mx-0 px-0')
            for t in self.topics.keys()
        ]

        config = vue.Html(tag='div',
                          class_='d-flex flex-row',
                          children=[
                              vue.Html(tag='div',
                                       class_='d-flex flex-column',
                                       children=[
                                           vue.Html(tag='h3',
                                                    children=['Options']),
                                           vue.Container(children=options)
                                       ]),
                              vue.Html(tag='div',
                                       class_='d-flex flex-column',
                                       children=[
                                           vue.Html(tag='h3',
                                                    children=['Topics']),
                                           vue.Container(children=topics)
                                       ]),
                          ])

        #config = widgets.HBox([options, topics])

        #btn_init = widgets.Button(description="Initialize", button_style='warning')
        #btn_play = widgets.Button(description="Play", icon='play', button_style='success')
        #btn_pause = widgets.Button(description="Pause", icon='pause', disabled=True)
        #btn_step = widgets.Button(description="Step", icon='step-forward')
        #btn_stop = widgets.Button(description="Stop", icon='stop', button_style='danger', disabled=True)

        btn_init = vue.Btn(color='warning',
                           children=['Initialize'],
                           class_='mx-2')
        btn_play = vue.Btn(
            color='success',
            disabled=True,
            children=[vue.Icon(left=True, children=['play']), 'Play'],
            class_='mx-2')
        btn_pause = vue.Btn(
            color='primary',
            disabled=True,
            children=[vue.Icon(left=True, children=['pause']), 'Pause'],
            class_='mx-2')
        btn_step = vue.Btn(
            color='primary',
            disabled=True,
            children=[vue.Icon(left=True, children=['step-forward']), 'Step'],
            class_='mx-2')
        btn_stop = vue.Btn(
            color='error',
            disabled=True,
            children=[vue.Icon(left=True, children=['stop']), 'Stop'],
            class_='mx-2')

        #output = widgets.widgets.Text()
        output = vue.TextField(label='Output')

        def btn_init_on_click(widget, event, data):
            btn_init.disabled = True
            btn_play.disabled = False
            btn_pause.disabled = False
            btn_step.disabled = True
            btn_stop.disabled = False

            opt = [o.value for o in options if o.v_model != None]
            top = [t.value for t in topics if t.v_model != None]

            command = ' '.join(['rosbag', 'play', '--pause'] + list(opt) +
                               ['--topics'] + [' '.join(top)] +
                               ['--bags=' + self.bag.filename])
            self.cmd = Command(command, output)
            self.cmd.start()

        def btn_play_on_click(widget, event, data):
            btn_init.disabled = True
            btn_play.disabled = True
            btn_pause.disabled = False
            btn_step.disabled = True
            btn_stop.disabled = False

            if self.cmd != None:
                print("cmd.play")
                self.cmd.play()
            else:
                output.value = "You should initialize the command."

        def btn_pause_on_click(widget, event, data):
            btn_init.disabled = True
            btn_play.disabled = False
            btn_pause.disabled = True
            btn_step.disabled = False
            btn_stop.disabled = False

            if self.cmd != None:
                self.cmd.pause()
            else:
                output.value = "You should initialize the command."

        def btn_step_on_click(widget, event, data):
            btn_init.disabled = True
            btn_play.disabled = False
            btn_pause.disabled = True
            btn_step.disabled = False
            btn_stop.disabled = False

            if self.cmd != None:
                self.cmd.step()
            else:
                output.value = "You should initialize the command."

        def btn_stop_on_click(widget, event, data):
            btn_init.disabled = False
            btn_play.disabled = True
            btn_pause.disabled = True
            btn_step.disabled = True
            btn_stop.disabled = True

            if self.cmd != None:
                self.cmd.stop()
            else:
                output.value = "You should initialize the command."

        #btn_init.on_click(btn_init_on_click)
        #btn_play.on_click(btn_play_on_click)
        #btn_pause.on_click(btn_pause_on_click)
        #btn_step.on_click(btn_step_on_click)
        #btn_stop.on_click(btn_stop_on_click)

        btn_init.on_event('click', btn_init_on_click)
        btn_play.on_event('click', btn_play_on_click)
        btn_pause.on_event('click', btn_pause_on_click)
        btn_step.on_event('click', btn_step_on_click)
        btn_stop.on_event('click', btn_stop_on_click)

        #btns = widgets.VBox([widgets.HBox([btn_init, btn_play, btn_pause, btn_step, btn_stop]), output])

        btns = vue.Html(
            tag='div',
            class_='d-flex flex-row',
            children=[btn_init, btn_play, btn_pause, btn_step, btn_stop])

        #display( widgets.VBox([labels, config, btns]) )
        display(vue.Container(children=[config, btns, output]))
Example #30
0
    def get_items(self):
        """return the list of items inside the folder"""

        self.loading.indeterminate = not self.loading.indeterminate

        folder = Path(self.folder)

        list_dir = [
            el for el in folder.glob('*/') if not el.name.startswith('.')
        ]

        if self.extentions:
            list_dir = [
                el for el in list_dir
                if el.is_dir() or el.suffix in self.extentions
            ]

        folder_list = []
        file_list = []

        for el in list_dir:

            if el.suffix in ICON_TYPES.keys():
                icon = ICON_TYPES[el.suffix]['icon']
                color = ICON_TYPES[el.suffix]['color']
            else:
                icon = ICON_TYPES['DEFAULT']['icon']
                color = ICON_TYPES['DEFAULT']['color']

            children = [
                v.ListItemAction(
                    children=[v.Icon(color=color, children=[icon])]),
                v.ListItemContent(
                    children=[v.ListItemTitle(children=[el.stem +
                                                        el.suffix])]),
            ]

            if el.is_dir():
                folder_list.append(v.ListItem(value=str(el),
                                              children=children))
            else:
                file_size = str(
                    round(Path(el).stat().st_size / (1024 * 1024), 2)) + ' MB'
                children.append(v.ListItemActionText(children=[file_size]))
                file_list.append(v.ListItem(value=str(el), children=children))

        folder_list = sorted(folder_list, key=lambda x: x.value)
        file_list = sorted(file_list, key=lambda x: x.value)

        parent_path = str(folder.parent)
        parent_item = v.ListItem(
            value=parent_path,
            children=[
                v.ListItemAction(children=[
                    v.Icon(color=ICON_TYPES['PARENT']['color'],
                           children=[ICON_TYPES['PARENT']['icon']])
                ]),
                v.ListItemContent(
                    children=[v.ListItemTitle(children=[f'..{parent_path}'])]),
            ])

        folder_list.extend(file_list)
        folder_list.insert(0, parent_item)

        self.loading.indeterminate = not self.loading.indeterminate
        return folder_list