Esempio n. 1
0
	def get_useful_filename(self, patient=None, make_unique=False, directory=None, include_gnumed_tag=True, date_before_type=False, name_first=True):
		patient_part = ''
		if patient is not None:
			if name_first:
				patient_part = '%s-' % patient.subdir_name
			else:
				patient_part = '-%s' % patient.subdir_name

		# preserve original filename extension if available
		suffix = '.dat'
		if self._payload[self._idx['filename']] is not None:
			tmp, suffix = os.path.splitext (
				gmTools.fname_sanitize(self._payload[self._idx['filename']]).lower()
			)
			if suffix == '':
				suffix = '.dat'

		if include_gnumed_tag:
			fname_template = 'gm_doc-part_%s-%%s' % self._payload[self._idx['seq_idx']]
		else:
			fname_template = '%%s-part_%s' % self._payload[self._idx['seq_idx']]

		if date_before_type:
			date_type_part = '%s-%s' % (
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days),
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
			)
		else:
			date_type_part = '%s-%s' % (
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days)
			)

		if name_first:
			date_type_name_part = patient_part + date_type_part
		else:
			date_type_name_part = date_type_part + patient_part

		fname = fname_template % date_type_name_part

		if make_unique:
			fname = gmTools.get_unique_filename (
				prefix = '%s-' % gmTools.fname_sanitize(fname),
				suffix = suffix,
				tmp_dir = directory
			)
		else:
			fname = gmTools.fname_sanitize(os.path.join(gmTools.coalesce(directory, gmTools.gmPaths().tmp_dir), fname + suffix))

		return fname
Esempio n. 2
0
	def get_useful_filename(self, patient=None, make_unique=False, directory=None, include_gnumed_tag=True, date_before_type=False, name_first=True):
		patient_part = ''
		if patient is not None:
			if name_first:
				patient_part = '%s-' % patient.subdir_name
			else:
				patient_part = '-%s' % patient.subdir_name

		# preserve original filename extension if available
		suffix = '.dat'
		if self._payload[self._idx['filename']] is not None:
			tmp, suffix = os.path.splitext (
				gmTools.fname_sanitize(self._payload[self._idx['filename']]).lower()
			)
			if suffix == '':
				suffix = '.dat'

		if include_gnumed_tag:
			fname_template = 'gm_doc-part_%s-%%s' % self._payload[self._idx['seq_idx']]
		else:
			fname_template = '%%s-part_%s' % self._payload[self._idx['seq_idx']]

		if date_before_type:
			date_type_part = '%s-%s' % (
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days),
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
			)
		else:
			date_type_part = '%s-%s' % (
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days)
			)

		if name_first:
			date_type_name_part = patient_part + date_type_part
		else:
			date_type_name_part = date_type_part + patient_part

		fname = fname_template % date_type_name_part

		if make_unique:
			fname = gmTools.get_unique_filename (
				prefix = '%s-' % gmTools.fname_sanitize(fname),
				suffix = suffix,
				tmp_dir = directory
			)
		else:
			fname = gmTools.fname_sanitize(os.path.join(gmTools.coalesce(directory, gmTools.gmPaths().tmp_dir), fname + suffix))

		return fname
Esempio n. 3
0
def mirror_url(url: str, base_dir: str = None, verbose: bool = False) -> str:
    """Mirror the web*page* at _url_, non-recursively.

	Note: Not for mirroring a *site* (recursively).

	Args:
		url: the URL to mirror
		base_dir: where to store the page and its prerequisites, sandbox dir under tmp_dir if None
	"""
    assert (url is not None), '<url> must not be None'
    _log.debug('mirroring: %s', url)
    if base_dir is None:
        prefix = url.split('://')[-1]
        prefix = prefix.strip(':').strip('/').replace('/', '#')
        prefix = gmTools.fname_sanitize(prefix)
        base_dir = gmTools.mk_sandbox_dir(prefix=prefix + '-')
    _log.debug('base dir: %s', base_dir)
    wget_cmd = [
        'wget',
        '--directory-prefix=%s' % base_dir,
        #'--adjust-extension',
        '--no-remove-listing',
        '--timestamping',
        '--page-requisites',
        '--continue',
        '--convert-links',
        '--user-agent=""',
        '--execute',
        'robots=off',
        '--wait=1'
    ]
    if verbose:
        wget_cmd.append('--debug')
    wget_cmd.append(url)
    #wget --output-file=logfile
    #'<a href="%s">%s</a>' % (url, url),
    success, ret_code, STDOUT = gmShellAPI.run_process(cmd_line=wget_cmd,
                                                       timeout=15,
                                                       verbose=verbose)
    if success:
        return base_dir

    return None
Esempio n. 4
0
    def get_useful_filename(self, patient=None, directory=None):
        patient_part = ''
        if patient is not None:
            patient_part = '-%s' % patient['dirname']

        # preserve original filename extension if available
        suffix = '.dat'
        if self._payload[self._idx['filename']] is not None:
            tmp, suffix = os.path.splitext(
                gmTools.fname_sanitize(
                    self._payload[self._idx['filename']]).lower())
            if suffix == u'':
                suffix = '.dat'

        fname = gmTools.get_unique_filename(prefix='gm-export_item%s-' %
                                            patient_part,
                                            suffix=suffix,
                                            tmp_dir=directory)

        return os.path.join(directory, fname)
Esempio n. 5
0
def save_screenshot_to_file(filename=None, widget=None, settle_time=None):
    """Take screenshot of widget.

	<settle_time> in milliseconds
	"""
    assert (isinstance(widget,
                       wx.Window)), '<widget> must be (sub)class of wx.Window'

    if filename is None:
        filename = gmTools.get_unique_filename(
            prefix='gm-screenshot-%s-' %
            pyDT.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
            suffix='.png'
            # for testing:
            #,tmp_dir = os.path.join(gmTools.gmPaths().home_dir, 'gnumed')
        )
    else:
        filename = gmTools.fname_sanitize(filename)

    _log.debug('filename: %s', filename)
    _log.debug('widget: %s', widget)
    _log.debug('display size: %s', wx.DisplaySize())

    # let it settle a bit for, say, tooltips
    if settle_time is not None:
        for wait_slice in range(int(settle_time // 100)):
            wx.SafeYield()
            time.sleep(0.1)

    widget_rect_on_screen = widget.GetScreenRect()
    client_area_origin_on_screen = widget.ClientToScreen((0, 0))
    widget_rect_local = widget.GetRect()
    widget_rect_client_area = widget.GetClientRect()
    client_area_origin_local = widget.GetClientAreaOrigin()

    _log.debug('widget.GetScreenRect(): %s', widget_rect_on_screen)
    _log.debug('widget.ClientToScreen(0, 0): %s', client_area_origin_on_screen)
    _log.debug('widget.GetRect(): %s', widget_rect_local)
    _log.debug('widget.GetClientRect(): %s', widget_rect_client_area)
    _log.debug('widget.GetClientAreaOrigin(): %s', client_area_origin_local)

    width2snap = widget_rect_local.width
    height2snap = widget_rect_local.height
    border_x = client_area_origin_on_screen.x - widget_rect_local.x
    x2snap_from = 0 - border_x
    title_and_menu_height = client_area_origin_on_screen.y - widget_rect_on_screen.y
    y2snap_from = 0 - title_and_menu_height

    # those are the correct dimensions but we don't get to
    # *see* the window decorations on a WindowDC or ClientDC :-(
    # (and a screendc doesn't work either)
    _log.debug('left (x) border: %s', border_x)
    _log.debug('top (y) border: %s', title_and_menu_height)
    _log.debug('x2snap_from: %s', x2snap_from)
    _log.debug('y2snap_from: %s', y2snap_from)
    _log.debug('width2snap: %s', width2snap)
    _log.debug('height2snap: %s', height2snap)

    # WindowDC includes decorations, supposedly, but Windows only
    window_dc = wx.WindowDC(widget)
    wxbmp = __snapshot_to_bitmap(source_dc=window_dc,
                                 x2snap_from=x2snap_from,
                                 y2snap_from=y2snap_from,
                                 width2snap=width2snap,
                                 height2snap=height2snap)
    window_dc.Destroy()
    del window_dc
    wxbmp.SaveFile(filename, wx.BITMAP_TYPE_PNG)
    del wxbmp

    x2snap_on_screen = widget_rect_on_screen.x
    y2snap_on_screen = widget_rect_on_screen.y  # adjust for menu/title ?
    sane_x2snap_on_screen = max(0, x2snap_on_screen)
    sane_y2snap_on_screen = max(0, y2snap_on_screen)

    _log.debug('x2snap_on_screen: %s', x2snap_on_screen)
    _log.debug('y2snap_on_screen: %s', y2snap_on_screen)
    _log.debug('sane x2snap_on_screen: %s', sane_x2snap_on_screen)
    _log.debug('sane x2snap_on_screen: %s', sane_y2snap_on_screen)

    screen_dc = wx.ScreenDC()
    # not implemented:
    #wxbmp = screen_dc.GetAsBitmap()		# can use subrect=...
    wxbmp = __snapshot_to_bitmap(source_dc=screen_dc,
                                 x2snap_from=sane_x2snap_on_screen,
                                 y2snap_from=sane_y2snap_on_screen,
                                 width2snap=width2snap,
                                 height2snap=height2snap)
    screen_dc.Destroy()
    del screen_dc
    wxbmp.SaveFile(filename + '.screendc.png', wx.BITMAP_TYPE_PNG)
    del wxbmp

    # ClientDC does not include decorations, only client area
    #client_dc = wx.ClientDC(widget)
    #wxbmp = __snapshot_to_bitmap (
    #	source_dc = client_dc,
    #	x2snap_from = x2snap_from,
    #	y2snap_from = y2snap_from,
    #	width2snap = width2snap,
    #	height2snap = height2snap
    #)
    #client_dc.Destroy()
    #del client_dc
    #wxbmp.SaveFile(filename + '.clientdc.png', wx.BITMAP_TYPE_PNG)
    #del wxbmp

    # adjust for window decoration on Linux
    #if sys.platform == 'linux':
    # If the widget has a menu bar, remove that from the title bar height.
    #if hasattr(widget, 'GetMenuBar'):
    #	if widget.GetMenuBar():
    #		title_bar_height /= 2
    #		print('title bar height:', title_bar_height)
    #width2snap += (border_width * 2)
    #height2snap += title_bar_height + border_width

    gmDispatcher.send(signal='statustext',
                      msg=_('Saved screenshot to file [%s].') % filename)
    return filename
Esempio n. 6
0
def save_screenshot_to_file(filename:str=None, widget=None, settle_time:int=None) -> str:
	"""Take screenshot of widget or screen.

	Args:
		widget: the widget to screenshot (wx.Window descendent) or None for the whole screen
		settle_time: milliseconds to wait before taking screenshot

	Returns:
		Screenshot filename.

	https://github.com/wxWidgets/Phoenix/issues/259#issuecomment-801786528
	"""
	assert (isinstance(widget, wx.Window) or widget is None), '<widget> must be (sub)class of wx.Window, or None'

	if filename is None:
		filename = gmTools.get_unique_filename (
			prefix = 'gm-screenshot-%s-' % pyDT.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
			suffix = '.png'
			# for testing:
			#,tmp_dir = gmTools.gmPaths().user_work_dir
		)
	else:
		filename = gmTools.fname_sanitize(filename)
	if settle_time is not None:
		for wait_slice in range(int(settle_time // 100)):
			wx.SafeYield()
			time.sleep(0.1)
	screen_dc = wx.ScreenDC()
	screen_dc_size = screen_dc.GetSize()
	_log.debug('filename: %s', filename)
	_log.debug('widget: %s', widget)
	_log.debug('wx.DisplaySize(): %s', wx.DisplaySize())
	_log.debug('wx.ScreenDC size: %s', screen_dc_size)
	# this line makes multiple screenshots work (perhaps it updates a cached/global screen_dc from a more "hardwary" screen ?)
	screen_dc.Blit(0, 0, screen_dc_size[0], screen_dc_size[1], screen_dc, 0, 0, logicalFunc = wx.OR)
	if widget is None:
		width2snap = screen_dc_size[0]
		height2snap = screen_dc_size[1]
		sane_x2snap_from_on_screen = 0
		sane_y2snap_from_on_screen = 0
	else:
		widget_rect_on_screen = widget.GetScreenRect()
		widget_rect_local = widget.GetRect()
		width2snap = widget_rect_local.width
		height2snap = widget_rect_local.height
		x2snap_from_on_screen = widget_rect_on_screen.x
		y2snap_from_on_screen = widget_rect_on_screen.y
		sane_x2snap_from_on_screen = max(0, x2snap_from_on_screen)
		sane_y2snap_from_on_screen = max(0, y2snap_from_on_screen)
		_log.debug('widget.GetScreenRect(): %s (= widget coords on screen)', widget_rect_on_screen)
		_log.debug('widget.GetRect(): %s (= widget coords on client area)', widget_rect_local)
		_log.debug('x2snap_from_on_screen: %s (neg is off-screen)', x2snap_from_on_screen)
		_log.debug('y2snap_from_on_screen: %s (neg is off-screen)', y2snap_from_on_screen)
	_log.debug('sane x2snap_from_on_screen: %s (on-screen part only)', sane_x2snap_from_on_screen)
	_log.debug('sane y2snap_from_on_screen: %s (on-screen part only)', sane_y2snap_from_on_screen)
	_log.debug('width2snap: %s', width2snap)
	_log.debug('height2snap: %s', height2snap)
	wxbmp = __snapshot_to_bitmap (
		source_dc = screen_dc,
		x2snap_from = sane_x2snap_from_on_screen,
		y2snap_from = sane_y2snap_from_on_screen,
		width2snap = width2snap,
		height2snap = height2snap
	)
	screen_dc.Destroy()
	del screen_dc
	wxbmp.SaveFile(filename, wx.BITMAP_TYPE_PNG)
	del wxbmp
	gmDispatcher.send(signal = 'statustext', msg = _('Saved screenshot to file [%s].') % filename)
	return filename