def modal(self, context, event):

        if event.type in {'RIGHTMOUSE', 'ESC'}:
            StreamingPanel.is_streaming = False
            bpy.context.scene.update()
            self.cancel(context)
            return {'PASS_THROUGH'}

        if event.type == 'TIMER':
            if StreamingPanel.is_streaming and time.time() - self._time > bpy.context.scene.streaming_buffer_size / 1000.0:
                print(time.time() - self._time)
                self._time = time.time()
                data = mu.queue_get(StreamingPanel.udp_queue)
                if not data is None:
                    # if len(np.where(data)[0]) > 0:
                    #     print('spike!!!!!')
                    # else:
                        # print('only zeros!')
                    change_graph_all_vals(data, StreamButton._channels_names, StreamButton._stim_channels,
                                          bpy.context.scene.stim_length)
                    if bpy.context.scene.stream_type == 'offline' or self._first_time:
                        mu.view_all_in_graph_editor()
                        self._first_time = False
                    # if self._first_timer and bpy.context.scene.frame_current > 10:
                    #     print('Setting _first_timer to False! ', bpy.context.scene.frame_current)
                    #     self._first_timer = False

        return {'PASS_THROUGH'}
Exemple #2
0
    def modal(self, context, event):
        func_data = mu.queue_get(PizcoPanel.q_in)
        if not func_data is None:
            print('Message in the server queue!')
            options, attr, meth = func_data
            ret = meth(*options.get('args', ()), **options.get('kwargs', {}))
            print('Putting the ret in pizco out queue')
            if ret is None:
                ret = True
            PizcoPanel.q_out.put(ret)

        return {'PASS_THROUGH'}
Exemple #3
0
    def modal(self, context, event):
        # def show_fcurves(obj):
        #     mu.change_fcurves_colors(obj)
            # mu.view_all_in_graph_editor()

        if self.right_clicked:
            if len(bpy.context.selected_objects):
                selected_obj_name = bpy.context.selected_objects[0].name
                selected_obj_type = mu.check_obj_type(selected_obj_name)
                if selected_obj_type in [mu.OBJ_TYPE_CORTEX_LH, mu.OBJ_TYPE_CORTEX_RH, mu.OBJ_TYPE_ELECTRODE,
                                         mu.OBJ_TYPE_EEG]:
                    obj = bpy.data.objects.get(selected_obj_name)
                    if obj:
                        mu.change_fcurves_colors(obj)
                if selected_obj_type in [mu.OBJ_TYPE_CORTEX_INFLATED_LH, mu.OBJ_TYPE_CORTEX_INFLATED_RH]:
                    pial_obj_name = selected_obj_name[len('inflated_'):]
                    pial_obj = bpy.data.objects.get(pial_obj_name)
                    if not pial_obj is None:
                        pial_obj.select = True
                        mu.change_fcurves_colors(pial_obj)
            self.right_clicked = False

        if time.time() - self.press_time > 1:
            if event.type == 'RIGHTMOUSE':
                self.press_time = time.time()
                self.right_clicked = True
            if event.type == 'LEFTMOUSE':
                if _addon().fMRI_clusters_files_exist() and bpy.context.scene.plot_fmri_cluster_per_click:
                    _addon().find_closest_cluster(only_within=True)

        if not _addon().render_in_queue() is None:
            rendering_data = mu.queue_get(_addon().render_in_queue())
            if not rendering_data is None:
                try:
                    rendering_data = rendering_data.decode(sys.getfilesystemencoding(), 'ignore')
                    if '*** finish rendering! ***' in rendering_data.lower():
                        print('Finish rendering!')
                        _addon().finish_rendering()
                except:
                    print("Can't read the stdout from the rendering")

        return {'PASS_THROUGH'}
Exemple #4
0
    def modal(self, context, event):

        if event.type in {'RIGHTMOUSE', 'ESC'}:
            StreamingPanel.is_streaming = False
            bpy.context.scene.update()
            self.cancel(context)
            return {'PASS_THROUGH'}

        if event.type == 'TIMER':
            if StreamingPanel.is_streaming and time.time() - self._time > bpy.context.scene.streaming_buffer_size / 1000.0:
                self._time = time.time()
                data = mu.queue_get(StreamingPanel.udp_queue)
                if not data is None:
                    change_graph_all_vals(data)
                    if bpy.context.scene.stream_type == 'offline':
                        mu.view_all_in_graph_editor()
                    # if self._first_timer and bpy.context.scene.frame_current > 10:
                    #     print('Setting _first_timer to False! ', bpy.context.scene.frame_current)
                    #     self._first_timer = False

        return {'PASS_THROUGH'}
Exemple #5
0
    def modal(self, context, event):
        if self.left_clicked:
            self.left_clicked = False
            active_image, pos = click_inside_images_view(event)
            if active_image is not None:
                xyz = _addon().slices_were_clicked(active_image, pos)
                bpy.context.scene.cursor_location = tuple(xyz)
                set_cursor_pos()
                if bpy.context.scene.cursor_is_snapped:  # and is_view_3d():
                    _addon().set_tkreg_ras(
                        bpy.context.scene.cursor_location * 10, False)
                    snap_cursor(True)
                    if bpy.context.scene.slices_rotate_view_on_click:
                        mu.rotate_view_to_vertice()
                # if bpy.context.scene.slices_zoom > 1:
                #     ohad(pos/bpy.context.scene.slices_zoom)
                return {'PASS_THROUGH'}
            if not click_inside_3d_view(event):
                return {'PASS_THROUGH'}
            if _addon().meg.change_cursor_on_selection():
                cluster = _addon().select_meg_cluster(
                    event, context, bpy.context.scene.cursor_location)
                if cluster is not None:
                    return {'PASS_THROUGH'}
            cursor_moved = np.linalg.norm(
                SelectionListener.cursor_pos -
                bpy.context.scene.cursor_location) > 1e-3
            if cursor_moved and bpy.data.objects.get('inner_skull',
                                                     None) is not None:
                _addon().find_point_thickness()
                return {'PASS_THROUGH'}
            if bpy.context.scene.cursor_is_snapped:  # and is_view_3d():
                snap_cursor(True)
            if _addon().fMRI_clusters_files_exist(
            ) and bpy.context.scene.plot_fmri_cluster_per_click:
                _addon().find_closest_cluster(only_within=True)

            tkreg_ras = _addon().calc_tkreg_ras_from_cursor()
            if tkreg_ras is not None:
                _addon().set_tkreg_ras(tkreg_ras, move_cursor=False)
            # if _addon().is_pial():
            #     tkreg_ras = bpy.context.scene.cursor_location * 10
            #     _addon().set_tkreg_ras(tkreg_ras)
            # elif bpy.context.scene.cursor_is_snapped:
            #     tkreg_ras = _addon().calc_tkreg_ras_from_snapped_cursor()
            #     _addon().set_tkreg_ras(tkreg_ras)

            if cursor_moved:
                set_cursor_pos()
                # print('cursor position was changed by the user!')
                _addon().create_slices(pos=tkreg_ras)
                _addon().freeview.save_cursor_position()
                clear_slice()
            if bpy.context.scene.find_closest_label_on_click:  # coloring_panel.WIC_CONTOURS in _addon().what_is_colored():
                _addon().find_closest_label(
                    plot_contour=bpy.context.scene.plot_closest_label_contour)

        if self.right_clicked:
            self.right_clicked = False
            if not click_inside_3d_view(event):
                return {'PASS_THROUGH'}
            # print(bpy.context.selected_objects)
            # cluster = _addon().select_meg_cluster(event, context)
            # if cluster is not None:
            #     return {'PASS_THROUGH'}
            if len(bpy.context.selected_objects):
                mu.unfilter_graph_editor()
                if bpy.context.scene.fit_graph_on_selection:
                    mu.view_all_in_graph_editor()
                selected_obj = bpy.context.active_object  # bpy.context.selected_objects[-1]
                selected_obj_name = selected_obj.name
                selected_obj_type = mu.check_obj_type(selected_obj_name)
                if selected_obj_type in [
                        mu.OBJ_TYPE_CORTEX_LH, mu.OBJ_TYPE_CORTEX_RH
                ]:
                    _addon().select_roi(selected_obj_name)
                elif selected_obj_type in [
                        mu.OBJ_TYPE_CORTEX_INFLATED_LH,
                        mu.OBJ_TYPE_CORTEX_INFLATED_RH
                ]:
                    pial_obj_name = selected_obj_name[len('inflated_'):]
                    pial_obj = bpy.data.objects.get(pial_obj_name)
                    if not pial_obj is None:
                        # pial_obj.select = True
                        _addon().select_roi(pial_obj_name)
                        # mu.change_selected_fcurves_colors(pial_obj)
                        # mu.change_selected_fcurves_colors()
                elif selected_obj_type == mu.OBJ_TYPE_CON:
                    _addon().select_connection(selected_obj_name)
                elif selected_obj_type == mu.OBJ_TYPE_CON_VERTICE:
                    _addon().vertices_selected(selected_obj_name)
                elif selected_obj_type == mu.OBJ_TYPE_ELECTRODE:
                    bpy.context.scene.cursor_is_snapped = False
                    _addon().electode_was_manually_selected(selected_obj_name)
                    try:
                        _addon().dell.dell_ct_electrode_was_selected(
                            selected_obj_name)
                    except:
                        pass
                if bpy.context.scene.find_curves_sep_auto:
                    _addon().calc_best_curves_sep()
                elif bpy.context.scene.curves_sep > 0:
                    _addon().curves_sep_update()
            else:
                _addon().clear_electrodes_selection()
                #todo: should call to _addon().clear_rois_selection()
                # if is_activity():
                #     bpy.context.scene.cursor_location = mouse_coo_to_3d_loc(event, context)
                #     snap_cursor(True)
                #     _addon().find_closest_label()

        if time.time() - self.press_time > 1 and event.value == 'PRESS':
            if event.type == 'RIGHTMOUSE':
                self.press_time = time.time()
                self.right_clicked = True
            if event.type == 'LEFTMOUSE':
                self.press_time = time.time()
                self.left_clicked = True

        if time.time() - self.press_time > 0.1:
            if event.type == 'TIMER':
                if bpy.context.scene.rotate_brain:
                    if _addon().render.is_camera_view():
                        _addon().render.camera_mode('ORTHO')
                        _addon().show_hide.rotate_brain()
                        _addon().render.camera_mode('CAMERA')
                    else:
                        _addon().show_hide.rotate_brain()

        if _addon() and _addon().render_in_queue():
            rendering_data = mu.queue_get(_addon().render_in_queue())
            if not rendering_data is None:
                try:
                    rendering_data = rendering_data.decode(
                        sys.getfilesystemencoding(), 'ignore')
                    if '*** finish rendering! ***' in rendering_data.lower():
                        print('Finish rendering!')
                        _addon().finish_rendering()
                except:
                    print("Can't read the stdout from the rendering")

        return {'PASS_THROUGH'}
Exemple #6
0
    def on_request(self, sender, topic, content, msgid):
        """Handles Proxy Server communication, handling attribute access in served_object.

        Messages between proxy and server are handled using a tuple
        containing three elements: a string 'PSMessage', `action` and `options`.

        From Proxy to Server, valid actions are:

        - `exec`: execute a method from an attribute served object.
        - `getattr`: get an attribute from the served object.
        - `setattr`: set an attribute to the served object.
        - `get`: get an attribute from the served object, returning a remote object
                 when necessary.

        From Server to Proxy, valid action are:

        - `return`: return a value.
        - `remote`: return a RemoteAttribute object.
        - `raise`: raise an exception.


        """
        try:
            content_type, action, options = content
            if content_type != 'PSMessage':
                raise ValueError()
        except:
            return super(Server, self).on_request(sender, topic, content,
                                                  msgid)

        try:
            if action == 'exec':
                if options['name'].startswith('mmvt_utils.'):
                    func_name = options['name'].split('.')[-1]
                    attr = getattr(mu, func_name)
                else:
                    attr = getattr(self.served_object, options['name'])
                meth = getattr(attr, options['method'])
                PizcoPanel.q_in.put((options, attr, meth))
                ret = mu.queue_get(PizcoPanel.q_out)
                while ret is None:
                    time.sleep(0.1)
                    ret = mu.queue_get(PizcoPanel.q_out)

            elif action == 'getattr':
                ret = getattr(self.served_object, options['name'])

            elif action == 'setattr':
                setattr(self.served_object, options['name'], options['value'])
                return PSMessage('return', None)

            elif action == 'get':
                if options['name'].startswith('mmvt_utils.'):
                    func_name = options['name'].split('.')[-1]
                    attr = getattr(mu, func_name)
                else:
                    attr = getattr(self.served_object, options['name'])
                if options.get('force_as_object',
                               False) or self.force_as_object(attr):
                    ret = attr
                elif self.return_as_remote(attr):
                    return PSMessage('remote', None)
                else:
                    ret = attr

            elif action == 'inspect':
                return PSMessage('return', self.inspect())

            elif action == 'instantiate':
                if self.served_object is not None:
                    return PSMessage(
                        'raise',
                        (Exception('Cannot instantiate another object.'), ''))

                mod_name, class_name = options['class'].rsplit('.', 1)
                mod = __import__(mod_name, fromlist=[class_name])
                klass = getattr(mod, class_name)
                self.served_object = klass(*options['args'],
                                           **options['kwargs'])
                return PSMessage('return', None)
            else:
                ret = Exception('invalid message action {}'.format(action))
                return PSMessage('raise', (ret, ''))

            if isinstance(ret, futures.Future):
                ret.add_done_callback(lambda fut: self.publish(
                    '__future__', {
                        'msgid': msgid,
                        'result': fut.result()
                        if not fut.exception() else None,
                        'exception': fut.exception()
                    }))
                return PSMessage('future_register', msgid)

            return PSMessage('return', ret)

        except Exception as ex:
            exc_type, exc_value, exc_tb = sys.exc_info()
            tb = traceback.format_exception(exc_type, exc_value, exc_tb)[1:]
            return PSMessage('raise', (ex, tb))
Exemple #7
0
    def modal(self, context, event):
        # def show_fcurves(obj):
        #     mu.change_fcurves_colors(obj)
        # mu.view_all_in_graph_editor()
        if self.left_clicked:
            self.left_clicked = False
            if bpy.context.scene.cursor_is_snapped:
                snap_cursor(True)
            if _addon().fMRI_clusters_files_exist(
            ) and bpy.context.scene.plot_fmri_cluster_per_click:
                _addon().find_closest_cluster(only_within=True)
            if _addon().is_pial():
                _addon().set_tkreg_ras_coo(bpy.context.scene.cursor_location *
                                           10)
            if self.cursor_pos != tuple(bpy.context.scene.cursor_location):
                self.cursor_pos = tuple(bpy.context.scene.cursor_location)
                _addon().create_slices()
                _addon().save_cursor_position()
                if bpy.context.scene.is_sliced_ind > -1:
                    tmp_new = bpy.context.scene.cursor_location[
                        bpy.context.scene.is_sliced_ind]
                    tmp_old = bpy.context.scene.last_cursor_location[
                        bpy.context.scene.is_sliced_ind]
                    if abs(tmp_new - tmp_old) > 0.005:
                        _addon().clear_slice()
                if bpy.data.objects.get('inner_skull', None) is not None:
                    _addon().find_point_thickness()
            _addon().slices_were_clicked()

        if self.right_clicked:
            self.right_clicked = False
            # print(bpy.context.selected_objects)
            if len(bpy.context.selected_objects):
                mu.unfilter_graph_editor()
                if bpy.context.scene.fit_graph_on_selection:
                    mu.view_all_in_graph_editor()
                selected_obj = bpy.context.active_object  # bpy.context.selected_objects[-1]
                selected_obj_name = selected_obj.name
                selected_obj_type = mu.check_obj_type(selected_obj_name)
                if selected_obj_type in [
                        mu.OBJ_TYPE_CORTEX_LH, mu.OBJ_TYPE_CORTEX_RH
                ]:
                    _addon().select_roi(selected_obj_name)
                elif selected_obj_type in [
                        mu.OBJ_TYPE_CORTEX_INFLATED_LH,
                        mu.OBJ_TYPE_CORTEX_INFLATED_RH
                ]:
                    pial_obj_name = selected_obj_name[len('inflated_'):]
                    pial_obj = bpy.data.objects.get(pial_obj_name)
                    if not pial_obj is None:
                        # pial_obj.select = True
                        _addon().select_roi(pial_obj_name)
                        # mu.change_selected_fcurves_colors(pial_obj)
                        # mu.change_selected_fcurves_colors()
                elif selected_obj_type == mu.OBJ_TYPE_CON:
                    _addon().select_connection(selected_obj_name)
                elif selected_obj_type == mu.OBJ_TYPE_CON_VERTICE:
                    _addon().vertices_selected(selected_obj_name)
                elif selected_obj_type == mu.OBJ_TYPE_ELECTRODE:
                    _addon().electode_was_manually_selected(selected_obj_name)
                if bpy.context.scene.find_curves_sep_auto:
                    _addon().calc_best_curves_sep()
                elif bpy.context.scene.curves_sep > 0:
                    _addon().curves_sep_update()
            else:
                _addon().clear_electrodes_selection()
        if time.time() - self.press_time > 1:
            if event.type == 'RIGHTMOUSE':
                self.press_time = time.time()
                self.right_clicked = True
            if event.type == 'LEFTMOUSE':
                self.press_time = time.time()
                self.left_clicked = True

        if time.time() - self.press_time > 0.1:
            if event.type == 'TIMER':
                if bpy.context.scene.rotate_brain:
                    _addon().rotate_brain()

        if _addon() and _addon().render_in_queue():
            rendering_data = mu.queue_get(_addon().render_in_queue())
            if not rendering_data is None:
                try:
                    rendering_data = rendering_data.decode(
                        sys.getfilesystemencoding(), 'ignore')
                    if '*** finish rendering! ***' in rendering_data.lower():
                        print('Finish rendering!')
                        _addon().finish_rendering()
                except:
                    print("Can't read the stdout from the rendering")

        return {'PASS_THROUGH'}