def get_params(prop_names_and_fallbacks, direct=False): """ This function returns an object which you can use the . op on. example usage: from sverchok.settings import get_params props = get_params({'prop_name_1': 20, 'prop_name_2': 30}) # props.prop_name_1 20 # props.prop_name_2 30 example usage using direct=True props = get_params({'prop_name_1': 20, 'prop_name_2': 30}, direct=True) # props[0] 20 # props[1] 30 """ from sverchok.utils.context_managers import sv_preferences props = lambda: None with sv_preferences() as prefs: for k, v in prop_names_and_fallbacks.items(): try: value = getattr(prefs, k) except: print(f'returning a default for {k}') value = v setattr(props, k, value) if direct: return [getattr(props, k) for k in prop_names_and_fallbacks.keys()] return props
def get_scale(self): try: with sv_preferences() as prefs: scale = prefs.index_viewer_scale except: scale = 1.0 return scale
def process(self): inputs = self.inputs n_id = node_id(self) # end early nvBGL.callback_disable(n_id) if self.activate and inputs[0].is_linked: try: with sv_preferences() as prefs: scale = prefs.stethoscope_view_scale location_theta = prefs.stethoscope_view_xy_multiplier except: # print('did not find preferences - you need to save user preferences') scale = 1.0 location_theta = 1.0 # gather vertices from input data = inputs[0].sv_get(deepcopy=False) self.num_elements = len(data) if self.selected_mode == 'text-based': props = lambda: None props.line_width = self.line_width props.compact = self.compact props.depth = self.depth or None processed_data = nvBGL.parse_socket( inputs[0], self.rounding, self.element_index, self.view_by_element, props ) else: # # implement another nvBGL parses for gfx processed_data = data node_width = (self.width_hidden + 30.0) if self.hide else self.width # adjust proposed text location in case node is framed. # take into consideration the hidden state _x, _y = recursive_framed_location_finder(self, self.location[:]) _x, _y = Vector((_x, _y)) + Vector((node_width + 20, 0)) # this alters location based on DPI/Scale settings. location = adjust_location(_x, _y, location_theta) draw_data = { 'tree_name': self.id_data.name[:], 'content': processed_data, 'location': location, 'color': self.text_color[:], 'scale' : float(scale), 'mode': self.selected_mode[:], 'font_id': int(self.font_id) } nvBGL.callback_enable(n_id, draw_data)
def process(self): inputs = self.inputs n_id = node_id(self) # end early nvBGL.callback_disable(n_id) if self.activate and inputs[0].is_linked: try: with sv_preferences() as prefs: scale = prefs.stethoscope_view_scale location_theta = prefs.render_location_xy_multiplier except: # print('did not find preferences - you need to save user preferences') scale = 1.0 location_theta = 1.0 # gather vertices from input data = inputs[0].sv_get(deepcopy=False) self.num_elements = len(data) if self.selected_mode == 'text-based': props = lambda: None props.line_width = self.line_width props.compact = self.compact props.depth = self.depth or None processed_data = nvBGL.parse_socket( inputs[0], self.rounding, self.element_index, self.view_by_element, props ) else: # # implement another nvBGL parses for gfx processed_data = data node_width = (self.width_hidden + 30.0) if self.hide else self.width # adjust proposed text location in case node is framed. # take into consideration the hidden state _x, _y = recursive_framed_location_finder(self, self.location[:]) _x, _y = Vector((_x, _y)) + Vector((node_width + 20, 0)) # this alters location based on DPI/Scale settings. location = adjust_location(_x, _y, location_theta) draw_data = { 'tree_name': self.id_data.name[:], 'content': processed_data, 'location': location, 'color': self.text_color[:], 'scale' : float(scale), 'mode': self.selected_mode[:], 'font_id': int(self.font_id) } nvBGL.callback_enable(n_id, draw_data)
def is_profiling_enabled_in_settings(): """ Check if profiling is not set to NONE in addon preferences. """ with sv_preferences() as prefs: if prefs is None: return True return prefs.profile_mode != "NONE"
def register(): with sv_preferences() as prefs: level = getattr(logging, prefs.log_level) logging.basicConfig(level=level, format=log_format) logging.captureWarnings(True) info( "Registering Sverchok addon. Messages issued during registration will be only available in the console and in file (if configured)." )
def poll(cls, context): try: if context.space_data.edit_tree.bl_idname != 'SverchCustomTreeType': return False with sv_preferences() as prefs: return prefs.developer_mode except: return False
def poll(cls, context): # only show up in this tree if not context.space_data.tree_type == 'SverchCustomTreeType': return # only show up if developer_mode has been set to True with sv_preferences() as prefs: return prefs.developer_mode
def poll(cls, context): try: if context.space_data.tree_type != 'SverchCustomTreeType': return False with sv_preferences() as prefs: return prefs.developer_mode except: return False
def set_vals(**kwargs): with sv_preferences() as prefs: for key, val in kwargs.items(): print('set: key({0}) = value({1})'.format(key, val)) try: setattr(prefs, key, val) except Exception as err: print(err) print('failed prefs.{0}={1}'.format(key, val))
def is_profiling_enabled(section): """ Check if profiling is enabled in general, and if it is enabled for specified section. """ global is_currently_enabled if not is_currently_enabled: return False with sv_preferences() as prefs: return prefs.profile_mode == section
def register(): global consoleHandler with sv_preferences() as prefs: level = getattr(logging, prefs.log_level) logging.basicConfig(level=level, format=log_format) # Remember the first handler. We may need it in future # to remove from list. consoleHandler = logging.getLogger().handlers[0] logging.captureWarnings(True) info("Registering Sverchok addon. Messages issued during registration will be only available in the console and in file (if configured).")
def poll(cls, context): # do not show if there is no node tree if not context.space_data.node_tree: return False # do not show if the tree is not a sverchock node tree if not context.space_data.tree_type == 'SverchCustomTreeType': return False # only show up if developer_mode has been set to True with sv_preferences() as prefs: return prefs.developer_mode
def process(self): if not self.inputs['Float'].is_linked: return n_id = node_id(self) self.delete_texture() nvBGL2.callback_disable(n_id) size_tex = 0 width = 0 height = 0 if self.to_image_viewer: mode = self.color_mode pixels = np.array( self.inputs['Float'].sv_get(deepcopy=False)).flatten() width, height = self.texture_width_height resized_np_array = np.resize(pixels, self.calculate_total_size()) transfer_to_image(resized_np_array, self.texture_name, width, height, mode) if self.activate: texture = self.get_buffer() width, height = self.texture_width_height x, y = self.xy_offset gl_color_constant = gl_color_dict.get(self.color_mode) name = bgl.Buffer(bgl.GL_INT, 1) bgl.glGenTextures(1, name) self.texture[n_id] = name[0] init_texture(width, height, name[0], texture, gl_color_constant) # adjust render location based on preference multiplier setting try: with sv_preferences() as prefs: multiplier = prefs.render_location_xy_multiplier scale = prefs.render_scale except: # print('did not find preferences - you need to save user preferences') multiplier = 1.0 scale = 1.0 x, y = [x * multiplier, y * multiplier] width, height = [width * scale, height * scale] draw_data = { 'tree_name': self.id_data.name[:], 'mode': 'custom_function', 'custom_function': simple_screen, 'loc': (x, y), 'args': (texture, self.texture[n_id], width, height) } nvBGL2.callback_enable(n_id, draw_data)
def get_drawing_attributes(self): """ adjust render location based on preference multiplier setting """ try: with sv_preferences() as prefs: multiplier = prefs.render_location_xy_multiplier except: multiplier = 1.0 # cache this. self.location_theta = multiplier
def process(self): if not self.inputs['Float'].is_linked: return n_id = node_id(self) self.delete_texture() nvBGL2.callback_disable(n_id) size_tex = 0 width = 0 height = 0 if self.to_image_viewer: mode = self.color_mode pixels = np.array(self.inputs['Float'].sv_get(deepcopy=False)).flatten() width, height = self.texture_width_height resized_np_array = np.resize(pixels, self.calculate_total_size()) transfer_to_image(resized_np_array, self.texture_name, width, height, mode) if self.activate: texture = self.get_buffer() width, height = self.texture_width_height x, y = self.xy_offset gl_color_constant = gl_color_dict.get(self.color_mode) name = bgl.Buffer(bgl.GL_INT, 1) bgl.glGenTextures(1, name) self.texture[n_id] = name[0] init_texture(width, height, name[0], texture, gl_color_constant) # adjust render location based on preference multiplier setting try: with sv_preferences() as prefs: multiplier = prefs.render_location_xy_multiplier scale = prefs.render_scale except: # print('did not find preferences - you need to save user preferences') multiplier = 1.0 scale = 1.0 x, y = [x * multiplier, y * multiplier] width, height =[width * scale, height * scale] draw_data = { 'tree_name': self.id_data.name[:], 'mode': 'custom_function', 'custom_function': simple_screen, 'loc': (x, y), 'args': (texture, self.texture[n_id], width, height) } nvBGL2.callback_enable(n_id, draw_data)
def draw(self, context): col = self.layout.column() col.operator('node.sv_show_latest_commits') with sv_preferences() as prefs: if prefs.available_new_version: col_alert = self.layout.column() col_alert.alert = True col_alert.operator("node.sverchok_update_addon", text='Upgrade Sverchok addon') else: col.operator("node.sverchok_check_for_upgrades_wsha", text='Check for updates') # with sv_preferences() as prefs: if prefs.developer_mode: col.operator("node.sv_run_pydoc")
def try_initialize(): """ Try to initialize logging subsystem. Does nothing if everything is already initialized. Prints an error if it is called too early. """ global internal_buffer_initialized global initialized with sv_preferences() as prefs: if not prefs: logging.error("Can't obtain logging preferences, it's too early") return if not internal_buffer_initialized: if prefs.log_to_buffer: buffer = get_log_buffer(prefs.log_buffer_name) if buffer is not None: if prefs.log_to_buffer_clean: buffer.clear() logging.debug("Internal text buffer cleared") handler = logging.StreamHandler(buffer) handler.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(handler) for area in bpy.context.screen.areas: if area.type == 'TEXT_EDITOR': if area.spaces[0].text is None: area.spaces[0].text = buffer break internal_buffer_initialized = True else: internal_buffer_initialized = True if not initialized: if prefs.log_to_file: handler = logging.handlers.RotatingFileHandler(prefs.log_file_name, maxBytes = 10*1024*1024, backupCount = 3) handler.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(handler) setLevel(prefs.log_level) logging.info("Initializing Sverchok logging. Blender version %s, Sverchok version %s", bpy.app.version_string, get_version_string()) logging.debug("Current log level: %s, log to text buffer: %s, log to file: %s", prefs.log_level, ("no" if not prefs.log_to_buffer else prefs.log_buffer_name), ("no" if not prefs.log_to_file else prefs.log_file_name) ) initialized = True
def get_and_set_gl_scale_info(self, origin=None): # todo, probably openGL viewers should have its own mixin class """ This function is called in sv_init in nodes that draw GL instructions to the nodeview, the nodeview scale and dpi differs between users and must be queried to get correct nodeview x,y and dpi scale info. """ # print('get_and_set_gl_scale_info called from', origin or self.name) try: # print('getting gl scale params') from sverchok.utils.context_managers import sv_preferences with sv_preferences() as prefs: prefs.set_nodeview_render_params(None) except Exception as err: print('failed to get gl scale info', err)
def get_and_set_gl_scale_info(self, origin=None): """ This function is called in sv_init in nodes that draw GL instructions to the nodeview, the nodeview scale and dpi differs between users and must be queried to get correct nodeview x,y and dpi scale info. """ print('get_and_set_gl_scale_info called from', origin or self.name) try: print('getting gl scale params') from sverchok.utils.context_managers import sv_preferences with sv_preferences() as prefs: getattr(prefs, 'set_nodeview_render_params')(None) except Exception as err: print('failed to get gl scale info', err)
def update_gl_scale_info(self, origin=None): """ the nodeview scale and dpi differs between users and must be queried to get correct nodeview x,y and dpi scale info. this is instead of calling `get_dpi_factor` on every redraw. """ debug(f"update_gl_scale_info called from {origin or self.name}") try: from sverchok.utils.context_managers import sv_preferences with sv_preferences() as prefs: prefs.set_nodeview_render_params(None) except Exception as err: debug('failed to get gl scale info', err)
def get_drawing_attributes(self): """ adjust render location based on preference multiplier setting """ try: with sv_preferences() as prefs: multiplier = prefs.render_location_xy_multiplier scale = prefs.render_scale except: # print('did not find preferences - you need to save user preferences') multiplier = 1.0 scale = 1.0 self.location_theta = multiplier # x, y = [x * multiplier, y * multiplier] return scale
def execute(self, context): n = context.active_node fpath = self.get_filepath_from_node(n) with sv_preferences() as prefs: app_name = prefs.external_editor if prefs.real_sverchok_path: print(fpath) _dst = os.path.dirname(sverchok.__file__) _src = prefs.real_sverchok_path fpath = fpath.replace(_dst, _src) print(fpath) subprocess.Popen([app_name, fpath]) return {'FINISHED'} return {'CANCELLED'}
def get_param(prop_name, fallback): """ for getting a single parameter from sv preferences example usage: from sverchok.settings import get_params prop = get_param("render_scale", 1.0) # prop = 1.0 if settings wasn't available, or else the current value """ from sverchok.utils.context_managers import sv_preferences with sv_preferences() as prefs: try: value = getattr(prefs, prop_name) except: print(f'returning a default for {prop_name}') value = fallback return value
def get_drawing_attributes(self): """ adjust render location based on preference multiplier setting """ x, y = [int(j) for j in (Vector(self.absolute_location) + Vector((self.width + 20, 0)))[:]] try: with sv_preferences() as prefs: multiplier = prefs.render_location_xy_multiplier scale = prefs.render_scale except: # print('did not find preferences - you need to save user preferences') multiplier = 1.0 scale = 1.0 x, y = [x * multiplier, y * multiplier] return x, y, scale, multiplier
def upload_gist(): with sv_preferences() as prefs: token = prefs.github_token if not token: info("GitHub API access token is not specified") show_token_help() return info("Uploading: %s", gist_filename) headers = {"Authorization": "token " + token} req = Request(API_URL, data=json_post_data, headers=headers) json_to_parse = urlopen(req, data=json_post_data) info('Received response from server') found_json = json_to_parse.read().decode() return get_gist_url(found_json)
def process(self): p = self.inputs['Float'].sv_get() n_id = node_id(self) # end early nvBGL2.callback_disable(n_id) float_out = self.outputs['Float'] easing_func = easing_dict.get(int(self.selected_mode)) if float_out.is_linked: out = [] for obj in p: r = [] for i in obj: r.append(easing_func(i)) out.append(r) float_out.sv_set(out) else: float_out.sv_set([[None]]) if self.activate: palette = palette_dict.get(self.selected_theme_mode)[:] x, y = [int(j) for j in (self.location + Vector((self.width + 20, 0)))[:]] # adjust render location based on preference multiplier setting try: with sv_preferences() as prefs: multiplier = prefs.render_location_xy_multiplier scale = prefs.render_scale except: # print('did not find preferences - you need to save user preferences') multiplier = 1.0 scale = 1.0 x, y = [x * multiplier, y * multiplier] draw_data = { 'tree_name': self.id_data.name[:], 'mode': 'custom_function', 'custom_function': simple_grid_xy, 'loc': (x, y), 'args': (easing_func, palette, scale) } nvBGL2.callback_enable(n_id, draw_data)
def process(self): inputs = self.inputs n_id = node_id(self) # end early nvBGL.callback_disable(n_id) if self.activate and inputs[0].is_linked: try: with sv_preferences() as prefs: scale = prefs.stethoscope_view_scale location_theta = prefs.stethoscope_view_xy_multiplier except: # print('did not find preferences - you need to save user preferences') scale = 1.0 location_theta = 1.0 # gather vertices from input data = inputs[0].sv_get(deepcopy=False) self.num_elements = len(data) if self.selected_mode == 'text-based': processed_data = nvBGL.parse_socket(inputs[0], self.rounding, self.element_index, self.view_by_element) else: # # implement another nvBGL parses for gfx processed_data = data _x, _y = (self.location + Vector((self.width + 20, 0))) location = adjust_location(_x, _y, location_theta) draw_data = { 'tree_name': self.id_data.name[:], 'content': processed_data, 'location': location, 'color': self.text_color[:], 'scale': float(scale), 'mode': self.selected_mode[:], 'font_id': int(self.font_id) } nvBGL.callback_enable(n_id, draw_data)
def execute(self, context): n = context.active_node fpath = self.get_filepath_from_node(n) string_dir = remapper.get(n.bl_idname) with sv_preferences() as prefs: if prefs.real_sverchok_path: _dst = os.path.dirname(sverchok.__file__) _src = prefs.real_sverchok_path fpath = fpath.replace(_dst, _src) if self.kind == 'internal': self.view_source_internal(context.screen.areas, fpath) elif self.kind == 'external': self.view_source_external(prefs, fpath) return {'FINISHED'} return {'CANCELLED'}
def draw_buttons(self, context, layout): with sv_preferences() as prefs: #addon = context.user_preferences.addons.get(sverchok.__name__) over_sized_buttons = prefs.over_sized_buttons #addon.preferences.over_sized_buttons col = layout.column(align=True) row = col.row() row.prop(self, 'folder', toggle=True, text='') col = layout.column(align=True) row = col.row() row.prop(self, 'gcode_mode', expand=True, toggle=True) #col = layout.column(align=True) col = layout.column(align=True) col.label(text="Extrusion:", icon='MOD_FLUIDSIM') #col.prop(self, 'esteps') col.prop(self, 'filament') col.prop(self, 'nozzle') col.separator() col.label(text="Speed (Feed Rate F):", icon='DRIVER') col.prop(self, 'feed', text='Print') if self.gcode_mode == 'RETR': col.prop(self, 'feed_vertical', text='Z Lift') col.prop(self, 'feed_horizontal', text='Travel') col.separator() if self.gcode_mode == 'RETR': col.label(text="Retraction:", icon='NOCURVE') col.prop(self, 'pull', text='Retraction') col.prop(self, 'dz', text='Z Hop') col.prop(self, 'push', text='Preload') col.prop(self, 'auto_sort', text="Sort Layers (z)") col.prop(self, 'close_all') col.separator() col.label(text='Custom Code:', icon='SCRIPT') col.prop_search(self, 'start_code', bpy.data, 'texts') col.prop_search(self, 'end_code', bpy.data, 'texts') col.separator() row = col.row(align=True) row.scale_y = 4.0 row.operator(TEXT_IO_CALLBACK, text='Export Gcode').fn_name = 'process'
def process(self): n_id = node_id(self) self.delete_texture() nvBGL2.callback_disable(n_id) if self.output_mode == 'bgl': width, height, colm = self.width_custom_tex, self.height_custom_tex, self.color_mode total_size = width * height * factor_buffer_dict.get(colm) texture = bgl.Buffer(bgl.GL_FLOAT, total_size, np.resize(self.inputs[0].sv_get(), total_size).tolist()) name = bgl.Buffer(bgl.GL_INT, 1) bgl.glGenTextures(1, name) self.texture[n_id] = name[0] init_texture(width, height, name[0], texture, gl_color_dict.get(colm)) # adjust render location based on preference multiplier setting try: with sv_preferences() as prefs: multiplier = prefs.render_location_xy_multiplier scale = prefs.render_scale except: # print('did not find preferences - you need to save user preferences') multiplier = 1.0 scale = 1.0 x, y = [self.location[0] * multiplier, self.location[1] * multiplier] width, height =[width * scale, height * scale] draw_data = { 'tree_name': self.id_data.name, 'mode': 'custom_function', 'custom_function': simple_screen, 'loc': (x + self.width*scale + 20, y), 'args': (texture, self.texture[n_id], width, height) } nvBGL2.callback_enable(n_id, draw_data) else: Im = bpy.data.images[self.image] Im.pixels = np.resize(self.inputs[0].sv_get(), len(Im.pixels))
def get_params(settings_and_fallbacks): """ This function returns an object which you can use the . op on. example usage: from sverchok.settings import get_params props = get_params({'prop_name_1': 20, 'prop_name_2': 30}) # 20 = props.prop_name_1 # 30 = props.prop_name_2 """ from sverchok.utils.context_managers import sv_preferences props = lambda: None with sv_preferences() as prefs: for k, v in settings_and_fallbacks.items(): try: value = getattr(prefs, k) except: print(f'returning a default for {k}') value = v setattr(props, k, value) return props
def draw_callback_px(n_id, draw_verts, draw_edges, draw_faces, draw_matrix, draw_bg, settings, text): context = bpy.context # ensure data or empty lists. data_vector = Vector_generate(draw_verts) if draw_verts else [] data_edges = draw_edges data_faces = draw_faces data_matrix = Matrix_generate(draw_matrix) if draw_matrix else [] data_text = text if (data_vector, data_matrix) == (0, 0): # callback_disable(n_id) # not sure that it is safe to disable the callback in callback # just return instead. return region = context.region region3d = context.space_data.region_3d vert_idx_color = settings['numid_verts_col'] edge_idx_color = settings['numid_edges_col'] face_idx_color = settings['numid_faces_col'] vert_bg_color = settings['bg_verts_col'] edge_bg_color = settings['bg_edges_col'] face_bg_color = settings['bg_faces_col'] display_vert_index = settings['display_vert_index'] display_edge_index = settings['display_edge_index'] display_face_index = settings['display_face_index'] try: with sv_preferences() as prefs: scale = prefs.index_viewer_scale except: # print('did not find preferences - you need to save user preferences') scale = 1.0 font_id = 0 text_height = int(13.0 * scale) blf.size(font_id, text_height, 72) # should check prefs.dpi region_mid_width = region.width / 2.0 region_mid_height = region.height / 2.0 # vars for projection perspective_matrix = region3d.perspective_matrix.copy() def draw_index(rgb, rgb2, index, vec, text=''): vec_4d = perspective_matrix * vec.to_4d() if vec_4d.w <= 0.0: return x = region_mid_width + region_mid_width * (vec_4d.x / vec_4d.w) y = region_mid_height + region_mid_height * (vec_4d.y / vec_4d.w) if text: index = str(text[0]) else: index = str(index) if draw_bg: polyline = get_points(index) ''' draw polygon ''' bgl.glColor4f(*rgb2) bgl.glBegin(bgl.GL_POLYGON) for pointx, pointy in polyline: bgl.glVertex2f(pointx+x, pointy+y) bgl.glEnd() ''' draw text ''' txt_width, txt_height = blf.dimensions(0, index) bgl.glColor4f(*rgb) blf.position(0, x - (txt_width / 2), y - (txt_height / 2), 0) blf.draw(0, index) ######## # points def calc_median(vlist): a = Vector((0, 0, 0)) for v in vlist: a += v return a / len(vlist) for obj_index, verts in enumerate(data_vector): final_verts = verts if data_text: text_obj = data_text[obj_index] else: text_obj = '' # quicklt apply matrix if necessary if draw_matrix: matrix = data_matrix[obj_index] final_verts = [matrix * v for v in verts] if display_vert_index: for idx, v in enumerate(final_verts): if text_obj: draw_index(vert_idx_color, vert_bg_color, idx, v, text_obj[idx]) else: draw_index(vert_idx_color, vert_bg_color, idx, v) if data_edges and display_edge_index: for edge_index, (idx1, idx2) in enumerate(data_edges[obj_index]): v1 = Vector(final_verts[idx1]) v2 = Vector(final_verts[idx2]) loc = v1 + ((v2 - v1) / 2) if text_obj: draw_index(edge_idx_color, edge_bg_color, edge_index, loc, text_obj[edge_index]) else: draw_index(edge_idx_color, edge_bg_color, edge_index, loc) if data_faces and display_face_index: for face_index, f in enumerate(data_faces[obj_index]): verts = [Vector(final_verts[idx]) for idx in f] median = calc_median(verts) if text_obj: draw_index(face_idx_color, face_bg_color, face_index, median, text_obj[face_index]) else: draw_index(face_idx_color, face_bg_color, face_index, median)
def try_initialize(): """ Try to initialize logging subsystem. Does nothing if everything is already initialized. Prints an error if it is called too early. """ global internal_buffer_initialized global file_initialized global initialized if sverchok.reload_event: return with sv_preferences() as prefs: if not prefs: logging.error( "Can't obtain logging preferences, it's too early. Stack:\n%s", "".join(traceback.format_stack())) return if not internal_buffer_initialized: if prefs.log_to_buffer: buffer = get_log_buffer(prefs.log_buffer_name) if buffer is not None: if prefs.log_to_buffer_clean: buffer.clear() logging.debug("Internal text buffer cleared") handler = TextBufferHandler(prefs.log_buffer_name) handler.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(handler) for area in bpy.context.screen.areas: if area.type == 'TEXT_EDITOR': if area.spaces[0].text is None: area.spaces[0].text = buffer break internal_buffer_initialized = True else: internal_buffer_initialized = True if not file_initialized: if prefs.log_to_file: handler = logging.handlers.RotatingFileHandler( prefs.log_file_name, maxBytes=10 * 1024 * 1024, backupCount=3) handler.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(handler) file_initialized = True if internal_buffer_initialized and file_initialized and not initialized: setLevel(prefs.log_level) logging.info( "Initializing Sverchok logging. Blender version %s, Sverchok version %s", bpy.app.version_string, get_version_string()) logging.debug( "Current log level: %s, log to text buffer: %s, log to file: %s", prefs.log_level, ("no" if not prefs.log_to_buffer else prefs.log_buffer_name), ("no" if not prefs.log_to_file else prefs.log_file_name)) initialized = True
def get_val(param_name): with sv_preferences() as prefs: return getattr(prefs, param_name)
def register_node_panels(identifier, std_menu): global node_panels def get_cat_list(): extra_categories = get_extra_categories() cat_list = std_menu[:] cat_list.extend(extra_categories) return cat_list with sv_preferences() as prefs: if prefs.node_panels == "N": def draw_node_item(self, context): layout = self.layout col = SvOperatorLayout.get(prefs.node_panels_icons_only, layout.column(align=True), prefs.node_panels_columns) for item in self.category.items(context): item.draw(item, col, context) for category in get_cat_list(): panel_type = type( "NODE_PT_category_sv_" + category.identifier, (bpy.types.Panel, ), { "bl_space_type": "NODE_EDITOR", "bl_region_type": "UI", "bl_label": category.name, "bl_category": category.name, "category": category, "poll": category.poll, "draw": draw_node_item, }) node_panels.append(panel_type) bpy.utils.register_class(panel_type) elif prefs.node_panels == "T": class SV_PT_NodesTPanel(bpy.types.Panel): """Nodes panel under the T panel""" bl_space_type = "NODE_EDITOR" bl_region_type = "TOOLS" bl_label = "Sverchok Nodes" @classmethod def poll(cls, context): return context.space_data.tree_type == 'SverchCustomTreeType' def draw(self, context): layout = self.layout row = layout.row(align=True) row.prop(context.scene, "sv_node_search", text="") row.operator("node.sv_reset_node_search", icon="X", text="") if not context.scene.sv_node_search: layout.prop(context.scene, "sv_selected_category", text="") col = SvOperatorLayout.get(prefs.node_panels_icons_only, layout.column(align=True), prefs.node_panels_columns) needle = context.scene.sv_node_search # We will search either by category selected in the popup menu, # or by search term. check_search = needle != "" check_category = not check_search category_is_first = True for category in get_cat_list(): category_ok = category.identifier == context.scene.sv_selected_category if check_category: if not category_ok: continue items_to_draw = [] has_nodes = False for item in category.items(context): if check_search: if not hasattr(item, 'search_match'): continue if not item.search_match(needle): continue if not isinstance(item, SverchSeparator): has_nodes = True # Do not show separators if we are searching by text - # otherwise search results would take too much vertical space. if not (check_search and isinstance(item, SverchSeparator)): items_to_draw.append(item) # Show category only if it has some nodes to display # according to search terms. if has_nodes: if check_search: if not category_is_first: col.separator() col.label(category.name + ":") for item in items_to_draw: item.draw(item, col, context) category_is_first = False node_panels.append(SV_PT_NodesTPanel) bpy.utils.register_class(SV_PT_NodesTPanel)
def get_archive_path(): from sverchok.utils.context_managers import sv_preferences with sv_preferences() as prefs: return prefs.dload_archive_path, prefs.dload_archive_name
def try_initialize(): """ Try to initialize logging subsystem. Does nothing if everything is already initialized. Prints an error if it is called too early. """ global internal_buffer_initialized global file_initialized global initialized if sverchok.reload_event: return with sv_preferences() as prefs: if not prefs: logging.error("Can't obtain logging preferences, it's too early. Stack:\n%s", "".join(traceback.format_stack())) return if not internal_buffer_initialized: if prefs.log_to_buffer: buffer = get_log_buffer(prefs.log_buffer_name) if buffer is not None: if prefs.log_to_buffer_clean: buffer.clear() logging.debug("Internal text buffer cleared") handler = TextBufferHandler(prefs.log_buffer_name) handler.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(handler) for area in bpy.context.screen.areas: if area.type == 'TEXT_EDITOR': if area.spaces[0].text is None: area.spaces[0].text = buffer break internal_buffer_initialized = True else: internal_buffer_initialized = True if not file_initialized: if prefs.log_to_file: handler = logging.handlers.RotatingFileHandler(prefs.log_file_name, maxBytes = 10*1024*1024, backupCount = 3) handler.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(handler) file_initialized = True if internal_buffer_initialized and file_initialized and not initialized: setLevel(prefs.log_level) if not prefs.log_to_console: # Remove console output handler. # The trick is we have to remove it *after* other handlers # have been initialized, otherwise it will be re-enabled automatically. global consoleHandler if consoleHandler is not None: logging.debug("Log output to console is disabled. Further messages will be available only in text buffer and file (if configured).") logging.getLogger().removeHandler(consoleHandler) logging.info("Initializing Sverchok logging. Blender version %s, Sverchok version %s", bpy.app.version_string, get_version_string()) logging.debug("Current log level: %s, log to text buffer: %s, log to file: %s, log to console: %s", prefs.log_level, ("no" if not prefs.log_to_buffer else prefs.log_buffer_name), ("no" if not prefs.log_to_file else prefs.log_file_name), ("yes" if prefs.log_to_console else "no")) initialized = True
def is_profiling_enabled_in_settings(): """ Check if profiling is not set to NONE in addon preferences. """ with sv_preferences() as prefs: return prefs.profile_mode != "NONE"