Beispiel #1
0
    def __init__(self):
        self.__config_file = None

        # the active video sources (hardware sources). this list is updated when a video camera device is registered or
        # unregistered with the hardware source manager.
        self.video_sources = ListModel.ListModel()

        # the list of instances of video cameras. this is similar to the video sources but is the devices plus settings
        # for the device. some devices might not have instances if the factory to create the instance hasn't been
        # registered yet.
        self.__instances = list()

        # the list of video device factories. this is populated by responding to the registry messages.
        self.__video_device_factories = list()

        def component_registered(component, component_types):
            if "video_device_factory" in component_types:
                if not component in self.__video_device_factories:
                    self.__video_device_factories.append(component)
                self.__make_video_devices()

        def component_unregistered(component, component_types):
            if "video_device_factory" in component_types:
                if component in self.__video_device_factories:
                    self.__video_device_factories.remove(component)

        self.__component_registered_listener = Registry.listen_component_registered_event(
            component_registered)
        self.__component_unregistered_listener = Registry.listen_component_unregistered_event(
            component_unregistered)

        for component in Registry.get_components_by_type(
                "video_device_factory"):
            component_registered(component, {"video_device_factory"})
def run():
    def component_registered(component, component_types):
        if "camera_device" in component_types:
            stem_controller_id = getattr(component, "stem_controller_id",
                                         "autostem_controller")
            camera_hardware_source = CameraHardwareSource(
                stem_controller_id, component)
            HardwareSource.HardwareSourceManager().register_hardware_source(
                camera_hardware_source)

    def component_unregistered(component, component_types):
        if "camera_device" in component_types:
            HardwareSource.HardwareSourceManager().unregister_hardware_source(
                component)

    global _component_registered_listener
    global _component_unregistered_listener

    _component_registered_listener = Registry.listen_component_registered_event(
        component_registered)
    _component_unregistered_listener = Registry.listen_component_unregistered_event(
        component_unregistered)

    for component in Registry.get_components_by_type("camera_device"):
        component_registered(component, {"camera_device"})
Beispiel #3
0
def run():
    def component_registered(component, component_types):
        if "video_device" in component_types:
            hardware_source = VideoHardwareSource(component)
            HardwareSource.HardwareSourceManager().register_hardware_source(
                hardware_source)
            video_configuration.video_sources.append_item(hardware_source)

    def component_unregistered(component, component_types):
        if "video_device" in component_types:
            for hardware_source in HardwareSource.HardwareSourceManager(
            ).hardware_sources:
                if getattr(hardware_source, "video_device",
                           None) and hardware_source.video_device == component:
                    video_configuration.video_sources.remove_item(
                        video_configuration.video_sources.items.index(
                            hardware_source))
                    video_configuration._remove_video_device(component)
                    HardwareSource.HardwareSourceManager(
                    ).unregister_hardware_source(hardware_source)

    global _component_registered_listener
    global _component_unregistered_listener

    _component_registered_listener = Registry.listen_component_registered_event(
        component_registered)
    _component_unregistered_listener = Registry.listen_component_unregistered_event(
        component_unregistered)

    for component in Registry.get_components_by_type("video_device"):
        component_registered(component, {"video_device"})
def run():
    def component_registered(component, component_types):
        if "camera_device" in component_types:
            stem_controller_id = getattr(component, "stem_controller_id",
                                         "autostem_controller")
            camera_hardware_source = CameraHardwareSource(
                stem_controller_id, component)
            if hasattr(component, "priority"):
                camera_hardware_source.priority = component.priority
            component_types = {
                "hardware_source", "camera_hardware_source"
            }.union({component.camera_type + "_camera_hardware_source"})
            Registry.register_component(camera_hardware_source,
                                        component_types)
            HardwareSource.HardwareSourceManager().register_hardware_source(
                camera_hardware_source)
            component.hardware_source = camera_hardware_source

    def component_unregistered(component, component_types):
        if "camera_device" in component_types:
            camera_hardware_source = component.hardware_source
            Registry.unregister_component(camera_hardware_source)
            HardwareSource.HardwareSourceManager().unregister_hardware_source(
                camera_hardware_source)

    global _component_registered_listener
    global _component_unregistered_listener

    _component_registered_listener = Registry.listen_component_registered_event(
        component_registered)
    _component_unregistered_listener = Registry.listen_component_unregistered_event(
        component_unregistered)

    for component in Registry.get_components_by_type("camera_device"):
        component_registered(component, {"camera_device"})
def run():
    def component_registered(component, component_types):
        if "scan_device" in component_types:
            stem_controller = HardwareSource.HardwareSourceManager(
            ).get_instrument_by_id(component.stem_controller_id)
            if not stem_controller:
                print("STEM Controller (" + component.stem_controller_id +
                      ") for (" + component.scan_device_id +
                      ") not found. Using proxy.")
                from nion.instrumentation import stem_controller
                stem_controller = stem_controller.STEMController()
            scan_hardware_source = ScanHardwareSource(
                stem_controller, component, component.scan_device_id,
                component.scan_device_name)
            HardwareSource.HardwareSourceManager().register_hardware_source(
                scan_hardware_source)

    def component_unregistered(component, component_types):
        if "scan_device" in component_types:
            HardwareSource.HardwareSourceManager().unregister_hardware_source(
                component)

    global _component_registered_listener
    global _component_unregistered_listener

    _component_registered_listener = Registry.listen_component_registered_event(
        component_registered)
    _component_unregistered_listener = Registry.listen_component_unregistered_event(
        component_unregistered)

    for component in Registry.get_components_by_type("scan_device"):
        component_registered(component, {"scan_device"})
Beispiel #6
0
 def execute(self, spectrum_image_data_item: Facade.DataItem,
             background_model, fit_interval_graphics):
     try:
         assert spectrum_image_data_item.xdata.is_datum_1d
         assert spectrum_image_data_item.xdata.is_navigable
         assert spectrum_image_data_item.xdata.datum_dimensional_calibrations[
             0].units == "eV"
         spectrum_image_xdata = spectrum_image_data_item.xdata
         # fit_interval_graphics.interval returns normalized coordinates. create calibrated intervals.
         fit_intervals: typing.List[
             BackgroundModel.BackgroundInterval] = list()
         for fit_interval_graphic in fit_interval_graphics:
             fit_intervals.append(fit_interval_graphic.interval)
         subtracted_xdata = None
         if background_model._data_structure.entity:
             entity_id = background_model._data_structure.entity.entity_type.entity_id
             for component in Registry.get_components_by_type(
                     "background-model"):
                 if entity_id == component.background_model_id:
                     integrate_result = component.subtract_background(
                         spectrum_xdata=spectrum_image_xdata,
                         fit_intervals=fit_intervals)
                     subtracted_xdata = integrate_result["subtracted"]
         if subtracted_xdata is None:
             subtracted_xdata = DataAndMetadata.new_data_and_metadata(
                 numpy.zeros(
                     spectrum_image_xdata.navigation_dimension_shape),
                 dimensional_calibrations=spectrum_image_xdata.
                 navigation_dimensional_calibrations)
         self.__subtracted_xdata = subtracted_xdata
     except Exception as e:
         import traceback
         print(traceback.format_exc())
         print(e)
         raise
Beispiel #7
0
    def __init__(self, document_controller: DocumentController.DocumentController, panel_id: str, properties: Persistence.PersistentDictType) -> None:
        super().__init__(document_controller, panel_id, _("Toolbar"))

        self.__component_registered_listener = Registry.listen_component_registered_event(self.__component_registered)

        self.widget = self.ui.create_column_widget()

        # note: "maximum" here means the size hint is maximum and the widget can be smaller. Qt layout is atrocious.
        self.__toolbar_widget_row = self.ui.create_row_widget(properties={"size-policy-horizontal": "maximum"})

        toolbar_row_widget = self.ui.create_row_widget()
        toolbar_row_widget.add(self.__toolbar_widget_row)
        toolbar_row_widget.add_stretch()

        self.widget.add(toolbar_row_widget)

        # make a map from widget_id to widget factory.
        widget_factories = dict()
        for component in Registry.get_components_by_type("toolbar-widget"):
            widget_factories[component.toolbar_widget_id] = component

        # define the order of widgets.
        # this part is hard coded for now; needs some work to make it dynamically order widgets as they become
        # available from packages.
        widget_id_list = [
            "nion.swift.toolbar-widget.tool-mode",
            "nion.swift.toolbar-widget.raster-zoom",
            "nion.swift.toolbar-widget.workspace"
        ]

        # add the widgets.
        for widget_id in widget_id_list:
            widget_factory = widget_factories[widget_id]
            widget_handler = widget_factory(document_controller=self.document_controller)
            widget = Declarative.DeclarativeWidget(self.ui, self.document_controller.event_loop, widget_handler)
            widget_section = self.ui.create_row_widget()
            widget_section.add(widget)
            section_bar = self.ui.create_canvas_widget(properties={"width": 9, "size_policy_vertical": "expanding"})

            def draw(drawing_context: DrawingContext.DrawingContext, canvas_size: Geometry.IntSize, *args: typing.Any, **kwargs: typing.Any) -> None:
                with drawing_context.saver():
                    drawing_context.rect(0, 0, canvas_size.width, canvas_size.height)
                    drawing_context.fill_style = "#DDD"
                    drawing_context.stroke_style = "#AAA"
                    drawing_context.fill()
                    drawing_context.stroke()

            section_bar.canvas_item.add_canvas_item(CanvasItem.DrawCanvasItem(draw))
            self.__toolbar_widget_row.add(section_bar)
            self.__toolbar_widget_row.add_spacing(8)
            self.__toolbar_widget_row.add(widget_section)
            self.__toolbar_widget_row.add_spacing(8)

        end_divider = self.ui.create_canvas_widget(properties={"width": 1, "size_policy_vertical": "expanding"})
        end_divider.canvas_item.add_canvas_item(CanvasItem.DividerCanvasItem(color="#888"))
        self.__toolbar_widget_row.add(end_divider)
Beispiel #8
0
 def execute(self, eels_spectrum_data_item, background_model,
             fit_interval_graphics, **kwargs) -> None:
     try:
         spectrum_xdata = eels_spectrum_data_item.xdata
         assert spectrum_xdata.is_datum_1d
         assert spectrum_xdata.datum_dimensional_calibrations[
             0].units == "eV"
         eels_spectrum_xdata = spectrum_xdata
         # fit_interval_graphics.interval returns normalized coordinates. create calibrated intervals.
         fit_intervals: typing.List[
             BackgroundModel.BackgroundInterval] = list()
         for fit_interval_graphic in fit_interval_graphics:
             fit_intervals.append(fit_interval_graphic.interval)
         fit_minimum = min(
             [fit_interval[0] for fit_interval in fit_intervals])
         signal_interval = fit_minimum, 1.0
         signal_xdata = BackgroundModel.get_calibrated_interval_slice(
             eels_spectrum_xdata, signal_interval)
         background_xdata = None
         subtracted_xdata = None
         if background_model._data_structure.entity:
             entity_id = background_model._data_structure.entity.entity_type.entity_id
             for component in Registry.get_components_by_type(
                     "background-model"):
                 if entity_id == component.background_model_id:
                     fit_result = component.fit_background(
                         spectrum_xdata=spectrum_xdata,
                         fit_intervals=fit_intervals,
                         background_interval=signal_interval)
                     background_xdata = fit_result["background_model"]
                     # use 'or' to avoid doing subtraction if subtracted_spectrum already present
                     subtracted_xdata = fit_result.get(
                         "subtracted_spectrum",
                         None) or Core.calibrated_subtract_spectrum(
                             spectrum_xdata, background_xdata)
         if background_xdata is None:
             background_xdata = DataAndMetadata.new_data_and_metadata(
                 numpy.zeros_like(signal_xdata.data),
                 intensity_calibration=signal_xdata.intensity_calibration,
                 dimensional_calibrations=signal_xdata.
                 dimensional_calibrations)
         if subtracted_xdata is None:
             subtracted_xdata = DataAndMetadata.new_data_and_metadata(
                 signal_xdata.data,
                 intensity_calibration=signal_xdata.intensity_calibration,
                 dimensional_calibrations=signal_xdata.
                 dimensional_calibrations)
         self.__background_xdata = background_xdata
         self.__subtracted_xdata = subtracted_xdata
     except Exception as e:
         import traceback
         print(traceback.format_exc())
         print(e)
         raise
Beispiel #9
0
 def execute(self, spectrum_image_data_item: Facade.DataItem,
             background_model, fit_interval_graphics,
             signal_interval_graphic):
     try:
         assert spectrum_image_data_item.xdata.is_datum_1d
         assert spectrum_image_data_item.xdata.is_navigable
         assert spectrum_image_data_item.xdata.datum_dimensional_calibrations[
             0].units == "eV"
         spectrum_image_xdata = spectrum_image_data_item.xdata
         # fit_interval_graphics.interval returns normalized coordinates. create calibrated intervals.
         fit_intervals = list()
         for fit_interval_graphic in fit_interval_graphics:
             fit_interval = Calibration.CalibratedInterval(
                 Calibration.Coordinate(
                     Calibration.CoordinateType.NORMALIZED,
                     fit_interval_graphic.interval[0]),
                 Calibration.Coordinate(
                     Calibration.CoordinateType.NORMALIZED,
                     fit_interval_graphic.interval[1]))
             fit_intervals.append(fit_interval)
         signal_interval = Calibration.CalibratedInterval(
             Calibration.Coordinate(Calibration.CoordinateType.NORMALIZED,
                                    signal_interval_graphic.interval[0]),
             Calibration.Coordinate(Calibration.CoordinateType.NORMALIZED,
                                    signal_interval_graphic.interval[1]))
         mapped_xdata = None
         if background_model._data_structure.entity:
             entity_id = background_model._data_structure.entity.entity_type.entity_id
             for component in Registry.get_components_by_type(
                     "background-model"):
                 if entity_id == component.background_model_id:
                     # import time
                     # t0 = time.perf_counter()
                     integrate_result = component.integrate_signal(
                         spectrum_xdata=spectrum_image_xdata,
                         fit_intervals=fit_intervals,
                         signal_interval=signal_interval)
                     # t1 = time.perf_counter()
                     # print(f"{component.background_model_id} {((t1 - t0) * 1000)}ms")
                     mapped_xdata = integrate_result["integrated"]
         if mapped_xdata is None:
             mapped_xdata = DataAndMetadata.new_data_and_metadata(
                 numpy.zeros(
                     spectrum_image_xdata.navigation_dimension_shape),
                 dimensional_calibrations=spectrum_image_xdata.
                 navigation_dimensional_calibrations)
         self.__mapped_xdata = mapped_xdata
     except Exception as e:
         import traceback
         print(traceback.format_exc())
         print(e)
         raise
Beispiel #10
0
 def create_handler(self, component_id: str, container: typing.Any = None, item: typing.Any = None, **kwargs: typing.Any) -> typing.Optional[Declarative.HandlerLike]:
     # this is called to construct contained declarative component handlers within this handler.
     if component_id == "notification":
         assert container is not None
         assert item is not None
         notification = typing.cast(Notification.Notification, item)
         for component in Registry.get_components_by_type("notification-component-factory"):
             notification_handler = typing.cast(NotificationComponentFactory, component)
             notification_component = notification_handler.make_component(notification)
             if notification_component:
                 return notification_component
         return NotificationHandler(notification)
     return None
 def __init__(self,
              document_controller: DocumentController.DocumentController,
              panel_id: str, properties: dict):
     super().__init__(document_controller, panel_id, 'libertem-panel')
     panel_type = properties.get('panel_type')
     for component in Registry.get_components_by_type('libertem-panel'):
         if component.panel_type == panel_type:
             ui_handler = component.get_ui_handler(
                 api_broker=PlugInManager.APIBroker(),
                 event_loop=document_controller.event_loop)
             self.widget = Declarative.DeclarativeWidget(
                 document_controller.ui, document_controller.event_loop,
                 ui_handler)
Beispiel #12
0
 def data_changed():
     current_xdata = self.__data_item.xdata
     if current_xdata and not current_xdata.is_sequence:
         # allow registered metadata_display components to populate a dictionary
         # the recorder will look at 'valid_rows'
         d = dict()
         for component in Registry.get_components_by_type("metadata_display"):
             component.populate(d, current_xdata.metadata)
         # grab valid_rows to determine if frame is incomplete
         valid_rows = d.get("valid_rows", 0) if "valid_rows" in d else current_xdata.data_shape[0]
         if len(current_xdata.data_shape) == 1 or valid_rows >= current_xdata.data_shape[0]:
             self.__last_complete_xdata = current_xdata
     else:
         self.__recording_error = True
Beispiel #13
0
 def execute(self, eels_spectrum_data_item, zlp_model, **kwargs) -> None:
     try:
         spectrum_xdata = eels_spectrum_data_item.xdata
         assert spectrum_xdata.is_datum_1d
         assert spectrum_xdata.datum_dimensional_calibrations[
             0].units == "eV"
         eels_spectrum_xdata = spectrum_xdata
         model_xdata = None
         subtracted_xdata = None
         if zlp_model._data_structure.entity:
             entity_id = zlp_model._data_structure.entity.entity_type.entity_id
             for component in Registry.get_components_by_type("zlp-model"):
                 # print(f"{entity_id=} {component.zero_loss_peak_model_id=}")
                 if entity_id == component.zero_loss_peak_model_id:
                     fit_result = component.fit_zero_loss_peak(
                         spectrum_xdata=spectrum_xdata)
                     model_xdata = fit_result["zero_loss_peak_model"]
                     # use 'or' to avoid doing subtraction if subtracted_spectrum already present
                     subtracted_xdata = fit_result.get(
                         "subtracted_spectrum",
                         None) or Core.calibrated_subtract_spectrum(
                             spectrum_xdata, model_xdata)
         if model_xdata is None:
             model_xdata = DataAndMetadata.new_data_and_metadata(
                 numpy.zeros_like(eels_spectrum_xdata.data),
                 intensity_calibration=eels_spectrum_xdata.
                 intensity_calibration,
                 dimensional_calibrations=eels_spectrum_xdata.
                 dimensional_calibrations)
         if subtracted_xdata is None:
             subtracted_xdata = DataAndMetadata.new_data_and_metadata(
                 eels_spectrum_xdata.data,
                 intensity_calibration=eels_spectrum_xdata.
                 intensity_calibration,
                 dimensional_calibrations=eels_spectrum_xdata.
                 dimensional_calibrations)
         self.__model_xdata = model_xdata
         self.__subtracted_xdata = subtracted_xdata
     except Exception as e:
         import traceback
         print(traceback.format_exc())
         print(e)
         raise
def run(configuration_location: pathlib.Path):
    def component_registered(component, component_types):
        if "camera_module" in component_types:
            camera_module = component
            stem_controller_id = getattr(camera_module, "stem_controller_id",
                                         "autostem_controller")
            camera_settings = camera_module.camera_settings
            camera_device = camera_module.camera_device
            camera_panel_type = getattr(camera_module, "camera_panel_type",
                                        None)
            camera_hardware_source = CameraHardwareSource(
                stem_controller_id, camera_device, camera_settings,
                configuration_location, camera_panel_type)
            if hasattr(camera_module, "priority"):
                camera_hardware_source.priority = camera_module.priority
            component_types = {
                "hardware_source", "camera_hardware_source"
            }.union({camera_device.camera_type + "_camera_hardware_source"})
            Registry.register_component(camera_hardware_source,
                                        component_types)
            HardwareSource.HardwareSourceManager().register_hardware_source(
                camera_hardware_source)
            camera_module.hardware_source = camera_hardware_source

    def component_unregistered(component, component_types):
        if "camera_module" in component_types:
            camera_hardware_source = component.hardware_source
            Registry.unregister_component(camera_hardware_source)
            HardwareSource.HardwareSourceManager().unregister_hardware_source(
                camera_hardware_source)

    global _component_registered_listener
    global _component_unregistered_listener

    _component_registered_listener = Registry.listen_component_registered_event(
        component_registered)
    _component_unregistered_listener = Registry.listen_component_unregistered_event(
        component_unregistered)

    for component in Registry.get_components_by_type("camera_module"):
        component_registered(component, {"camera_module"})
Beispiel #15
0
 def create_handler(
         self,
         component_id: str,
         container: typing.Any = None,
         item: typing.Any = None,
         **kwargs: typing.Any) -> typing.Optional[Declarative.HandlerLike]:
     # this is called to construct contained declarative component handlers within this handler.
     if component_id == "activity":
         assert container is not None
         assert item is not None
         activity = typing.cast(Activity.Activity, item)
         for component in Registry.get_components_by_type(
                 "activity-component-factory"):
             activity_handler = typing.cast(ActivityComponentFactory,
                                            component)
             activity_component = activity_handler.make_activity_component(
                 activity)
             if activity_component:
                 return activity_component
         return ActivityHandler(activity)
     return None
Beispiel #16
0
    target_data_item = window.target_data_item
    target_display_item = window.target_display
    if target_data_item:
        add_peak_fitting_computation(api, window.library, target_display_item,
                                     target_data_item)


Symbolic.register_computation_type("eels.fit_zlp", FitZeroLossPeak)

ZeroLossPeakModel = Schema.entity("zlp_model", None, None, {})


def component_registered(component, component_types):
    if "zlp-model" in component_types:
        # when a background model is registered, create an empty (for now) entity type, and register it with the data
        # structure so that an entity for use with the UI and computations can be created when the data structure loads.
        zlp_model_entity = Schema.entity(component.zero_loss_peak_model_id,
                                         ZeroLossPeakModel, None, {})
        DataStructure.DataStructure.register_entity(
            zlp_model_entity,
            entity_name=component.title,
            entity_package_name=component.package_title)


_component_registered_listener = Registry.listen_component_registered_event(
    component_registered)

# handle any components that have already been registered.
for component in Registry.get_components_by_type("zlp-model"):
    component_registered(component, {"zlp-model"})
Beispiel #17
0
def subtract_background_from_signal(api, window):
    window._document_controller.event_loop.create_task(
        use_interval_as_background(api, window))


Symbolic.register_computation_type("eels.background_subtraction3",
                                   EELSBackgroundSubtraction)
Symbolic.register_computation_type("eels.mapping3", EELSMapping)

BackgroundModel = Schema.entity("background_model", None, None, {})


def component_registered(component, component_types):
    if "background-model" in component_types:
        # when a background model is registered, create an empty (for now) entity type, and register it with the data
        # structure so that an entity for use with the UI and computations can be created when the data structure loads.
        background_model_entity = Schema.entity(component.background_model_id,
                                                BackgroundModel, None, {})
        DataStructure.DataStructure.register_entity(
            background_model_entity,
            entity_name=component.title,
            entity_package_name=component.package_title)


_component_registered_listener = Registry.listen_component_registered_event(
    component_registered)

# handle any components that have already been registered.
for component in Registry.get_components_by_type("background-model"):
    component_registered(component, {"background-model"})
Beispiel #18
0
 def update_camera_list(self):
     cameras = list(
         Registry.get_components_by_type('camera_hardware_source'))
     self.camera_choice_combo_box.items = cameras
     self.update_current_camera()
    def build(self, ui: UserInterface.UserInterface,
              event_loop: asyncio.AbstractEventLoop,
              **kwargs: typing.Any) -> Declarative.DeclarativeWidget:
        u = Declarative.DeclarativeUI()

        video_device_factories: typing.List[
            video_base.VideoDeviceFactoryLike] = list(
                Registry.get_components_by_type("video_device_factory"))

        class Handler(Declarative.HandlerLike):
            def __init__(
                self, ui_view: Declarative.UIDescription,
                video_sources: ListModel.ListModel[
                    video_base.VideoHardwareSource]
            ) -> None:
                self.ui_view = ui_view
                self.video_sources = video_sources
                self.video_source_type_index = Model.PropertyModel(0)

            def close(self) -> None:
                pass

            def create_new_video_device(self,
                                        widget: UserInterface.Widget) -> None:
                video_base.video_configuration.create_hardware_source(
                    video_device_factories[self.video_source_type_index.value
                                           or 0])

            def create_handler(
                self,
                component_id: str,
                container: typing.Any = None,
                item: typing.Any = None,
                **kwargs: typing.Any
            ) -> typing.Optional[Declarative.HandlerLike]:
                class SectionHandler:
                    def __init__(
                        self, container: typing.Any,
                        hardware_source: video_base.VideoHardwareSource
                    ) -> None:
                        self.container = container
                        self.hardware_source = hardware_source
                        self.settings = video_base.video_configuration.get_settings_model(
                            hardware_source)
                        self.settings_original = copy.deepcopy(self.settings)
                        self.needs_saving_model = Model.PropertyModel(False)
                        self.property_changed_event = Event.Event()
                        # these will be assigned by declarative setup
                        self.apply_button: typing.Optional[
                            UserInterface.PushButtonWidget] = None
                        self.revert_button: typing.Optional[
                            UserInterface.PushButtonWidget] = None

                        def settings_changed(property_name: str) -> None:
                            self.needs_saving_model.value = True

                        self.__settings_changed_event_listener = self.settings.property_changed_event.listen(
                            settings_changed) if self.settings else None

                        def needs_saving_model_changed(
                                property_name: str) -> None:
                            if self.apply_button:
                                self.apply_button.enabled = self.needs_saving_model.value or False
                            if self.revert_button:
                                self.revert_button.enabled = self.needs_saving_model.value or False

                        self.__needs_saving_changed_event_listener = self.needs_saving_model.property_changed_event.listen(
                            needs_saving_model_changed)

                    def close(self) -> None:
                        if self.__settings_changed_event_listener:
                            self.__settings_changed_event_listener.close()
                            self.__settings_changed_event_listener = None

                    def init_handler(self) -> None:
                        if self.apply_button:
                            self.apply_button.enabled = self.needs_saving_model.value or False
                        if self.revert_button:
                            self.revert_button.enabled = self.needs_saving_model.value or False

                    def create_handler(
                        self,
                        component_id: str,
                        container: typing.Any = None,
                        item: typing.Any = None,
                        **kwargs: typing.Any
                    ) -> typing.Optional[Declarative.HandlerLike]:
                        if component_id == "edit_group":
                            if self.__video_device_factory:
                                return typing.cast(
                                    Declarative.HandlerLike,
                                    self.__video_device_factory.
                                    create_editor_handler(self.settings))
                            else:
                                return self
                        raise ValueError("Unable to create component.")

                    @property
                    def resources(self) -> typing.Mapping[str, typing.Any]:
                        if self.__video_device_factory:
                            content = self.__video_device_factory.get_editor_description(
                            )
                        else:
                            content = u.create_label(text=_("Not Available"))

                        component = u.define_component(
                            content=content, component_id="edit_group")

                        return {"edit_group": component}

                    @property
                    def __video_device_factory(
                        self
                    ) -> typing.Optional[video_base.VideoDeviceFactoryLike]:
                        for video_device_factory in video_device_factories:
                            if video_device_factory.factory_id == getattr(
                                    self.settings, "driver", None):
                                return video_device_factory
                        return None

                    @property
                    def driver_display_name(self) -> str:
                        video_device_factory = self.__video_device_factory
                        return video_device_factory.display_name if video_device_factory else _(
                            "Unknown")

                    def apply(self, widget: UserInterface.Widget) -> None:
                        settings = self.settings
                        if settings:
                            video_base.video_configuration.set_settings_model(
                                self.hardware_source, settings)
                            self.needs_saving_model.value = False

                    def revert(self, widget: UserInterface.Widget) -> None:
                        if self.settings:
                            self.settings.copy_from(self.settings_original)
                            self.needs_saving_model.value = False

                    def remove(self, widget: UserInterface.Widget) -> None:
                        video_base.video_configuration.remove_hardware_source(
                            self.hardware_source)

                if component_id == "section":
                    return SectionHandler(container, item)

                raise ValueError("Unable to create component.")

            @property
            def resources(self) -> typing.Mapping[str, typing.Any]:
                u = Declarative.DeclarativeUI()

                driver_display_name_label = u.create_label(
                    text="@binding(driver_display_name)")

                device_id_field = u.create_line_edit(
                    text="@binding(settings.device_id)", width=180)

                display_name_field = u.create_line_edit(
                    text="@binding(settings.name)", width=240)

                edit_group_content = u.create_component_instance("edit_group")

                edit_group = u.create_group(edit_group_content, margin=8)

                edit_row = u.create_row(edit_group, u.create_stretch())

                apply_button = u.create_push_button(name="apply_button",
                                                    text=_("Apply"),
                                                    on_clicked="apply")
                revert_button = u.create_push_button(name="revert_button",
                                                     text=_("Revert"),
                                                     on_clicked="revert")
                remove_button = u.create_push_button(text=_("Remove"),
                                                     on_clicked="remove")
                remove_row = u.create_row(apply_button, revert_button,
                                          remove_button, u.create_stretch())

                label_column = u.create_column(
                    u.create_label(text=_("Driver:")),
                    u.create_label(text=_("Device ID:")),
                    u.create_label(text=_("Display Name:")),
                    spacing=4)
                field_column = u.create_column(driver_display_name_label,
                                               device_id_field,
                                               display_name_field,
                                               spacing=4)

                content_row = u.create_row(label_column,
                                           field_column,
                                           u.create_stretch(),
                                           spacing=12)

                content = u.create_column(content_row,
                                          edit_row,
                                          remove_row,
                                          spacing=8)

                component = u.define_component(content=content,
                                               component_id="section")

                return {"section": component}

        sources_column = u.create_column(items="video_sources.items",
                                         item_component_id="section",
                                         spacing=8)

        sources_content = u.create_scroll_area(
            u.create_column(sources_column, u.create_stretch()))

        video_source_types = [
            video_device_factory.display_name
            for video_device_factory in video_device_factories
        ]

        video_source_type_combo = u.create_combo_box(
            items=video_source_types,
            current_index="@binding(video_source_type_index.value)")

        button_row = u.create_row(u.create_stretch(),
                                  video_source_type_combo,
                                  u.create_push_button(
                                      text=_("New"),
                                      on_clicked="create_new_video_device"),
                                  spacing=8)

        content = u.create_column(sources_content, button_row)

        return Declarative.DeclarativeWidget(
            ui, event_loop,
            Handler(content, self.__video_configuration.video_sources))
Beispiel #20
0
    def build(self, ui, event_loop=None, **kwargs):
        u = Declarative.DeclarativeUI()

        video_device_factories = list(Registry.get_components_by_type("video_device_factory"))

        class Handler:
            def __init__(self, ui_view, video_sources):
                self.ui_view = ui_view
                self.video_sources = video_sources
                self.video_source_type_index = Model.PropertyModel(0)

            def create_new_video_device(self, widget):
                video_base.video_configuration.create_hardware_source(video_device_factories[self.video_source_type_index.value])

            def create_handler(self, component_id: str, container=None, item=None, **kwargs):

                class SectionHandler:

                    def __init__(self, container, hardware_source):
                        self.container = container
                        self.hardware_source = hardware_source
                        self.settings = video_base.video_configuration.get_settings_model(hardware_source)
                        self.settings_original = copy.deepcopy(self.settings)
                        self.needs_saving_model = Model.PropertyModel(False)
                        self.property_changed_event = Event.Event()
                        self.apply_button = None
                        self.revert_button = None

                        def settings_changed(property_name):
                            self.needs_saving_model.value = True

                        self.__settings_changed_event_listener = self.settings.property_changed_event.listen(settings_changed)

                        def needs_saving_model_changed(property_name):
                            if self.apply_button:
                                self.apply_button.enabled = self.needs_saving_model.value
                            if self.revert_button:
                                self.revert_button.enabled = self.needs_saving_model.value

                        self.__needs_saving_changed_event_listener = self.needs_saving_model.property_changed_event.listen(needs_saving_model_changed)

                    def close(self):
                        self.__settings_changed_event_listener.close()
                        self.__settings_changed_event_listener = None

                    def init_handler(self):
                        self.apply_button.enabled = self.needs_saving_model.value
                        self.revert_button.enabled = self.needs_saving_model.value

                    def create_handler(self, component_id: str, container=None, item=None, **kwargs):
                        if component_id == "edit_group":
                            if self.__video_device_factory:
                                return self.__video_device_factory.create_editor_handler(self.settings)
                            else:
                                return self

                    @property
                    def resources(self):
                        if self.__video_device_factory:
                            content = self.__video_device_factory.get_editor_description()
                        else:
                            content = u.create_label(text=_("Not Available"))

                        component = u.define_component(content=content, component_id="edit_group")

                        return {"edit_group": component}

                    @property
                    def __video_device_factory(self):
                        for video_device_factory in video_device_factories:
                            if video_device_factory.factory_id == self.settings.driver:
                                return video_device_factory
                        return None

                    @property
                    def driver_display_name(self) -> str:
                        video_device_factory = self.__video_device_factory
                        return video_device_factory.display_name if video_device_factory else _("Unknown")

                    def apply(self, widget):
                        video_base.video_configuration.set_settings_model(self.hardware_source, self.settings)
                        self.needs_saving_model.value = False

                    def revert(self, widget):
                        self.settings.copy_from(self.settings_original)
                        self.needs_saving_model.value = False

                    def remove(self, widget):
                        video_base.video_configuration.remove_hardware_source(self.hardware_source)

                if component_id == "section":
                    return SectionHandler(container, item)

            @property
            def resources(self):
                u = Declarative.DeclarativeUI()

                driver_display_name_label = u.create_label(text="@binding(driver_display_name)")

                device_id_field = u.create_line_edit(text="@binding(settings.device_id)", width=180)

                display_name_field = u.create_line_edit(text="@binding(settings.name)", width=240)

                edit_group_content = u.create_component_instance("edit_group")

                edit_group = u.create_group(edit_group_content, margin=8)

                edit_row = u.create_row(edit_group, u.create_stretch())

                apply_button = u.create_push_button(name="apply_button", text=_("Apply"), on_clicked="apply")
                revert_button = u.create_push_button(name="revert_button", text=_("Revert"), on_clicked="revert")
                remove_button = u.create_push_button(text=_("Remove"), on_clicked="remove")
                remove_row = u.create_row(apply_button, revert_button, remove_button, u.create_stretch())

                label_column = u.create_column(u.create_label(text=_("Driver:")), u.create_label(text=_("Device ID:")), u.create_label(text=_("Display Name:")), spacing=4)
                field_column = u.create_column(driver_display_name_label, device_id_field, display_name_field, spacing=4)

                content_row = u.create_row(label_column, field_column, u.create_stretch(), spacing=12)

                content = u.create_column(content_row, edit_row, remove_row, spacing=8)

                component = u.define_component(content=content, component_id="section")

                return {"section": component}

        sources_column = u.create_column(items="video_sources.items", item_component_id="section", spacing=8)

        sources_content = u.create_scroll_area(u.create_column(sources_column, u.create_stretch()))

        video_source_types = [video_device_factory.display_name for video_device_factory in video_device_factories]

        video_source_type_combo = u.create_combo_box(items=video_source_types, current_index="@binding(video_source_type_index.value)")

        button_row = u.create_row(u.create_stretch(), video_source_type_combo, u.create_push_button(text=_("New"), on_clicked="create_new_video_device"), spacing=8)

        content = u.create_column(sources_content, button_row)

        return Declarative.DeclarativeWidget(ui, event_loop, Handler(content, self.__video_configuration.video_sources))
Beispiel #21
0

# the plan is to migrate away from the hardware manager as a registration system.
# but keep this here until that migration is complete.


def component_registered(component, component_types):
    if "stem_controller" in component_types:
        HardwareSource.HardwareSourceManager().register_instrument(
            component.instrument_id, component)


def component_unregistered(component, component_types):
    if "stem_controller" in component_types:
        HardwareSource.HardwareSourceManager().unregister_instrument(
            component.instrument_id)


component_registered_listener = Registry.listen_component_registered_event(
    component_registered)
component_unregistered_listener = Registry.listen_component_unregistered_event(
    component_unregistered)

for component in Registry.get_components_by_type("stem_controller"):
    component_registered(component, {"stem_controller"})
"""
from nion.swift.model import HardwareSource
s = HardwareSource.HardwareSourceManager().get_instrument_by_id('usim_stem_controller')
s._subscan_region_value.value = ((0.1, 0.1), (0.2, 0.3))
"""