def prev(self,*k): root = self.root if self.page <= 1: return self.page-=1 posts= iter(self.api.get_posts("pony rating:s",self.page,12)) for pic in self.pictures: def remove(*k): root.remove_widget(pic) pic.prev_animation.bind(on_complete=remove) pic.prev_animation.start(pic) self.pictures=[] for x in range(0,4): for y in range(0,3): try: post=posts.next() # load the image picture = Picture(post,(x*200+50,y*200+50),pos=(2000,y*200+50), scale=0.1, rotation=0 ) picture.back_animation.start(picture) picture.bind( selected=self.picture_on_selected ) # add to the main field root.add_widget(picture) self.pictures.append(picture) except Exception, e: Logger.exception('Pictures: Unable to load <%s>')
def calculate_break_point(forces,material): materials = {13: 20.4, 16: 30.6, 18:38.5, 19:42.9, 22:57.2,25.4:75.8, 26:79.3 , 28:91.6, 30:105, 32:119 } ton = 2000 try: for force in forces: if abs(float(forces[0])) > materials[float(material)] * ton: print "BREAKS" print "\nMax tension to break:" print materials[float(material)] * ton print " \nCurrent tension:" print abs(float(forces[0])) pass_image.source = 'breaks.jpg' pass_image.reload() else: print "PASS" print "\nMax tension to break:" print materials[float(material)] * ton print " \nCurrent tension:" print abs(float(forces[0])) pass_image.source = 'pass.jpg' pass_image.reload() except Exception as e: Logger.exception('Material does not exist')
def delete_clock(self, touch, *args): # TODO: Fix touch_up passing through when popup dismissed. try: Clock.unschedule(touch.ud['event']) except KeyError: Logger.exception( 'Application: Touch up passed through and unscheduled clock event could not be unscheduled. A bug...')
def read_from_in_pipe(self, *l): txt = '\n' txt_line = '' os_read = os.read self_stdin_pipe = self.stdin_pipe self_mode = self.mode self_write = self.write Clock_schedule_once = Clock.schedule_once self_update_cache = self.update_cache self_flush = self.flush obj = self.obj try: while txt != '': txt = os_read(self_stdin_pipe, 1) txt_line = u''.join((txt_line, txt)) if txt == '\n': if self_mode == 'stdin': # run command self_write(txt_line) else: Clock_schedule_once( partial(self_update_cache, txt_line, obj), 0) self_flush() txt_line = '' except OSError as e: Logger.exception(e)
def texture_update(self, *largs): if not self.source: self.texture = None else: filename = resource_find(self.source) self._loops = 0 if filename is None: return Logger.error('Image: Error reading file {filename}'. format(filename=self.source)) mipmap = self.mipmap if self._coreimage is not None: self._coreimage.unbind(on_texture=self._on_tex_change) try: if PY2: filename = filename.decode('utf-8') self._coreimage = ci = CoreImage(filename, mipmap=mipmap, anim_delay=self.anim_delay, keep_data=self.keep_data, nocache=self.nocache) except Exception as e: Logger.exception(e) self._coreimage = ci = None if ci: ci.bind(on_texture=self._on_tex_change) self.texture = ci.texture
def build(self): # the root is created in pictures.kv root = self.root # get any files into images directory curdir = dirname(__file__) ## for filename in glob(join(curdir, 'images', '*')): #try: # # load the image # URL = 'https://farm1.staticflickr.com/176/478156552_9badc190eb_o.jpg' # img = AsyncImage(source=URL) # #picture = Picture(source=filename, rotation=randint(-30, 30)) # # add to the main field # #root.add_widget(picture) # root.add_widget(img) #except Exception as e: # Logger.exception('Pictures: Unable to load <%s>' % filename) for filename in glob(join(curdir, 'images', '*')): try: # load the image picture = Picture(source=filename, rotation=randint(-30, 30)) # add to the main field root.add_widget(picture) except Exception as e: Logger.exception('Pictures: Unable to load <%s>' % filename)
def body_layout(self): layout = self from main import SOURCE if SOURCE: curdir = SOURCE else: curdir = join(dirname(__file__),self.par_folder) pos_x = pos_y =0 thumb_folder = "thumbs" for filename in glob(join(curdir,self.folder,'*')): if(not isdir(filename)): try: file_parts = NT.basename(filename).rsplit('.',1) thumbnail = join(curdir,self.folder,thumb_folder,file_parts[0]) + '.png' video = CustomPlayer(source=filename, state='stop',size_hint=(None,None),size=(400, 200),\ allow_fullscreen=False,allow_stretch=True, thumbnail=thumbnail) scatter = MyScatter(height=200, width=400,size_hint=(None, None),rotation=randint(-30,30), \ scale_min=.5,scale_max=4.,auto_bring_to_front = True) scatter.add_widget(video) layout.add_widget(scatter) #combine image widget with scatter video.parent.size = video.size video.parent.pos = pos_x,pos_y if (pos_x+400 >= 1200): pos_y += 220 else: pos_y = pos_y pos_x = (pos_x+420)%1200 except Exception as e: Logger.exception('Videos: Unable to load <%s>' % filename) return layout
def tile_draw(self, nx, ny, tx, ty, sx, sy, zoom, bound): '''Draw a specific tile on the screen. Return False if the tile is not yet available.''' # nx, ny = index of tile # tx, ty = real position on scatter # sx, sy = real size on scatter # pzoom = current zoom level image = self.tileserver.get(nx, bound-ny-1, zoom, self.maptype) if image in (None, False): return if not image.texture: Logger.exception('Returned image has no texture.') return if image.texture.wrap is None: image.texture.wrap = GL_CLAMP alpha = Cache.get('tileserver.tilesalpha', image.id) if alpha is None: alpha = 0 if image.loaded: # as soon as we have the image alpha += min(self._dt * 4, 1.0) # fade it in Cache.append('tileserver.tilesalpha', image.id, alpha) with self.canvas: Color(1, 1, 1, alpha) Rectangle(pos=(tx, ty), size=(sx, sy), texture=image.texture)
def read_from_in_pipe(self, *l): """Read the output from the command """ txt = "\n" txt_line = "" os_read = os.read self_stdin_pipe = self.stdin_pipe self_mode = self.mode self_write = self.write Clock_schedule_once = Clock.schedule_once self_update_cache = self.update_cache self_flush = self.flush obj = self.obj try: while txt != "": txt = os_read(self_stdin_pipe, 1) txt_line = u"".join((txt_line, txt)) if txt == "\n": if self_mode == "stdin": # run command self_write(txt_line) else: Clock_schedule_once(partial(self_update_cache, txt_line, obj), 0) self_flush() txt_line = "" except OSError as e: Logger.exception(e)
def run(self): self.haveSocket = False # create socket self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # fix trouble if python leave without cleaning well the socket # not needed under windows, he can reuse addr even if the socket # are in fin2 or wait state. if os.name in ['posix', 'mac'] and hasattr(socket, 'SO_REUSEADDR'): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # try to bind the socket, retry if necessary while not self.haveSocket and self.isRunning: try : self.socket.bind((self.ipAddr, self.port)) self.socket.settimeout(0.5) self.haveSocket = True except socket.error, e: error, message = e.args # special handle for EADDRINUSE if error == errno.EADDRINUSE: Logger.error('OSC: Address %s:%i already in use, retry in 2 second' % (self.ipAddr, self.port)) else: Logger.exception(e) self.haveSocket = False # sleep 2 second before retry time.sleep(2)
def _update_files(self, *args): # Clear current files self.dispatch("on_entries_cleared") # Add the components that are always needed if platform == "win32": is_root = splitdrive(self.path)[1] in (sep, altsep) elif platform in ("darwin", "linux2"): is_root = normpath(expanduser(self.path)) == sep else: # Unknown file system; Just always add the .. entry but also log Logger.warning("Filechooser: Unsupported OS: %r" % platform) is_root = False if not is_root: back = ".." + sep pardir = Builder.template( self._ENTRY_TEMPLATE, **dict( name=back, size="", path=back, controller=self, isdir=True, parent=None, sep=sep, get_nice_size=lambda: "", ) ) self.dispatch("on_entry_added", pardir) try: self._add_files(self.path) except OSError, e: Logger.exception("Unable to open directory <%s>" % self.path)
def _update_files(self, *args): # Clear current files self.dispatch('on_entries_cleared') self._items = [] # Add the components that are always needed if platform == 'win': is_root = splitdrive(self.path)[1] in (sep, altsep) elif platform in ('macosx', 'linux', 'android', 'ios'): is_root = normpath(expanduser(self.path)) == sep else: # Unknown file system; Just always add the .. entry but also log Logger.warning('Filechooser: Unsupported OS: %r' % platform) is_root = False if not is_root: back = '..' + sep pardir = Builder.template(self._ENTRY_TEMPLATE, **dict(name=back, size='', path=back, controller=self, isdir=True, parent=None, sep=sep, get_nice_size=lambda: '')) self._items.append(pardir) self.dispatch('on_entry_added', pardir) try: self._add_files(self.path) except OSError: Logger.exception('Unable to open directory <%s>' % self.path)
def _update(self, dt): if self.stopped: return if self._texture is None: # Create the texture self._texture = Texture.create(self._resolution) self._texture.flip_vertical() self.dispatch('on_load') try: bufsize = self.raw_buffer_size() output = numpy.empty( (bufsize[0] * bufsize[1] * 3,), dtype=numpy.uint8) self._camera.capture(output, self._format, use_video_port=True) # Trim the buffer to fit the actual requested resolution. # TODO: Is there a simpler way to do all this reshuffling? output = output.reshape((bufsize[0], bufsize[1], 3)) output = output[:self.resolution[0], :self.resolution[1], :] self._buffer = output.reshape( (self.resolution[0] * self.resolution[1] * 3,)) self._copy_to_gpu() except KeyboardInterrupt: raise except Exception: Logger.exception('PiCamera: Couldn\'t get image from Camera')
def on_ref_press(self, refid): try: self.dispatch('on_item_press', self.references[int(refid)]) except Exception as ex: Logger.exception('Exception dispatching on_item_press(%s)\n%r' % (self.references[int(refid)], ex) )
def build(self): # the root is created in pictures.kv self.root self.osc_id = osc.listen(ipAddr='0.0.0.0', port=activity_port) if platform == 'android': from android import AndroidService service = AndroidService('Mentor Service', 'running') service.start('service started') self.service = service # get any files into images directory curdir = dirname(__file__) list = glob(join(curdir, 'images', '*')) Logger.debug("{}".format(list)) shuffle(list) Logger.debug("{}".format(list)) for filename in list: try: # load the image picture = Picture(source=filename, id=filename, rotation=randint(-30, 30)) # add to the main field self.root.add_widget(picture) except Exception as e: Logger.exception('Pictures: Unable to load <%s>' % filename) osc.init() self.last_name = "" osc.sendMsg('/say', ["La ap di Michele e' pronta", ], port=service_port) return self.root
def start_server(self, threadnum): self.setup_chronograph() try: if os.fork() == 0: #self.redirect_output() self.execute_manager(self.settings, [ 'manage.py', 'runcherrypyserver', "host={}".format(self.app.server_host), "port={}".format(self.app.server_port), "pidfile={}".format(self.pid_file), 'daemonize=True', threadnum, '--verbose']) # self.execute_manager(self.settings, [ # 'manage.py', 'kaserve', # "host={}".format(self.app.server_host), # "pidfile={}".format(self.pid_file), # 'daemonize=true', # 'production=true', # 'threads=3']) sys.exit(0) except OSError, e: Logger.exception("Fork error: {type}{args}".format(type=type(e), args=e.args)) return 'fail'
def _load_urllib(self, filename, kwargs): '''(internal) Loading a network file. First download it, save it to a temporary file, and pass it to _load_local()''' import urllib2 proto = filename.split(':', 1)[0] if proto == 'smb': try: # note: it's important to load SMBHandler every time # otherwise the data is occasionaly not loaded from smb.SMBHandler import SMBHandler except ImportError: Logger.warning( 'Loader: can not load PySMB: make sure it is installed') return import tempfile data = fd = _out_osfd = None try: _out_filename = '' suffix = '.%s' % (filename.split('.')[-1]) _out_osfd, _out_filename = tempfile.mkstemp( prefix='kivyloader', suffix=suffix) if proto == 'smb': # read from samba shares fd = urllib2.build_opener(SMBHandler).open(filename) else: # read from internet fd = urllib2.urlopen(filename) idata = fd.read() fd.close() fd = None # write to local filename write(_out_osfd, idata) close(_out_osfd) _out_osfd = None # load data data = self._load_local(_out_filename, kwargs) # FIXME create a clean API for that for imdata in data._data: imdata.source = filename except Exception: Logger.exception('Failed to load image <%s>' % filename) # close file when remote file not found or download error try: close(_out_osfd) except OSError: pass return self.error_image finally: if fd: fd.close() if _out_osfd: close(_out_osfd) if _out_filename != '': unlink(_out_filename) return data
def parse_color(c, default=None): if not c: return default if c == 'none': return None if c[0] == '#': c = c[1:] if c.startswith('url(#'): return c[5:-1] try: if str(c) in colormap: c = colormap[str(c)][1:] r = int(c[0:2], 16) g = int(c[2:4], 16) b = int(c[4:6], 16) elif len(c) == 6: r = int(c[0:2], 16) g = int(c[2:4], 16) b = int(c[4:6], 16) elif len(c) == 3: r = int(c[0], 16) * 17 g = int(c[1], 16) * 17 b = int(c[2], 16) * 17 else: Logger.exception('Squirtle: incorrect length for color %s' % str(c)) return [r, g, b, 255] except Exception, ex: Logger.exception('Squirtle: exception parsing color %s' % str(c)) return None
def _load_urllib(self, filename): '''(internal) Loading a network file. First download it, save it to a temporary file, and pass it to _load_local()''' import urllib2 import tempfile data = None try: _out_filename = '' suffix = '.%s' % (filename.split('.')[-1]) _out_osfd, _out_filename = tempfile.mkstemp( prefix='kivyloader', suffix=suffix) # read from internet fd = urllib2.urlopen(filename) idata = fd.read() fd.close() # write to local filename write(_out_osfd, idata) close(_out_osfd) # load data data = self._load_local(_out_filename) except Exception: Logger.exception('Failed to load image <%s>' % filename) return self.error_image finally: if _out_filename != '': unlink(_out_filename) return data
def create_window(self, *largs): if self._fake_fullscreen: if not self.borderless: self.fullscreen = self._fake_fullscreen = False elif not self.fullscreen or self.fullscreen == 'auto': self.borderless = self._fake_fullscreen = False if self.fullscreen == 'fake': self.borderless = self._fake_fullscreen = True Logger.warning("The 'fake' fullscreen option has been " "deprecated, use Window.borderless or the " "borderless Config option instead.") if not self.initialized: if self.position == 'auto': pos = None, None elif self.position == 'custom': pos = self.left, self.top # setup ! w, h = self._size resizable = Config.getboolean('graphics', 'resizable') gl_size = self._win.setup_window(pos[0], pos[1], w, h, self.borderless, self.fullscreen, resizable) # never stay with a None pos, application using w.center # will be fired. self._pos = (0, 0) else: w, h = self._size self._win.resize_window(w, h) self._win.set_border_state(self.borderless) self._win.set_fullscreen_mode(self.fullscreen) super(WindowSDL, self).create_window() # auto add input provider Logger.info('Window: auto add sdl input provider') from kivy.base import EventLoop SDL2MotionEventProvider.win = self EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', '')) # set window icon before calling set_mode try: filename_icon = self.icon or Config.get('kivy', 'window_icon') if filename_icon == '': logo_size = 32 if platform == 'macosx': logo_size = 512 elif platform == 'win': logo_size = 64 filename_icon = 'kivy-icon-{}.png'.format(logo_size) filename_icon = resource_find( join(kivy_data_dir, 'logo', filename_icon)) self.set_icon(filename_icon) except: Logger.exception('Window: cannot set icon')
def set_icon(self, filename): try: if not exists(filename): return False icon = pygame.image.load(filename) pygame.display.set_icon(icon) except: Logger.exception('WinPygame: unable to set icon')
def show_error_popup(self, title, message): try: content = Label(text=message) self._popup = Popup(title=title, content=content, size_hint=(0.9, None)) self._popup.open() except Exception as e: Logger.exception('VisComp: Error %s' %message)
def show_exception(e): """Show th latest exception in a pop-up dialog.""" tb = traceback.format_exc() Logger.exception(str(e)) Logger.exception(tb) popup = Popup(title='Python exception occured', content=TextInput(text=str(e) + "\n\n" + tb), size_hint=(.8, .8)) popup.open()
def open_in_file_manager(path): if system == 'Windows': subprocess.Popen(['start', path], shell=True) elif system == 'Darwin': subprocess.Popen(['open', path]) else: try: subprocess.Popen(['xdg-open', path]) except OSError: Logger.exception('Cannot open external file manager')
def _update(self, dt): if self.stopped: return try: frame = hg.cvQueryFrame(self._device) self._format = 'bgr' self._buffer = frame.imageData self._copy_to_gpu() except: Logger.exception('OpenCV: Couldn\'t get image from Camera')
def __init__(self, **kwargs): super(Harvest, self).__init__(**kwargs) self.inputs = [] for i in range(int(self.sizeX)): for y in range(int(self.sizeY)): try: tmp = Image(source=self.filename, pos=(i * 30, y * 30)) self.add_widget(tmp) except Exception, e: Logger.exception('Harvest: Unable to load <%s>' % self.filename)
def is_hidden_win(fn): if not _have_win32file: return False try: return GetFileAttributesEx(fn)[0] & FILE_ATTRIBUTE_HIDDEN except error: # This error can occured when a file is already accessed by someone # else. So don't return to True, because we have lot of chances to not # being able to do anything with it. Logger.exception('unable to access to <%s>' % fn) return True
def is_hidden_win(fn): if not _have_win32file: return False try: return GetFileAttributesEx(fn)[0] & FILE_ATTRIBUTE_HIDDEN except error: # This error can occur when a file is already being accessed by someone # else. Return True because it's likely we will not be # able to do anything with it. Logger.exception('unable to access to <%s>' % fn) return True
def _worker_run(self, c_in, q_in, q_out): '''Internal. Main function for every worker ''' do = self._worker_run_once while not self.want_close: try: do(c_in, q_in, q_out) except: Logger.exception('TileServerWorker: Unknown exception, stop the worker') return
def main(): from font_render.app import FontRenderApp Config.set("kivy", "log_level", "debug") Config.write() try: FontRenderApp().run() except: exc = get_exception(full_tb=True) Logger.exception(str(exc))
def create_window(self, *largs): if self._fake_fullscreen: if not self.borderless: self.fullscreen = self._fake_fullscreen = False elif not self.fullscreen or self.fullscreen == 'auto': self.borderless = self._fake_fullscreen = False if self.fullscreen == 'fake': self.borderless = self._fake_fullscreen = True Logger.warning("The 'fake' fullscreen option has been " "deprecated, use Window.borderless or the " "borderless Config option instead.") if not self.initialized: if self.position == 'auto': pos = None, None elif self.position == 'custom': pos = self.left, self.top # setup ! w, h = self._size resizable = Config.getboolean('graphics', 'resizable') gl_size = self._win.setup_window(pos[0], pos[1], w, h, self.borderless, self.fullscreen, resizable) # never stay with a None pos, application using w.center # will be fired. self._pos = (0, 0) else: w, h = self._size self._win.resize_window(w, h) self._win.set_border_state(self.borderless) self._win.set_fullscreen_mode(self.fullscreen) super(WindowSDL, self).create_window() if self.initialized: return # auto add input provider Logger.info('Window: auto add sdl2 input provider') from kivy.base import EventLoop SDL2MotionEventProvider.win = self EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', '')) # set window icon before calling set_mode try: filename_icon = self.icon or Config.get('kivy', 'window_icon') if filename_icon == '': logo_size = 32 if platform == 'macosx': logo_size = 512 elif platform == 'win': logo_size = 64 filename_icon = 'kivy-icon-{}.png'.format(logo_size) filename_icon = resource_find( join(kivy_data_dir, 'logo', filename_icon)) self.set_icon(filename_icon) except: Logger.exception('Window: cannot set icon')
class WindowPygame(WindowBase): def create_window(self, *largs): # ensure the mouse is still not up after window creation, otherwise, we # have some weird bugs self.dispatch('on_mouse_up', 0, 0, 'all', []) # force display to show (available only for fullscreen) displayidx = Config.getint('graphics', 'display') if not 'SDL_VIDEO_FULLSCREEN_HEAD' in environ and displayidx != -1: environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx # init some opengl, same as before. self.flags = pygame.HWSURFACE | pygame.OPENGL | \ pygame.DOUBLEBUF # right now, activate resizable window only on linux. # on window / macosx, the opengl context is lost, and we need to # reconstruct everything. Check #168 for a state of the work. if platform() in ('linux', 'macosx', 'win') and \ Config.getint('graphics', 'resizable'): self.flags |= pygame.RESIZABLE try: pygame.display.init() except pygame.error, e: raise CoreCriticalException(e.message) multisamples = Config.getint('graphics', 'multisamples') if multisamples > 0: pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1) pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, multisamples) pygame.display.gl_set_attribute(pygame.GL_DEPTH_SIZE, 16) pygame.display.gl_set_attribute(pygame.GL_STENCIL_SIZE, 1) pygame.display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8) pygame.display.set_caption(self.title) if self.position == 'auto': self._pos = None elif self.position == 'custom': self._pos = self.left, self.top else: raise ValueError('position token in configuration accept only ' '"auto" or "custom"') if self.fullscreen == 'fake': Logger.debug('WinPygame: Set window to fake fullscreen mode') self.flags |= pygame.NOFRAME # if no position set, in fake mode, we always need to set the # position. so replace 0, 0. if self._pos is None: self._pos = (0, 0) environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos elif self.fullscreen is True: Logger.debug('WinPygame: Set window to fullscreen mode') self.flags |= pygame.FULLSCREEN elif self._pos is not None: environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos # never stay with a None pos, application using w.center will be fired. self._pos = (0, 0) # prepare keyboard repeat_delay = int(Config.get('kivy', 'keyboard_repeat_delay')) repeat_rate = float(Config.get('kivy', 'keyboard_repeat_rate')) pygame.key.set_repeat(repeat_delay, int(1000. / repeat_rate)) # set window icon before calling set_mode try: #filename_icon = Config.get('kivy', 'window_icon') filename_icon = self.icon or Config.get('kivy', 'window_icon') if filename_icon == '': logo_size = 512 if platform() == 'macosx' else 32 filename_icon = join(kivy_home_dir, 'icon', 'kivy-icon-%d.png' % logo_size) self.set_icon(filename_icon) except: Logger.exception('Window: cannot set icon') # try to use mode with multisamples try: self._pygame_set_mode() except pygame.error, e: if multisamples: Logger.warning('WinPygame: Video: failed (multisamples=%d)' % multisamples) Logger.warning('WinPygame: trying without antialiasing') pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 0) pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 0) multisamples = 0 try: self._pygame_set_mode() except pygame.error, e: raise CoreCriticalException(e.message)
def create_window(self, *largs): if self._fake_fullscreen: if not self.borderless: self.fullscreen = self._fake_fullscreen = False elif not self.fullscreen or self.fullscreen == 'auto': self.custom_titlebar = \ self.borderless = self._fake_fullscreen = False elif self.custom_titlebar: if platform == 'win': # use custom behaviour # To handle aero snapping and rounded corners self.borderless = False if self.fullscreen == 'fake': self.borderless = self._fake_fullscreen = True Logger.warning("The 'fake' fullscreen option has been " "deprecated, use Window.borderless or the " "borderless Config option instead.") if not self.initialized: if self.position == 'auto': pos = None, None elif self.position == 'custom': pos = self.left, self.top # ensure we have an event filter self._win.set_event_filter(self._event_filter) # setup window w, h = self.system_size resizable = Config.getboolean('graphics', 'resizable') state = (Config.get('graphics', 'window_state') if self._is_desktop else None) self.system_size = _size = self._win.setup_window( pos[0], pos[1], w, h, self.borderless, self.fullscreen, resizable, state, self.get_gl_backend_name()) # calculate density/dpi if platform == 'win': from ctypes import windll self._density = 1. try: hwnd = windll.user32.GetActiveWindow() self.dpi = float(windll.user32.GetDpiForWindow(hwnd)) except AttributeError: pass else: sz = self._win._get_gl_size()[0] self._density = density = sz / _size[0] if self._is_desktop and self.size[0] != _size[0]: self.dpi = density * 96. # never stay with a None pos, application using w.center # will be fired. self._pos = (0, 0) self._set_minimum_size() self._set_allow_screensaver() if state == 'hidden': self._focus = False else: w, h = self.system_size self._win.resize_window(w, h) if platform == 'win': if self.custom_titlebar: # check dragging+resize or just dragging if Config.getboolean('graphics', 'resizable'): import win32con import ctypes self._win.set_border_state(False) # make windows dispatch, # WM_NCCALCSIZE explicitly ctypes.windll.user32.SetWindowPos( self._win.get_window_info().window, win32con.HWND_TOP, *self._win.get_window_pos(), *self.system_size, win32con.SWP_FRAMECHANGED) else: self._win.set_border_state(True) else: self._win.set_border_state(self.borderless) else: self._win.set_border_state(self.borderless or self.custom_titlebar) self._win.set_fullscreen_mode(self.fullscreen) super(WindowSDL, self).create_window() # set mouse visibility self._set_cursor_state(self.show_cursor) if self.initialized: return # auto add input provider Logger.info('Window: auto add sdl2 input provider') from kivy.base import EventLoop SDL2MotionEventProvider.win = self EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', '')) # set window icon before calling set_mode try: filename_icon = self.icon or Config.get('kivy', 'window_icon') if filename_icon == '': logo_size = 32 if platform == 'macosx': logo_size = 512 elif platform == 'win': logo_size = 64 filename_icon = 'kivy-icon-{}.png'.format(logo_size) filename_icon = resource_find( join(kivy_data_dir, 'logo', filename_icon)) self.set_icon(filename_icon) except: Logger.exception('Window: cannot set icon') if platform == 'win' and self._win_dpi_watch is None: self._win_dpi_watch = _WindowsSysDPIWatch(window=self) self._win_dpi_watch.start()
def _load_urllib(self, filename, kwargs): '''(internal) Loading a network file. First download it, save it to a temporary file, and pass it to _load_local()''' if PY2: import urllib2 as urllib_request else: import urllib.request as urllib_request proto = filename.split(':', 1)[0] if proto == 'smb': try: # note: it's important to load SMBHandler every time # otherwise the data is occasionaly not loaded from smb.SMBHandler import SMBHandler except ImportError: Logger.warning( 'Loader: can not load PySMB: make sure it is installed') return import tempfile data = fd = _out_osfd = None try: _out_filename = '' suffix = '.%s' % (filename.split('.')[-1]) _out_osfd, _out_filename = tempfile.mkstemp(prefix='kivyloader', suffix=suffix) if proto == 'smb': # read from samba shares fd = urllib_request.build_opener(SMBHandler).open(filename) else: # read from internet fd = urllib_request.urlopen(filename) idata = fd.read() fd.close() fd = None # write to local filename write(_out_osfd, idata) close(_out_osfd) _out_osfd = None # load data data = self._load_local(_out_filename, kwargs) # FIXME create a clean API for that for imdata in data._data: imdata.source = filename except Exception: Logger.exception('Failed to load image <%s>' % filename) # close file when remote file not found or download error try: close(_out_osfd) except OSError: pass return self.error_image finally: if fd: fd.close() if _out_osfd: close(_out_osfd) if _out_filename != '': unlink(_out_filename) return data
# Read, analyse configuration file # Support upgrade of older config file versions # # Create default configuration Config = ConfigParser(name='kivy') Config.add_callback(logger_config_update, 'kivy', 'log_level') # Read config file if exist if (exists(kivy_config_fn) and 'KIVY_USE_DEFAULTCONFIG' not in environ and 'KIVY_NO_CONFIG' not in environ): try: Config.read(kivy_config_fn) except Exception as e: Logger.exception('Core: error while reading local' 'configuration') version = Config.getdefaultint('kivy', 'config_version', 0) # Add defaults section Config.adddefaultsection('kivy') Config.adddefaultsection('graphics') Config.adddefaultsection('input') Config.adddefaultsection('postproc') Config.adddefaultsection('widgets') Config.adddefaultsection('modules') # Upgrade default configuration until we have the current version need_save = False if version != KIVY_CONFIG_VERSION and 'KIVY_NO_CONFIG' not in environ: Logger.warning('Config: Older configuration version detected'
platform = core_platform() if platform == 'win' or 'KIVY_DOC' in os.environ: try: __import__('kivy.input.providers.wm_touch') __import__('kivy.input.providers.wm_pen') except: err = 'Input: WM_Touch/WM_Pen not supported by your version of Windows' Logger.warning(err) if platform == 'macosx' or 'KIVY_DOC' in os.environ: try: __import__('kivy.input.providers.mactouch') except: err = 'Input: MacMultitouchSupport is not supported by your system' Logger.exception(err) if platform == 'linux' or 'KIVY_DOC' in os.environ: try: __import__('kivy.input.providers.probesysfs') except: err = 'Input: ProbeSysfs is not supported by your version of linux' Logger.exception(err) try: __import__('kivy.input.providers.mtdev') except: err = 'Input: MTDev is not supported by your version of linux' Logger.exception(err) try: __import__('kivy.input.providers.hidinput') except:
def _generate_file_entries(self, *args, **kwargs): # Generator that will create all the files entries. # the generator is used via _update_files() and _create_files_entries() # don't use it directly. is_root = False path = kwargs.get('path', self.path) have_parent = kwargs.get('parent', None) is not None # Add the components that are always needed if self.rootpath: rootpath = realpath(self.rootpath) path = realpath(path) if not path.startswith(rootpath): self.path = rootpath return elif path == rootpath: is_root = True else: if platform == 'win': is_root = splitdrive(path)[1] in (sep, altsep) elif platform in ('macosx', 'linux', 'android', 'ios'): is_root = normpath(expanduser(path)) == sep else: # Unknown fs, just always add the .. entry but also log Logger.warning('Filechooser: Unsupported OS: %r' % platform) # generate an entries to go back to previous if not is_root and not have_parent: back = '..' + sep if platform == 'win': new_path = path[:path.rfind(sep)] if sep not in new_path: new_path += sep pardir = self._create_entry_widget( dict(name=back, size='', path=new_path, controller=ref(self), isdir=True, parent=None, sep=sep, get_nice_size=lambda: '', icon='none')) else: pardir = self._create_entry_widget( dict(name=back, size='', path=back, controller=ref(self), isdir=True, parent=None, sep=sep, get_nice_size=lambda: '', icon='none')) yield 0, 1, pardir # generate all the entries for files try: for index, total, item in self._add_files(path): yield index, total, item except OSError: Logger.exception('Unable to open directory <%s>' % self.path) self.files[:] = []
def _load_urllib(self, filename, kwargs): '''(internal) Loading a network file. First download it, save it to a temporary file, and pass it to _load_local().''' if PY2: import urllib2 as urllib_request def gettype(info): return info.gettype() else: import urllib.request as urllib_request def gettype(info): return info.get_content_type() proto = filename.split(':', 1)[0] if proto == 'smb': try: # note: it's important to load SMBHandler every time # otherwise the data is occasionaly not loaded from smb.SMBHandler import SMBHandler except ImportError: Logger.warning( 'Loader: can not load PySMB: make sure it is installed') return import tempfile data = fd = _out_osfd = None try: _out_filename = '' if proto == 'smb': # read from samba shares fd = urllib_request.build_opener(SMBHandler).open(filename) else: # read from internet fd = urllib_request.urlopen(filename) if '#.' in filename: # allow extension override from URL fragment suffix = '.' + filename.split('#.')[-1] else: ctype = gettype(fd.info()) suffix = mimetypes.guess_extension(ctype) if not suffix: # strip query string and split on path parts = filename.split('?')[0].split('/')[1:] while len(parts) > 1 and not parts[0]: # strip out blanks from '//' parts = parts[1:] if len(parts) > 1 and '.' in parts[-1]: # we don't want '.com', '.net', etc. as the extension suffix = '.' + parts[-1].split('.')[-1] _out_osfd, _out_filename = tempfile.mkstemp( prefix='kivyloader', suffix=suffix) idata = fd.read() fd.close() fd = None # write to local filename write(_out_osfd, idata) close(_out_osfd) _out_osfd = None # load data data = self._load_local(_out_filename, kwargs) # FIXME create a clean API for that for imdata in data._data: imdata.source = filename except Exception: Logger.exception('Loader: Failed to load image <%s>' % filename) # close file when remote file not found or download error try: close(_out_osfd) except OSError: pass return self.error_image finally: if fd: fd.close() if _out_osfd: close(_out_osfd) if _out_filename != '': unlink(_out_filename) return data
def create_window(self, *largs): # ensure the mouse is still not up after window creation, otherwise, we # have some weird bugs self.dispatch('on_mouse_up', 0, 0, 'all', []) # force display to show (available only for fullscreen) displayidx = Config.getint('graphics', 'display') if not 'SDL_VIDEO_FULLSCREEN_HEAD' in environ and displayidx != -1: environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx # init some opengl, same as before. self.flags = pygame.HWSURFACE | pygame.OPENGL | pygame.DOUBLEBUF # right now, activate resizable window only on linux. # on window / macosx, the opengl context is lost, and we need to # reconstruct everything. Check #168 for a state of the work. if platform in ('linux', 'macosx', 'win') and \ Config.getboolean('graphics', 'resizable'): self.flags |= pygame.RESIZABLE try: pygame.display.init() except pygame.error as e: raise CoreCriticalException(e.message) multisamples = Config.getint('graphics', 'multisamples') if multisamples > 0: pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1) pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, multisamples) pygame.display.gl_set_attribute(pygame.GL_DEPTH_SIZE, 16) pygame.display.gl_set_attribute(pygame.GL_STENCIL_SIZE, 1) pygame.display.set_caption(self.title) if self.position == 'auto': self._pos = None elif self.position == 'custom': self._pos = self.left, self.top else: raise ValueError('position token in configuration accept only ' '"auto" or "custom"') if self._fake_fullscreen: if not self.borderless: self.fullscreen = self._fake_fullscreen = False elif not self.fullscreen or self.fullscreen == 'auto': self.borderless = self._fake_fullscreen = False if self.fullscreen == 'fake': self.borderless = self._fake_fullscreen = True Logger.warning("The 'fake' fullscreen option has been " "deprecated, use Window.borderless or the " "borderless Config option instead.") if self.fullscreen == 'fake' or self.borderless: Logger.debug('WinPygame: Set window to borderless mode.') self.flags |= pygame.NOFRAME # If no position set in borderless mode, we always need # to set the position. So use 0, 0. if self._pos is None: self._pos = (0, 0) environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos elif self.fullscreen in ('auto', True): Logger.debug('WinPygame: Set window to fullscreen mode') self.flags |= pygame.FULLSCREEN elif self._pos is not None: environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos # never stay with a None pos, application using w.center will be fired. self._pos = (0, 0) # prepare keyboard repeat_delay = int(Config.get('kivy', 'keyboard_repeat_delay')) repeat_rate = float(Config.get('kivy', 'keyboard_repeat_rate')) pygame.key.set_repeat(repeat_delay, int(1000. / repeat_rate)) # set window icon before calling set_mode try: filename_icon = self.icon or Config.get('kivy', 'window_icon') if filename_icon == '': logo_size = 32 if platform == 'macosx': logo_size = 512 elif platform == 'win': logo_size = 64 filename_icon = 'kivy-icon-{}.png'.format(logo_size) filename_icon = resource_find( join(kivy_data_dir, 'logo', filename_icon)) self.set_icon(filename_icon) except: Logger.exception('Window: cannot set icon') # try to use mode with multisamples try: self._pygame_set_mode() except pygame.error as e: if multisamples: Logger.warning('WinPygame: Video: failed (multisamples=%d)' % multisamples) Logger.warning('WinPygame: trying without antialiasing') pygame.display.gl_set_attribute( pygame.GL_MULTISAMPLEBUFFERS, 0) pygame.display.gl_set_attribute( pygame.GL_MULTISAMPLESAMPLES, 0) multisamples = 0 try: self._pygame_set_mode() except pygame.error as e: raise CoreCriticalException(e.message) else: raise CoreCriticalException(e.message) if pygame.RESIZABLE & self.flags: self._pygame_set_mode() info = pygame.display.Info() self._size = (info.current_w, info.current_h) #self.dispatch('on_resize', *self._size) # in order to debug futur issue with pygame/display, let's show # more debug output. Logger.debug('Window: Display driver ' + pygame.display.get_driver()) Logger.debug('Window: Actual window size: %dx%d', info.current_w, info.current_h) if platform != 'android': # unsupported platform, such as android that doesn't support # gl_get_attribute. Logger.debug( 'Window: Actual color bits r%d g%d b%d a%d', pygame.display.gl_get_attribute(pygame.GL_RED_SIZE), pygame.display.gl_get_attribute(pygame.GL_GREEN_SIZE), pygame.display.gl_get_attribute(pygame.GL_BLUE_SIZE), pygame.display.gl_get_attribute(pygame.GL_ALPHA_SIZE)) Logger.debug( 'Window: Actual depth bits: %d', pygame.display.gl_get_attribute(pygame.GL_DEPTH_SIZE)) Logger.debug( 'Window: Actual stencil bits: %d', pygame.display.gl_get_attribute(pygame.GL_STENCIL_SIZE)) Logger.debug( 'Window: Actual multisampling samples: %d', pygame.display.gl_get_attribute(pygame.GL_MULTISAMPLESAMPLES)) super(WindowPygame, self).create_window() # set mouse visibility pygame.mouse.set_visible( Config.getboolean('graphics', 'show_cursor')) # if we are on android platform, automaticly create hooks if android: from kivy.support import install_android install_android()
) } # Read environment for option in kivy_options: key = 'KIVY_%s' % option.upper() if key in environ: try: if type(kivy_options[option]) in (list, tuple): kivy_options[option] = environ[key].split(',') else: kivy_options[option] = environ[key].lower() in \ ('true', '1', 'yes') except Exception: Logger.warning('Core: Wrong value for %s environment key' % key) Logger.exception('') # Extract all needed path in kivy #: Kivy directory kivy_base_dir = dirname(sys.modules[__name__].__file__) #: Kivy modules directory kivy_modules_dir = environ.get('KIVY_MODULES_DIR', join(kivy_base_dir, 'modules')) #: Kivy data directory kivy_data_dir = environ.get('KIVY_DATA_DIR', join(kivy_base_dir, 'data')) #: Kivy binary deps directory kivy_binary_deps_dir = environ.get('KIVY_BINARY_DEPS', join(kivy_base_dir, 'binary_deps')) #: Kivy glsl shader directory kivy_shader_dir = join(kivy_data_dir, 'glsl')
def create_window(self, *largs): if self._fake_fullscreen: if not self.borderless: self.fullscreen = self._fake_fullscreen = False elif not self.fullscreen or self.fullscreen == 'auto': self.borderless = self._fake_fullscreen = False if self.fullscreen == 'fake': self.borderless = self._fake_fullscreen = True Logger.warning("The 'fake' fullscreen option has been " "deprecated, use Window.borderless or the " "borderless Config option instead.") if not self.initialized: if self.position == 'auto': pos = None, None elif self.position == 'custom': pos = self.left, self.top # ensure we have an event filter self._win.set_event_filter(self._event_filter) # setup window w, h = self.system_size resizable = Config.getboolean('graphics', 'resizable') state = (Config.get('graphics', 'window_state') if self._is_desktop else None) self.system_size = _size = self._win.setup_window( pos[0], pos[1], w, h, self.borderless, self.fullscreen, resizable, state, self.get_gl_backend_name()) # calculate density sz = self._win._get_gl_size()[0] self._density = density = sz / _size[0] if self._is_desktop and self.size[0] != _size[0]: self.dpi = density * 96. # never stay with a None pos, application using w.center # will be fired. self._pos = (0, 0) self._set_minimum_size() self._set_allow_screensaver() if state == 'hidden': self._focus = False else: w, h = self.system_size self._win.resize_window(w, h) self._win.set_border_state(self.borderless) self._win.set_fullscreen_mode(self.fullscreen) super(WindowSDL, self).create_window() # set mouse visibility self._set_cursor_state(self.show_cursor) if self.initialized: return # auto add input provider Logger.info('Window: auto add sdl2 input provider') from kivy.base import EventLoop SDL2MotionEventProvider.win = self EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', '')) # set window icon before calling set_mode try: filename_icon = self.icon or Config.get('kivy', 'window_icon') if filename_icon == '': logo_size = 32 if platform == 'macosx': logo_size = 512 elif platform == 'win': logo_size = 64 filename_icon = 'kivy-icon-{}.png'.format(logo_size) filename_icon = resource_find( join(kivy_data_dir, 'logo', filename_icon)) self.set_icon(filename_icon) except: Logger.exception('Window: cannot set icon')
def execute_directives(self): global __KV_INCLUDES__ for ln, cmd in self.directives: cmd = cmd.strip() if __debug__: trace('Parser: got directive <%s>' % cmd) if cmd[:5] == 'kivy ': version = cmd[5:].strip() if len(version.split('.')) == 2: version += '.0' require(version) elif cmd[:4] == 'set ': try: name, value = cmd[4:].strip().split(' ', 1) except: Logger.exception('') raise ParserException(self, ln, 'Invalid directive syntax') try: value = eval(value, global_idmap) except: Logger.exception('') raise ParserException(self, ln, 'Invalid value') global_idmap[name] = value elif cmd[:8] == 'include ': ref = cmd[8:].strip() force_load = False if ref[:6] == 'force ': ref = ref[6:].strip() force_load = True # if #:include [force] "path with quotes around" if ref[0] == ref[-1] and ref[0] in ('"', "'"): c = ref[:3].count(ref[0]) ref = ref[c:-c] if c != 2 else ref if ref[-3:] != '.kv': Logger.warn('Lang: {0} does not have a valid Kivy' 'Language extension (.kv)'.format(ref)) break if ref in __KV_INCLUDES__: if not os.path.isfile(resource_find(ref) or ref): raise ParserException( self, ln, 'Invalid or unknown file: {0}'.format(ref)) if not force_load: Logger.warn( 'Lang: {0} has already been included!'.format(ref)) continue else: Logger.debug('Lang: Reloading {0} ' + 'because include was forced.'.format(ref)) kivy.lang.builder.Builder.unload_file(ref) kivy.lang.builder.Builder.load_file(ref) continue Logger.debug('Lang: Including file: {0}'.format(0)) __KV_INCLUDES__.append(ref) kivy.lang.builder.Builder.load_file(ref) elif cmd[:7] == 'import ': package = cmd[7:].strip() z = package.split() if len(z) != 2: raise ParserException(self, ln, 'Invalid import syntax') alias, package = z try: if package not in sys.modules: try: mod = __import__(package) except ImportError: mod = __import__('.'.join(package.split('.')[:-1])) # resolve the whole thing for part in package.split('.')[1:]: mod = getattr(mod, part) else: mod = sys.modules[package] global_idmap[alias] = mod except ImportError: Logger.exception('') raise ParserException( self, ln, 'Unable to import package %r' % package) else: raise ParserException(self, ln, 'Unknown directive')