<commit_before>#!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# 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.

"""Cron jobs.
"""

__authors__ = [
    '"Sverre Rabbelier" <sverre@rabbelier.nl>',
    '"Lennard de Rijk" <ljvderijk@gmail.com>',
  ]

import logging

from google.appengine.ext import db
from google.appengine.runtime import DeadlineExceededError

from soc.cron import student_proposal_mailer
from soc.models.job import Job

class Error(Exception):
  """Base class for all exceptions raised by this module.
  """
  pass

class FatalJobError(Error):
  """Class for all errors that lead to immediate job abortion.
  """
  pass

class Handler(object):
  """A handler that dispatches a cron job.

  The tasks that are mapped into tasks will be called when a worker
  has claimed the job. However, there is no guarantee as to how long
  the task will be allowed to run. If an Exception is raised the task
  is automatically rescheduled for execution.
  """

  def __init__(self):
    """Constructs a new Handler with all known jobs set.
    """

    self.tasks = {}
    self.tasks['setupStudentProposalMailing'] = \
        student_proposal_mailer.setupStudentProposalMailing
    self.tasks['sendStudentProposalMail'] = \
        student_proposal_mailer.sendStudentProposalMail

  def claimJob(self, job_key):
    """A transaction to claim a job.
    """

    job = Job.get_by_id(job_key)

    if job.status != 'waiting':
      raise db.Rollback()

    job.status = 'started'

    if job.put():
      return job
    else:
      return None

  def freeJob(self, job_key):
    """A transaction to free a job.
    """

    job = Job.get_by_id(job_key)

    job.status = 'waiting'

    return job.put()

  def timeoutJob(self, job_key):
    """A transaction to tiemout a job.
    """

    job = Job.get_by_id(job_key)

    job.timeouts += 1

    if job.timeouts > 50:
      job.status = 'aborted'
    else:
      job.status = 'waiting'

    job_id = job.key().id()
    logging.debug("job %d now timeout %d time(s)" % (job_id, job.timeouts))

    return job.put()

  def failJob(self, job_key):
    """A transaction to fail a job.
    """

    job = Job.get_by_id(job_key)

    job.errors += 1

    if job.errors > 5:
      job.status = 'aborted'
    else:
      job.status = 'waiting'

    job_id = job.key().id()
    logging.warning("job %d now failed %d time(s)" % (job_id, job.errors))

    return job.put()

  def finishJob(self, job_key):
    """A transaction to finish a job.
    """

    job = Job.get_by_id(job_key)
    job.status = 'finished'

    return job.put()

  def abortJob(self, job_key):
    """A transaction to abort a job.
    """

    job = Job.get_by_id(job_key)
    job.status = 'aborted'

    return job.put()

  def handle(self, job_key):
    """Handle one job.

    Returns: whether another job should be started after this one
    """

    try:
      job = db.run_in_transaction(self.claimJob, job_key)

      if not job:
        # someone already claimed the job
        return True

      if job.task_name not in self.tasks:
        logging.error("Unknown job %s" % job.task_name)
        db.run_in_transaction(self.abortJob, job_key)
        return True

      task = self.tasks[job.task_name]

      # execute the actual job
      task(job)

      db.run_in_transaction(self.finishJob, job_key)
      return True
    except DeadlineExceededError, exception:
      db.run_in_transaction(self.timeoutJob, job_key)
      return False
    except FatalJobError, exception:
      logging.exception(exception)
      db.run_in_transaction(self.abortJob, job_key)
      return True
    except Exception, exception:
      logging.exception(exception)
      db.run_in_transaction(self.failJob, job_key)
      return True

handler = Handler()
<commit_msg>Use status codes in job.py<commit_after>#!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# 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.

"""Cron jobs.
"""

__authors__ = [
    '"Sverre Rabbelier" <sverre@rabbelier.nl>',
    '"Lennard de Rijk" <ljvderijk@gmail.com>',
  ]

import logging

from google.appengine.ext import db
from google.appengine.runtime import DeadlineExceededError

from soc.cron import student_proposal_mailer
from soc.models.job import Job

class Error(Exception):
  """Base class for all exceptions raised by this module.
  """
  pass

class FatalJobError(Error):
  """Class for all errors that lead to immediate job abortion.
  """
  pass

class Handler(object):
  """A handler that dispatches a cron job.

  The tasks that are mapped into tasks will be called when a worker
  has claimed the job. However, there is no guarantee as to how long
  the task will be allowed to run. If an Exception is raised the task
  is automatically rescheduled for execution.
  """

  def __init__(self):
    """Constructs a new Handler with all known jobs set.
    """

    self.OUT_OF_TIME = 0
    self.ALREADY_CLAIMED = 1
    self.SUCCESS = 2
    self.ABORTED = 3
    self.ERRORED = 4

    self.tasks = {}
    self.tasks['setupStudentProposalMailing'] = \
        student_proposal_mailer.setupStudentProposalMailing
    self.tasks['sendStudentProposalMail'] = \
        student_proposal_mailer.sendStudentProposalMail

  def claimJob(self, job_key):
    """A transaction to claim a job.
    """

    job = Job.get_by_id(job_key)

    if job.status != 'waiting':
      raise db.Rollback()

    job.status = 'started'

    if job.put():
      return job
    else:
      return None

  def freeJob(self, job_key):
    """A transaction to free a job.
    """

    job = Job.get_by_id(job_key)

    job.status = 'waiting'

    return job.put()

  def timeoutJob(self, job_key):
    """A transaction to tiemout a job.
    """

    job = Job.get_by_id(job_key)

    job.timeouts += 1

    if job.timeouts > 50:
      job.status = 'aborted'
    else:
      job.status = 'waiting'

    job_id = job.key().id()
    logging.debug("job %d now timeout %d time(s)" % (job_id, job.timeouts))

    return job.put()

  def failJob(self, job_key):
    """A transaction to fail a job.
    """

    job = Job.get_by_id(job_key)

    job.errors += 1

    if job.errors > 5:
      job.status = 'aborted'
    else:
      job.status = 'waiting'

    job_id = job.key().id()
    logging.warning("job %d now failed %d time(s)" % (job_id, job.errors))

    return job.put()

  def finishJob(self, job_key):
    """A transaction to finish a job.
    """

    job = Job.get_by_id(job_key)
    job.status = 'finished'

    return job.put()

  def abortJob(self, job_key):
    """A transaction to abort a job.
    """

    job = Job.get_by_id(job_key)
    job.status = 'aborted'

    return job.put()

  def handle(self, job_key):
    """Handle one job.

    Returns: whether another job should be started after this one
    """

    try:
      job = db.run_in_transaction(self.claimJob, job_key)

      if not job:
        # someone already claimed the job
        return self.ALREADY_CLAIMED

      if job.task_name not in self.tasks:
        logging.error("Unknown job %s" % job.task_name)
        db.run_in_transaction(self.abortJob, job_key)
        return self.ABORTED

      task = self.tasks[job.task_name]

      # execute the actual job
      task(job)

      db.run_in_transaction(self.finishJob, job_key)
      return self.SUCCESS
    except DeadlineExceededError, exception:
      db.run_in_transaction(self.timeoutJob, job_key)
      return self.OUT_OF_TIME
    except FatalJobError, exception:
      logging.exception(exception)
      db.run_in_transaction(self.abortJob, job_key)
      return self.ABORTED
    except Exception, exception:
      logging.exception(exception)
      db.run_in_transaction(self.failJob, job_key)
      return self.ERRORED

handler = Handler()
<|endoftext|>


<commit_before>#! /usr/bin/env python

# ------------------------------------------------------------------------------
# Common components used by various cbioportal scripts.
# ------------------------------------------------------------------------------

import os
import sys
from subprocess import *

# ------------------------------------------------------------------------------
# globals

ERROR_FILE = sys.stderr
OUTPUT_FILE = sys.stdout

IMPORT_STUDY_CLASS = "org.mskcc.cbio.portal.scripts.ImportCancerStudy";
REMOVE_STUDY_CLASS = "org.mskcc.cbio.portal.scripts.RemoveCancerStudy";
IMPORT_CANCER_TYPE_CLASS = "org.mskcc.cbio.portal.scripts.ImportTypesOfCancers"
IMPORT_CASE_LIST_CLASS = "org.mskcc.cbio.portal.scripts.ImportPatientList"

IMPORTER_CLASSNAME_BY_ALTERATION_TYPE = { "CLINICAL" : "org.mskcc.cbio.portal.scripts.ImportClinicalData",
                                            "COPY_NUMBER_ALTERATION" : "org.mskcc.cbio.portal.scripts.ImportProfileData",
                                            "FUSION" : "org.mskcc.cbio.portal.scripts.ImportProfileData",
                                            "GISTIC" : "org.mskcc.cbio.portal.scripts.ImportGisticData",
                                            "METHYLATION" : "org.mskcc.cbio.portal.scripts.ImportProfileData",
                                            "MRNA_EXPRESSION" : "org.mskcc.cbio.portal.scripts.ImportProfileData",
                                            "MUTATION_EXTENDED" : "org.mskcc.cbio.portal.scripts.ImportProfileData",
                                            "MUTATION_SIGNIFICANCE" : "org.mskcc.cbio.portal.scripts.ImportMutSigData",
                                            "RPPA" : "org.mskcc.cbio.portal.scripts.ImportProteinArrayData",
                                            "SEGMENT" : "org.mskcc.cbio.portal.scripts.ImportCopyNumberSegmentData",
                                            "TIMELINE" : "org.mskcc.cbio.portal.scripts.ImportTimelineData" }

IMPORTER_REQUIRES_METADATA = { "org.mskcc.cbio.portal.scripts.ImportClinicalData" : False,
                                "org.mskcc.cbio.portal.scripts.ImportCopyNumberSegmentData" : False,
                                "org.mskcc.cbio.portal.scripts.ImportGisticData" : False,
                                "org.mskcc.cbio.portal.scripts.ImportMutSigData" : False,
                                "org.mskcc.cbio.portal.scripts.ImportProteinArrayData" : False,
								"org.mskcc.cbio.portal.scripts.ImportProfileData" : True,
                                "org.mskcc.cbio.portal.scripts.ImportTimelineData" : True }

# ------------------------------------------------------------------------------
# class definitions

class MetastudyProperties(object):
    def __init__(self,
                 type_of_cancer, cancer_study_identifier,
                 name, description, short_name):
        self.type_of_cancer = type_of_cancer
        self.cancer_study_identifier = cancer_study_identifier
        self.name = name
        self.description = description
        self.short_name = short_name

class MetafileProperties(object):
    def __init__(self,
                 cancer_study_identifier, genetic_alteration_type,
                 datatype, stable_id, show_profile_in_analysis_tab,
                 profile_description, profile_name):
        self.cancer_study_identifier = cancer_study_identifier
        self.genetic_alteration_type = genetic_alteration_type
        self.datatype = datatype
        self.stable_id = stable_id
        self.show_profile_in_analysis_tab = show_profile_in_analysis_tab
        self.profile_description = profile_description
        self.profile_name = profile_name

# ------------------------------------------------------------------------------
# sub-routines

def importer_requires_metadata_file(importer_classname):
	return IMPORTER_REQUIRES_METADATA[importer_classname]

def get_properties(filename):
    properties = {}
    file = open(filename, 'r')
    for line in file:
        line = line.strip()
        # skip line if its blank or a comment
        if len(line) == 0:
            continue
        # store name/value
        property = line.split(': ', 1)
        if (len(property) != 2):
            print >> ERROR_FILE, 'Skipping invalid entry in file: ' + line
            continue
        properties[property[0]] = property[1].strip()
    file.close()
    return properties

def get_metastudy_properties(meta_filename):
    properties = get_properties(meta_filename)

    # ignoring groups, pmid, citation - not needed
    if ("type_of_cancer" not in properties or len(properties["type_of_cancer"]) == 0 or
        "cancer_study_identifier" not in properties or len(properties["cancer_study_identifier"]) == 0 or
        "name" not in properties or len(properties["name"]) == 0 or
        "description" not in properties or len(properties["description"]) == 0 or
        "short_name" not in properties or len(properties["short_name"]) == 0):
        print >> ERROR_FILE, 'Missing one or more required properties, please check metastudy file'
        return None

    # return an instance of PortalProperties
    return MetastudyProperties(properties["type_of_cancer"],
                            properties["cancer_study_identifier"],
                            properties["name"],
                            properties["description"],
                            properties["short_name"])

def get_metafile_properties(meta_filename):
    properties = get_properties(meta_filename)
    if ("show_profile_in_analysis_tab not in analysis_tab" not in properties):
        properties['show_profile_in_analysis_tab'] = 'false'

    # error check
    if ("cancer_study_identifier" not in properties or len(properties["cancer_study_identifier"]) == 0 or
    	"genetic_alteration_type" not in properties or len(properties["genetic_alteration_type"]) == 0 or
    	"datatype" not in properties or len(properties["datatype"]) == 0 or
    	"stable_id" not in properties or len(properties["stable_id"]) == 0 or
    	"show_profile_in_analysis_tab" not in properties or len(properties["show_profile_in_analysis_tab"]) == 0 or
    	"profile_name" not in properties or len(properties["profile_name"]) == 0 or
    	"profile_description" not in properties or len(properties["profile_description"]) == 0):
        print >> ERROR_FILE, 'Missing one or more required properties, please check metadata file'
        return None

    # return an instance of PortalProperties
    return MetafileProperties(properties["cancer_study_identifier"],
    						properties["genetic_alteration_type"],
                            properties["datatype"],
                            properties["stable_id"],
                            properties["show_profile_in_analysis_tab"],
                            properties["profile_name"],
                            properties["profile_description"])

def run_java(*args):
    java_home = os.environ['JAVA_HOME']
    if len(java_home) == 0:
        print >> ERROR_FILE, "$JAVA_HOME must be defined"
        return
    print >> OUTPUT_FILE, ("Executing command: " + java_home +
                           "/bin/java {}\n".format(args).replace('(\'', '').replace('\', \'', ' ').replace('\')', ''))
    process = Popen([ java_home + '/bin/java']+list(args), stdout=PIPE, stderr=STDOUT)
    ret = []
    while process.poll() is None:
        line = process.stdout.readline()
        if line != '' and line.endswith('\n'):
            print >> OUTPUT_FILE, line.strip()
            ret.append(line[:-1])
    return ret
<commit_msg>Disabled print<commit_after>#! /usr/bin/env python

# ------------------------------------------------------------------------------
# Common components used by various cbioportal scripts.
# ------------------------------------------------------------------------------

import os
import sys
from subprocess import *

# ------------------------------------------------------------------------------
# globals

ERROR_FILE = sys.stderr
OUTPUT_FILE = sys.stdout

IMPORT_STUDY_CLASS = "org.mskcc.cbio.portal.scripts.ImportCancerStudy";
REMOVE_STUDY_CLASS = "org.mskcc.cbio.portal.scripts.RemoveCancerStudy";
IMPORT_CANCER_TYPE_CLASS = "org.mskcc.cbio.portal.scripts.ImportTypesOfCancers"
IMPORT_CASE_LIST_CLASS = "org.mskcc.cbio.portal.scripts.ImportPatientList"

IMPORTER_CLASSNAME_BY_ALTERATION_TYPE = { "CLINICAL" : "org.mskcc.cbio.portal.scripts.ImportClinicalData",
                                            "COPY_NUMBER_ALTERATION" : "org.mskcc.cbio.portal.scripts.ImportProfileData",
                                            "FUSION" : "org.mskcc.cbio.portal.scripts.ImportProfileData",
                                            "GISTIC" : "org.mskcc.cbio.portal.scripts.ImportGisticData",
                                            "METHYLATION" : "org.mskcc.cbio.portal.scripts.ImportProfileData",
                                            "MRNA_EXPRESSION" : "org.mskcc.cbio.portal.scripts.ImportProfileData",
                                            "MUTATION_EXTENDED" : "org.mskcc.cbio.portal.scripts.ImportProfileData",
                                            "MUTATION_SIGNIFICANCE" : "org.mskcc.cbio.portal.scripts.ImportMutSigData",
                                            "RPPA" : "org.mskcc.cbio.portal.scripts.ImportProteinArrayData",
                                            "SEGMENT" : "org.mskcc.cbio.portal.scripts.ImportCopyNumberSegmentData",
                                            "TIMELINE" : "org.mskcc.cbio.portal.scripts.ImportTimelineData" }

IMPORTER_REQUIRES_METADATA = { "org.mskcc.cbio.portal.scripts.ImportClinicalData" : False,
                                "org.mskcc.cbio.portal.scripts.ImportCopyNumberSegmentData" : False,
                                "org.mskcc.cbio.portal.scripts.ImportGisticData" : False,
                                "org.mskcc.cbio.portal.scripts.ImportMutSigData" : False,
                                "org.mskcc.cbio.portal.scripts.ImportProteinArrayData" : False,
								"org.mskcc.cbio.portal.scripts.ImportProfileData" : True,
                                "org.mskcc.cbio.portal.scripts.ImportTimelineData" : True }

# ------------------------------------------------------------------------------
# class definitions

class MetastudyProperties(object):
    def __init__(self,
                 type_of_cancer, cancer_study_identifier,
                 name, description, short_name):
        self.type_of_cancer = type_of_cancer
        self.cancer_study_identifier = cancer_study_identifier
        self.name = name
        self.description = description
        self.short_name = short_name

class MetafileProperties(object):
    def __init__(self,
                 cancer_study_identifier, genetic_alteration_type,
                 datatype, stable_id, show_profile_in_analysis_tab,
                 profile_description, profile_name):
        self.cancer_study_identifier = cancer_study_identifier
        self.genetic_alteration_type = genetic_alteration_type
        self.datatype = datatype
        self.stable_id = stable_id
        self.show_profile_in_analysis_tab = show_profile_in_analysis_tab
        self.profile_description = profile_description
        self.profile_name = profile_name

# ------------------------------------------------------------------------------
# sub-routines

def importer_requires_metadata_file(importer_classname):
	return IMPORTER_REQUIRES_METADATA[importer_classname]

def get_properties(filename):
    properties = {}
    file = open(filename, 'r')
    for line in file:
        line = line.strip()
        # skip line if its blank or a comment
        if len(line) == 0:
            continue
        # store name/value
        property = line.split(': ', 1)
        if (len(property) != 2):
            print >> ERROR_FILE, 'Skipping invalid entry in file: ' + line
            continue
        properties[property[0]] = property[1].strip()
    file.close()
    return properties

def get_metastudy_properties(meta_filename):
    properties = get_properties(meta_filename)

    # ignoring groups, pmid, citation - not needed
    if ("type_of_cancer" not in properties or len(properties["type_of_cancer"]) == 0 or
        "cancer_study_identifier" not in properties or len(properties["cancer_study_identifier"]) == 0 or
        "name" not in properties or len(properties["name"]) == 0 or
        "description" not in properties or len(properties["description"]) == 0 or
        "short_name" not in properties or len(properties["short_name"]) == 0):
        print >> ERROR_FILE, 'Missing one or more required properties, please check metastudy file'
        return None

    # return an instance of PortalProperties
    return MetastudyProperties(properties["type_of_cancer"],
                            properties["cancer_study_identifier"],
                            properties["name"],
                            properties["description"],
                            properties["short_name"])

def get_metafile_properties(meta_filename):
    properties = get_properties(meta_filename)
    if ("show_profile_in_analysis_tab not in analysis_tab" not in properties):
        properties['show_profile_in_analysis_tab'] = 'false'

    # error check
    if ("cancer_study_identifier" not in properties or len(properties["cancer_study_identifier"]) == 0 or
    	"genetic_alteration_type" not in properties or len(properties["genetic_alteration_type"]) == 0 or
    	"datatype" not in properties or len(properties["datatype"]) == 0 or
    	"stable_id" not in properties or len(properties["stable_id"]) == 0 or
    	"show_profile_in_analysis_tab" not in properties or len(properties["show_profile_in_analysis_tab"]) == 0 or
    	"profile_name" not in properties or len(properties["profile_name"]) == 0 or
    	"profile_description" not in properties or len(properties["profile_description"]) == 0):
        print >> ERROR_FILE, 'Missing one or more required properties, please check metadata file'
        return None

    # return an instance of PortalProperties
    return MetafileProperties(properties["cancer_study_identifier"],
    						properties["genetic_alteration_type"],
                            properties["datatype"],
                            properties["stable_id"],
                            properties["show_profile_in_analysis_tab"],
                            properties["profile_name"],
                            properties["profile_description"])

def run_java(*args):
    java_home = os.environ['JAVA_HOME']
    if len(java_home) == 0:
        print >> ERROR_FILE, "$JAVA_HOME must be defined"
        return
    #print >> OUTPUT_FILE, ("Executing command: " + java_home +
                           #"/bin/java {}\n".format(args).replace('(\'', '').replace('\', \'', ' ').replace('\')', ''))
    process = Popen([ java_home + '/bin/java']+list(args), stdout=PIPE, stderr=STDOUT)
    ret = []
    while process.poll() is None:
        line = process.stdout.readline()
        if line != '' and line.endswith('\n'):
            print >> OUTPUT_FILE, line.strip()
            ret.append(line[:-1])
    return ret
<|endoftext|>


<commit_before>#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# 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.

"""Helpers used to display various views that are forms.
"""

__authors__ = [
  '"Chen Lunpeng" <forever.clp@gmail.com>',
  '"Todd Larsen" <tlarsen@google.com>',
  '"Pawel Solyga" <pawel.solyga@gmail.com>',
  ]

from google.appengine.ext.db import djangoforms

from django import forms
from django.utils import safestring
from django.utils.safestring import mark_safe

class BaseForm(djangoforms.ModelForm):
  """Subclass of Django ModelForm that fixes some label and help_text issues.

  The default behavior of ModelForm is to use the verbose_name in all
  lowercase, capitalizing only the first character, as the displayed field
  label.  This class uses verbose_name unaltered as the visible field label
  instead.

  The Property classes used by the App Engine Datastore do not have a
  help_text parameter to their constructor.  In a Model class, a help_text
  attribute *can* be added to the property after it is created, but the
  help text will not be automatically passed along to the Django ModelForm.
  This class detects the presence of a help_text attribute and adds it to
  the corresponding form field object.

  ugettext() proxies used for internationalization in the Model will
  still work correctly with this new behavior, as long as the original
  strings are used as the translation keys.
  """

  def __init__(self, *args, **kwargs):
    """Fixes label and help_text issues after parent initialization.

    Args:
      *args, **kwargs:  passed through to parent __init__() constructor
    """
    super(djangoforms.ModelForm, self).__init__(*args, **kwargs)

    for field_name in self.fields.iterkeys():
      # Since fields can be added only to the ModelForm subclass, check to
      # see if the Model has a corresponding field first.
      if hasattr(self.Meta.model, field_name):
        model_prop = getattr(self.Meta.model, field_name)

        # Check if the Model property defined verbose_name, and copy that
        # verbatim to the corresponding field label.
        if hasattr(model_prop, 'verbose_name'):
          self.fields[field_name].label = model_prop.verbose_name

        # Check if the Model property added help_text, and copy that verbatim
        # to the corresponding field help_text.
        if hasattr(model_prop, 'help_text'):
          self.fields[field_name].help_text = model_prop.help_text

        # Check if the Model property added example_text, and copy that verbatim
        # to the corresponding field help_text.
        if hasattr(model_prop, 'example_text'):
          self.fields[field_name].example_text = model_prop.example_text

class SelectQueryArgForm(forms.Form):
  """URL query argument change control implemented as a Django form.
  """

  ONCHANGE_JAVASCRIPT_FMT = '''

'''

  def __init__(self, page_path, arg_name, choices, field_name,
               *form_args, **form_kwargs):
    """
    Args:
      page_path: (usually request.path)
      arg_name: the URL query parameter that determines which choice is
        selected in the selection control
      choices: list (or tuple) of value/label string two-tuples, for example:
        (('10', '10 items per page'), ('25', '25 items per page'))
      field_name: name of the selection field in the form
      *form_args: positional arguments passed on to the Form base
        class __init__()
      *form_kwargs: keyword arguments passed on to the Form base
        class __init__()
    """
    super(SelectQueryArgForm, self).__init__(*form_args, **form_kwargs)

    self._script = safestring.mark_safe(self.ONCHANGE_JAVASCRIPT_FMT % {
        'arg_name': arg_name, 'page_path': page_path,})

    onchange_js_call = 'changeArg_%s(this)' % arg_name

    self.fields[field_name] = forms.ChoiceField(
        label='', choices=choices,
        widget=forms.widgets.Select(attrs={'onchange': onchange_js_call}))

  def as_table(self):
    """Returns form rendered as HTML
 rows -- with no

.

    Prepends
'''

  def __init__(self, page_path, arg_name, choices, field_name,
               *form_args, **form_kwargs):
    """
    Args:
      page_path: (usually request.path)
      arg_name: the URL query parameter that determines which choice is
        selected in the selection control
      choices: list (or tuple) of value/label string two-tuples, for example:
        (('10', '10 items per page'), ('25', '25 items per page'))
      field_name: name of the selection field in the form
      *form_args: positional arguments passed on to the Form base
        class __init__()
      *form_kwargs: keyword arguments passed on to the Form base
        class __init__()
    """
    super(SelectQueryArgForm, self).__init__(*form_args, **form_kwargs)

    self._script = safestring.mark_safe(self.ONCHANGE_JAVASCRIPT_FMT % {
        'arg_name': arg_name, 'page_path': page_path,})

    onchange_js_call = 'changeArg_%s(this)' % arg_name

    self.fields[field_name] = forms.ChoiceField(
        label='', choices=choices,
        widget=forms.widgets.Select(attrs={'onchange': onchange_js_call}))

  def as_table(self):
    """Returns form rendered as HTML
 rows -- with no

.

    Prepends


<commit_before>#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# 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.

"""Views for Groups.
"""

__authors__ = [
    '"Sverre Rabbelier" <sverre@rabbelier.nl>',
    '"Lennard de Rijk" <ljvderijk@gmail.com>',
  ]

from django import forms
from django import http
from django.utils.translation import ugettext

from soc.logic import cleaning
from soc.logic import dicts
from soc.logic.models import user as user_logic
from soc.views.helper import decorators
from soc.views.helper import lists as list_helper
from soc.views.helper import redirects
from soc.views.helper import responses
from soc.views.helper import widgets
from soc.views.models import presence
from soc.views.models import document as document_view
from soc.views.models.request import view as request_view
from soc.views.sitemap import sidebar

import soc.views.helper

class View(presence.View):
  """View methods for the Group model.
  """

  def __init__(self, params=None):
    """Defines the fields and methods required for the base View class
    to provide the user with list, public, create, edit and delete views.

    Params:
      params: a dict with params for this View
    """

    new_params = {}

    new_params['extra_dynaexclude'] = ['founder', 'home', 'tos',
                                       'member_template', 'status']
    new_params['edit_extra_dynaproperties'] = {
        'founded_by': forms.CharField(widget=widgets.ReadOnlyInput(),
                                   required=False),
        }

    #set the extra_django_patterns and include the one from params
    patterns = params.get('extra_django_patterns', [])

    patterns += [
        (r'^%(url_name)s/(?P<access_type>list_requests)/%(key_fields)s$',
        '%(module_package)s.%(module_name)s.list_requests',
        'List of requests for %(name)s'),
        (r'^%(url_name)s/(?P<access_type>list_roles)/%(key_fields)s$',
        '%(module_package)s.%(module_name)s.list_roles',
        'List of roles for %(name)s')]

    new_params['extra_django_patterns'] = patterns

    # TODO(tlarsen): Add support for Django style template lookup
    new_params['public_template'] = 'soc/group/public.html'

    new_params['list_row'] = 'soc/group/list/row.html'
    new_params['list_heading'] = 'soc/group/list/heading.html'

    new_params['create_extra_dynaproperties'] = {
       'email': forms.fields.EmailField(required=True),
       'clean_phone': cleaning.clean_phone_number('phone'),
       'clean_contact_street': cleaning.clean_ascii_only('contact_street'),
       'clean_contact_city': cleaning.clean_ascii_only('contact_city'),
       'clean_contact_state': cleaning.clean_ascii_only('contact_state'),
       'clean_contact_postalcode': cleaning.clean_ascii_only(
          'contact_postalcode'),
       'clean_shipping_street': cleaning.clean_ascii_only('shipping_street'),
       'clean_shipping_city': cleaning.clean_ascii_only('shipping_city'),
       'clean_shipping_state': cleaning.clean_ascii_only('shipping_state'),
       'clean_shipping_postalcode': cleaning.clean_ascii_only(
          'shipping_postalcode'),
       }

    new_params['role_views'] = {}

    new_params['public_field_keys'] = ["name", "link_id", "short_name"]
    new_params['public_field_names'] = ["Name", "Link ID", "Short name"]

    params = dicts.merge(params, new_params, sub_merge=True)

    super(View, self).__init__(params=params)

  def _editGet(self, request, entity, form):
    """See base.View._editGet().
    """

    # fill in the founded_by with data from the entity
    form.fields['founded_by'].initial = entity.founder.name
    super(View, self)._editGet(request, entity, form)

  def _editPost(self, request, entity, fields):
    """See base.View._editPost().
    """

    if not entity:
      # only if we are creating a new entity we should fill in founder
      user = user_logic.logic.getForCurrentAccount()
      fields['founder'] = user

    super(View, self)._editPost(request, entity, fields)

  @decorators.merge_params
  @decorators.check_access
  def applicant(self, request, access_type,
                page_name=None, params=None, **kwargs):
    """Handles the creation of a group via an approved group application.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # get the context for this webpage
    context = responses.getUniversalContext(request)
    responses.useJavaScript(context, params['js_uses_all'])
    context['page_name'] = page_name

    if request.method == 'POST':
      return self.applicantPost(request, context, params, **kwargs)
    else:
      # request.method == 'GET'
      return self.applicantGet(request, context, params, **kwargs)

  def applicantGet(self, request, context, params, **kwargs):
    """Handles the GET request concerning the creation of a group via an
    approved group application.

    Args:
      request: the standard Django HTTP request object
      context: dictionary containing the context for this view
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # find the application
    application_logic = params['application_logic']
    application = application_logic.logic.getFromKeyFields(kwargs)

    # extract the application fields
    field_names = application.properties().keys()
    fields = dict( [(i, getattr(application, i)) for i in field_names] )

    # create the form using the fields from the application as the initial value
    form = params['applicant_create_form'](initial=fields)

    # construct the appropriate response
    return super(View, self)._constructResponse(request, entity=None,
        context=context, form=form, params=params)

  def applicantPost(self, request, context, params, **kwargs):
    """Handles the POST request concerning the creation of a group via an
    approved group application.

    Args:
      request: the standard Django HTTP request object
      context: dictionary containing the context for this view
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # populate the form using the POST data
    form = params['applicant_create_form'](request.POST)

    if not form.is_valid():
      # return the invalid form response
      return self._constructResponse(request, entity=None, context=context,
          form=form, params=params)

    # collect the cleaned data from the valid form
    key_name, fields = soc.views.helper.forms.collectCleanedFields(form)

    # do post processing
    self._applicantPost(request, context, fields)

    if not key_name:
      key_name = self._logic.getKeyNameFromFields(fields)

    # create the group entity
    self._logic.updateOrCreateFromKeyName(fields, key_name)

    # redirect to notifications list to see the admin invite
    return http.HttpResponseRedirect('/notification/list')

  def _applicantPost(self, request, context, fields):
    """Performs any required processing on the entity to post its edit page.

    Args:
      request: the django request object
      context: the context for the webpage
      fields: the new field values
    """

     # fill in the founder of the group
    user = user_logic.logic.getForCurrentAccount()
    fields['founder'] = user

    # If scope_logic is not defined, this entity has no scope
    if not self._params['scope_logic']:
      return

    # If this entity is unscoped, do not try to retrieve a scope
    if 'scope_path' not in fields:
      return

    scope = self._params['scope_logic'].logic.getFromKeyName(
        fields['scope_path'])
    fields['scope'] = scope

  @decorators.merge_params
  @decorators.check_access
  def listRequests(self, request, access_type,
                   page_name=None, params=None, **kwargs):
    """Gives an overview of all the requests for a specific group.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # set the pagename to include the link_id
    page_name = '%s %s' % (page_name, kwargs['link_id'])

    # get the group from the request
    group_logic = params['logic']

    group_entity = group_logic.getFromKeyFields(kwargs)

    role_names = params['role_views'].keys()

    # list all incoming requests
    filter = {
        'group': group_entity,
        'role': role_names,
        }

    # create the list parameters
    req_params = request_view.getParams()

    # define the list redirect action to the request processing page
    req_params['public_row_extra'] = lambda entity: {
        'link': redirects.getProcessRequestRedirect(entity, None)
    }
    req_params['public_field_ignore'] = ['for']
    req_params['list_description'] = ugettext(
        "An overview of the %(name)s's invites and requests." % params)

    return self.list(request, access_type, page_name=page_name,
                     params=req_params, filter=filter, **kwargs)

  @decorators.merge_params
  @decorators.check_access
  def listRoles(self, request, access_type,
                page_name=None, params=None, **kwargs):
    """Gives an overview of all the roles in a specific group.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # set the pagename to include the link_id
    page_name = '%s %s' % (page_name, kwargs['link_id'])

    # get the group from the request
    group_logic = params['logic']

    group_entity = group_logic.getFromKeyFields(kwargs)

    # create the filter
    filter = {
        'scope' : group_entity,
        'status': 'active'
        }

    role_views = params['role_views']
    contents = []
    index = 0

    # for each role we create a separate list
    for role_name in role_views.keys():
      # create the list parameters
      list_params = role_views[role_name].getParams().copy()

      list_params['list_action'] = (redirects.getManageRedirect, list_params)
      list_params['list_description'] = ugettext(
          "An overview of the %s for this %s." % (
          list_params['name_plural'], params['name']))

      new_list_content = list_helper.getListContent(
          request, list_params, filter, idx=index)

      contents += [new_list_content]

      index += 1

    # call the _list method from base.View to show the list
    return self._list(request, params, contents, page_name)

  def registerRole(self, role_name, role_view):
    """Adds a role to the role_views param.

    Args:
      role_name: The name of the role that needs to be added
      role_view: The view that needs to be added to role_views.
    """

    role_views = self._params['role_views']
    role_views[role_name] = role_view

  def getExtraMenus(self, id, user, params=None):
    """Returns the extra menu's for this view.

    A menu item is generated for each group that the user has an active
    role for. The public page for each group is added as menu item,
    as well as all public documents for that group.

    Args:
      params: a dict with params for this View.
    """

    params = dicts.merge(params, self._params)

    # set fields to match every active/inactive role this user has
    fields = {
        'user': user,
        'status': ['active', 'inactive']
        }

    # get the role views and start filling group_entities
    role_views = self._params['role_views']
    role_descriptions = {}

    for role_name in role_views.keys():
      role_view = role_views[role_name]
      role_view_params = role_view.getParams()
      role_logic = role_view_params['logic']

      roles = role_logic.getForFields(fields)

      for role in roles:
        group_key_name = role.scope.key().id_or_name()
        existing_role_descriptions = role_descriptions.get(group_key_name)

        if existing_role_descriptions:
          # add this description to existing roles
          existing_roles = existing_role_descriptions['roles']
          existing_roles[role_name] = role
        else:
          # create a description of this role
          role_description = {'roles': {role_name: role},
              'group': role.scope}

          # add the new entry to our dictionary
          role_descriptions[group_key_name] = role_description

    # get the document view params to add the group's documents to the menu
    doc_params = document_view.view.getParams()

    menus = []

    # for each role description in our collection
    for role_description in role_descriptions.itervalues():
      #start with an empty menu
      menu = {}

      # get the group for this role description
      group_entity = role_description['group']

      # set the menu header name
      menu['heading'] = group_entity.short_name

      # get the documents for this group entity
      doc_items = document_view.view.getMenusForScope(group_entity, params)
      doc_items = sidebar.getSidebarMenu(id, user, doc_items,
                                         params=doc_params)

      # get the group specific items
      group_items = self._getExtraMenuItems(role_description, params)
      group_items = sidebar.getSidebarMenu(id, user, group_items,
                                           params=self._params)

      # add the items together
      menu['items'] = doc_items + group_items
      menu['group'] = params['name_plural']
      menu['collapse'] = 'collapse' if group_entity.status == 'inactive' \
          else ''

      # append this as a new menu
      menus.append(menu)

    return menus

  def _getExtraMenuItems(self, role_description, params=None):
    """Used to implement group instance specific needs for the side menu.

    Args:
      role_description : dict containing all the roles which is a dict of
                         name and the role entity to which it belongs. Also
                         group contains the group entity to which these roles
                         belong.
      params: a dict with params for this View.
    """
    return []
<commit_msg>Convert group.listRoles to the new list system<commit_after>#!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# 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.

"""Views for Groups.
"""

__authors__ = [
    '"Sverre Rabbelier" <sverre@rabbelier.nl>',
    '"Lennard de Rijk" <ljvderijk@gmail.com>',
  ]

from django import forms
from django import http
from django.utils import simplejson
from django.utils.translation import ugettext

from soc.logic import cleaning
from soc.logic import dicts
from soc.logic.models import user as user_logic
from soc.views.helper import decorators
from soc.views.helper import lists as list_helper
from soc.views.helper import redirects
from soc.views.helper import responses
from soc.views.helper import widgets
from soc.views.models import presence
from soc.views.models import document as document_view
from soc.views.models.request import view as request_view
from soc.views.sitemap import sidebar

import soc.views.helper

class View(presence.View):
  """View methods for the Group model.
  """

  def __init__(self, params=None):
    """Defines the fields and methods required for the base View class
    to provide the user with list, public, create, edit and delete views.

    Params:
      params: a dict with params for this View
    """

    new_params = {}

    new_params['extra_dynaexclude'] = ['founder', 'home', 'tos',
                                       'member_template', 'status']
    new_params['edit_extra_dynaproperties'] = {
        'founded_by': forms.CharField(widget=widgets.ReadOnlyInput(),
                                   required=False),
        }

    #set the extra_django_patterns and include the one from params
    patterns = params.get('extra_django_patterns', [])

    patterns += [
        (r'^%(url_name)s/(?P<access_type>list_requests)/%(key_fields)s$',
        '%(module_package)s.%(module_name)s.list_requests',
        'List of requests for %(name)s'),
        (r'^%(url_name)s/(?P<access_type>list_roles)/%(key_fields)s$',
        '%(module_package)s.%(module_name)s.list_roles',
        'List of roles for %(name)s')]

    new_params['extra_django_patterns'] = patterns

    # TODO(tlarsen): Add support for Django style template lookup
    new_params['public_template'] = 'soc/group/public.html'

    new_params['list_row'] = 'soc/group/list/row.html'
    new_params['list_heading'] = 'soc/group/list/heading.html'

    new_params['create_extra_dynaproperties'] = {
       'email': forms.fields.EmailField(required=True),
       'clean_phone': cleaning.clean_phone_number('phone'),
       'clean_contact_street': cleaning.clean_ascii_only('contact_street'),
       'clean_contact_city': cleaning.clean_ascii_only('contact_city'),
       'clean_contact_state': cleaning.clean_ascii_only('contact_state'),
       'clean_contact_postalcode': cleaning.clean_ascii_only(
          'contact_postalcode'),
       'clean_shipping_street': cleaning.clean_ascii_only('shipping_street'),
       'clean_shipping_city': cleaning.clean_ascii_only('shipping_city'),
       'clean_shipping_state': cleaning.clean_ascii_only('shipping_state'),
       'clean_shipping_postalcode': cleaning.clean_ascii_only(
          'shipping_postalcode'),
       }

    new_params['role_views'] = {}

    new_params['public_field_keys'] = ["name", "link_id", "short_name"]
    new_params['public_field_names'] = ["Name", "Link ID", "Short name"]

    params = dicts.merge(params, new_params, sub_merge=True)

    super(View, self).__init__(params=params)

  def _editGet(self, request, entity, form):
    """See base.View._editGet().
    """

    # fill in the founded_by with data from the entity
    form.fields['founded_by'].initial = entity.founder.name
    super(View, self)._editGet(request, entity, form)

  def _editPost(self, request, entity, fields):
    """See base.View._editPost().
    """

    if not entity:
      # only if we are creating a new entity we should fill in founder
      user = user_logic.logic.getForCurrentAccount()
      fields['founder'] = user

    super(View, self)._editPost(request, entity, fields)

  @decorators.merge_params
  @decorators.check_access
  def applicant(self, request, access_type,
                page_name=None, params=None, **kwargs):
    """Handles the creation of a group via an approved group application.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # get the context for this webpage
    context = responses.getUniversalContext(request)
    responses.useJavaScript(context, params['js_uses_all'])
    context['page_name'] = page_name

    if request.method == 'POST':
      return self.applicantPost(request, context, params, **kwargs)
    else:
      # request.method == 'GET'
      return self.applicantGet(request, context, params, **kwargs)

  def applicantGet(self, request, context, params, **kwargs):
    """Handles the GET request concerning the creation of a group via an
    approved group application.

    Args:
      request: the standard Django HTTP request object
      context: dictionary containing the context for this view
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # find the application
    application_logic = params['application_logic']
    application = application_logic.logic.getFromKeyFields(kwargs)

    # extract the application fields
    field_names = application.properties().keys()
    fields = dict( [(i, getattr(application, i)) for i in field_names] )

    # create the form using the fields from the application as the initial value
    form = params['applicant_create_form'](initial=fields)

    # construct the appropriate response
    return super(View, self)._constructResponse(request, entity=None,
        context=context, form=form, params=params)

  def applicantPost(self, request, context, params, **kwargs):
    """Handles the POST request concerning the creation of a group via an
    approved group application.

    Args:
      request: the standard Django HTTP request object
      context: dictionary containing the context for this view
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # populate the form using the POST data
    form = params['applicant_create_form'](request.POST)

    if not form.is_valid():
      # return the invalid form response
      return self._constructResponse(request, entity=None, context=context,
          form=form, params=params)

    # collect the cleaned data from the valid form
    key_name, fields = soc.views.helper.forms.collectCleanedFields(form)

    # do post processing
    self._applicantPost(request, context, fields)

    if not key_name:
      key_name = self._logic.getKeyNameFromFields(fields)

    # create the group entity
    self._logic.updateOrCreateFromKeyName(fields, key_name)

    # redirect to notifications list to see the admin invite
    return http.HttpResponseRedirect('/notification/list')

  def _applicantPost(self, request, context, fields):
    """Performs any required processing on the entity to post its edit page.

    Args:
      request: the django request object
      context: the context for the webpage
      fields: the new field values
    """

     # fill in the founder of the group
    user = user_logic.logic.getForCurrentAccount()
    fields['founder'] = user

    # If scope_logic is not defined, this entity has no scope
    if not self._params['scope_logic']:
      return

    # If this entity is unscoped, do not try to retrieve a scope
    if 'scope_path' not in fields:
      return

    scope = self._params['scope_logic'].logic.getFromKeyName(
        fields['scope_path'])
    fields['scope'] = scope

  @decorators.merge_params
  @decorators.check_access
  def listRequests(self, request, access_type,
                   page_name=None, params=None, **kwargs):
    """Gives an overview of all the requests for a specific group.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # set the pagename to include the link_id
    page_name = '%s %s' % (page_name, kwargs['link_id'])

    # get the group from the request
    group_logic = params['logic']

    group_entity = group_logic.getFromKeyFields(kwargs)

    role_names = params['role_views'].keys()

    # list all incoming requests
    filter = {
        'group': group_entity,
        'role': role_names,
        }

    # create the list parameters
    req_params = request_view.getParams()

    # define the list redirect action to the request processing page
    req_params['public_row_extra'] = lambda entity: {
        'link': redirects.getProcessRequestRedirect(entity, None)
    }
    req_params['public_field_ignore'] = ['for']
    req_params['list_description'] = ugettext(
        "An overview of the %(name)s's invites and requests." % params)

    return self.list(request, access_type, page_name=page_name,
                     params=req_params, filter=filter, **kwargs)

  def getListRolesData(self, request, list_params, group_entity):
    """Returns the list data for listRoles.
    """

    idx = request.GET.get('idx', '')
    idx = int(idx) if idx.isdigit() else -1

    if not 0 <= idx < len(list_params):
        return responses.jsonErrorResponse(request, "idx not valid")

    # create the filter
    fields= {
        'scope' : group_entity,
        'status': 'active'
        }

    params = list_params[idx]
    contents = list_helper.getListData(request, params, fields)

    json = simplejson.dumps(contents)
    return responses.jsonResponse(request, json)

  @decorators.merge_params
  @decorators.check_access
  def listRoles(self, request, access_type,
                page_name=None, params=None, **kwargs):
    """Gives an overview of all the roles in a specific group.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # set the pagename to include the link_id
    page_name = '%s %s' % (page_name, kwargs['link_id'])

    role_views = params['role_views']

    lists_params = []

    for role_name in sorted(role_views.keys()):
      # create the list parameters
      list_params = role_views[role_name].getParams().copy()

      list_params['public_row_extra'] = lambda entity: {
          'link': redirects.getManageRedirect(entity, list_params)
      }
      list_params['list_description'] = ugettext(
          "An overview of the %s for this %s." % (
          list_params['name_plural'], params['name']))

      lists_params.append(list_params)

    if request.GET.get('fmt') == 'json':
      group_logic = params['logic']
      group_entity = group_logic.getFromKeyFields(kwargs)
      return self.getListRolesData(request, lists_params, group_entity)

    contents = []

    index = 0
    for list_params in lists_params:
      list = list_helper.getListGenerator(request, list_params, idx=index)
      contents.append(list)
      index += 1

    # call the _list method from base.View to show the list
    return self._list(request, params, contents, page_name)

  def registerRole(self, role_name, role_view):
    """Adds a role to the role_views param.

    Args:
      role_name: The name of the role that needs to be added
      role_view: The view that needs to be added to role_views.
    """

    role_views = self._params['role_views']
    role_views[role_name] = role_view

  def getExtraMenus(self, id, user, params=None):
    """Returns the extra menu's for this view.

    A menu item is generated for each group that the user has an active
    role for. The public page for each group is added as menu item,
    as well as all public documents for that group.

    Args:
      params: a dict with params for this View.
    """

    params = dicts.merge(params, self._params)

    # set fields to match every active/inactive role this user has
    fields = {
        'user': user,
        'status': ['active', 'inactive']
        }

    # get the role views and start filling group_entities
    role_views = self._params['role_views']
    role_descriptions = {}

    for role_name in role_views.keys():
      role_view = role_views[role_name]
      role_view_params = role_view.getParams()
      role_logic = role_view_params['logic']

      roles = role_logic.getForFields(fields)

      for role in roles:
        group_key_name = role.scope.key().id_or_name()
        existing_role_descriptions = role_descriptions.get(group_key_name)

        if existing_role_descriptions:
          # add this description to existing roles
          existing_roles = existing_role_descriptions['roles']
          existing_roles[role_name] = role
        else:
          # create a description of this role
          role_description = {'roles': {role_name: role},
              'group': role.scope}

          # add the new entry to our dictionary
          role_descriptions[group_key_name] = role_description

    # get the document view params to add the group's documents to the menu
    doc_params = document_view.view.getParams()

    menus = []

    # for each role description in our collection
    for role_description in role_descriptions.itervalues():
      #start with an empty menu
      menu = {}

      # get the group for this role description
      group_entity = role_description['group']

      # set the menu header name
      menu['heading'] = group_entity.short_name

      # get the documents for this group entity
      doc_items = document_view.view.getMenusForScope(group_entity, params)
      doc_items = sidebar.getSidebarMenu(id, user, doc_items,
                                         params=doc_params)

      # get the group specific items
      group_items = self._getExtraMenuItems(role_description, params)
      group_items = sidebar.getSidebarMenu(id, user, group_items,
                                           params=self._params)

      # add the items together
      menu['items'] = doc_items + group_items
      menu['group'] = params['name_plural']

      # append this as a new menu
      menus.append(menu)

    return menus

  def _getExtraMenuItems(self, role_description, params=None):
    """Used to implement group instance specific needs for the side menu.

    Args:
      role_description : dict containing all the roles which is a dict of
                         name and the role entity to which it belongs. Also
                         group contains the group entity to which these roles
                         belong.
      params: a dict with params for this View.
    """
    return []
<|endoftext|>


<commit_before>#!/usr/bin/env python2.5
#
# Copyright 2008 the Melange authors.
#
# 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.

"""Views for Groups.
"""

__authors__ = [
    '"Sverre Rabbelier" <sverre@rabbelier.nl>',
    '"Lennard de Rijk" <ljvderijk@gmail.com>',
  ]

from django import forms
from django import http
from django.utils import simplejson
from django.utils.translation import ugettext

from soc.logic import cleaning
from soc.logic import dicts
from soc.logic.models import user as user_logic
from soc.views.helper import decorators
from soc.views.helper import lists as list_helper
from soc.views.helper import redirects
from soc.views.helper import responses
from soc.views.helper import widgets
from soc.views.models import presence
from soc.views.models import document as document_view
from soc.views.models.request import view as request_view
from soc.views.sitemap import sidebar

import soc.views.helper

class View(presence.View):
  """View methods for the Group model.
  """

  def __init__(self, params=None):
    """Defines the fields and methods required for the base View class
    to provide the user with list, public, create, edit and delete views.

    Params:
      params: a dict with params for this View
    """

    new_params = {}

    new_params['extra_dynaexclude'] = ['founder', 'home', 'tos',
                                       'member_template', 'status']
    new_params['edit_extra_dynaproperties'] = {
        'founded_by': forms.CharField(widget=widgets.ReadOnlyInput(),
                                   required=False),
        }

    #set the extra_django_patterns and include the one from params
    patterns = params.get('extra_django_patterns', [])

    patterns += [
        (r'^%(url_name)s/(?P<access_type>list_requests)/%(key_fields)s$',
        '%(module_package)s.%(module_name)s.list_requests',
        'List of requests for %(name)s'),
        (r'^%(url_name)s/(?P<access_type>list_roles)/%(key_fields)s$',
        '%(module_package)s.%(module_name)s.list_roles',
        'List of roles for %(name)s')]

    new_params['extra_django_patterns'] = patterns

    # TODO(tlarsen): Add support for Django style template lookup
    new_params['public_template'] = 'soc/group/public.html'

    new_params['create_extra_dynaproperties'] = {
       'email': forms.fields.EmailField(required=True),
       'clean_phone': cleaning.clean_phone_number('phone'),
       'clean_contact_street': cleaning.clean_ascii_only('contact_street'),
       'clean_contact_street_extra': cleaning.clean_ascii_only(
                                         'contact_street_extra'),
       'clean_contact_city': cleaning.clean_ascii_only('contact_city'),
       'clean_contact_state': cleaning.clean_ascii_only('contact_state'),
       'clean_contact_postalcode': cleaning.clean_ascii_only(
          'contact_postalcode'),
       'clean_shipping_street': cleaning.clean_ascii_only('shipping_street'),
       'clean_shipping_street_extra': cleaning.clean_ascii_only(
                                          'shipping_street_extra'),
       'clean_shipping_city': cleaning.clean_ascii_only('shipping_city'),
       'clean_shipping_state': cleaning.clean_ascii_only('shipping_state'),
       'clean_shipping_postalcode': cleaning.clean_ascii_only(
          'shipping_postalcode'),
       }

    new_params['role_views'] = {}

    new_params['public_field_keys'] = ["name", "link_id", "short_name"]
    new_params['public_field_names'] = ["Name", "Link ID", "Short name"]

    params = dicts.merge(params, new_params, sub_merge=True)

    super(View, self).__init__(params=params)

  def _editGet(self, request, entity, form):
    """See base.View._editGet().
    """

    # fill in the founded_by with data from the entity
    form.fields['founded_by'].initial = entity.founder.name
    super(View, self)._editGet(request, entity, form)

  def _editPost(self, request, entity, fields):
    """See base.View._editPost().
    """

    if not entity:
      # only if we are creating a new entity we should fill in founder
      user = user_logic.logic.getForCurrentAccount()
      fields['founder'] = user

    super(View, self)._editPost(request, entity, fields)

  @decorators.merge_params
  @decorators.check_access
  def listRequests(self, request, access_type,
                   page_name=None, params=None, **kwargs):
    """Gives an overview of all the requests for a specific group.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # set the pagename to include the link_id
    page_name = '%s %s' % (page_name, kwargs['link_id'])

    # get the group from the request
    group_logic = params['logic']

    group_entity = group_logic.getFromKeyFields(kwargs)

    role_names = params['role_views'].keys()

    # list all incoming requests
    filter = {
        'group': group_entity,
        'role': role_names,
        'status': ['new', 'group_accepted', 'ignored']
        }

    # create the list parameters
    req_params = request_view.getParams()

    # define the list redirect action to the request processing page
    req_params['public_row_extra'] = lambda entity: {
        'link': redirects.getProcessRequestRedirect(entity, None)
    }
    req_params['public_field_ignore'] = ['for']
    req_params['list_description'] = ugettext(
        "An overview of the %(name)s's invites and requests." % params)

    return self.list(request, access_type='allow', page_name=page_name,
                     params=req_params, filter=filter, **kwargs)

  def getListRolesData(self, request, list_params, group_entity):
    """Returns the list data for listRoles.
    """

    idx = request.GET.get('idx', '')
    idx = int(idx) if idx.isdigit() else -1

    if not 0 <= idx < len(list_params):
        return responses.jsonErrorResponse(request, "idx not valid")

    # create the filter
    fields= {
        'scope' : group_entity,
        'status': 'active'
        }

    params = list_params[idx]
    contents = list_helper.getListData(request, params, fields)

    json = simplejson.dumps(contents)
    return responses.jsonResponse(request, json)

  @decorators.merge_params
  @decorators.check_access
  def listRoles(self, request, access_type,
                page_name=None, params=None, **kwargs):
    """Gives an overview of all the roles in a specific group.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # set the pagename to include the link_id
    page_name = '%s %s' % (page_name, kwargs['link_id'])

    role_views = params['role_views']

    lists_params = []

    for role_name in sorted(role_views.keys()):
      # create the list parameters
      list_params = role_views[role_name].getParams().copy()

      list_params['public_row_extra'] = lambda entity: {
          'link': redirects.getManageRedirect(entity, list_params)
      }
      list_params['list_description'] = ugettext(
          "An overview of the %s for this %s." % (
          list_params['name_plural'], params['name']))

      lists_params.append(list_params)

    if request.GET.get('fmt') == 'json':
      group_logic = params['logic']
      group_entity = group_logic.getFromKeyFields(kwargs)
      return self.getListRolesData(request, lists_params, group_entity)

    contents = []

    index = 0
    for list_params in lists_params:
      list = list_helper.getListGenerator(request, list_params, idx=index)
      contents.append(list)
      index += 1

    # call the _list method from base.View to show the list
    return self._list(request, params, contents, page_name)

  def registerRole(self, role_name, role_view):
    """Adds a role to the role_views param.

    Args:
      role_name: The name of the role that needs to be added
      role_view: The view that needs to be added to role_views.
    """

    role_views = self._params['role_views']
    role_views[role_name] = role_view

  def getExtraMenus(self, id, user, params=None):
    """Returns the extra menu's for this view.

    A menu item is generated for each group that the user has an active
    role for. The public page for each group is added as menu item,
    as well as all public documents for that group.

    Args:
      params: a dict with params for this View.
    """

    params = dicts.merge(params, self._params)

    # set fields to match every active/inactive role this user has
    fields = {
        'user': user,
        'status': ['active', 'inactive']
        }

    # get the role views and start filling group_entities
    role_views = self._params['role_views']
    role_descriptions = {}

    for role_name in role_views.keys():
      role_view = role_views[role_name]
      role_view_params = role_view.getParams()
      role_logic = role_view_params['logic']

      roles = role_logic.getForFields(fields)

      for role in roles:
        group_key_name = role.scope.key().id_or_name()
        existing_role_descriptions = role_descriptions.get(group_key_name)

        if existing_role_descriptions:
          # add this description to existing roles
          existing_roles = existing_role_descriptions['roles']
          existing_roles[role_name] = role
        else:
          # create a description of this role
          role_description = {'roles': {role_name: role},
              'group': role.scope}

          # add the new entry to our dictionary
          role_descriptions[group_key_name] = role_description

    # get the document view params to add the group's documents to the menu
    doc_params = document_view.view.getParams()

    menus = []

    # for each role description in our collection
    for role_description in role_descriptions.itervalues():
      #start with an empty menu
      menu = {}

      # get the group for this role description
      group_entity = role_description['group']

      # set the menu header name
      heading = group_entity.short_name

      if group_entity.scope:
        scope = group_entity.scope
        heading = '%s (%s)' %(heading, scope.short_name)

      menu['heading'] = heading

      # get the documents for this group entity
      doc_items = document_view.view.getMenusForScope(group_entity, params)
      doc_items = sidebar.getSidebarMenu(id, user, doc_items,
                                         params=doc_params)

      # get the group specific items
      group_items = self._getExtraMenuItems(role_description, params)
      group_items = sidebar.getSidebarMenu(id, user, group_items,
                                           params=self._params)

      # add the items together
      menu['items'] = doc_items + group_items
      menu['group'] = params['name_plural']
      menu['collapse'] = 'collapse' if group_entity.status == 'inactive' \
          else ''

      # append this as a new menu
      menus.append(menu)

    return menus

  def _getExtraMenuItems(self, role_description, params=None):
    """Used to implement group instance specific needs for the side menu.

    Args:
      role_description : dict containing all the roles which is a dict of
                         name and the role entity to which it belongs. Also
                         group contains the group entity to which these roles
                         belong.
      params: a dict with params for this View.
    """
    return []
<commit_msg>fix list of list using the wrong params<commit_after>#!/usr/bin/env python2.5
#
# Copyright 2008 the Melange authors.
#
# 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.

"""Views for Groups.
"""

__authors__ = [
    '"Sverre Rabbelier" <sverre@rabbelier.nl>',
    '"Lennard de Rijk" <ljvderijk@gmail.com>',
  ]

from django import forms
from django import http
from django.utils import simplejson
from django.utils.translation import ugettext

from soc.logic import cleaning
from soc.logic import dicts
from soc.logic.models import user as user_logic
from soc.views.helper import decorators
from soc.views.helper import lists as list_helper
from soc.views.helper import redirects
from soc.views.helper import responses
from soc.views.helper import widgets
from soc.views.models import presence
from soc.views.models import document as document_view
from soc.views.models.request import view as request_view
from soc.views.sitemap import sidebar

import soc.views.helper

class View(presence.View):
  """View methods for the Group model.
  """

  def __init__(self, params=None):
    """Defines the fields and methods required for the base View class
    to provide the user with list, public, create, edit and delete views.

    Params:
      params: a dict with params for this View
    """

    new_params = {}

    new_params['extra_dynaexclude'] = ['founder', 'home', 'tos',
                                       'member_template', 'status']
    new_params['edit_extra_dynaproperties'] = {
        'founded_by': forms.CharField(widget=widgets.ReadOnlyInput(),
                                   required=False),
        }

    #set the extra_django_patterns and include the one from params
    patterns = params.get('extra_django_patterns', [])

    patterns += [
        (r'^%(url_name)s/(?P<access_type>list_requests)/%(key_fields)s$',
        '%(module_package)s.%(module_name)s.list_requests',
        'List of requests for %(name)s'),
        (r'^%(url_name)s/(?P<access_type>list_roles)/%(key_fields)s$',
        '%(module_package)s.%(module_name)s.list_roles',
        'List of roles for %(name)s')]

    new_params['extra_django_patterns'] = patterns

    # TODO(tlarsen): Add support for Django style template lookup
    new_params['public_template'] = 'soc/group/public.html'

    new_params['create_extra_dynaproperties'] = {
       'email': forms.fields.EmailField(required=True),
       'clean_phone': cleaning.clean_phone_number('phone'),
       'clean_contact_street': cleaning.clean_ascii_only('contact_street'),
       'clean_contact_street_extra': cleaning.clean_ascii_only(
                                         'contact_street_extra'),
       'clean_contact_city': cleaning.clean_ascii_only('contact_city'),
       'clean_contact_state': cleaning.clean_ascii_only('contact_state'),
       'clean_contact_postalcode': cleaning.clean_ascii_only(
          'contact_postalcode'),
       'clean_shipping_street': cleaning.clean_ascii_only('shipping_street'),
       'clean_shipping_street_extra': cleaning.clean_ascii_only(
                                          'shipping_street_extra'),
       'clean_shipping_city': cleaning.clean_ascii_only('shipping_city'),
       'clean_shipping_state': cleaning.clean_ascii_only('shipping_state'),
       'clean_shipping_postalcode': cleaning.clean_ascii_only(
          'shipping_postalcode'),
       }

    new_params['role_views'] = {}

    new_params['public_field_keys'] = ["name", "link_id", "short_name"]
    new_params['public_field_names'] = ["Name", "Link ID", "Short name"]

    params = dicts.merge(params, new_params, sub_merge=True)

    super(View, self).__init__(params=params)

  def _editGet(self, request, entity, form):
    """See base.View._editGet().
    """

    # fill in the founded_by with data from the entity
    form.fields['founded_by'].initial = entity.founder.name
    super(View, self)._editGet(request, entity, form)

  def _editPost(self, request, entity, fields):
    """See base.View._editPost().
    """

    if not entity:
      # only if we are creating a new entity we should fill in founder
      user = user_logic.logic.getForCurrentAccount()
      fields['founder'] = user

    super(View, self)._editPost(request, entity, fields)

  @decorators.merge_params
  @decorators.check_access
  def listRequests(self, request, access_type,
                   page_name=None, params=None, **kwargs):
    """Gives an overview of all the requests for a specific group.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # set the pagename to include the link_id
    page_name = '%s %s' % (page_name, kwargs['link_id'])

    # get the group from the request
    group_logic = params['logic']

    group_entity = group_logic.getFromKeyFields(kwargs)

    role_names = params['role_views'].keys()

    # list all incoming requests
    filter = {
        'group': group_entity,
        'role': role_names,
        'status': ['new', 'group_accepted', 'ignored']
        }

    # create the list parameters
    req_params = request_view.getParams()

    # define the list redirect action to the request processing page
    req_params['public_row_extra'] = lambda entity: {
        'link': redirects.getProcessRequestRedirect(entity, None)
    }
    req_params['public_field_ignore'] = ['for']
    req_params['list_description'] = ugettext(
        "An overview of the %(name)s's invites and requests." % params)

    return self.list(request, access_type='allow', page_name=page_name,
                     params=req_params, filter=filter, **kwargs)

  def getListRolesData(self, request, list_params, group_entity):
    """Returns the list data for listRoles.
    """

    idx = request.GET.get('idx', '')
    idx = int(idx) if idx.isdigit() else -1

    if not 0 <= idx < len(list_params):
        return responses.jsonErrorResponse(request, "idx not valid")

    # create the filter
    fields= {
        'scope' : group_entity,
        'status': 'active'
        }

    params = list_params[idx]
    contents = list_helper.getListData(request, params, fields)

    json = simplejson.dumps(contents)
    return responses.jsonResponse(request, json)

  @decorators.merge_params
  @decorators.check_access
  def listRoles(self, request, access_type,
                page_name=None, params=None, **kwargs):
    """Gives an overview of all the roles in a specific group.

    Args:
      request: the standard Django HTTP request object
      access_type : the name of the access type which should be checked
      page_name: the page name displayed in templates as page and header title
      params: a dict with params for this View
      kwargs: the Key Fields for the specified entity
    """

    # set the pagename to include the link_id
    page_name = '%s %s' % (page_name, kwargs['link_id'])

    role_views = params['role_views']

    lists_params = []

    for role_name in sorted(role_views.keys()):
      # create the list parameters
      list_params = role_views[role_name].getParams().copy()

      # Required because without this the lambda refers to list_params,
      # which is set to a different value due to the iteration.
      def getter(list_params):
        return lambda entity: {
            'link': redirects.getManageRedirect(entity, list_params)
        }
      list_params['public_row_extra'] = getter(list_params)
      list_params['list_description'] = ugettext(
          "An overview of the %s for this %s." % (
          list_params['name_plural'], params['name']))

      lists_params.append(list_params)

    if request.GET.get('fmt') == 'json':
      group_logic = params['logic']
      group_entity = group_logic.getFromKeyFields(kwargs)
      return self.getListRolesData(request, lists_params, group_entity)

    contents = []

    index = 0
    for list_params in lists_params:
      list = list_helper.getListGenerator(request, list_params, idx=index)
      contents.append(list)
      index += 1

    # call the _list method from base.View to show the list
    return self._list(request, params, contents, page_name)

  def registerRole(self, role_name, role_view):
    """Adds a role to the role_views param.

    Args:
      role_name: The name of the role that needs to be added
      role_view: The view that needs to be added to role_views.
    """

    role_views = self._params['role_views']
    role_views[role_name] = role_view

  def getExtraMenus(self, id, user, params=None):
    """Returns the extra menu's for this view.

    A menu item is generated for each group that the user has an active
    role for. The public page for each group is added as menu item,
    as well as all public documents for that group.

    Args:
      params: a dict with params for this View.
    """

    params = dicts.merge(params, self._params)

    # set fields to match every active/inactive role this user has
    fields = {
        'user': user,
        'status': ['active', 'inactive']
        }

    # get the role views and start filling group_entities
    role_views = self._params['role_views']
    role_descriptions = {}

    for role_name in role_views.keys():
      role_view = role_views[role_name]
      role_view_params = role_view.getParams()
      role_logic = role_view_params['logic']

      roles = role_logic.getForFields(fields)

      for role in roles:
        group_key_name = role.scope.key().id_or_name()
        existing_role_descriptions = role_descriptions.get(group_key_name)

        if existing_role_descriptions:
          # add this description to existing roles
          existing_roles = existing_role_descriptions['roles']
          existing_roles[role_name] = role
        else:
          # create a description of this role
          role_description = {'roles': {role_name: role},
              'group': role.scope}

          # add the new entry to our dictionary
          role_descriptions[group_key_name] = role_description

    # get the document view params to add the group's documents to the menu
    doc_params = document_view.view.getParams()

    menus = []

    # for each role description in our collection
    for role_description in role_descriptions.itervalues():
      #start with an empty menu
      menu = {}

      # get the group for this role description
      group_entity = role_description['group']

      # set the menu header name
      heading = group_entity.short_name

      if group_entity.scope:
        scope = group_entity.scope
        heading = '%s (%s)' %(heading, scope.short_name)

      menu['heading'] = heading

      # get the documents for this group entity
      doc_items = document_view.view.getMenusForScope(group_entity, params)
      doc_items = sidebar.getSidebarMenu(id, user, doc_items,
                                         params=doc_params)

      # get the group specific items
      group_items = self._getExtraMenuItems(role_description, params)
      group_items = sidebar.getSidebarMenu(id, user, group_items,
                                           params=self._params)

      # add the items together
      menu['items'] = doc_items + group_items
      menu['group'] = params['name_plural']
      menu['collapse'] = 'collapse' if group_entity.status == 'inactive' \
          else ''

      # append this as a new menu
      menus.append(menu)

    return menus

  def _getExtraMenuItems(self, role_description, params=None):
    """Used to implement group instance specific needs for the side menu.

    Args:
      role_description : dict containing all the roles which is a dict of
                         name and the role entity to which it belongs. Also
                         group contains the group entity to which these roles
                         belong.
      params: a dict with params for this View.
    """
    return []
<|endoftext|>


<commit_before>import traceback

from PySide import QtGui

DEFAULT_WIDTH = 500

BTN_OK = QtGui.QMessageBox.Ok
BTN_OPEN = QtGui.QMessageBox.Open
BTN_SAVE = QtGui.QMessageBox.Save
BTN_CANCEL = QtGui.QMessageBox.Cancel
BTN_CLOSE = QtGui.QMessageBox.Close
BTN_DISCARD = QtGui.QMessageBox.Discard
BTN_APPLY = QtGui.QMessageBox.Apply
BTN_RESET = QtGui.QMessageBox.Reset
BTN_RESTORE_DEFAULTS = QtGui.QMessageBox.RestoreDefaults
BTN_HELP = QtGui.QMessageBox.Help
BTN_SAVE_ALL = QtGui.QMessageBox.SaveAll
BTN_YES = QtGui.QMessageBox.Yes
BTN_YES_TO_ALL = QtGui.QMessageBox.YesToAll
BTN_NO = QtGui.QMessageBox.No
BTN_NO_TO_ALL = QtGui.QMessageBox.NoToAll
BTN_ABORT = QtGui.QMessageBox.Abort
BTN_RETRY = QtGui.QMessageBox.Retry
BTN_IGNORE = QtGui.QMessageBox.Ignore
BTN_NO_BUTTON = QtGui.QMessageBox.NoButton

ICON_NONE = QtGui.QMessageBox.NoIcon
ICON_QUESTION = QtGui.QMessageBox.Question
ICON_INFORMATION = QtGui.QMessageBox.Information
ICON_WARNING = QtGui.QMessageBox.Warning
ICON_CRITICAL = QtGui.QMessageBox.Critical

def messageBox(
        text,
        parent=None,
        title=None,
        textInformative=None,
        textDetailed=None,
        icon=ICON_NONE,
        buttons=None,
        defaultButton=None,
        escapeButton=None,
        width=DEFAULT_WIDTH
):

    dlg = QtGui.QMessageBox(parent)
    if title:
        dlg.setWindowTitle(title)
    if text:
        dlg.setText(text)
    if textInformative:
        dlg.setInformativeText(textInformative)
    if textDetailed:
        dlg.setDetailedText(textDetailed)
    if buttons:
        dlg.setStandardButtons(buttons)
    if defaultButton:
        dlg.setDefaultButton(defaultButton)
    if escapeButton:
        dlg.setEscapeButton(escapeButton)
    dlg.setIcon(icon)

    # hack for making predefined width message box
    if width:
        # noinspection PyArgumentList
        spacer = QtGui.QSpacerItem(width, 0, QtGui.QSizePolicy.Minimum, QtGui. QSizePolicy.Expanding)
        gridLayout = dlg.layout()
        gridLayout.addItem(spacer, gridLayout.rowCount(), 0, 1, gridLayout.columnCount())

    return dlg.exec_()

def info(
        text,
        parent=None,
        title='Information',
        textInformative=None,
        textDetailed=None,
        width=DEFAULT_WIDTH
):

    return messageBox(
        text,
        parent=parent,
        title=title,
        textInformative=textInformative,
        textDetailed=textDetailed,
        icon=ICON_INFORMATION,
        width=width
    )

def warning(
        text,
        parent=None,
        title='Warning',
        textInformative=None,
        textDetailed=None,
        width=DEFAULT_WIDTH
):
    return messageBox(
        text,
        parent=parent,
        title=title,
        textInformative=textInformative,
        textDetailed=textDetailed,
        icon=ICON_WARNING,
        width=width
    )

def error(
        text,
        parent=None,
        title='Error',
        textInformative=None,
        textDetailed=None,
        width=DEFAULT_WIDTH
):

    return messageBox(
        text,
        parent=parent,
        title=title,
        textInformative=textInformative,
        textDetailed=textDetailed,
        icon=ICON_CRITICAL,
        width=width
    )

def exception(
        text,
        parent=None,
        title='Fatal Error',
        textInformative='Press "Show Details" for more information',
        width=DEFAULT_WIDTH
):
    return messageBox(
        text,
        parent=parent,
        title=title,
        textInformative=textInformative,
        textDetailed=traceback.format_exc(),
        icon=ICON_CRITICAL,
        width=width
    )
<commit_msg>nano update to message_box<commit_after>import sys
import traceback

from PySide import QtGui

DEFAULT_WIDTH = 500

BTN_OK = QtGui.QMessageBox.Ok
BTN_OPEN = QtGui.QMessageBox.Open
BTN_SAVE = QtGui.QMessageBox.Save
BTN_CANCEL = QtGui.QMessageBox.Cancel
BTN_CLOSE = QtGui.QMessageBox.Close
BTN_DISCARD = QtGui.QMessageBox.Discard
BTN_APPLY = QtGui.QMessageBox.Apply
BTN_RESET = QtGui.QMessageBox.Reset
BTN_RESTORE_DEFAULTS = QtGui.QMessageBox.RestoreDefaults
BTN_HELP = QtGui.QMessageBox.Help
BTN_SAVE_ALL = QtGui.QMessageBox.SaveAll
BTN_YES = QtGui.QMessageBox.Yes
BTN_YES_TO_ALL = QtGui.QMessageBox.YesToAll
BTN_NO = QtGui.QMessageBox.No
BTN_NO_TO_ALL = QtGui.QMessageBox.NoToAll
BTN_ABORT = QtGui.QMessageBox.Abort
BTN_RETRY = QtGui.QMessageBox.Retry
BTN_IGNORE = QtGui.QMessageBox.Ignore
BTN_NO_BUTTON = QtGui.QMessageBox.NoButton

ICON_NONE = QtGui.QMessageBox.NoIcon
ICON_QUESTION = QtGui.QMessageBox.Question
ICON_INFORMATION = QtGui.QMessageBox.Information
ICON_WARNING = QtGui.QMessageBox.Warning
ICON_CRITICAL = QtGui.QMessageBox.Critical

def messageBox(
        text,
        parent=None,
        title=None,
        textInformative=None,
        textDetailed=None,
        icon=ICON_NONE,
        buttons=None,
        defaultButton=None,
        escapeButton=None,
        width=DEFAULT_WIDTH
):

    dlg = QtGui.QMessageBox(parent)
    if title:
        dlg.setWindowTitle(title)
    if text:
        dlg.setText(text)
    if textInformative:
        dlg.setInformativeText(textInformative)
    if textDetailed:
        dlg.setDetailedText(textDetailed)
    if buttons:
        dlg.setStandardButtons(buttons)
    if defaultButton:
        dlg.setDefaultButton(defaultButton)
    if escapeButton:
        dlg.setEscapeButton(escapeButton)
    dlg.setIcon(icon)

    # hack for making predefined width message box
    if width:
        # noinspection PyArgumentList
        spacer = QtGui.QSpacerItem(width, 0, QtGui.QSizePolicy.Minimum, QtGui. QSizePolicy.Expanding)
        gridLayout = dlg.layout()
        gridLayout.addItem(spacer, gridLayout.rowCount(), 0, 1, gridLayout.columnCount())

    return dlg.exec_()

def info(
        text,
        parent=None,
        title='Information',
        textInformative=None,
        textDetailed=None,
        width=DEFAULT_WIDTH
):

    return messageBox(
        text,
        parent=parent,
        title=title,
        textInformative=textInformative,
        textDetailed=textDetailed,
        icon=ICON_INFORMATION,
        width=width
    )

def warning(
        text,
        parent=None,
        title='Warning',
        textInformative=None,
        textDetailed=None,
        width=DEFAULT_WIDTH
):
    return messageBox(
        text,
        parent=parent,
        title=title,
        textInformative=textInformative,
        textDetailed=textDetailed,
        icon=ICON_WARNING,
        width=width
    )

def error(
        text,
        parent=None,
        title='Error',
        textInformative=None,
        textDetailed=None,
        width=DEFAULT_WIDTH
):

    return messageBox(
        text,
        parent=parent,
        title=title,
        textInformative=textInformative,
        textDetailed=textDetailed,
        icon=ICON_CRITICAL,
        width=width
    )

def exception(
        text,
        parent=None,
        title='Fatal Error',
        width=DEFAULT_WIDTH
):
    return messageBox(
        text,
        parent=parent,
        title=title,
        textInformative=str(sys.exc_info()[1]),
        textDetailed=traceback.format_exc(),
        icon=ICON_CRITICAL,
        width=width
    )
<|endoftext|>