<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django import template
from django.db.models import Avg, Count, Sum
from django.db.models.functions import TruncDate
from django.utils import timezone

from core import models

register = template.Library()

@register.inclusion_tag('cards/diaperchange_last.html')
def card_diaperchange_last(child):
    """
    Information about the most recent diaper change.
    :param child: an instance of the Child model.
    :returns: a dictionary with the most recent Diaper Change instance.
    """
    instance = models.DiaperChange.objects.filter(
        child=child).order_by('-time').first()
    return {'type': 'diaperchange', 'change': instance}

@register.inclusion_tag('cards/diaperchange_types.html')
def card_diaperchange_types(child):
    """
    Creates a break down of wet and solid Diaper Change instances for the past
    seven days.
    :param child: an instance of the Child model.
    :returns: a dictionary with the wet/dry statistics.
    """
    stats = {}
    max_date = (timezone.localtime() + timezone.timedelta(
        days=1)).replace(hour=0, minute=0, second=0)
    min_date = (max_date - timezone.timedelta(
        days=6)).replace(hour=0, minute=0, second=0)

    for x in range(6):
        stats[x] = {'wet': 0, 'solid': 0}

    instances = models.DiaperChange.objects.filter(child=child) \
        .filter(time__gt=min_date).filter(time__lt=max_date).order_by('-time')
    for instance in instances:
        key = (max_date - instance.time).days
        if instance.wet:
            stats[key]['wet'] += 1
        if instance.solid:
            stats[key]['solid'] += 1

    for key, info in stats.items():
        total = info['wet'] + info['solid']
        if total > 0:
            stats[key]['wet_pct'] = info['wet'] / total * 100
            stats[key]['solid_pct'] = info['solid'] / total * 100

    return {'type': 'diaperchange', 'stats': stats}

@register.inclusion_tag('cards/feeding_last.html')
def card_feeding_last(child):
    """
    Information about the most recent feeding.
    :param child: an instance of the Child model.
    :returns: a dictionary with the most recent Feeding instance.
    """
    instance = models.Feeding.objects.filter(child=child) \
        .order_by('-end').first()
    return {'type': 'feeding', 'feeding': instance}

@register.inclusion_tag('cards/feeding_last_method.html')
def card_feeding_last_method(child):
    """
    Information about the most recent feeding method.
    :param child: an instance of the Child model.
    :returns: a dictionary with the most recent Feeding instance.
    """
    instance = models.Feeding.objects.filter(child=child) \
        .order_by('-end').first()
    return {'type': 'feeding', 'feeding': instance}

@register.inclusion_tag('cards/sleep_last.html')
def card_sleep_last(child):
    """
    Information about the most recent sleep entry.
    :param child: an instance of the Child model.
    :returns: a dictionary with the most recent Sleep instance.
    """
    instance = models.Sleep.objects.filter(child=child) \
        .order_by('-end').first()
    return {'type': 'sleep', 'sleep': instance}

@register.inclusion_tag('cards/sleep_day.html')
def card_sleep_day(child, date=None):
    """
    Filters Sleep instances to get count and total values for a specific date.
    :param child: an instance of the Child model.
    :param date: a Date object for the day to filter.
    :returns: a dictionary with count and total values for the Sleep instances.
    """
    if not date:
        date = timezone.localtime().date()
    instances = models.Sleep.objects.filter(child=child).filter(
        start__year=date.year,
        start__month=date.month,
        start__day=date.day) | models.Sleep.objects.filter(child=child).filter(
        end__year=date.year,
        end__month=date.month,
        end__day=date.day)

    total = timezone.timedelta(seconds=0)
    for instance in instances:
        start = timezone.localtime(instance.start)
        end = timezone.localtime(instance.end)
        # Account for dates crossing midnight.
        if start.date() != date:
            start = start.replace(year=end.year, month=end.month, day=end.day,
                                  hour=0, minute=0, second=0)
        elif end.date() != date:
            end = start.replace(year=start.year, month=start.month,
                                day=start.day, hour=23, minute=59, second=59)

        total += end - start

    count = len(instances)

    return {'type': 'sleep', 'total': total, 'count': count}

@register.inclusion_tag('cards/sleep_naps_day.html')
def card_sleep_naps_day(child, date=None):
    """
    Filters Sleep instances categorized as naps and generates statistics for a
    specific date.
    :param child: an instance of the Child model.
    :param date: a Date object for the day to filter.
    :returns: a dictionary of nap data statistics.
    """
    date = timezone.localtime(date).astimezone(timezone.utc)
    instances = models.Sleep.naps.filter(child=child, start__date=date)
    return {
        'type': 'sleep',
        'total': instances.aggregate(Sum('duration')),
        'count': len(instances)}

@register.inclusion_tag('cards/statistics.html')
def card_statistics(child):
    """
    Statistics data for all models.
    :param child: an instance of the Child model.
    :returns: a list of dictionaries with "type", "stat" and "title" entries.
    """
    stats = []

    changes = _diaperchange_statistics(child)
    stats.append({
        'type': 'duration',
        'stat': changes['btwn_average'],
        'title': 'Diaper change frequency'})

    feedings = _feeding_statistics(child)
    stats.append({
        'type': 'duration',
        'stat': feedings['btwn_average'],
        'title': 'Feeding frequency'})

    naps = _nap_statistics(child)
    stats.append({
        'type': 'duration',
        'stat': naps['average'],
        'title': 'Average nap duration'})
    stats.append({
        'type': 'float',
        'stat': naps['avg_per_day'],
        'title': 'Average naps per day'})

    sleep = _sleep_statistics(child)
    stats.append({
        'type': 'duration',
        'stat': sleep['average'],
        'title': 'Average sleep duration'})
    stats.append({
        'type': 'duration',
        'stat': sleep['btwn_average'],
        'title': 'Average awake duration'})

    weight = _weight_statistics(child)
    stats.append({
        'type': 'float',
        'stat': weight['change_weekly'],
        'title': 'Weight change per week'})

    return {'stats': stats}

def _diaperchange_statistics(child):
    """
    Averaged Diaper Change data.
    :param child: an instance of the Child model.
    :returns: a dictionary of statistics.
    """
    instances = models.DiaperChange.objects.filter(child=child) \
        .order_by('time')
    changes = {
        'btwn_total': timezone.timedelta(0),
        'btwn_count': instances.count() - 1,
        'btwn_average': 0}
    last_instance = None

    for instance in instances:
        if last_instance:
            changes['btwn_total'] += instance.time - last_instance.time
        last_instance = instance

    if changes['btwn_count'] > 0:
        changes['btwn_average'] = changes['btwn_total'] / changes['btwn_count']

    return changes

def _feeding_statistics(child):
    """
    Averaged Feeding data.
    :param child: an instance of the Child model.
    :returns: a dictionary of statistics.
    """
    instances = models.Feeding.objects.filter(child=child).order_by('start')
    feedings = {
        'btwn_total': timezone.timedelta(0),
        'btwn_count': instances.count() - 1,
        'btwn_average': 0}
    last_instance = None

    for instance in instances:
        if last_instance:
            feedings['btwn_total'] += instance.start - last_instance.end
        last_instance = instance

    if feedings['btwn_count'] > 0:
        feedings['btwn_average'] = \
            feedings['btwn_total'] / feedings['btwn_count']

    return feedings

def _nap_statistics(child):
    """
    Averaged nap data.
    :param child: an instance of the Child model.
    :returns: a dictionary of statistics.
    """
    instances = models.Sleep.naps.filter(child=child).order_by('start')
    naps = {
        'total': instances.aggregate(Sum('duration'))['duration__sum'],
        'count': instances.count(),
        'average': 0,
        'avg_per_day': 0}
    if naps['count'] > 0:
        naps['average'] = naps['total'] / naps['count']

    naps_avg = instances.annotate(date=TruncDate('start')).values('date') \
        .annotate(naps_count=Count('id')).order_by() \
        .aggregate(Avg('naps_count'))
    naps['avg_per_day'] = naps_avg['naps_count__avg']

    return naps

def _sleep_statistics(child):
    """
    Averaged Sleep data.
    :param child: an instance of the Child model.
    :returns: a dictionary of statistics.
    """
    instances = models.Sleep.objects.filter(child=child).order_by('start')
    sleep = {
        'total': instances.aggregate(Sum('duration'))['duration__sum'],
        'count': instances.count(),
        'average': 0,
        'btwn_total': timezone.timedelta(0),
        'btwn_count': instances.count() - 1,
        'btwn_average': 0}

    last_instance = None
    for instance in instances:
        if last_instance:
            sleep['btwn_total'] += instance.start - last_instance.end
        last_instance = instance

    if sleep['count'] > 0:
        sleep['average'] = sleep['total'] / sleep['count']
    if sleep['btwn_count'] > 0:
        sleep['btwn_average'] = sleep['btwn_total'] / sleep['btwn_count']

    return sleep

def _weight_statistics(child):
    """
    Statistical weight data.
    :param child: an instance of the Child model.
    :returns: a dictionary of statistics.
    """
    weight = {'change_weekly': 0}

    instances = models.Weight.objects.filter(child=child).order_by('-date')
    newest = instances.first()
    oldest = instances.last()

    if newest != oldest:
        weight_change = newest.weight - oldest.weight
        weeks = (newest.date - oldest.date).days/7
        weight['change_weekly'] = weight_change/weeks

    return weight

@register.inclusion_tag('cards/timer_list.html')
def card_timer_list():
    """
    Filters for currently active Timer instances.
    :returns: a dictionary with a list of active Timer instances.
    """
    instances = models.Timer.objects.filter(active=True).order_by('-start')
    return {'type': 'timer', 'instances': list(instances)}

@register.inclusion_tag('cards/tummytime_last.html')
def card_tummytime_last(child):
    """
    Filters the most recent tummy time.
    :param child: an instance of the Child model.
    :returns: a dictionary with the most recent Tummy Time instance.
    """
    instance = models.TummyTime.objects.filter(child=child) \
        .order_by('-end').first()
    return {'type': 'tummytime', 'tummytime': instance}

@register.inclusion_tag('cards/tummytime_day.html')
def card_tummytime_day(child, date=None):
    """
    Filters Tummy Time instances and generates statistics for a specific date.
    :param child: an instance of the Child model.
    :param date: a Date object for the day to filter.
    :returns: a dictionary of all Tummy Time instances and stats for date.
    """
    if not date:
        date = timezone.localtime().date()
    instances = models.TummyTime.objects.filter(
        child=child, end__year=date.year, end__month=date.month,
        end__day=date.day).order_by('-end')
    stats = {
        'total': timezone.timedelta(seconds=0),
        'count': instances.count()
    }
    for instance in instances:
        stats['total'] += timezone.timedelta(seconds=instance.duration.seconds)
    return {
        'type': 'tummytime',
        'stats': stats,
        'instances': instances,
        'last': instances.first()}
<commit_msg>Add an optional date parameter for Diaper Change types and remove some unused code.<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django import template
from django.db.models import Avg, Count, Sum
from django.db.models.functions import TruncDate
from django.utils import timezone

from core import models

register = template.Library()

@register.inclusion_tag('cards/diaperchange_last.html')
def card_diaperchange_last(child):
    """
    Information about the most recent diaper change.
    :param child: an instance of the Child model.
    :returns: a dictionary with the most recent Diaper Change instance.
    """
    instance = models.DiaperChange.objects.filter(
        child=child).order_by('-time').first()
    return {'type': 'diaperchange', 'change': instance}

@register.inclusion_tag('cards/diaperchange_types.html')
def card_diaperchange_types(child, date=None):
    """
    Creates a break down of wet and solid Diaper Change instances for the past
    seven days.
    :param child: an instance of the Child model.
    :param date: a Date object for the day to filter.
    :returns: a dictionary with the wet/dry statistics.
    """
    if not date:
        time = timezone.localtime()
    else:
        time = timezone.datetime.combine(date, timezone.localtime().min.time())
        time = timezone.make_aware(time)
    stats = {}
    max_date = (time + timezone.timedelta(days=1)).replace(
        hour=0, minute=0, second=0)
    min_date = (max_date - timezone.timedelta(days=7)).replace(
        hour=0, minute=0, second=0)

    for x in range(7):
        stats[x] = {'wet': 0, 'solid': 0}

    instances = models.DiaperChange.objects.filter(child=child) \
        .filter(time__gt=min_date).filter(time__lt=max_date).order_by('-time')
    for instance in instances:
        key = (max_date - instance.time).days
        if instance.wet:
            stats[key]['wet'] += 1
        if instance.solid:
            stats[key]['solid'] += 1

    for key, info in stats.items():
        total = info['wet'] + info['solid']
        if total > 0:
            stats[key]['wet_pct'] = info['wet'] / total * 100
            stats[key]['solid_pct'] = info['solid'] / total * 100

    return {'type': 'diaperchange', 'stats': stats}

@register.inclusion_tag('cards/feeding_last.html')
def card_feeding_last(child):
    """
    Information about the most recent feeding.
    :param child: an instance of the Child model.
    :returns: a dictionary with the most recent Feeding instance.
    """
    instance = models.Feeding.objects.filter(child=child) \
        .order_by('-end').first()
    return {'type': 'feeding', 'feeding': instance}

@register.inclusion_tag('cards/feeding_last_method.html')
def card_feeding_last_method(child):
    """
    Information about the most recent feeding method.
    :param child: an instance of the Child model.
    :returns: a dictionary with the most recent Feeding instance.
    """
    instance = models.Feeding.objects.filter(child=child) \
        .order_by('-end').first()
    return {'type': 'feeding', 'feeding': instance}

@register.inclusion_tag('cards/sleep_last.html')
def card_sleep_last(child):
    """
    Information about the most recent sleep entry.
    :param child: an instance of the Child model.
    :returns: a dictionary with the most recent Sleep instance.
    """
    instance = models.Sleep.objects.filter(child=child) \
        .order_by('-end').first()
    return {'type': 'sleep', 'sleep': instance}

@register.inclusion_tag('cards/sleep_day.html')
def card_sleep_day(child, date=None):
    """
    Filters Sleep instances to get count and total values for a specific date.
    :param child: an instance of the Child model.
    :param date: a Date object for the day to filter.
    :returns: a dictionary with count and total values for the Sleep instances.
    """
    if not date:
        date = timezone.localtime().date()
    instances = models.Sleep.objects.filter(child=child).filter(
        start__year=date.year,
        start__month=date.month,
        start__day=date.day) | models.Sleep.objects.filter(child=child).filter(
        end__year=date.year,
        end__month=date.month,
        end__day=date.day)

    total = timezone.timedelta(seconds=0)
    for instance in instances:
        start = timezone.localtime(instance.start)
        end = timezone.localtime(instance.end)
        # Account for dates crossing midnight.
        if start.date() != date:
            start = start.replace(year=end.year, month=end.month, day=end.day,
                                  hour=0, minute=0, second=0)

        total += end - start

    count = len(instances)

    return {'type': 'sleep', 'total': total, 'count': count}

@register.inclusion_tag('cards/sleep_naps_day.html')
def card_sleep_naps_day(child, date=None):
    """
    Filters Sleep instances categorized as naps and generates statistics for a
    specific date.
    :param child: an instance of the Child model.
    :param date: a Date object for the day to filter.
    :returns: a dictionary of nap data statistics.
    """
    date = timezone.localtime(date).astimezone(timezone.utc)
    instances = models.Sleep.naps.filter(child=child, start__date=date)
    return {
        'type': 'sleep',
        'total': instances.aggregate(Sum('duration')),
        'count': len(instances)}

@register.inclusion_tag('cards/statistics.html')
def card_statistics(child):
    """
    Statistics data for all models.
    :param child: an instance of the Child model.
    :returns: a list of dictionaries with "type", "stat" and "title" entries.
    """
    stats = []

    changes = _diaperchange_statistics(child)
    stats.append({
        'type': 'duration',
        'stat': changes['btwn_average'],
        'title': 'Diaper change frequency'})

    feedings = _feeding_statistics(child)
    stats.append({
        'type': 'duration',
        'stat': feedings['btwn_average'],
        'title': 'Feeding frequency'})

    naps = _nap_statistics(child)
    stats.append({
        'type': 'duration',
        'stat': naps['average'],
        'title': 'Average nap duration'})
    stats.append({
        'type': 'float',
        'stat': naps['avg_per_day'],
        'title': 'Average naps per day'})

    sleep = _sleep_statistics(child)
    stats.append({
        'type': 'duration',
        'stat': sleep['average'],
        'title': 'Average sleep duration'})
    stats.append({
        'type': 'duration',
        'stat': sleep['btwn_average'],
        'title': 'Average awake duration'})

    weight = _weight_statistics(child)
    stats.append({
        'type': 'float',
        'stat': weight['change_weekly'],
        'title': 'Weight change per week'})

    return {'stats': stats}

def _diaperchange_statistics(child):
    """
    Averaged Diaper Change data.
    :param child: an instance of the Child model.
    :returns: a dictionary of statistics.
    """
    instances = models.DiaperChange.objects.filter(child=child) \
        .order_by('time')
    changes = {
        'btwn_total': timezone.timedelta(0),
        'btwn_count': instances.count() - 1,
        'btwn_average': 0}
    last_instance = None

    for instance in instances:
        if last_instance:
            changes['btwn_total'] += instance.time - last_instance.time
        last_instance = instance

    if changes['btwn_count'] > 0:
        changes['btwn_average'] = changes['btwn_total'] / changes['btwn_count']

    return changes

def _feeding_statistics(child):
    """
    Averaged Feeding data.
    :param child: an instance of the Child model.
    :returns: a dictionary of statistics.
    """
    instances = models.Feeding.objects.filter(child=child).order_by('start')
    feedings = {
        'btwn_total': timezone.timedelta(0),
        'btwn_count': instances.count() - 1,
        'btwn_average': 0}
    last_instance = None

    for instance in instances:
        if last_instance:
            feedings['btwn_total'] += instance.start - last_instance.end
        last_instance = instance

    if feedings['btwn_count'] > 0:
        feedings['btwn_average'] = \
            feedings['btwn_total'] / feedings['btwn_count']

    return feedings

def _nap_statistics(child):
    """
    Averaged nap data.
    :param child: an instance of the Child model.
    :returns: a dictionary of statistics.
    """
    instances = models.Sleep.naps.filter(child=child).order_by('start')
    naps = {
        'total': instances.aggregate(Sum('duration'))['duration__sum'],
        'count': instances.count(),
        'average': 0,
        'avg_per_day': 0}
    if naps['count'] > 0:
        naps['average'] = naps['total'] / naps['count']

    naps_avg = instances.annotate(date=TruncDate('start')).values('date') \
        .annotate(naps_count=Count('id')).order_by() \
        .aggregate(Avg('naps_count'))
    naps['avg_per_day'] = naps_avg['naps_count__avg']

    return naps

def _sleep_statistics(child):
    """
    Averaged Sleep data.
    :param child: an instance of the Child model.
    :returns: a dictionary of statistics.
    """
    instances = models.Sleep.objects.filter(child=child).order_by('start')
    sleep = {
        'total': instances.aggregate(Sum('duration'))['duration__sum'],
        'count': instances.count(),
        'average': 0,
        'btwn_total': timezone.timedelta(0),
        'btwn_count': instances.count() - 1,
        'btwn_average': 0}

    last_instance = None
    for instance in instances:
        if last_instance:
            sleep['btwn_total'] += instance.start - last_instance.end
        last_instance = instance

    if sleep['count'] > 0:
        sleep['average'] = sleep['total'] / sleep['count']
    if sleep['btwn_count'] > 0:
        sleep['btwn_average'] = sleep['btwn_total'] / sleep['btwn_count']

    return sleep

def _weight_statistics(child):
    """
    Statistical weight data.
    :param child: an instance of the Child model.
    :returns: a dictionary of statistics.
    """
    weight = {'change_weekly': 0}

    instances = models.Weight.objects.filter(child=child).order_by('-date')
    newest = instances.first()
    oldest = instances.last()

    if newest != oldest:
        weight_change = newest.weight - oldest.weight
        weeks = (newest.date - oldest.date).days/7
        weight['change_weekly'] = weight_change/weeks

    return weight

@register.inclusion_tag('cards/timer_list.html')
def card_timer_list():
    """
    Filters for currently active Timer instances.
    :returns: a dictionary with a list of active Timer instances.
    """
    instances = models.Timer.objects.filter(active=True).order_by('-start')
    return {'type': 'timer', 'instances': list(instances)}

@register.inclusion_tag('cards/tummytime_last.html')
def card_tummytime_last(child):
    """
    Filters the most recent tummy time.
    :param child: an instance of the Child model.
    :returns: a dictionary with the most recent Tummy Time instance.
    """
    instance = models.TummyTime.objects.filter(child=child) \
        .order_by('-end').first()
    return {'type': 'tummytime', 'tummytime': instance}

@register.inclusion_tag('cards/tummytime_day.html')
def card_tummytime_day(child, date=None):
    """
    Filters Tummy Time instances and generates statistics for a specific date.
    :param child: an instance of the Child model.
    :param date: a Date object for the day to filter.
    :returns: a dictionary of all Tummy Time instances and stats for date.
    """
    if not date:
        date = timezone.localtime().date()
    instances = models.TummyTime.objects.filter(
        child=child, end__year=date.year, end__month=date.month,
        end__day=date.day).order_by('-end')
    stats = {
        'total': timezone.timedelta(seconds=0),
        'count': instances.count()
    }
    for instance in instances:
        stats['total'] += timezone.timedelta(seconds=instance.duration.seconds)
    return {
        'type': 'tummytime',
        'stats': stats,
        'instances': instances,
        'last': instances.first()}
<|endoftext|>


<commit_before><commit_msg>[FIX] project: remove horrific self-clean after project.run.<commit_after><|endoftext|>


<commit_before>#  Copyright 2008-2012 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""A test library providing dialogs for interacting with users.

`Dialogs` is Robot Framework's standard library that provides means
for pausing the test execution and getting input from users. The
dialogs are slightly different depending on are tests run on Python or
Jython but they provide the same functionality.

The library has following two limitations:
- It is not compatible with IronPython.
- It cannot be used with timeouts on Python.
"""

import sys

if sys.platform.startswith('java'):
    from .dialogs_jy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog
elif sys.platform == 'cli':
    from .dialogs_ipy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog
else:
    from .dialogs_py import MessageDialog, PassFailDialog, InputDialog, SelectionDialog

try:
    from robot.version import get_version
except ImportError:
    __version__ = 'unknown'
else:
    __version__ = get_version()

__all__ = ['execute_manual_step', 'get_value_from_user',
           'get_selection_from_user', 'pause_execution']

def pause_execution(message='Test execution paused. Press OK to continue.'):
    """Pauses test execution until user clicks `Ok` button.

    `message` is the message shown in the dialog.
    """
    MessageDialog(message)

def execute_manual_step(message, default_error=''):
    """Pauses test execution until user sets the keyword status.

    User can select 'PASS' or 'FAIL', and in the latter case an additional
    dialog is opened for defining the error message.

    `message` is the instruction shown in the initial dialog and
    `default_error` is the default value shown in the possible error message
    dialog.
    """
    if not PassFailDialog(message).result:
        msg = get_value_from_user('Give error message:', default_error)
        raise AssertionError(msg)

def get_value_from_user(message, default_value=''):
    """Pauses test execution and asks user to input a value.

    `message` is the instruction shown in the dialog and `default_value` is
    the possible default value shown in the input field. Selecting 'Cancel'
    fails the keyword.
    """
    return _validate_user_input(InputDialog(message, default_value).result)

def get_selection_from_user(message, *values):
    """Pauses test execution and asks user to select a value.

    `message` is the instruction shown in the dialog and `values` are
    the options given to the user. Selecting 'Cancel' fails the keyword.
    """
    return _validate_user_input(SelectionDialog(message, values).result)

def _validate_user_input(value):
    if value is None:
        raise RuntimeError('No value provided by user')
    return value
<commit_msg>cannot use relative imports here<commit_after>#  Copyright 2008-2012 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""A test library providing dialogs for interacting with users.

`Dialogs` is Robot Framework's standard library that provides means
for pausing the test execution and getting input from users. The
dialogs are slightly different depending on are tests run on Python or
Jython but they provide the same functionality.

The library has following two limitations:
- It is not compatible with IronPython.
- It cannot be used with timeouts on Python.
"""

import sys

if sys.platform.startswith('java'):
    from dialogs_jy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog
elif sys.platform == 'cli':
    from dialogs_ipy import MessageDialog, PassFailDialog, InputDialog, SelectionDialog
else:
    from dialogs_py import MessageDialog, PassFailDialog, InputDialog, SelectionDialog

try:
    from robot.version import get_version
except ImportError:
    __version__ = 'unknown'
else:
    __version__ = get_version()

__all__ = ['execute_manual_step', 'get_value_from_user',
           'get_selection_from_user', 'pause_execution']

def pause_execution(message='Test execution paused. Press OK to continue.'):
    """Pauses test execution until user clicks `Ok` button.

    `message` is the message shown in the dialog.
    """
    MessageDialog(message)

def execute_manual_step(message, default_error=''):
    """Pauses test execution until user sets the keyword status.

    User can select 'PASS' or 'FAIL', and in the latter case an additional
    dialog is opened for defining the error message.

    `message` is the instruction shown in the initial dialog and
    `default_error` is the default value shown in the possible error message
    dialog.
    """
    if not PassFailDialog(message).result:
        msg = get_value_from_user('Give error message:', default_error)
        raise AssertionError(msg)

def get_value_from_user(message, default_value=''):
    """Pauses test execution and asks user to input a value.

    `message` is the instruction shown in the dialog and `default_value` is
    the possible default value shown in the input field. Selecting 'Cancel'
    fails the keyword.
    """
    return _validate_user_input(InputDialog(message, default_value).result)

def get_selection_from_user(message, *values):
    """Pauses test execution and asks user to select a value.

    `message` is the instruction shown in the dialog and `values` are
    the options given to the user. Selecting 'Cancel' fails the keyword.
    """
    return _validate_user_input(SelectionDialog(message, values).result)

def _validate_user_input(value):
    if value is None:
        raise RuntimeError('No value provided by user')
    return value
<|endoftext|>


<commit_before>#  Copyright 2008-2011 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""A test library providing dialogs for interacting with users.

`Dialogs` is Robot Framework's standard library that provides means
for pausing the test execution and getting input from users. The
dialogs are slightly different depending on are tests run on Python or
Jython but they provide the same functionality.

Note: Dialogs library cannot be used with timeouts on Windows with Python.
"""

__all__ = ['execute_manual_step', 'get_value_from_user',
           'get_selection_from_user', 'pause_execution']

import sys

try:
    from robot.version import get_version as _get_version
except ImportError:
    __version__ = 'unknown'
else:
    __version__ = _get_version()

DIALOG_TITLE = 'Robot Framework'

def pause_execution(message='Test execution paused. Press OK to continue.'):
    """Pauses the test execution and shows dialog with the text `message`. """
    MessageDialog(message)

def execute_manual_step(message, default_error=''):
    """Pauses the test execution until user sets the keyword status.

    `message` is the instruction shown in the dialog. User can select
    PASS or FAIL, and in the latter case an additional dialog is
    opened for defining the error message. `default_error` is the
    possible default value shown in the error message dialog.
    """
    if not  PassFailDialog(message).result:
        msg = get_value_from_user('Give error message:', default_error)
        raise AssertionError(msg)

def get_value_from_user(message, default_value=''):
    """Pauses the test execution and asks user to input a value.

    `message` is the instruction shown in the dialog. `default_value` is the
    possible default value shown in the input field. Selecting 'Cancel' fails
    the keyword.
    """
    return _validate_user_input(InputDialog(message, default_value).result)

def get_selection_from_user(message, *values):
    """Pauses the test execution and asks user to select value

    `message` is the instruction shown in the dialog. and `values` are
    the options given to the user. Selecting 'Cancel' fails the keyword.

    This keyword was added into Robot Framework 2.1.2.
    """
    return _validate_user_input(SelectionDialog(message, values).result)

def _validate_user_input(value):
    if value is None:
        raise ValueError('No value provided by user')
    return value

if not sys.platform.startswith('java'):

    from Tkinter import (Tk, Toplevel, Frame, Listbox, Label, Button, Entry,
                         BOTH, END, LEFT, W)
    import tkMessageBox
    import tkSimpleDialog
    from threading import currentThread

    def prevent_execution_with_timeouts(method):
        def check_timeout(*args):
            if 'linux' not in sys.platform \
                    and currentThread().getName() != 'MainThread':
                raise RuntimeError('Dialogs library is not supported with '
                                   'timeouts on Python on this platform.')
            return method(*args)
        return check_timeout

    class _AbstractTkDialog(Toplevel):
        _left_button = 'OK'
        _right_button = 'Cancel'

        @prevent_execution_with_timeouts
        def __init__(self, message, *args):
            Toplevel.__init__(self, self._get_parent())
            self._init_dialog()
            self._create_body(message, args)
            self._create_buttons()
            self.wait_window(self)

        def _get_parent(self):
            parent = Tk()
            parent.withdraw()
            return parent

        def _init_dialog(self):
            self.title(DIALOG_TITLE)
            self.grab_set()
            self.protocol("WM_DELETE_WINDOW", self._right_button_clicked)
            self.bind("<Escape>", self._right_button_clicked)
            self.geometry("+%d+%d" % self._get_center_location())

        def _get_center_location(self):
            x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2
            y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2
            return x, y

        def _create_body(self, message, args):
            frame = Frame(self)
            Label(frame, text=message, anchor=W).pack(fill=BOTH)
            selector = self._create_selector(frame, *args)
            if selector:
                selector.pack(fill=BOTH)
                selector.focus_set()
            frame.pack(padx=5, pady=5, expand=1, fill=BOTH)

        def _create_buttons(self):
            frame = Frame(self)
            self._create_button(frame, self._left_button,
                                self._left_button_clicked)
            self._create_button(frame, self._right_button,
                                self._right_button_clicked)
            frame.pack()

        def _create_button(self, parent, label, command):
            button = Button(parent, text=label, width=10, command=command)
            button.pack(side=LEFT, padx=5, pady=5)

        def _left_button_clicked(self, event=None):
            if self._validate_value():
                self.withdraw()
                self.result = self._get_value()
                self.destroy()

        def _validate_value(self):
            return True

        def _right_button_clicked(self, event=None):
            self.result = self._get_right_button_value()
            self.destroy()

        def _get_right_button_value(self):
            return None

    class MessageDialog(object):

        @prevent_execution_with_timeouts
        def __init__(self, message):
            Tk().withdraw()
            tkMessageBox.showinfo(DIALOG_TITLE, message)

    class InputDialog(_AbstractTkDialog):

        def __init__(self, message, default=''):
            _AbstractTkDialog.__init__(self, message, default)

        def _create_selector(self, parent, default):
            self._entry = Entry(parent)
            self._entry.insert(0, default)
            self._entry.select_range(0, END)
            return self._entry

        def _get_value(self):
            return self._entry.get()

    class SelectionDialog(_AbstractTkDialog):

        def __init__(self, message, values):
            _AbstractTkDialog.__init__(self, message, values)

        def _create_selector(self, parent, values):
            self._listbox = Listbox(parent)
            for item in values:
                self._listbox.insert(END, item)
            return self._listbox

        def _validate_value(self):
            return bool(self._listbox.curselection())

        def _get_value(self):
            return self._listbox.get(self._listbox.curselection())

    class PassFailDialog(_AbstractTkDialog):
        _left_button = 'PASS'
        _right_button = 'FAIL'

        def __init__(self, message):
            _AbstractTkDialog.__init__(self, message)

        def _create_selector(self, frame):
            return None

        def _get_value(self):
            return True

        def _get_right_button_value(self):
            return False

else:

    import time
    from javax.swing import JOptionPane
    from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \
        YES_NO_OPTION, OK_CANCEL_OPTION, DEFAULT_OPTION

    class _AbstractSwingDialog:

        def __init__(self, pane):
            self._show_dialog(pane)
            self.result = self._get_value(pane)

        def _show_dialog(self, pane):
            dialog = pane.createDialog(None, DIALOG_TITLE)
            dialog.setModal(False)
            dialog.show()
            while dialog.isShowing():
                time.sleep(0.2)
            dialog.dispose()

        def _get_value(self, pane):
            value = pane.getInputValue()
            return value if value != UNINITIALIZED_VALUE else None

    class MessageDialog(_AbstractSwingDialog):

        def __init__(self, message):
            pane = JOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION)
            _AbstractSwingDialog.__init__(self, pane)

    class InputDialog(_AbstractSwingDialog):

        def __init__(self, message, default):
            pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            pane.setWantsInput(True)
            pane.setInitialSelectionValue(default)
            _AbstractSwingDialog.__init__(self, pane)

    class SelectionDialog(_AbstractSwingDialog):

        def __init__(self, message, options):
            pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            pane.setWantsInput(True)
            pane.setSelectionValues(options)
            _AbstractSwingDialog.__init__(self, pane)

    class PassFailDialog(_AbstractSwingDialog):

        def __init__(self, message):
            pane = JOptionPane(message, PLAIN_MESSAGE, YES_NO_OPTION,
                               None, ['PASS', 'FAIL'], 'PASS')
            _AbstractSwingDialog.__init__(self, pane)

        def _get_value(self, pane):
            return pane.getValue() == 'PASS'
<commit_msg>minor cleanup<commit_after>#  Copyright 2008-2011 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""A test library providing dialogs for interacting with users.

`Dialogs` is Robot Framework's standard library that provides means
for pausing the test execution and getting input from users. The
dialogs are slightly different depending on are tests run on Python or
Jython but they provide the same functionality.

Note: Dialogs library cannot be used with timeouts on Windows with Python.
"""

__all__ = ['execute_manual_step', 'get_value_from_user',
           'get_selection_from_user', 'pause_execution']

import sys

try:
    from robot.version import get_version as _get_version
except ImportError:
    __version__ = 'unknown'
else:
    __version__ = _get_version()

DIALOG_TITLE = 'Robot Framework'

def pause_execution(message='Test execution paused. Press OK to continue.'):
    """Pauses the test execution and shows dialog with the text `message`. """
    MessageDialog(message)

def execute_manual_step(message, default_error=''):
    """Pauses the test execution until user sets the keyword status.

    `message` is the instruction shown in the dialog. User can select
    PASS or FAIL, and in the latter case an additional dialog is
    opened for defining the error message. `default_error` is the
    possible default value shown in the error message dialog.
    """
    if not  PassFailDialog(message).result:
        msg = get_value_from_user('Give error message:', default_error)
        raise AssertionError(msg)

def get_value_from_user(message, default_value=''):
    """Pauses the test execution and asks user to input a value.

    `message` is the instruction shown in the dialog. `default_value` is the
    possible default value shown in the input field. Selecting 'Cancel' fails
    the keyword.
    """
    return _validate_user_input(InputDialog(message, default_value).result)

def get_selection_from_user(message, *values):
    """Pauses the test execution and asks user to select value

    `message` is the instruction shown in the dialog. and `values` are
    the options given to the user. Selecting 'Cancel' fails the keyword.

    This keyword was added into Robot Framework 2.1.2.
    """
    return _validate_user_input(SelectionDialog(message, values).result)

def _validate_user_input(value):
    if value is None:
        raise ValueError('No value provided by user')
    return value

if not sys.platform.startswith('java'):

    from Tkinter import (Tk, Toplevel, Frame, Listbox, Label, Button, Entry,
                         BOTH, END, LEFT, W)
    import tkMessageBox
    import tkSimpleDialog
    from threading import currentThread

    def prevent_execution_with_timeouts(method):
        def check_timeout(*args):
            if 'linux' not in sys.platform \
                    and currentThread().getName() != 'MainThread':
                raise RuntimeError('Dialogs library is not supported with '
                                   'timeouts on Python on this platform.')
            return method(*args)
        return check_timeout

    class _AbstractTkDialog(Toplevel):
        _left_button = 'OK'
        _right_button = 'Cancel'

        @prevent_execution_with_timeouts
        def __init__(self, message, *args):
            Toplevel.__init__(self, self._get_parent())
            self._init_dialog()
            self._create_body(message, args)
            self._create_buttons()
            self.wait_window(self)

        def _get_parent(self):
            parent = Tk()
            parent.withdraw()
            return parent

        def _init_dialog(self):
            self.title(DIALOG_TITLE)
            self.grab_set()
            self.protocol("WM_DELETE_WINDOW", self._right_button_clicked)
            self.bind("<Escape>", self._right_button_clicked)
            self.geometry("+%d+%d" % self._get_center_location())

        def _get_center_location(self):
            x = (self.winfo_screenwidth() - self.winfo_reqwidth()) / 2
            y = (self.winfo_screenheight() - self.winfo_reqheight()) / 2
            return x, y

        def _create_body(self, message, args):
            frame = Frame(self)
            Label(frame, text=message, anchor=W).pack(fill=BOTH)
            selector = self._create_selector(frame, *args)
            if selector:
                selector.pack(fill=BOTH)
                selector.focus_set()
            frame.pack(padx=5, pady=5, expand=1, fill=BOTH)

        def _create_buttons(self):
            frame = Frame(self)
            self._create_button(frame, self._left_button,
                                self._left_button_clicked)
            self._create_button(frame, self._right_button,
                                self._right_button_clicked)
            frame.pack()

        def _create_button(self, parent, label, callback):
            button = Button(parent, text=label, width=10, command=callback)
            button.pack(side=LEFT, padx=5, pady=5)

        def _left_button_clicked(self, event=None):
            if self._validate_value():
                self.result = self._get_value()
                self.destroy()

        def _validate_value(self):
            return True

        def _right_button_clicked(self, event=None):
            self.result = self._get_right_button_value()
            self.destroy()

        def _get_right_button_value(self):
            return None

    class MessageDialog(object):

        @prevent_execution_with_timeouts
        def __init__(self, message):
            Tk().withdraw()
            tkMessageBox.showinfo(DIALOG_TITLE, message)

    class InputDialog(_AbstractTkDialog):

        def __init__(self, message, default=''):
            _AbstractTkDialog.__init__(self, message, default)

        def _create_selector(self, parent, default):
            self._entry = Entry(parent)
            self._entry.insert(0, default)
            self._entry.select_range(0, END)
            return self._entry

        def _get_value(self):
            return self._entry.get()

    class SelectionDialog(_AbstractTkDialog):

        def __init__(self, message, values):
            _AbstractTkDialog.__init__(self, message, values)

        def _create_selector(self, parent, values):
            self._listbox = Listbox(parent)
            for item in values:
                self._listbox.insert(END, item)
            return self._listbox

        def _validate_value(self):
            return bool(self._listbox.curselection())

        def _get_value(self):
            return self._listbox.get(self._listbox.curselection())

    class PassFailDialog(_AbstractTkDialog):
        _left_button = 'PASS'
        _right_button = 'FAIL'

        def __init__(self, message):
            _AbstractTkDialog.__init__(self, message)

        def _create_selector(self, frame):
            return None

        def _get_value(self):
            return True

        def _get_right_button_value(self):
            return False

else:

    import time
    from javax.swing import JOptionPane
    from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \
        YES_NO_OPTION, OK_CANCEL_OPTION, DEFAULT_OPTION

    class _AbstractSwingDialog:

        def __init__(self, pane):
            self._show_dialog(pane)
            self.result = self._get_value(pane)

        def _show_dialog(self, pane):
            dialog = pane.createDialog(None, DIALOG_TITLE)
            dialog.setModal(False)
            dialog.show()
            while dialog.isShowing():
                time.sleep(0.2)
            dialog.dispose()

        def _get_value(self, pane):
            value = pane.getInputValue()
            return value if value != UNINITIALIZED_VALUE else None

    class MessageDialog(_AbstractSwingDialog):

        def __init__(self, message):
            pane = JOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION)
            _AbstractSwingDialog.__init__(self, pane)

    class InputDialog(_AbstractSwingDialog):

        def __init__(self, message, default):
            pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            pane.setWantsInput(True)
            pane.setInitialSelectionValue(default)
            _AbstractSwingDialog.__init__(self, pane)

    class SelectionDialog(_AbstractSwingDialog):

        def __init__(self, message, options):
            pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            pane.setWantsInput(True)
            pane.setSelectionValues(options)
            _AbstractSwingDialog.__init__(self, pane)

    class PassFailDialog(_AbstractSwingDialog):

        def __init__(self, message):
            pane = JOptionPane(message, PLAIN_MESSAGE, YES_NO_OPTION,
                               None, ['PASS', 'FAIL'], 'PASS')
            _AbstractSwingDialog.__init__(self, pane)

        def _get_value(self, pane):
            return pane.getValue() == 'PASS'
<|endoftext|>


<commit_before>#  Copyright 2009 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""A test library providing dialogs for interacting with users.

`Dialogs` is Robot Framework's standard library that provides means
for pausing the test execution and getting input from users. The
dialogs are slightly different depending on are tests run on Python or
Jython but they provide the same functionality.
"""

import sys

try:
    from robot import utils
except ImportError:
    __version__ = 'unknown'
else:
    __version__ = utils.get_version()

DIALOG_TITLE = 'Robot Framework'

def pause_execution(message='Test execution paused. Press OK to continue.'):
    """Pauses the test execution and shows dialog with the text `message`. """
    MessageDialog(message)

def execute_manual_step(message, default_error=''):
    """Pauses the test execution until user sets the keyword status.

    `message` is the instruction shown in the dialog. User can select
    PASS or FAIL, and in the latter case an additional dialog is
    opened for defining the error message. `default_error` is the
    possible default value shown in the error message dialog.
    """
    if not  PassFailDialog(message).result:
        msg = get_value_from_user('Give error message:', default_error)
        raise AssertionError(msg)

def get_value_from_user(message, default_value=''):
    """Pauses the test execution and asks user to input a value.

    `message` is the instruction shown in the dialog. `default_value` is the
    possible default value shown in the input field. Selecting 'Cancel' fails
    the keyword.
    """
    return _validate_user_input(InputDialog(message, default_value).result)

def get_selection_from_user(message, *values):
    """Pauses the test execution and asks user to select value

    `message` is the instruction shown in the dialog. and `values` are
    the options given to the user. Selecting 'Cancel' fails the keyword.
    """
    return _validate_user_input(SelectionDialog(message, values).result)

def _validate_user_input(value):
    if value is None:
        raise ValueError('No value provided by user')
    return value

if not sys.platform.startswith('java'):

    from Tkinter import Tk, Toplevel, Frame, Listbox, Label, Button,\
                        BOTH, END, LEFT
    import tkMessageBox
    import tkSimpleDialog

    class _AbstractTkDialog(Toplevel):

        def __init__(self, title):
            parent = Tk()
            parent.withdraw()
            Toplevel.__init__(self, parent)
            self._init_dialog(parent, title)
            self._create_body()
            self._create_buttons()
            self.result = None
            self._initial_focus.focus_set()
            self.wait_window(self)

        def _init_dialog(self, parent, title):
            self.title(title)
            self.grab_set()
            self.protocol("WM_DELETE_WINDOW", self._right_clicked)
            self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
                                      parent.winfo_rooty()+50))

        def _create_body(self):
            frame = Frame(self)
            self._initial_focus = self.create_components(frame)
            frame.pack(padx=5, pady=5, expand=1, fill=BOTH)

        def _create_buttons(self):
            frame = Frame(self)
            self._create_button(frame, self._left_button, self._left_clicked)
            self._create_button(frame, self._right_button, self._right_clicked)
            self.bind("<Escape>", self._right_clicked)
            frame.pack()

        def _create_button(self, parent, label, command):
            w = Button(parent, text=label, width=10, command=command)
            w.pack(side=LEFT, padx=5, pady=5)

        def _left_clicked(self, event=None):
            if not self.validate():
                self._initial_focus.focus_set()
                return
            self.withdraw()
            self.apply()
            self.destroy()

        def _right_clicked(self, event=None):
            self.destroy()

        def create_components(self, parent):
            raise NotImplementedError()

        def validate(self):
            raise NotImplementedError()

        def apply(self):
            raise NotImplementedError()

    class MessageDialog:

        def __init__(self, message):
            Tk().withdraw()
            tkMessageBox.showinfo(DIALOG_TITLE, message)

    class InputDialog:

        def __init__(self, message, default):
            Tk().withdraw()
            self.result = tkSimpleDialog.askstring(DIALOG_TITLE, message,
                                                   initialvalue=default)

    class SelectionDialog(_AbstractTkDialog):
        _left_button = 'OK'
        _right_button = 'Cancel'

        def __init__(self, message, values):
            self._message = message
            self._values = values
            _AbstractTkDialog.__init__(self, "Select one option")

        def create_components(self, parent):
            Label(parent, text=self._message).pack(fill=BOTH)
            self._listbox = Listbox(parent)
            self._listbox.pack(fill=BOTH)
            for item in self._values:
                self._listbox.insert(END, item)
            return self._listbox

        def validate(self):
            return bool(self._listbox.curselection())

        def apply(self):
            self.result = self._listbox.get(self._listbox.curselection())

    class PassFailDialog(_AbstractTkDialog):
        _left_button = 'PASS'
        _right_button = 'FAIL'

        def __init__(self, message):
            self._message = message
            _AbstractTkDialog.__init__(self, DIALOG_TITLE)

        def create_components(self, parent):
            label = Label(parent, text=self._message)
            label.pack(fill=BOTH)
            return label

        def validate(self):
            return True

        def apply(self):
            self.result = True

else:

    import time
    from javax.swing import JOptionPane
    from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \
        YES_NO_OPTION, OK_CANCEL_OPTION, DEFAULT_OPTION

    class _AbstractSwingDialog:

        def __init__(self, message):
            self.result = self._show_dialog(message)

        def _show_dialog(self, message):
            self._init_dialog(message)
            self._show_dialog_and_wait_it_to_be_closed()
            return self._get_value()

        def _show_dialog_and_wait_it_to_be_closed(self):
            dialog = self._pane.createDialog(None, DIALOG_TITLE)
            dialog.setModal(0);
            dialog.show()
            while dialog.isShowing():
                time.sleep(0.2)
            dialog.dispose()

        def _get_value(self):
            value = self._pane.getInputValue()
            if value == UNINITIALIZED_VALUE:
                return None
            return value

    class MessageDialog(_AbstractSwingDialog):

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION)

    class InputDialog(_AbstractSwingDialog):

        def __init__(self, message, default):
            self._default = default
            _AbstractSwingDialog.__init__(self, message)

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            self._pane.setWantsInput(True)
            self._pane.setInitialSelectionValue(self._default)

    class SelectionDialog(_AbstractSwingDialog):

        def __init__(self, message, options):
            self._options = options
            _AbstractSwingDialog.__init__(self, message)

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            self._pane.setWantsInput(True)
            self._pane.setSelectionValues(self._options)

    class PassFailDialog(_AbstractSwingDialog):

        def _init_dialog(self, message):
            self._buttons = ['PASS', 'FAIL']
            self._pane = JOptionPane(message, PLAIN_MESSAGE, YES_NO_OPTION,
                                     None, self._buttons, 'PASS')

        def _get_value(self):
            value = self._pane.getValue()
            if value in self._buttons and self._buttons.index(value) == 0:
                return True
            return False
<commit_msg>mention version when kw added<commit_after>#  Copyright 2009 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""A test library providing dialogs for interacting with users.

`Dialogs` is Robot Framework's standard library that provides means
for pausing the test execution and getting input from users. The
dialogs are slightly different depending on are tests run on Python or
Jython but they provide the same functionality.
"""

import sys

try:
    from robot import utils
except ImportError:
    __version__ = 'unknown'
else:
    __version__ = utils.get_version()

DIALOG_TITLE = 'Robot Framework'

def pause_execution(message='Test execution paused. Press OK to continue.'):
    """Pauses the test execution and shows dialog with the text `message`. """
    MessageDialog(message)

def execute_manual_step(message, default_error=''):
    """Pauses the test execution until user sets the keyword status.

    `message` is the instruction shown in the dialog. User can select
    PASS or FAIL, and in the latter case an additional dialog is
    opened for defining the error message. `default_error` is the
    possible default value shown in the error message dialog.
    """
    if not  PassFailDialog(message).result:
        msg = get_value_from_user('Give error message:', default_error)
        raise AssertionError(msg)

def get_value_from_user(message, default_value=''):
    """Pauses the test execution and asks user to input a value.

    `message` is the instruction shown in the dialog. `default_value` is the
    possible default value shown in the input field. Selecting 'Cancel' fails
    the keyword.
    """
    return _validate_user_input(InputDialog(message, default_value).result)

def get_selection_from_user(message, *values):
    """Pauses the test execution and asks user to select value

    `message` is the instruction shown in the dialog. and `values` are
    the options given to the user. Selecting 'Cancel' fails the keyword.

    This keyword was added into Robot Framework 2.1.2.
    """
    return _validate_user_input(SelectionDialog(message, values).result)

def _validate_user_input(value):
    if value is None:
        raise ValueError('No value provided by user')
    return value

if not sys.platform.startswith('java'):

    from Tkinter import Tk, Toplevel, Frame, Listbox, Label, Button,\
                        BOTH, END, LEFT
    import tkMessageBox
    import tkSimpleDialog

    class _AbstractTkDialog(Toplevel):

        def __init__(self, title):
            parent = Tk()
            parent.withdraw()
            Toplevel.__init__(self, parent)
            self._init_dialog(parent, title)
            self._create_body()
            self._create_buttons()
            self.result = None
            self._initial_focus.focus_set()
            self.wait_window(self)

        def _init_dialog(self, parent, title):
            self.title(title)
            self.grab_set()
            self.protocol("WM_DELETE_WINDOW", self._right_clicked)
            self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
                                      parent.winfo_rooty()+50))

        def _create_body(self):
            frame = Frame(self)
            self._initial_focus = self.create_components(frame)
            frame.pack(padx=5, pady=5, expand=1, fill=BOTH)

        def _create_buttons(self):
            frame = Frame(self)
            self._create_button(frame, self._left_button, self._left_clicked)
            self._create_button(frame, self._right_button, self._right_clicked)
            self.bind("<Escape>", self._right_clicked)
            frame.pack()

        def _create_button(self, parent, label, command):
            w = Button(parent, text=label, width=10, command=command)
            w.pack(side=LEFT, padx=5, pady=5)

        def _left_clicked(self, event=None):
            if not self.validate():
                self._initial_focus.focus_set()
                return
            self.withdraw()
            self.apply()
            self.destroy()

        def _right_clicked(self, event=None):
            self.destroy()

        def create_components(self, parent):
            raise NotImplementedError()

        def validate(self):
            raise NotImplementedError()

        def apply(self):
            raise NotImplementedError()

    class MessageDialog:

        def __init__(self, message):
            Tk().withdraw()
            tkMessageBox.showinfo(DIALOG_TITLE, message)

    class InputDialog:

        def __init__(self, message, default):
            Tk().withdraw()
            self.result = tkSimpleDialog.askstring(DIALOG_TITLE, message,
                                                   initialvalue=default)

    class SelectionDialog(_AbstractTkDialog):
        _left_button = 'OK'
        _right_button = 'Cancel'

        def __init__(self, message, values):
            self._message = message
            self._values = values
            _AbstractTkDialog.__init__(self, "Select one option")

        def create_components(self, parent):
            Label(parent, text=self._message).pack(fill=BOTH)
            self._listbox = Listbox(parent)
            self._listbox.pack(fill=BOTH)
            for item in self._values:
                self._listbox.insert(END, item)
            return self._listbox

        def validate(self):
            return bool(self._listbox.curselection())

        def apply(self):
            self.result = self._listbox.get(self._listbox.curselection())

    class PassFailDialog(_AbstractTkDialog):
        _left_button = 'PASS'
        _right_button = 'FAIL'

        def __init__(self, message):
            self._message = message
            _AbstractTkDialog.__init__(self, DIALOG_TITLE)

        def create_components(self, parent):
            label = Label(parent, text=self._message)
            label.pack(fill=BOTH)
            return label

        def validate(self):
            return True

        def apply(self):
            self.result = True

else:

    import time
    from javax.swing import JOptionPane
    from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \
        YES_NO_OPTION, OK_CANCEL_OPTION, DEFAULT_OPTION

    class _AbstractSwingDialog:

        def __init__(self, message):
            self.result = self._show_dialog(message)

        def _show_dialog(self, message):
            self._init_dialog(message)
            self._show_dialog_and_wait_it_to_be_closed()
            return self._get_value()

        def _show_dialog_and_wait_it_to_be_closed(self):
            dialog = self._pane.createDialog(None, DIALOG_TITLE)
            dialog.setModal(0);
            dialog.show()
            while dialog.isShowing():
                time.sleep(0.2)
            dialog.dispose()

        def _get_value(self):
            value = self._pane.getInputValue()
            if value == UNINITIALIZED_VALUE:
                return None
            return value

    class MessageDialog(_AbstractSwingDialog):

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION)

    class InputDialog(_AbstractSwingDialog):

        def __init__(self, message, default):
            self._default = default
            _AbstractSwingDialog.__init__(self, message)

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            self._pane.setWantsInput(True)
            self._pane.setInitialSelectionValue(self._default)

    class SelectionDialog(_AbstractSwingDialog):

        def __init__(self, message, options):
            self._options = options
            _AbstractSwingDialog.__init__(self, message)

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            self._pane.setWantsInput(True)
            self._pane.setSelectionValues(self._options)

    class PassFailDialog(_AbstractSwingDialog):

        def _init_dialog(self, message):
            self._buttons = ['PASS', 'FAIL']
            self._pane = JOptionPane(message, PLAIN_MESSAGE, YES_NO_OPTION,
                                     None, self._buttons, 'PASS')

        def _get_value(self):
            value = self._pane.getValue()
            if value in self._buttons and self._buttons.index(value) == 0:
                return True
            return False
<|endoftext|>


<commit_before>#  Copyright 2008-2010 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""A test library providing dialogs for interacting with users.

`Dialogs` is Robot Framework's standard library that provides means
for pausing the test execution and getting input from users. The
dialogs are slightly different depending on are tests run on Python or
Jython but they provide the same functionality.
"""

import sys

try:
    from robot.version import get_version
except ImportError:
    __version__ = 'unknown'
else:
    __version__ = get_version()

DIALOG_TITLE = 'Robot Framework'

def pause_execution(message='Test execution paused. Press OK to continue.'):
    """Pauses the test execution and shows dialog with the text `message`. """
    MessageDialog(message)

def execute_manual_step(message, default_error=''):
    """Pauses the test execution until user sets the keyword status.

    `message` is the instruction shown in the dialog. User can select
    PASS or FAIL, and in the latter case an additional dialog is
    opened for defining the error message. `default_error` is the
    possible default value shown in the error message dialog.
    """
    if not  PassFailDialog(message).result:
        msg = get_value_from_user('Give error message:', default_error)
        raise AssertionError(msg)

def get_value_from_user(message, default_value=''):
    """Pauses the test execution and asks user to input a value.

    `message` is the instruction shown in the dialog. `default_value` is the
    possible default value shown in the input field. Selecting 'Cancel' fails
    the keyword.
    """
    return _validate_user_input(InputDialog(message, default_value).result)

def get_selection_from_user(message, *values):
    """Pauses the test execution and asks user to select value

    `message` is the instruction shown in the dialog. and `values` are
    the options given to the user. Selecting 'Cancel' fails the keyword.

    This keyword was added into Robot Framework 2.1.2.
    """
    return _validate_user_input(SelectionDialog(message, values).result)

def _validate_user_input(value):
    if value is None:
        raise ValueError('No value provided by user')
    return value

if not sys.platform.startswith('java'):

    from Tkinter import Tk, Toplevel, Frame, Listbox, Label, Button,\
                        BOTH, END, LEFT
    import tkMessageBox
    import tkSimpleDialog

    class _AbstractTkDialog(Toplevel):

        def __init__(self, title):
            parent = Tk()
            parent.withdraw()
            Toplevel.__init__(self, parent)
            self._init_dialog(parent, title)
            self._create_body()
            self._create_buttons()
            self.result = None
            self._initial_focus.focus_set()
            self.wait_window(self)

        def _init_dialog(self, parent, title):
            self.title(title)
            self.grab_set()
            self.protocol("WM_DELETE_WINDOW", self._right_clicked)
            self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
                                      parent.winfo_rooty()+50))

        def _create_body(self):
            frame = Frame(self)
            self._initial_focus = self.create_components(frame)
            frame.pack(padx=5, pady=5, expand=1, fill=BOTH)

        def _create_buttons(self):
            frame = Frame(self)
            self._create_button(frame, self._left_button, self._left_clicked)
            self._create_button(frame, self._right_button, self._right_clicked)
            self.bind("<Escape>", self._right_clicked)
            frame.pack()

        def _create_button(self, parent, label, command):
            w = Button(parent, text=label, width=10, command=command)
            w.pack(side=LEFT, padx=5, pady=5)

        def _left_clicked(self, event=None):
            if not self.validate():
                self._initial_focus.focus_set()
                return
            self.withdraw()
            self.apply()
            self.destroy()

        def _right_clicked(self, event=None):
            self.destroy()

        def create_components(self, parent):
            raise NotImplementedError()

        def validate(self):
            raise NotImplementedError()

        def apply(self):
            raise NotImplementedError()

    class MessageDialog:

        def __init__(self, message):
            Tk().withdraw()
            tkMessageBox.showinfo(DIALOG_TITLE, message)

    class InputDialog:

        def __init__(self, message, default):
            Tk().withdraw()
            self.result = tkSimpleDialog.askstring(DIALOG_TITLE, message,
                                                   initialvalue=default)

    class SelectionDialog(_AbstractTkDialog):
        _left_button = 'OK'
        _right_button = 'Cancel'

        def __init__(self, message, values):
            self._message = message
            self._values = values
            _AbstractTkDialog.__init__(self, "Select one option")

        def create_components(self, parent):
            Label(parent, text=self._message).pack(fill=BOTH)
            self._listbox = Listbox(parent)
            self._listbox.pack(fill=BOTH)
            for item in self._values:
                self._listbox.insert(END, item)
            return self._listbox

        def validate(self):
            return bool(self._listbox.curselection())

        def apply(self):
            self.result = self._listbox.get(self._listbox.curselection())

    class PassFailDialog(_AbstractTkDialog):
        _left_button = 'PASS'
        _right_button = 'FAIL'

        def __init__(self, message):
            self._message = message
            _AbstractTkDialog.__init__(self, DIALOG_TITLE)

        def create_components(self, parent):
            label = Label(parent, text=self._message)
            label.pack(fill=BOTH)
            return label

        def validate(self):
            return True

        def apply(self):
            self.result = True

else:

    import time
    from javax.swing import JOptionPane
    from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \
        YES_NO_OPTION, OK_CANCEL_OPTION, DEFAULT_OPTION

    class _AbstractSwingDialog:

        def __init__(self, message):
            self.result = self._show_dialog(message)

        def _show_dialog(self, message):
            self._init_dialog(message)
            self._show_dialog_and_wait_it_to_be_closed()
            return self._get_value()

        def _show_dialog_and_wait_it_to_be_closed(self):
            dialog = self._pane.createDialog(None, DIALOG_TITLE)
            dialog.setModal(0);
            dialog.show()
            while dialog.isShowing():
                time.sleep(0.2)
            dialog.dispose()

        def _get_value(self):
            value = self._pane.getInputValue()
            if value == UNINITIALIZED_VALUE:
                return None
            return value

    class MessageDialog(_AbstractSwingDialog):

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION)

    class InputDialog(_AbstractSwingDialog):

        def __init__(self, message, default):
            self._default = default
            _AbstractSwingDialog.__init__(self, message)

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            self._pane.setWantsInput(True)
            self._pane.setInitialSelectionValue(self._default)

    class SelectionDialog(_AbstractSwingDialog):

        def __init__(self, message, options):
            self._options = options
            _AbstractSwingDialog.__init__(self, message)

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            self._pane.setWantsInput(True)
            self._pane.setSelectionValues(self._options)

    class PassFailDialog(_AbstractSwingDialog):

        def _init_dialog(self, message):
            self._buttons = ['PASS', 'FAIL']
            self._pane = JOptionPane(message, PLAIN_MESSAGE, YES_NO_OPTION,
                                     None, self._buttons, 'PASS')

        def _get_value(self):
            value = self._pane.getValue()
            if value in self._buttons and self._buttons.index(value) == 0:
                return True
            return False
<commit_msg>Added some tests to use for debugging the problem.<commit_after>#  Copyright 2008-2010 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""A test library providing dialogs for interacting with users.

`Dialogs` is Robot Framework's standard library that provides means
for pausing the test execution and getting input from users. The
dialogs are slightly different depending on are tests run on Python or
Jython but they provide the same functionality.
"""

import sys

try:
    from robot.version import get_version
except ImportError:
    __version__ = 'unknown'
else:
    __version__ = get_version()

DIALOG_TITLE = 'Robot Framework'

def pause_execution(message='Test execution paused. Press OK to continue.'):
    """Pauses the test execution and shows dialog with the text `message`. """
    MessageDialog(message)

def execute_manual_step(message, default_error=''):
    """Pauses the test execution until user sets the keyword status.

    `message` is the instruction shown in the dialog. User can select
    PASS or FAIL, and in the latter case an additional dialog is
    opened for defining the error message. `default_error` is the
    possible default value shown in the error message dialog.
    """
    if not  PassFailDialog(message).result:
        msg = get_value_from_user('Give error message:', default_error)
        raise AssertionError(msg)

def get_value_from_user(message, default_value=''):
    """Pauses the test execution and asks user to input a value.

    `message` is the instruction shown in the dialog. `default_value` is the
    possible default value shown in the input field. Selecting 'Cancel' fails
    the keyword.
    """
    return _validate_user_input(InputDialog(message, default_value).result)

def get_selection_from_user(message, *values):
    """Pauses the test execution and asks user to select value

    `message` is the instruction shown in the dialog. and `values` are
    the options given to the user. Selecting 'Cancel' fails the keyword.

    This keyword was added into Robot Framework 2.1.2.
    """
    return _validate_user_input(SelectionDialog(message, values).result)

def _validate_user_input(value):
    if value is None:
        raise ValueError('No value provided by user')
    return value

if not sys.platform.startswith('java'):

    from Tkinter import Tk, Toplevel, Frame, Listbox, Label, Button,\
                        BOTH, END, LEFT
    import tkMessageBox
    import tkSimpleDialog

    class _AbstractTkDialog(Toplevel):

        def __init__(self, title):
            parent = Tk()
            parent.withdraw()
            Toplevel.__init__(self, parent)
            self._init_dialog(parent, title)
            self._create_body()
            self._create_buttons()
            self.result = None
            self._initial_focus.focus_set()
            self.wait_window(self)

        def _init_dialog(self, parent, title):
            self.title(title)
            self.grab_set()
            self.protocol("WM_DELETE_WINDOW", self._right_clicked)
            self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
                                      parent.winfo_rooty()+50))

        def _create_body(self):
            frame = Frame(self)
            self._initial_focus = self.create_components(frame)
            frame.pack(padx=5, pady=5, expand=1, fill=BOTH)

        def _create_buttons(self):
            frame = Frame(self)
            self._create_button(frame, self._left_button, self._left_clicked)
            self._create_button(frame, self._right_button, self._right_clicked)
            self.bind("<Escape>", self._right_clicked)
            frame.pack()

        def _create_button(self, parent, label, command):
            w = Button(parent, text=label, width=10, command=command)
            w.pack(side=LEFT, padx=5, pady=5)

        def _left_clicked(self, event=None):
            if not self.validate():
                self._initial_focus.focus_set()
                return
            self.withdraw()
            self.apply()
            self.destroy()

        def _right_clicked(self, event=None):
            self.destroy()

        def create_components(self, parent):
            raise NotImplementedError()

        def validate(self):
            raise NotImplementedError()

        def apply(self):
            raise NotImplementedError()

    class MessageDialog:

        def __init__(self, message):
            Tk().withdraw()
            tkMessageBox.showinfo(DIALOG_TITLE, message)

    class InputDialog:

        def __init__(self, message, default):
            Tk().withdraw()
            self.result = tkSimpleDialog.askstring(DIALOG_TITLE, message,
                                                   initialvalue=default)

    class SelectionDialog(_AbstractTkDialog):
        _left_button = 'OK'
        _right_button = 'Cancel'

        def __init__(self, message, values):
            self._message = message
            self._values = values
            _AbstractTkDialog.__init__(self, "Select one option")

        def create_components(self, parent):
            Label(parent, text=self._message).pack(fill=BOTH)
            self._listbox = Listbox(parent)
            self._listbox.pack(fill=BOTH)
            for item in self._values:
                self._listbox.insert(END, item)
            return self._listbox

        def validate(self):
            return bool(self._listbox.curselection())

        def apply(self):
            self.result = self._listbox.get(self._listbox.curselection())

    class PassFailDialog(_AbstractTkDialog):
        _left_button = 'PASS'
        _right_button = 'FAIL'

        def __init__(self, message):
            self._message = message
            _AbstractTkDialog.__init__(self, DIALOG_TITLE)

        def create_components(self, parent):
            label = Label(parent, text=self._message)
            label.pack(fill=BOTH)
            return label

        def validate(self):
            return True

        def apply(self):
            self.result = True

    #FIXME: Remove when not needed anymore
    def _run_in_thread(callable):
        print "Running in python thread"
        from threading import Thread
        import time
        t = Thread(target=callable)
        t.run()
        while t.isAlive():
            time.sleep(1)

    def _run_in_rf_thread(callable):
        print "Running in rf thread"
        from robot.utils.robotthread import ThreadedRunner
        t = ThreadedRunner(callable)
        t.run_in_thread(10)
        print t.get_result()

    if __name__ == '__main__':
        _run_in_thread(pause_execution)
        _run_in_thread(pause_execution)
        _run_in_thread(pause_execution)
        _run_in_thread(pause_execution)
        _run_in_rf_thread(pause_execution)
        _run_in_rf_thread(pause_execution)

else:

    import time
    from javax.swing import JOptionPane
    from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \
        YES_NO_OPTION, OK_CANCEL_OPTION, DEFAULT_OPTION

    class _AbstractSwingDialog:

        def __init__(self, message):
            self.result = self._show_dialog(message)

        def _show_dialog(self, message):
            self._init_dialog(message)
            self._show_dialog_and_wait_it_to_be_closed()
            return self._get_value()

        def _show_dialog_and_wait_it_to_be_closed(self):
            dialog = self._pane.createDialog(None, DIALOG_TITLE)
            dialog.setModal(0);
            dialog.show()
            while dialog.isShowing():
                time.sleep(0.2)
            dialog.dispose()

        def _get_value(self):
            value = self._pane.getInputValue()
            if value == UNINITIALIZED_VALUE:
                return None
            return value

    class MessageDialog(_AbstractSwingDialog):

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION)

    class InputDialog(_AbstractSwingDialog):

        def __init__(self, message, default):
            self._default = default
            _AbstractSwingDialog.__init__(self, message)

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            self._pane.setWantsInput(True)
            self._pane.setInitialSelectionValue(self._default)

    class SelectionDialog(_AbstractSwingDialog):

        def __init__(self, message, options):
            self._options = options
            _AbstractSwingDialog.__init__(self, message)

        def _init_dialog(self, message):
            self._pane = JOptionPane(message, PLAIN_MESSAGE, OK_CANCEL_OPTION)
            self._pane.setWantsInput(True)
            self._pane.setSelectionValues(self._options)

    class PassFailDialog(_AbstractSwingDialog):

        def _init_dialog(self, message):
            self._buttons = ['PASS', 'FAIL']
            self._pane = JOptionPane(message, PLAIN_MESSAGE, YES_NO_OPTION,
                                     None, self._buttons, 'PASS')

        def _get_value(self):
            value = self._pane.getValue()
            if value in self._buttons and self._buttons.index(value) == 0:
                return True
            return False
<|endoftext|>


<commit_before># tm - Task management.
# Github abstraction module.
# Author: Julian Ailan
# ===================================

# Built-in modules.
try:
    from subprocess import run, check_output, Popen, PIPE
except ImportError:
    from subprocess import call, check_output, Popen, PIPE

def add_files(files):
    """Performs 'git add [-files]' operation."""
    if not files:
        raise ValueError("No files received for adding.")
    files_to_add = " ".join(files)
    git_cmd_string = "git add {}".format(files_to_add)
    _execute(git_cmd_string.strip().split(" "))

def status(flags=""):
    """Performs 'git status [-flags]' operation."""
    git_cmd_string = "git status {}".format(" ".join(flags))
    _execute(git_cmd_string.strip().split(" "))

def commit(message):
    """Performs 'git commit -m [-message]' operation."""
    if message == "" or not message:
        raise ValueError("No valid message/flag values received.")
    git_cmd_list = "git commit -m".split(" ")
    git_cmd_list.append(message)
    _execute(git_cmd_list)

def push(server, branch):
    """Performs 'git push [-server] [-branch]' operation."""
    if not (server and branch):
        raise ValueError("Not valid server and/or branch values given.")
    git_cmd_string = "git push {0} {1}".format(server, branch)
    _execute(git_cmd_string.strip().split(" "))

def branch(name):
    """Performs 'git checkout -b [-name]' operation."""
    if (not name) or (name == ""):
        raise ValueError("No valid branch name received.")
    git_cmd_string = "git checkout -b {}".format(name)
    _execute(git_cmd_string.strip().split(" "))

def merge(from_branch, to_branch):
    """Performs the merging of two branches."""
    if not (from_branch and to_branch):
        raise ValueError("No valid branch names received.")
    git_checkout_string = "git checkout {}".format(to_branch)
    _execute(git_checkout_string)
    git_merge_string = "git merge {}".format(from_branch)
    _execute(git_merge_string)
    git_delete_branch_string = "git branch -d {}".format(from_branch)
    _execute(git_delete_branch_string)

# --> Utilities.
def _changed_files():
    """Returns a list with all the changed files after the last commit"""
    # Get all changed files, avoiding the use of shell=True.
    status = Popen(("git", "status", "-s"), stdout=PIPE)
    files = check_output(('cut', '-c4-'), stdin=status.stdout)
    return filter(None, files.split("\n"))

def _execute(git_cmd_list):
    """Runs the git commands."""
    # Python 2.X and 3.X compatibility.
    try:
        run(git_cmd_list)
    except NameError:
        call(git_cmd_list)

def make(commit_message, server, branch, files=_changed_files(), flags=""):
    """Pushes commits to the remote repository."""
    add_files(files)
    status(flags)
    commit(commit_message)
    push(server, branch)
<commit_msg>Modified merge method by adding instructions to delete branches in the remote repository.<commit_after># tm - Task management.
# Github abstraction module.
# Author: Julian Ailan
# ===================================

# Built-in modules.
import os
try:
    from subprocess import run, check_output, Popen, PIPE
except ImportError:
    from subprocess import call, check_output, Popen, PIPE

def add_files(files):
    """Performs 'git add [-files]' operation."""
    if not files:
        raise ValueError("No files received for adding.")
    files_to_add = " ".join(files)
    git_cmd_string = "git add {}".format(files_to_add)
    _execute(git_cmd_string.strip().split(" "))

def status(flags=""):
    """Performs 'git status [-flags]' operation."""
    git_cmd_string = "git status {}".format(" ".join(flags))
    _execute(git_cmd_string.strip().split(" "))

def commit(message):
    """Performs 'git commit -m [-message]' operation."""
    if message == "" or not message:
        raise ValueError("No valid message/flag values received.")
    git_cmd_list = "git commit -m".split(" ")
    git_cmd_list.append(message)
    _execute(git_cmd_list)

def push(server, branch):
    """Performs 'git push [-server] [-branch]' operation."""
    if not (server and branch):
        raise ValueError("Not valid server and/or branch values given.")
    git_cmd_string = "git push {0} {1}".format(server, branch)
    _execute(git_cmd_string.strip().split(" "))

def branch(name):
    """Performs 'git checkout -b [-name]' operation."""
    if (not name) or (name == ""):
        raise ValueError("No valid branch name received.")
    git_cmd_string = "git checkout -b {}".format(name)
    _execute(git_cmd_string.strip().split(" "))

def merge(from_branch, to_branch):
    """Performs the merging of two branches."""
    if not (from_branch and to_branch):
        raise ValueError("No valid branch names received.")
    os.chdir("..")
    git_checkout_string = "git checkout {}".format(to_branch)
    _execute(git_checkout_string)
    git_merge_string = "git merge {}".format(from_branch)
    _execute(git_merge_string)
    git_delete_branch_local = "git branch -d {}".format(from_branch)
    _execute(git_delete_branch_local)
    git_delete_branch_remote = ("git push origin --delete {}".
                                format(from_branch))
    _execute(git_delete_branch_remote)
    os.chdir("./tm")

# --> Utilities.
def _changed_files():
    """Returns a list with all the changed files after the last commit"""
    # Get all changed files, avoiding the use of shell=True.
    status = Popen(("git", "status", "-s"), stdout=PIPE)
    files = check_output(('cut', '-c4-'), stdin=status.stdout)
    return filter(None, files.split("\n"))

def _execute(git_cmd_list):
    """Runs the git commands."""
    # Python 2.X and 3.X compatibility.
    try:
        run(git_cmd_list)
    except NameError:
        call(git_cmd_list)

def make(commit_message, server, branch, files=_changed_files(), flags=""):
    """Pushes commits to the remote repository."""
    add_files(files)
    status(flags)
    commit(commit_message)
    push(server, branch)
<|endoftext|>


<commit_before><commit_msg>Web page preview with http?<commit_after><|endoftext|>


<commit_before><commit_msg>Db molweight features fill script<commit_after><|endoftext|>