def draw_dialog(dialog_id): _dialog = get_dialog(dialog_id) _last_message = get_last_message(dialog_id) _x = numbers.clip(MAP_WINDOW_SIZE[0]/2-len(_last_message['text'])/2, 3, 100) _y = 10 _line_of_sight = drawing.diag_line(LIFE[_dialog['started_by']]['pos'], LIFE[_dialog['target']]['pos']) locks.unlock('camera_free') if len(_line_of_sight)<=1: _center_pos = LIFE[_dialog['started_by']]['pos'] else: _center_pos = list(_line_of_sight[len(_line_of_sight)/2]) _center_pos.append(2) if SETTINGS['controlling'] == _dialog['started_by']: _target = _dialog['target'] else: _target = _dialog['started_by'] _target_portrait = lfe.draw_life_icon(LIFE[_target]) _lines = [] gfx.camera_track(_center_pos) gfx.blit_string(_x-2, _y-2, ' '.join(LIFE[_target]['name']), 'overlay', fore_color=_target_portrait[1]) gfx.blit_string(_x-2, _y, _target_portrait[0], 'overlay', fore_color=_target_portrait[1])#, back_color=tcod.darkest_gray) _text = _last_message['text'] _y_mod = 0 while _text: _x = MAP_WINDOW_SIZE[0]/2-len(_text[:MAP_WINDOW_SIZE[0]-4])/2 gfx.blit_string(_x, _y+_y_mod, _text[:MAP_WINDOW_SIZE[0]-4], 'overlay') _text = _text[MAP_WINDOW_SIZE[0]-4:] _y_mod += 1 for choice in _dialog['choices']: _text = choice['text'][choice['text'].index('\"')+1:choice['text'].index('\"')-1] if not _text.startswith('>'): _text = '> '+_text _n_x = MAP_WINDOW_SIZE[0]/2-len(_text)/2 if _n_x < _x: _x = _n_x for choice in _dialog['choices']: _text = choice['text'][choice['text'].index('\"')+1:choice['text'].index('\"')-1] if _dialog['cursor_index'] == _dialog['choices'].index(choice): _text = '> '+_text _lines.append(_text) for line in _lines: gfx.blit_string(_x, _y+3, line, 'overlay')#, back_color=tcod.darkest_gray) _y += 2
def file_move_safe(old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False): """ Moves a file from one location to another in the safest way possible. First, tries ``os.rename``, which is simple but will break across filesystems. If that fails, streams manually from one file to another in pure Python. If the destination file exists and ``allow_overwrite`` is ``False``, this function will throw an ``IOError``. """ # There's no reason to move if we don't have to. if _samefile(old_file_name, new_file_name): return try: # If the destination file exists and allow_overwrite is False then raise an IOError if not allow_overwrite and os.access(new_file_name, os.F_OK): raise IOError( "Destination file %s exists and allow_overwrite is False" % new_file_name) os.rename(old_file_name, new_file_name) return except OSError: # This will happen with os.rename if moving to another filesystem # or when moving opened files on certain operating systems pass # first open the old file, so that it won't go away with open(old_file_name, 'rb') as old_file: # now open the new file, not forgetting allow_overwrite fd = os.open(new_file_name, (os.O_WRONLY | os.O_CREAT | getattr(os, 'O_BINARY', 0) | (os.O_EXCL if not allow_overwrite else 0))) try: locks.lock(fd, locks.LOCK_EX) current_chunk = None while current_chunk != b'': current_chunk = old_file.read(chunk_size) os.write(fd, current_chunk) finally: locks.unlock(fd) os.close(fd) copystat(old_file_name, new_file_name) try: os.remove(old_file_name) except OSError as e: # Certain operating systems (Cygwin and Windows) # fail when deleting opened files, ignore it. (For the # systems where this happens, temporary files will be auto-deleted # on close anyway.) if getattr(e, 'winerror', 0) != 32 and getattr(e, 'errno', 0) != 13: raise
def process(life, dialog_id): if not is_turn_to_talk(life, dialog_id): return False _last_message = get_last_message(dialog_id) if _last_message['next_gist'] == 'end': end_dialog(dialog_id) locks.lock('camera_free') elif 'player' in life: locks.unlock('camera_free', reason='Process dialog') process_dialog_for_player(dialog_id, loop=_last_message['loop']) else: say_via_gist(life, dialog_id, _last_message['next_gist'], loop=_last_message['loop'])
def draw_event(): _event = None for event in EVENTS: if not event['delay']: _event = event break if not _event: return False locks.unlock('camera_free') gfx.camera_track(_event['pos']) if len(event['text'])>=MAP_WINDOW_SIZE[0]-1: _lines = list(_event['text'].partition(',')) if not len(_lines[1]): _lines = list(_event['text'].partition('.')) if len(_lines[1]): _lines.pop(1) else: lines = ['????'] else: _lines = [_event['text']] for line in _lines: if len(line)>=MAP_WINDOW_SIZE[0]-1: _lines = ['The most annoying error.'] break _i = 0 for line in _lines: _half = len(line)/2 _x = bad_numbers.clip((MAP_WINDOW_SIZE[0]/2)-_half, 0, MAP_WINDOW_SIZE[0]-len(line)-1) gfx.blit_string(_x, 10+_i, line, 'overlay') _i += 1 return True
def bot(): try: logger.debug("Checking if script already run...") logger.debug(" testing lock of " + flockd_name) f = os.open(flockd_name, os.O_TRUNC | os.O_CREAT | os.O_RDWR) fres = locks.lock(f, locks.LOCK_EX + locks.LOCK_NB) if fres: logger.debug(" bot is not active") main() else: logger.debug("Script already running...") except IOError: logger.debug("Bot is already running") except Exception as inst: logger.error(type(inst)) logger.error(inst.args) logger.error(inst) else: logger.debug("Exiting script and unlocking") locks.unlock(f) os.close(f) os.remove(flockd_name) logger.debug("Bot is off...")
parser.add_argument("-v", "--verbose", action="store_true", help="detailed/debug log") args = parser.parse_args() logger = tg_logger.initLogger(args.verbose) logger.debug("Checking if script already run...") logger.debug(" testing lock of " + flockm_name) fm = os.open(flockm_name, os.O_TRUNC | os.O_CREAT | os.O_RDWR) fmres = locks.lock(fm, locks.LOCK_EX + locks.LOCK_NB) if fmres: #main is not run logger.debug(" check if daemon is run: " + flockd_name) fd = os.open(flockd_name, os.O_TRUNC | os.O_CREAT | os.O_RDWR) fdres = locks.lock(fd, locks.LOCK_EX + locks.LOCK_NB) if fdres: #not run - unlock and re-run as daemon locks.unlock(fd) logger.debug("dAemonize bot...") if args.daemon: if os.name == 'nt': logger.warning( "daemon mode is not supported in Windows") else: with daemon.DaemonContext( files_preserve=tg_logger.logger_handlers): bot() else: bot() locks.unlock(fm) else: logger.debug("main is already running. Exiting") except IOError:
def _save(self, name, content): full_path = self.path(name) # Create any intermediate directories that do not exist. # Note that there is a race between os.path.exists and os.makedirs: # if os.makedirs fails with EEXIST, the directory was created # concurrently, and we can continue normally. Refs #16082. directory = os.path.dirname(full_path) if not os.path.exists(directory): try: if self.directory_permissions_mode is not None: # os.makedirs applies the global umask, so we reset it, # for consistency with file_permissions_mode behavior. old_umask = os.umask(0) try: os.makedirs(directory, self.directory_permissions_mode) finally: os.umask(old_umask) else: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise if not os.path.isdir(directory): raise IOError("%s exists and is not a directory." % directory) # There's a potential race condition between get_available_name and # saving the file; it's possible that two threads might return the # same name, at which point all sorts of fun happens. So we need to # try to create the file, but if it already exists we have to go back # to get_available_name() and try again. while True: try: # This file has a file path that we can move. if hasattr(content, 'temporary_file_path'): shutil.move(content.temporary_file_path(), full_path) # This is a normal uploadedfile that we can stream. else: # This fun binary flag incantation makes os.open throw an # OSError if the file already exists before we open it. flags = (os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_BINARY', 0)) # The current umask value is masked out by os.open! fd = os.open(full_path, flags, 0o666) _file = None try: locks.lock(fd, locks.LOCK_EX) for chunk in content.chunks(): if _file is None: mode = 'wb' if isinstance(chunk, bytes) else 'wt' _file = os.fdopen(fd, mode) _file.write(chunk) finally: locks.unlock(fd) if _file is not None: _file.close() else: os.close(fd) except OSError as e: if e.errno == errno.EEXIST: # Ooops, the file exists. We need a new file name. name = self.get_available_name(name) full_path = self.path(name) else: raise else: # OK, the file save worked. Break out of the loop. break if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) return name
def draw_dialog(dialog_id): _dialog = get_dialog(dialog_id) _last_message = get_last_message(dialog_id) _x = bad_numbers.clip( MAP_WINDOW_SIZE[0] / 2 - len(_last_message['text']) / 2, 3, 100) _y = 10 _line_of_sight = drawing.diag_line(LIFE[_dialog['started_by']]['pos'], LIFE[_dialog['target']]['pos']) locks.unlock('camera_free') if len(_line_of_sight) <= 1: _center_pos = LIFE[_dialog['started_by']]['pos'] else: _center_pos = list(_line_of_sight[len(_line_of_sight) / 2]) _center_pos.append(2) if SETTINGS['controlling'] == _dialog['started_by']: _target = _dialog['target'] else: _target = _dialog['started_by'] _target_portrait = lfe.draw_life_icon(LIFE[_target]) _lines = [] gfx.camera_track(_center_pos) gfx.blit_string(_x - 2, _y - 2, ' '.join(LIFE[_target]['name']), 'overlay', fore_color=_target_portrait[1]) gfx.blit_string( _x - 2, _y, _target_portrait[0], 'overlay', fore_color=_target_portrait[1]) #, back_color=tcod.darkest_gray) _text = _last_message['text'] _y_mod = 0 while _text: _x = MAP_WINDOW_SIZE[0] / 2 - len(_text[:MAP_WINDOW_SIZE[0] - 4]) / 2 gfx.blit_string(_x, _y + _y_mod, _text[:MAP_WINDOW_SIZE[0] - 4], 'overlay') _text = _text[MAP_WINDOW_SIZE[0] - 4:] _y_mod += 1 for choice in _dialog['choices']: _text = choice['text'][choice['text'].index('\"') + 1:choice['text'].index('\"') - 1] if not _text.startswith('>'): _text = '> ' + _text _n_x = MAP_WINDOW_SIZE[0] / 2 - len(_text) / 2 if _n_x < _x: _x = _n_x for choice in _dialog['choices']: _text = choice['text'][choice['text'].index('\"') + 1:choice['text'].index('\"') - 1] if _dialog['cursor_index'] == _dialog['choices'].index(choice): _text = '> ' + _text _lines.append(_text) for line in _lines: gfx.blit_string(_x, _y + 3, line, 'overlay') #, back_color=tcod.darkest_gray) _y += 2