예제 #1
0
 def get_state(self, model_context):
     state = super(OpenNewView, self).get_state(model_context)
     state.verbose_name = self.verbose_name or ugettext('New %s') % (
         self._entity_admin.get_verbose_name())
     state.tooltip = ugettext('Create a new %s') % (
         self._entity_admin.get_verbose_name())
     return state
예제 #2
0
    def get_state(self, model_context):
        state = Action.get_state(self, model_context)
        admin = model_context.admin
        self.attributes = admin.get_field_attributes(self.attribute)
        type_type = self.attributes['target']

        choices = [(t, t.code) for t in type_type.query.all()]

        state.modes = []
        modes = []
        self.column = getattr(admin.entity, self.attribute)

        for value, name in choices:
            mode = list_filter.FilterMode(
                value=value,
                verbose_name=name,
                checked=(self.exclusive == False),
            )
            modes.append(mode)

        if self.exclusive:
            all_mode = list_filter.FilterMode(
                value=list_filter.All,
                verbose_name=ugettext('All'),
                checked=(self.default == list_filter.All))
            modes.insert(0, all_mode)
        else:
            none_mode = list_filter.FilterMode(value=None,
                                               verbose_name=ugettext('None'),
                                               checked=True)
            modes.append(none_mode)

        state.modes = modes
        state.verbose_name = self.attributes['name']
        return state
예제 #3
0
    def _setupUi(self):
        # controls
        self._default_radio = QtGui.QRadioButton(ugettext('Default Location'))
        self._custom_radio = QtGui.QRadioButton(ugettext('Custom Location'))
        self._custom_edit = QtGui.QLineEdit()
        self._custom_button = QtGui.QPushButton(ugettext('Browse...'))
        button_group = QtGui.QButtonGroup(self)
        button_group.addButton(self._default_radio)
        button_group.addButton(self._custom_radio)

        # layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self._default_radio)
        self._hlayout = QtGui.QHBoxLayout()
        layout.addLayout(self._hlayout)
        layout.addWidget(self._custom_radio)
        hlayout2 = QtGui.QHBoxLayout()
        hlayout2.addWidget(self._custom_edit)
        hlayout2.addWidget(self._custom_button)
        layout.addLayout(hlayout2)
        
        self.setLayout(layout)

        # connect signals to slots
        button_group.buttonClicked[QtGui.QAbstractButton].connect(self._showWidgets)
        button_group.buttonClicked[QtGui.QAbstractButton].connect(self.completeChanged)
        self._custom_button.clicked.connect(self._customButtonClicked)
        self._custom_edit.textChanged.connect(self.completeChanged)
예제 #4
0
    def __init__(
        self,
        obj,
        admin,
        title=_("Please complete"),
        subtitle=_("Complete the form and press the OK button"),
        icon=Icon("tango/22x22/categories/preferences-system.png"),
        parent=None,
        flags=QtCore.Qt.Dialog,
    ):
        from camelot.view.controls.formview import FormWidget
        from camelot.view.proxy.collection_proxy import CollectionProxy

        super(ChangeObjectDialog, self).__init__("", parent, flags)

        self.setWindowTitle(admin.get_verbose_name())
        self.set_banner_logo_pixmap(icon.getQPixmap())
        self.set_banner_title(unicode(title))
        self.set_banner_subtitle(unicode(subtitle))
        self.banner_widget().setStyleSheet("background-color: white;")

        model = CollectionProxy(admin, lambda: [obj], admin.get_fields)
        validator = model.get_validator()
        layout = QtGui.QHBoxLayout()
        layout.setObjectName("form_and_actions_layout")
        form_widget = FormWidget(parent=self, admin=admin)
        layout.addWidget(form_widget)
        validator.validity_changed_signal.connect(self._validity_changed)
        form_widget.set_model(model)
        form_widget.setObjectName("form")
        self.main_widget().setLayout(layout)

        self.gui_context = FormActionGuiContext()
        self.gui_context.workspace = self
        self.gui_context.admin = admin
        self.gui_context.view = self
        self.gui_context.widget_mapper = self.findChild(QtGui.QDataWidgetMapper, "widget_mapper")

        cancel_button = QtGui.QPushButton(ugettext("Cancel"))
        cancel_button.setObjectName("cancel")
        ok_button = QtGui.QPushButton(ugettext("OK"))
        ok_button.setObjectName("ok")
        ok_button.setEnabled(False)
        layout = QtGui.QHBoxLayout()
        layout.setDirection(QtGui.QBoxLayout.RightToLeft)
        layout.addWidget(ok_button)
        layout.addWidget(cancel_button)
        layout.addStretch()
        self.buttons_widget().setLayout(layout)
        cancel_button.pressed.connect(self.reject)
        ok_button.pressed.connect(self.accept)

        # do inital validation, so the validity changed signal is valid
        self._validity_changed(0)

        # set the actions in the actions panel
        get_actions = admin.get_form_actions
        post(functools.update_wrapper(functools.partial(get_actions, None), get_actions), self.set_actions)
예제 #5
0
 def next( self ):
     self.line += 1
     try:
         row = self.reader.next()
         return [unicode(s, 'utf-8') for s in row]
     except UnicodeError, exception:
         raise UserException( text = ugettext('This file contains unexpected characters'),
                              resolution = ugettext('Recreate the file with %s encoding') % self.encoding,
                              detail = ugettext('Exception occured at line %s : ') % self.line + unicode( exception ) )
예제 #6
0
 def __init__( self, default_storage, default_label, parent = None ):
     super(SelectBackupDialog, self).__init__( ugettext('Select backup file'),
                                               default_storage,
                                               default_label,
                                               parent )
     
     self.set_banner_logo_pixmap( self.icon.getQPixmap() )
     self.set_banner_title( ugettext('Select file') )
     self.set_banner_subtitle( ugettext('Please select a backup file. All data in this file will be overwritten.') )
     self.banner_widget().setStyleSheet('background-color: white;')
예제 #7
0
 def __init__( self, 
               cls, 
               field_name, 
               field_attributes, 
               default_operator = None,
               default_value_1 = None,
               default_value_2 = None,
               parent = None ):
     super( FilterOperator, self ).__init__( parent )        
     self._entity, self._field_name = cls, field_name
     self._field_attributes = copy.copy( field_attributes )
     self._field_attributes['editable'] = True
     layout = QtGui.QVBoxLayout()
     layout.setContentsMargins( 2, 2, 2, 2 )
     layout.setSpacing( 2 )
     layout.addWidget( UserTranslatableLabel( field_attributes['name'] ) )
     self._operators = field_attributes.get('operators', [])
     default_index = 0
     self._choices = [(0, ugettext('All')), (1, ugettext('None'))]
     for i, operator in enumerate(self._operators):
         self._choices.append( (i+2, unicode(operator_names[operator])) )
         if operator == default_operator:
             default_index = i + 2
     combobox = QtGui.QComboBox(self)
     layout.addWidget(combobox)
     for i, name in self._choices:
         combobox.insertItem(i, unicode(name))
     combobox.setCurrentIndex( default_index )
     combobox.currentIndexChanged.connect( self.combobox_changed )
     delegate = self._field_attributes['delegate'](**self._field_attributes)
     option = QtGui.QStyleOptionViewItem()
     option.version = 5
     self._editor = delegate.createEditor( self, option, None )
     self._editor2 = delegate.createEditor( self, option, None )
     # explicitely set a value, otherways the current value remains 
     # ValueLoading
     self._editor.set_value( default_value_1 )
     self._editor2.set_value( default_value_2 )
     editing_finished_slot = self.editor_editing_finished
     self._editor.editingFinished.connect( editing_finished_slot )
     self._editor2.editingFinished.connect( editing_finished_slot )
     layout.addWidget(self._editor)
     layout.addWidget(self._editor2)
     layout.addStretch()
     self.setLayout(layout)
     self._editor.setEnabled(False)
     self._editor2.setEnabled(False)
     self._editor.hide()
     self._editor2.hide()
     self._index = default_index
     self._value = default_value_1
     self._value2 = default_value_2
     self.update_editors()
예제 #8
0
 def __init__( self, memento, row ):
     self.id = row.id
     self.type = row.memento_type
     self.at = row.at
     self.by = row.by
     self.changes = None
     if self.type == 'create':
         self.changes = ugettext('Created')
     elif self.type == 'before_delete':
         self.changes = ugettext('Deleted')
     elif row.previous_attributes:
         self.changes = u', '.join( ugettext('%s was %s')%(k,unicode(v)) for k,v in row.previous_attributes.items() )
     self.memento_type = row.memento_type
예제 #9
0
 def __init__( self, default_storage, stored_files, parent = None ):
     self.stored_files = stored_files
     super( SelectRestoreDialog, self ).__init__( ugettext('Select restore file'),
                                                  default_storage,
                                                  None,
                                                  parent )
     self.set_banner_logo_pixmap( self.icon.getQPixmap() )
     self.set_banner_title( ugettext('Select file') )
     self.set_banner_subtitle( ugettext('Please select a backup file from which to restore the database. <br/>All data in the database will be overwritten with data from this file') )
     self.banner_widget().setStyleSheet('background-color: white;')
     if not len( stored_files ):
         self._default_radio.setEnabled( False )
         self._custom_radio.setChecked( True )
         self.show_widgets( self._custom_radio )
예제 #10
0
 def __init__(self,
              parent=None,
              yes="Yes",
              no="No",
              color_yes=None,
              color_no=None,
              **kwargs):
     QtGui.QLabel.__init__(self, parent)
     AbstractCustomEditor.__init__(self)
     self.setEnabled(False)
     self.yes = ugettext(yes)
     self.no = ugettext(no)
     self.color_yes = color_yes
     self.color_no = color_no
예제 #11
0
 def set_default_buttons( self ):
     """add an :guilabel:`ok` and a :guilabel:`cancel` button.
     """
     cancel_button = QtGui.QPushButton( ugettext('Cancel') )
     ok_button = QtGui.QPushButton( ugettext('OK') )
     ok_button.setObjectName( 'ok' )
     layout = QtGui.QHBoxLayout()
     layout.setDirection( QtGui.QBoxLayout.RightToLeft )
     layout.addWidget( ok_button )
     layout.addWidget( cancel_button )
     layout.addStretch()
     self.buttons_widget().setLayout( layout )
     cancel_button.pressed.connect( self.reject )
     ok_button.pressed.connect( self.accept )   
예제 #12
0
 def __init__(self,
              parent=None,
              yes="Yes",
              no="No",
              color_yes=None,
              color_no=None,
              **kwargs):
     QtGui.QLabel.__init__(self, parent)
     AbstractCustomEditor.__init__(self)
     self.setEnabled(False)
     self.yes = ugettext(yes)
     self.no = ugettext(no)
     self.color_yes = color_yes
     self.color_no = color_no
예제 #13
0
 def __next__(self):
     self.line += 1
     try:
         row = six.next(self.reader)
         if six.PY3 == False:
             return [six.text_type(s, 'utf-8') for s in row]
         else:
             return row
     except UnicodeError as exception:
         raise UserException(
             text=ugettext('This file contains unexpected characters'),
             resolution=ugettext('Recreate the file with %s encoding') %
             self.encoding,
             detail=ugettext('Exception occured at line %s : ') % self.line
             + six.text_type(exception))
예제 #14
0
    def __init__( self, 
                  objects, 
                  admin, 
                  parent = None, 
                  flags = QtCore.Qt.Window ):
        from camelot.view.controls import editors
        from camelot.view.proxy.collection_proxy import CollectionProxy
        
        super(ChangeObjectsDialog, self).__init__( '', parent, flags )
        
        self.setWindowTitle( admin.get_verbose_name_plural() )
        self.set_banner_title( _('Data Preview') )
        self.set_banner_subtitle( _('Please review the data below.') )
        self.banner_widget().setStyleSheet('background-color: white;')
        self.set_banner_logo_pixmap( Icon('tango/32x32/mimetypes/x-office-spreadsheet.png').getQPixmap() )
        model = CollectionProxy( admin, lambda:objects, admin.get_columns)
        self.validator = model.get_validator()
        self.validator.validity_changed_signal.connect( self.update_complete )
        model.layoutChanged.connect( self.validate_all_rows )

        table_widget = editors.One2ManyEditor(
            admin = admin,
            parent = self,
            create_inline = True,
        )
        table_widget.set_value( model )
        table_widget.setObjectName( 'table_widget' )
        note = editors.NoteEditor( parent=self )
        note.set_value(None)
        note.setObjectName( 'note' )
        layout = QtGui.QVBoxLayout()
        layout.addWidget( table_widget )
        layout.addWidget( note )
        self.main_widget().setLayout( layout )
    
        cancel_button = QtGui.QPushButton( ugettext('Cancel') )
        ok_button = QtGui.QPushButton( ugettext('OK') )
        ok_button.setObjectName( 'ok' )
        ok_button.setEnabled( False )
        layout = QtGui.QHBoxLayout()
        layout.setDirection( QtGui.QBoxLayout.RightToLeft )
        layout.addWidget( ok_button )
        layout.addWidget( cancel_button )
        layout.addStretch()
        self.buttons_widget().setLayout( layout )
        cancel_button.pressed.connect( self.reject )
        ok_button.pressed.connect( self.accept )
        self.validate_all_rows()
예제 #15
0
 def gui_run(self, gui_context):
     self.view = QtWebKit.QWebView(None)
     self.view.load(
         gui_context.admin.get_application_admin().get_help_url())
     self.view.setWindowTitle(ugettext('Help Browser'))
     self.view.setWindowIcon(self.icon.getQIcon())
     self.view.show()
예제 #16
0
 def __init__(self, action, gui_context, parent):
     from ..remote_signals import get_signal_handler
     QtWidgets.QFrame.__init__(self, parent)
     AbstractActionWidget.init(self, action, gui_context)
     layout = QtWidgets.QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     face = QtWidgets.QToolButton()
     face.setObjectName('face')
     face.setAutoRaise(True)
     face.clicked.connect(self.face_clicked)
     face.setToolTip(ugettext('Change avatar'))
     layout.addWidget(face)
     info_layout = QtWidgets.QVBoxLayout()
     user_name = QtWidgets.QLabel()
     font = user_name.font()
     font.setBold(True)
     font.setPointSize(10)
     user_name.setFont(font)
     user_name.setObjectName('user_name')
     info_layout.addWidget(user_name)
     groups = QtWidgets.QLabel()
     font = groups.font()
     font.setPointSize(8)
     groups.setFont(font)
     groups.setObjectName('groups')
     info_layout.addWidget(groups)
     info_layout.setSpacing(0)
     info_layout.setContentsMargins(0, 0, 0, 0)
     layout.addLayout(info_layout)
     self.setLayout(layout)
     signal_handler = get_signal_handler()
     signal_handler.entity_update_signal.connect(self.entity_update)
예제 #17
0
 def set_ok_hidden(self, hidden=True):
     ok_button = self.findChild(QtWidgets.QPushButton, 'ok')
     progress_bar = self.findChild(QtWidgets.QProgressBar, 'progress_bar')
     if ok_button:
         ok_button.setHidden(hidden)
         progress_bar.setHidden(not hidden)
         self.setWindowTitle(
             self.title if hidden else ugettext('Completed'))
예제 #18
0
    def paint(self, painter, option, index):
        painter.save()
        self.drawBackground(painter, option, index)
        value = variant_to_pyobject( index.model().data( index, Qt.EditRole ) )
        
        value_str = u''
        if self._forever != None and value == self._forever:
            value_str = ugettext('Forever')
        elif value not in (None, ValueLoading):
            years, months = divmod( value, 12 )
            if years:
                value_str = value_str + ugettext('%i years ')%(years)
            if months:
                value_str = value_str + ugettext('%i months')%(months)        

        self.paint_text(painter, option, index, value_str)
        painter.restore()
예제 #19
0
    def paint(self, painter, option, index):
        painter.save()
        self.drawBackground(painter, option, index)
        value = variant_to_pyobject(index.model().data(index, Qt.EditRole))

        value_str = u''
        if self._forever != None and value == self._forever:
            value_str = ugettext('Forever')
        elif value not in (None, ValueLoading):
            years, months = divmod(value, 12)
            if years:
                value_str = value_str + ugettext('%i years ') % (years)
            if months:
                value_str = value_str + ugettext('%i months') % (months)

        self.paint_text(painter, option, index, value_str)
        painter.restore()
예제 #20
0
파일: backup.py 프로젝트: vortexR2/camelot
 def _setPath(self, dir):
     path = QtGui.QFileDialog.getOpenFileName(
         self,
         six.text_type(self.caption),
         dir or '',
         ugettext('Database files (*%s);;All files (*.*)' % self.extension),
     )
     return path
예제 #21
0
    def get_state(self, model_context):
        state = Action.get_state(self, model_context)
        admin = model_context.admin
        self.attributes = admin.get_field_attributes(self.attribute)
        history_type = self.attributes['target']
        history_admin = admin.get_related_admin(history_type)
        classification_fa = history_admin.get_field_attributes('classified_by')

        target = classification_fa.get('target')
        if target is not None:
            choices = [(st, st.code) for st in target.query.all()]
        else:
            choices = classification_fa['choices']

        state.modes = []
        modes = []
        current_date = sql.functions.current_date()
        self.joins = (history_type,
                      sql.and_(history_type.status_from_date <= current_date,
                               history_type.status_for_id == admin.entity.id,
                               history_type.status_thru_date >= current_date))
        self.column = getattr(history_type, 'classified_by')

        for value, name in choices:
            mode = list_filter.FilterMode(value=value,
                                          verbose_name=name,
                                          checked=((self.default == value) or
                                                   (self.exclusive == False)))
            modes.append(mode)

        if self.exclusive:
            all_mode = list_filter.FilterMode(
                value=list_filter.All,
                verbose_name=ugettext('All'),
                checked=(self.default == list_filter.All))
            modes.insert(0, all_mode)
        else:
            none_mode = list_filter.FilterMode(value=None,
                                               verbose_name=ugettext('None'),
                                               checked=True)
            modes.append(none_mode)

        state.modes = modes
        state.verbose_name = self.attributes['name']
        return state
예제 #22
0
    def _create_tempfile(self, suffix, prefix):
        import tempfile
        # @todo suffix and prefix should be cleaned, because the user might be
        #       able to get directory separators in here or something related
        try:
            return tempfile.mkstemp(suffix=suffix,
                                    prefix=prefix,
                                    dir=self.upload_to,
                                    text='b')
        except EnvironmentError, e:
            if not self.available():
                raise UserException(
                    text=ugettext('The directory %s does not exist') %
                    (self.upload_to),
                    resolution=ugettext('Contact your system administrator'))
            if not self.writeable():
                raise UserException(
                    text=ugettext('You have no write permissions for %s') %
                    (self.upload_to),
                    resolution=ugettext('Contact your system administrator'))

            raise UserException(
                text=ugettext('Unable to write file to %s') % (self.upload_to),
                resolution=ugettext('Contact your system administrator'),
                detail=ugettext(
                    'OS Error number : %s \nError : %s \nPrefix : %s \nSuffix : %s'
                ) % (e.errno, e.strerror, prefix, suffix))
예제 #23
0
 def __init__( self,
               admin,
               field_attributes, 
               parent = None, 
               flags=QtCore.Qt.Dialog ):
     super(ChangeFieldDialog, self).__init__( '', parent, flags )
     from camelot.view.controls.editors import ChoicesEditor
     self.field_attributes = field_attributes
     self.field = None
     self.value = None
     self.setWindowTitle( admin.get_verbose_name_plural() )
     self.set_banner_title( _('Replace field contents') )
     self.set_banner_subtitle( _('Select the field to update and enter its new value') )
     self.banner_widget().setStyleSheet('background-color: white;')
     editor = ChoicesEditor( parent=self )
     editor.setObjectName( 'field_choice' )
     layout = QtGui.QVBoxLayout()
     layout.addWidget( editor )
     self.main_widget().setLayout( layout )
     
     def filter(attributes):
         if not attributes['editable']:
             return False
         if attributes['delegate'] in (delegates.One2ManyDelegate,):
             return False
         return True
     
     choices = [(field, attributes['name']) for field, attributes in field_attributes.items() if filter(attributes)]
     choices.sort( key = lambda choice:choice[1] )
     editor.set_choices( choices )
     editor.set_value( ( choices+[(None,None)] )[-1][0] )
     self.field_changed( 0 )  
     editor.currentIndexChanged.connect( self.field_changed )
     
     cancel_button = QtGui.QPushButton( ugettext('Cancel') )
     ok_button = QtGui.QPushButton( ugettext('OK') )
     ok_button.setObjectName( 'ok' )
     layout = QtGui.QHBoxLayout()
     layout.setDirection( QtGui.QBoxLayout.RightToLeft )
     layout.addWidget( ok_button )
     layout.addWidget( cancel_button )
     layout.addStretch()
     self.buttons_widget().setLayout( layout )
     cancel_button.pressed.connect( self.reject )
     ok_button.pressed.connect( self.accept )
예제 #24
0
파일: memento.py 프로젝트: vortexR2/camelot
 def __init__( self, memento, row ):
     self.id = row.id
     self.type = row.memento_type
     self.at = row.at
     self.by = row.by
     self.changes = None
     if row.previous_attributes:
         self.changes = u', '.join( ugettext('%s was %s')%(k,six.text_type(v)) for k,v in six.iteritems(row.previous_attributes) )
     self.memento_type = row.memento_type
예제 #25
0
 def __init__( self, 
               obj, 
               admin,
               title =  _('Please complete'),
               subtitle = _('Complete the form and press the OK button'),
               icon = Icon('tango/22x22/categories/preferences-system.png'),
               parent=None, 
               flags=QtCore.Qt.Dialog ):
     from camelot.view.controls.formview import FormWidget
     from camelot.view.proxy.collection_proxy import CollectionProxy
     super(ChangeObjectDialog, self).__init__( '', parent, flags )
     
     self.setWindowTitle( admin.get_verbose_name() )
     self.set_banner_logo_pixmap( icon.getQPixmap() )
     self.set_banner_title( unicode(title) )
     self.set_banner_subtitle( unicode(subtitle) )
     self.banner_widget().setStyleSheet('background-color: white;')
     
     model = CollectionProxy(admin, lambda:[obj], admin.get_fields)
     validator = model.get_validator()
     layout = QtGui.QVBoxLayout()
     form_widget = FormWidget( parent=self, admin=admin )
     layout.addWidget( form_widget )
     validator.validity_changed_signal.connect( self._validity_changed )
     form_widget.set_model( model )
     form_widget.setObjectName( 'form' )
     self.main_widget().setLayout(layout)
 
     cancel_button = QtGui.QPushButton( ugettext('Cancel') )
     cancel_button.setObjectName( 'cancel' )
     ok_button = QtGui.QPushButton( ugettext('OK') )
     ok_button.setObjectName( 'ok' )
     ok_button.setEnabled( False )
     layout = QtGui.QHBoxLayout()
     layout.setDirection( QtGui.QBoxLayout.RightToLeft )
     layout.addWidget( ok_button )
     layout.addWidget( cancel_button )
     layout.addStretch()
     self.buttons_widget().setLayout( layout )
     cancel_button.pressed.connect( self.reject )
     ok_button.pressed.connect( self.accept )
     
     # do inital validation, so the validity changed signal is valid
     self._validity_changed( 0 )
예제 #26
0
 def __init__(self, name, icon=progress_icon):
     QtWidgets.QProgressDialog.__init__(self, q_string(u''), q_string(u''),
                                        0, 0)
     label = QtWidgets.QLabel(six.text_type(name))
     progress_bar = QtWidgets.QProgressBar()
     progress_bar.setObjectName('progress_bar')
     cancel_button = QtWidgets.QPushButton(ugettext('Cancel'))
     cancel_button.setObjectName('cancel')
     ok_button = QtWidgets.QPushButton(ugettext('OK'))
     ok_button.setObjectName('ok')
     ok_button.clicked.connect(self.accept)
     ok_button.hide()
     copy_button = QtWidgets.QPushButton(ugettext('Copy'))
     copy_button.setObjectName('copy')
     copy_button.clicked.connect(self.copy_clicked)
     copy_button.hide()
     copy_button.setToolTip(ugettext('Copy details to clipboard'))
     self.setBar(progress_bar)
     self.setLabel(label)
     self.setCancelButton(cancel_button)
     self._window_title = ugettext('Please wait')
     self.setWindowTitle(self._window_title)
     # use a list view to display details, for performance reasons,
     # since this widget will not freeze in case the list of details
     # becomes long
     details = QtWidgets.QListView(parent=self)
     details.setObjectName('details')
     details.hide()
     layout = QtWidgets.QVBoxLayout()
     layout.addWidget(label)
     layout.addWidget(progress_bar)
     button_layout = QtWidgets.QHBoxLayout()
     button_layout.setDirection(QtWidgets.QBoxLayout.RightToLeft)
     button_layout.addWidget(ok_button)
     button_layout.addWidget(cancel_button)
     button_layout.addWidget(copy_button)
     button_layout.addStretch()
     layout.addWidget(details)
     layout.addLayout(button_layout)
     self.setLayout(layout)
     # show immediately, to prevent a pop up before another window
     # opened in an action_step
     self.show()
예제 #27
0
파일: backup.py 프로젝트: vortexR2/camelot
    def setup_widgets(self):
        # controls
        self._default_radio = QtGui.QRadioButton(ugettext('Default Location'))
        self._custom_radio = QtGui.QRadioButton(ugettext('Custom Location'))
        self._custom_edit = QtWidgets.QLineEdit()
        self._custom_button = QtWidgets.QPushButton(ugettext('Browse...'))
        button_group = QtGui.QButtonGroup(self)
        button_group.addButton(self._default_radio)
        button_group.addButton(self._custom_radio)

        # layout
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self._default_radio)
        self._hlayout = QtWidgets.QHBoxLayout()
        layout.addLayout(self._hlayout)
        layout.addWidget(self._custom_radio)
        hlayout2 = QtWidgets.QHBoxLayout()
        hlayout2.addWidget(self._custom_edit)
        hlayout2.addWidget(self._custom_button)
        layout.addLayout(hlayout2)
        self.main_widget().setLayout(layout)

        # connect signals to slots
        button_group.buttonClicked[QtGui.QAbstractButton].connect(
            self.show_widgets)
        button_group.buttonClicked[QtGui.QAbstractButton].connect(
            self.complete_changed)
        self._custom_button.clicked.connect(self._customButtonClicked)
        self._custom_edit.textChanged.connect(self.complete_changed)

        # buttons
        cancel_button = QtWidgets.QPushButton(ugettext('Cancel'))
        ok_button = QtWidgets.QPushButton(ugettext('OK'))
        ok_button.setObjectName('ok')
        ok_button.setEnabled(False)
        layout = QtWidgets.QHBoxLayout()
        layout.setDirection(QtWidgets.QBoxLayout.RightToLeft)
        layout.addWidget(ok_button)
        layout.addWidget(cancel_button)
        layout.addStretch()
        self.buttons_widget().setLayout(layout)
        cancel_button.pressed.connect(self.reject)
        ok_button.pressed.connect(self.accept)
예제 #28
0
파일: backup.py 프로젝트: vortexR2/camelot
 def setup_widgets(self):
     super(SelectBackupDialog, self).setup_widgets()
     self._default_label = QtWidgets.QLabel(ugettext('Label:'))
     self._default_edit = LabelLineEdit(self.default_storage)
     self._default_label.setBuddy(self._default_edit)
     self._hlayout.addWidget(self._default_label)
     self._hlayout.addWidget(self._default_edit)
     self._default_edit.textChanged.connect(self._onDefaultEditChanged)
     self._default_edit.textChanged.connect(self.complete_changed)
     self._default_edit.setText(self.default_label)
예제 #29
0
    def paint(self, painter, option, index):
        painter.save()
        self.drawBackground(painter, option, index)
        value = variant_to_pyobject(index.model().data(index, Qt.EditRole))

        value_str = u''
        if value not in (None, ValueLoading):
            value_str = ugettext(value)

        self.paint_text(painter, option, index, value_str)
        painter.restore()
예제 #30
0
 def gui_run( self, gui_context ):
     #
     # Import QtWebKit as late as possible, since it's the largest
     # part of the QT Library (15 meg on Ubuntu linux)
     #
     from PyQt4 import QtWebKit
     self.view = QtWebKit.QWebView( None )
     self.view.load( gui_context.admin.get_application_admin().get_help_url() )
     self.view.setWindowTitle( ugettext('Help Browser') )
     self.view.setWindowIcon( self.icon.getQIcon() )
     self.view.show()
예제 #31
0
    def paint(self, painter, option, index):
        painter.save()
        self.drawBackground(painter, option, index)
        value = variant_to_pyobject( index.model().data( index, Qt.EditRole ) )
        
        value_str = u''
        if value not in (None, ValueLoading):
            value_str = ugettext(value)

        self.paint_text(painter, option, index, value_str)
        painter.restore()
예제 #32
0
 def _setupUi(self):
     from camelot.view.model_thread import post
     self._default_label = QtGui.QLabel(ugettext('Label:'))
     self._default_edit = LabelLineEdit(self._storage)
     self._default_label.setBuddy(self._default_edit)
     super(SelectBackupFilePage, self)._setupUi()
     self._hlayout.addWidget(self._default_label)
     self._hlayout.addWidget(self._default_edit)
     self._default_edit.textChanged.connect(self._onDefaultEditChanged)
     self._default_edit.textChanged.connect(self.completeChanged)
     post(self._get_default_label, self._set_default_label)
예제 #33
0
 def __init__(self, memento, row):
     self.id = row.id
     self.type = row.memento_type
     self.at = row.at
     self.by = row.by
     self.changes = None
     if row.previous_attributes:
         self.changes = u", ".join(
             ugettext("%s was %s") % (k, unicode(v)) for k, v in row.previous_attributes.items()
         )
     self.memento_type = row.memento_type
예제 #34
0
 def gui_run(self, gui_context):
     #
     # Import QtWebKit as late as possible, since it's the largest
     # part of the QT Library (15 meg on Ubuntu linux)
     #
     from PyQt4 import QtWebKit
     self.view = QtWebKit.QWebView(None)
     self.view.load(
         gui_context.admin.get_application_admin().get_help_url())
     self.view.setWindowTitle(ugettext('Help Browser'))
     self.view.setWindowIcon(self.icon.getQIcon())
     self.view.show()
예제 #35
0
    def __init__(self, parent=None):
        super(SelectFilePage, self).__init__(parent)
        self.setTitle(unicode(self.title))
        self.setSubTitle(unicode(self.sub_title))
        self.setPixmap(QtGui.QWizard.LogoPixmap, self.icon.getQPixmap())

        label = QtGui.QLabel(ugettext("Select file:"))
        self.filelineedit = QtGui.QLineEdit()
        label.setBuddy(self.filelineedit)
        browsebutton = QtGui.QPushButton(ugettext("Browse..."))

        # file path is a mandatory field
        self.registerField("datasource*", self.filelineedit)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(label)
        hlayout = QtGui.QHBoxLayout()
        hlayout.addWidget(self.filelineedit)
        hlayout.addWidget(browsebutton)
        layout.addLayout(hlayout)
        self.setLayout(layout)
        browsebutton.clicked.connect(self.setpath)
예제 #36
0
 def model_run( self, model_context ):
     import sqlalchemy.exc as sa_exc
     from camelot.core.orm import Session
     from camelot.view import action_steps
     from camelot.view.remote_signals import get_signal_handler
     LOGGER.debug('session refresh requested')
     progress_db_message = ugettext('Reload data from database')
     progress_view_message = ugettext('Update screens')
     session = Session()
     signal_handler = get_signal_handler()
     refreshed_objects = []
     expunged_objects = []
     #
     # Loop over the objects one by one to be able to detect the deleted
     # objects
     #
     session_items = len( session.identity_map )
     for i, (_key, obj) in enumerate( session.identity_map.items() ):
         try:
             session.refresh( obj )
             refreshed_objects.append( obj )
         except sa_exc.InvalidRequestError:
             #
             # this object could not be refreshed, it was probably deleted
             # outside the scope of this session, so assume it is deleted
             # from the application its point of view
             #
             session.expunge( obj )
             expunged_objects.append( obj )
         if i%10 == 0:
             yield action_steps.UpdateProgress( i, 
                                                session_items, 
                                                progress_db_message )
     yield action_steps.UpdateProgress( text = progress_view_message )
     for obj in refreshed_objects:
         signal_handler.sendEntityUpdate( None, obj )
     for obj in expunged_objects:
         signal_handler.sendEntityDelete( None, obj )
     yield action_steps.Refresh()
예제 #37
0
    def __init__(self, parent=None):
        super(SelectFilePage, self).__init__(parent)
        self.setTitle(unicode(self.title))
        self.setSubTitle(unicode(self.sub_title))
        self.setPixmap(QtGui.QWizard.LogoPixmap, self.icon.getQPixmap())

        label = QtGui.QLabel(ugettext('Select file:'))
        self.filelineedit = QtGui.QLineEdit()
        label.setBuddy(self.filelineedit)
        browsebutton = QtGui.QPushButton(ugettext('Browse...'))

        # file path is a mandatory field
        self.registerField('datasource*', self.filelineedit)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(label)
        hlayout = QtGui.QHBoxLayout()
        hlayout.addWidget(self.filelineedit)
        hlayout.addWidget(browsebutton)
        layout.addLayout(hlayout)
        self.setLayout(layout)
        browsebutton.clicked.connect(self.setpath)
예제 #38
0
 def model_run(self, model_context):
     import sqlalchemy.exc as sa_exc
     from camelot.core.orm import Session
     from camelot.view import action_steps
     from camelot.view.remote_signals import get_signal_handler
     LOGGER.debug('session refresh requested')
     progress_db_message = ugettext('Reload data from database')
     progress_view_message = ugettext('Update screens')
     session = Session()
     signal_handler = get_signal_handler()
     refreshed_objects = []
     expunged_objects = []
     #
     # Loop over the objects one by one to be able to detect the deleted
     # objects
     #
     session_items = len(session.identity_map)
     for i, (_key, obj) in enumerate(six.iteritems(session.identity_map)):
         try:
             session.refresh(obj)
             refreshed_objects.append(obj)
         except sa_exc.InvalidRequestError:
             #
             # this object could not be refreshed, it was probably deleted
             # outside the scope of this session, so assume it is deleted
             # from the application its point of view
             #
             session.expunge(obj)
             expunged_objects.append(obj)
         if i % 10 == 0:
             yield action_steps.UpdateProgress(i, session_items,
                                               progress_db_message)
     yield action_steps.UpdateProgress(text=progress_view_message)
     for obj in refreshed_objects:
         signal_handler.sendEntityUpdate(self, obj)
     for obj in expunged_objects:
         signal_handler.sendEntityDelete(self, obj)
     yield action_steps.Refresh()
예제 #39
0
    def paint(self, painter, option, index):
        painter.save()
        self.drawBackground(painter, option, index)
        value = variant_to_py(index.model().data(index, Qt.EditRole))

        value_str = u''
        if value not in (None, ValueLoading):
            if self._translate_content:
                value_str = ugettext(six.text_type(value))
            else:
                value_str = six.text_type(value)

        self.paint_text(painter, option, index, value_str)
        painter.restore()
예제 #40
0
 def model_run(self, model_context):
     from camelot.model.authentication import get_current_authentication
     from camelot.view import action_steps
     from camelot.view.controls.editors.imageeditor import ImageEditor
     select_file = action_steps.SelectFile(
         file_name_filter=ImageEditor.filter)
     filenames = yield select_file
     for filename in filenames:
         yield action_steps.UpdateProgress(text=ugettext('Scale image'))
         image = QtGui.QImage(filename)
         image = image.scaled(self.image_size, self.image_size,
                              Qt.KeepAspectRatio)
         authentication = get_current_authentication()
         authentication.set_representation(image)
         yield action_steps.FlushSession(model_context.session)
예제 #41
0
 def __init__(self, entity, field_name, field_attributes, parent):
     QtGui.QGroupBox.__init__(self, unicode(field_attributes['name']), parent)
     self._entity, self._field_name, self._field_attributes = entity, field_name, field_attributes
     self._field_attributes['editable'] = True
     layout = QtGui.QVBoxLayout()
     self._operators = field_attributes.get('operators', [])
     self._choices = [(0, ugettext('All')), (1, ugettext('None'))] + \
                     [(i+2, ugettext(operator_names[operator])) for i, operator in enumerate(self._operators)]
     combobox = QtGui.QComboBox(self)
     layout.addWidget(combobox)
     for i, name in self._choices:
         combobox.insertItem(i, unicode(name))
     combobox.currentIndexChanged.connect( self.combobox_changed )
     delegate = self._field_attributes['delegate'](**self._field_attributes)
     option = QtGui.QStyleOptionViewItem()
     option.version = 5
     self._editor = delegate.createEditor( self, option, None )
     self._editor2 = delegate.createEditor( self, option, None )
     # explicitely set a value, otherways the current value remains 
     # ValueLoading
     self._editor.set_value(None)
     self._editor2.set_value(None)
     editing_finished_slot = self.editor_editing_finished
     self._editor.editingFinished.connect( editing_finished_slot )
     self._editor2.editingFinished.connect( editing_finished_slot )
     layout.addWidget(self._editor)
     layout.addWidget(self._editor2)
     layout.addStretch()
     self.setLayout(layout)
     self._editor.setEnabled(False)
     self._editor2.setEnabled(False)
     self._editor.hide()
     self._editor2.hide()
     self._index = 0
     self._value = None
     self._value2 = None
예제 #42
0
    def get_dynamic_field_attributes(self, obj, field_names):
        """Takes the dynamic field attributes from through the ObjectAdmin its
        get_dynamic_field_attributes and add the new_message attributes for
        One2Many fields where the object was not flushed yet
        """
        from sqlalchemy.orm.session import Session

        session = Session.object_session(obj)
        # when a previous flush failed, obj might have no session
        if session and obj in session.new:
            new_message = ugettext("Please complete the form first")
        else:
            new_message = None
        for attributes in super(EntityAdmin, self).get_dynamic_field_attributes(obj, field_names):
            attributes["new_message"] = new_message
            yield attributes
예제 #43
0
 def get_dynamic_field_attributes(self, obj, field_names):
     """Takes the dynamic field attributes from through the ObjectAdmin its
     get_dynamic_field_attributes and add the new_message attributes for
     One2Many fields where the object was not flushed yet
     """
     from sqlalchemy.orm.session import Session
     session = Session.object_session(obj)
     # when a previous flush failed, obj might have no session
     if session and obj in session.new:
         new_message = ugettext('Please complete the form first')
     else:
         new_message = None
     for attributes in super(EntityAdmin,
                             self).get_dynamic_field_attributes(
                                 obj, field_names):
         attributes['new_message'] = new_message
         yield attributes
예제 #44
0
        class SelectView(admin.TableView):
            table_model = SelectQueryTableProxy
            entity_selected_signal = QtCore.pyqtSignal(object)
            title_format = ugettext('Select %s')

            def __init__(self, admin, parent):
                gui_context = GuiContext()
                super(SelectView, self).__init__(gui_context,
                                                 admin,
                                                 search_text=search_text,
                                                 parent=parent)
                self.row_selected_signal.connect(self.sectionClicked)
                self.setUpdatesEnabled(True)

                table = self.findChild(QtGui.QTableView, 'AdminTableWidget')
                if table != None:
                    table.keyboard_selection_signal.connect(
                        self.on_keyboard_selection)
                    table.setEditTriggers(
                        QtGui.QAbstractItemView.NoEditTriggers)

            def emit_entity_selected(self, instance_getter):
                self.entity_selected_signal.emit(instance_getter)

            @QtCore.pyqtSlot()
            def on_keyboard_selection(self):
                table = self.findChild(QtGui.QTableView, 'AdminTableWidget')
                if table != None:
                    self.row_selected_signal.emit(table.currentIndex().row())

            @QtCore.pyqtSlot(int)
            def sectionClicked(self, index):
                # table model will be set by the model thread, we can't
                # decently select if it has not been set yet
                if self.table.model():

                    def create_constant_getter(cst):
                        return lambda: cst

                    def create_instance_getter():
                        entity = self.table.model()._get_object(index)
                        return create_constant_getter(entity)

                    post(create_instance_getter, self.emit_entity_selected)
예제 #45
0
파일: storage.py 프로젝트: Governa/Camelot
 def _create_tempfile( self, suffix, prefix ):
     import tempfile
     # @todo suffix and prefix should be cleaned, because the user might be
     #       able to get directory separators in here or something related
     try:
         return tempfile.mkstemp( suffix = suffix, prefix = prefix, dir = self.upload_to, text = 'b' )
     except EnvironmentError, e:
         if not self.available():
             raise UserException( text = ugettext('The directory %s does not exist')%(self.upload_to),
                                  resolution = ugettext( 'Contact your system administrator' ) )
         if not self.writeable():
             raise UserException( text = ugettext('You have no write permissions for %s')%(self.upload_to),
                                  resolution = ugettext( 'Contact your system administrator' ) )
         
         raise UserException( text = ugettext('Unable to write file to %s')%(self.upload_to),
                              resolution = ugettext( 'Contact your system administrator' ),
                              detail = ugettext('OS Error number : %s \nError : %s \nPrefix : %s \nSuffix : %s')%( e.errno,
                                                                                                                   e.strerror,
                                                                                                                   prefix,
                                                                                                                   suffix ) )
예제 #46
0
 def gui_run( self, gui_context ):
     abtmsg = gui_context.admin.get_application_admin().get_about()
     QtGui.QMessageBox.about( gui_context.workspace, 
                              ugettext('About'), 
                              unicode( abtmsg ) )
예제 #47
0
 def model_run( self, model_context ):
     from decimal import Decimal
     from xlwt import Font, Borders, XFStyle, Pattern, Workbook
     from camelot.view.utils import ( local_date_format, 
                                      local_datetime_format,
                                      local_time_format )
     from camelot.view import action_steps
     #
     # setup worksheet
     #
     yield action_steps.UpdateProgress( text = _('Create worksheet') )
     admin = model_context.admin
     workbook = Workbook()
     worksheet = workbook.add_sheet('Sheet1')
     #
     # keep a global cache of styles, since the number of styles that
     # can be used is limited.
     #
     styles = dict()
     freeze = lambda d:tuple(sorted(d.iteritems()))
     
     def get_style( font_specs=dict(), 
                    border_specs = dict(), 
                    pattern = None,
                    num_format_str = None, ):
         
         style_key = ( freeze(font_specs), 
                       freeze(border_specs), 
                       pattern, 
                       num_format_str )
         
         try:
             return styles[style_key]
         except KeyError:
             style = XFStyle()
             style.font = Font()
             for key, value in font_specs.items():
                 setattr( style.font, key, value )
             style.borders = Borders()
             for key, value in border_specs.items():
                 setattr( style.borders, key, value )
             if pattern:
                 style.pattern = pattern
             if num_format_str:
                 style.num_format_str = num_format_str
             styles[ style_key ] = style
             return style
     
     #
     # write style
     #
     title_style = get_style( dict( font_name = self.font_name,
                                    bold = True,
                                    height = 240 ) )
     worksheet.write( 0, 0, admin.get_verbose_name_plural(), title_style )
     #
     # create some patterns and formats
     #
     date_format = local_date_format()
     datetime_format = local_datetime_format()
     time_format = local_time_format()
     header_pattern = Pattern()
     header_pattern.pattern = Pattern.SOLID_PATTERN
     header_pattern.pattern_fore_colour = 0x16
     #
     # write headers
     #
     columns = admin.get_columns()
     field_names = []
     for i, (name, field_attributes) in enumerate( columns ):
         verbose_name = unicode( field_attributes.get( 'name', name ) )
         field_names.append( name )
         font_specs = dict( font_name = self.font_name, 
                            bold = True, 
                            height = 200 )
         border_specs = dict( top = 0x01 )
         name = unicode( name )
         if i == 0:
             border_specs[ 'left' ] = 0x01                
         elif i == len( columns ) - 1:
             border_specs[ 'right' ] = 0x01 
         header_style = get_style( font_specs, border_specs, header_pattern )
         worksheet.write( 2, i, verbose_name, header_style)
             
         if len( name ) < 8:
             worksheet.col( i ).width = 8 *  375
         else:
             worksheet.col( i ).width = len( verbose_name ) *  375
     #
     # write data
     #
     offset = 3
     for j, obj in enumerate( model_context.get_collection( yield_per = 100 ) ):
         dynamic_attributes = admin.get_dynamic_field_attributes( obj, 
                                                                  field_names )
         row = offset + j
         if j % 100 == 0:
             yield action_steps.UpdateProgress( j, model_context.collection_count )
         for i, ((_name, attributes), delta_attributes)  in enumerate( zip( columns, dynamic_attributes ) ):
             attributes.update( delta_attributes )
             value = attributes['getter']( obj )
             format_string = '0'
             if value != None:
                 if isinstance( value, Decimal ):
                     value = float( str( value ) )
                 if isinstance( value, (unicode, str) ):
                     if attributes.get( 'translate_content', False ) == True:
                         value = ugettext( value )
                 # handle fields of type code
                 elif isinstance( value, list ):
                     value = u'.'.join(value)
                 elif isinstance( value, float ):
                     precision = attributes.get( 'precision', 2 )
                     format_string = '0.' + '0'*precision
                 elif isinstance( value, int ):
                     format_string = '0'
                 elif isinstance( value, datetime.date ):
                     format_string = date_format
                 elif isinstance( value, datetime.datetime ):
                     format_string = datetime_format
                 elif isinstance( value, datetime.time ):
                     format_string = time_format
                 else:
                     value = unicode( value )
             else:
                 # empty cells should be filled as well, to get the
                 # borders right
                 value = ''
                     
             font_specs = dict( font_name = self.font_name, height = 200 )
             border_specs = dict()
             if i == 0:
                 border_specs[ 'left' ] = 0x01                
             elif i == len( columns ) - 1:
                 border_specs[ 'right' ] = 0x01  
             if (row - offset + 1) == model_context.collection_count:
                 border_specs[ 'bottom' ] = 0x01
             style = get_style( font_specs, 
                                border_specs, 
                                None, 
                                format_string )
             worksheet.write( row, i, value, style )
             min_width = len( unicode( value ) ) * 300
             worksheet.col( i ).width = max( min_width, worksheet.col( i ).width )
     
     yield action_steps.UpdateProgress( text = _('Saving file') )
     filename = action_steps.OpenFile.create_temporary_file( '.xls' )
     workbook.save( filename )
     yield action_steps.UpdateProgress( text = _('Opening file') )
     yield action_steps.OpenFile( filename )
예제 #48
0
def enumeration_to_string(value):
    return ugettext(unicode(value or u'').replace('_', ' ').capitalize())
예제 #49
0
 def get_state( self, model_context ):
     state = super( OpenNewView, self ).get_state( model_context )
     state.verbose_name = self.verbose_name or ugettext('New %s')%(self._entity_admin.get_verbose_name())
     state.tooltip = ugettext('Create a new %s')%(self._entity_admin.get_verbose_name())
     return state
예제 #50
0
 def _setPath(self, dir):
     path = QtGui.QFileDialog.getSaveFileName(
             self, unicode(self.caption), dir, ugettext('Database files (*%s);;All files (*.*)' % self.extension),
         )
     return path