Beispiel #1
0
class SearchOnlyDialog(QDialog, SearchOnlyDialogUi):
    def __init__(self,
                 model,
                 sel_multi=True,
                 ids=None,
                 context=None,
                 domain=None,
                 parent=None):
        QDialog.__init__(self, parent)
        SearchOnlyDialogUi.__init__(self)
        self.setupUi(self)

        if ids is None:
            ids = []
        if context is None:
            context = {}
        if domain is None:
            domain = []

        self.setModal(True)

        self.ids = ids
        self.result = None
        self.context = context
        self.context.update(Rpc.session.context)
        self.allowMultipleSelection = sel_multi

        self.modelGroup = RecordGroup(model, context=self.context)
        if Settings.value('koo.sort_mode') == 'visible_items':
            self.modelGroup.setSortMode(RecordGroup.SortVisibleItems)
        self.modelGroup.setDomain(domain)
        if self.ids:
            self.modelGroup.setFilter([('id', 'in', ids)])
            # self.reload()

        self.screen.setRecordGroup(self.modelGroup)
        self.screen.setViewTypes(['tree'])

        self.view = self.screen.currentView()
        self.view.setAllowMultipleSelection(self.allowMultipleSelection)
        self.view.setReadOnly(True)
        self.view.activated.connect(self.accepted)

        self.model = model

        view_form = Rpc.session.execute('/object', 'execute', self.model,
                                        'fields_view_get', False, 'form',
                                        self.context)
        self.form.setup(view_form['arch'], view_form['fields'], model, domain)
        self.form.hideButtons()
        self.form.keyDownPressed.connect(self.setFocusToList)

        self.title = _('Search: %s') % self.form.name
        self.titleResults = _('Search: %s (%%d result(s))') % self.form.name

        self.setWindowTitle(self.title)

        # TODO: Use Designer Widget Promotion instead
        layout = self.layout()
        layout.insertWidget(0, self.screen)
        layout.insertWidget(0, self.form)

        self.form.setFocus()

        self.pushAccept.clicked.connect(self.accepted)
        self.pushCancel.clicked.connect(self.reject)
        self.pushFind.clicked.connect(self.find)
        self.form.performSearch.connect(self.find)

        # Selects all items
        self.select()

    def setFocusToList(self):
        self.screen.setFocus()

    def find(self):
        """
        Searches a value

        :return: None
        """
        self.modelGroup.setFilter(self.form.value())
        self.reload()

    def reload(self):
        self.modelGroup.update()
        self.select()
        self.screen.setFocus()

    def select(self):
        if self.allowMultipleSelection:
            self.view.selectAll()
        self.setWindowTitle(self.titleResults % self.modelGroup.count())

    def accepted(self):
        self.result = self.screen.selectedIds() or self.ids
        self.accept()

    def save(self):
        print("SearchDialog.save")
        pass

    def cancel(self):
        print("SearchDialog.cancel")
        pass
Beispiel #2
0
class FormWidget( QWidget, FormWidgetUi ):
	# form constructor:
	# model -> Name of the model the form should handle
	# res_id -> List of ids of type 'model' to load
	# domain -> Domain the models should be in
	# view_type -> type of view: form, tree, graph, calendar, ...
	# view_ids -> Id's of the views 'ir.ui.view' to show
	# context -> Context for the current data set
	# parent -> Parent widget of the form
	# name -> User visible title of the form
	def __init__(self, model, res_id=False, domain=None, view_type=None, view_ids=None, context=None, parent=None, name=False):
		QWidget.__init__(self,parent)
		FormWidgetUi.__init__(self)
		self.setupUi( self )

		if domain is None:
			domain = []
		if view_ids is None:
			view_ids = []
		if context is None:
			context = {}

		# This variable holds the id used to update status (and show number of attachments)
		# If it doesn't change we won't update the number of attachments, avoiding some server
		# calls.
		self.previousId = False
		self.previousAttachments = False

		# Workaround: In some cases (detected in some CRM actions) view_type and view_ids
		# may contain duplicate entries. Here we remove duplicates (ensuring lists order is kept).
		if view_type:
			new_view_ids = []
			new_view_type = []
			for i in xrange(len(view_type)):
				if not view_type[i] in new_view_type:
					if i < len(view_ids):
						new_view_ids.append( view_ids[i] )
					new_view_type.append( view_type[i] )
			view_ids = new_view_ids
			view_type = new_view_type

		if not view_type:
			view_type = ['form','tree']
		else:
			if view_type[0] in ['graph'] and not res_id:
				res_id = Rpc.session.execute('/object', 'execute', model, 'search', domain)
		fields = {}
		self.model = model
		self.previousAction = None
		self.fields = fields
		self.domain = domain
		self.context = context
		self.viewTypes = view_type
		self.viewIds = view_ids
		self.devel_mode = Settings.value("client.devel_mode", False)

		self._switchViewMenu = QMenu( self )
		self._viewActionGroup = QActionGroup( self )
		self._viewActionGroup.setExclusive( True )
		for view in self.viewTypes:
			action = ViewFactory.viewAction( view, self )
			if not action:
				continue
			self.connect( action, SIGNAL('triggered()'), self.switchView )
			self._switchViewMenu.addAction( action )
			self._viewActionGroup.addAction( action )

		self.group = RecordGroup( self.model, context=self.context )
		if Settings.value('koo.sort_mode') == 'visible_items':
			self.group.setSortMode( RecordGroup.SortVisibleItems )
		self.group.setDomain( domain )
		self.connect(self.group, SIGNAL('modified'), self.notifyRecordModified)

		self.screen.setRecordGroup( self.group )
		self.screen.setEmbedded( False )
		self.connect( self.screen, SIGNAL('activated()'), self.switchToForm )
		self.connect( self.screen, SIGNAL('currentChanged()'), self.updateStatus )
		self.connect( self.screen, SIGNAL('closed()'), self.closeWidget )
		self.connect( self.screen, SIGNAL('recordMessage(int,int,int)'), self.updateRecordStatus )
		self.connect( self.screen, SIGNAL('statusMessage(QString)'), self.updateStatus )

		self._allowOpenInNewWindow = True

		# Remove ids with False value
		self.screen.setupViews( view_type, view_ids )

		if name:
			self.name = name
		else:
			self.name = self.screen.currentView().title

		self.handlers = {
			'New': self.new,
			'Save': self.save,
			'Export': self.export,
			'Import': self.import_,
			'Delete': self.remove,
			'Find': self.search,
			'Previous': self.previous,
			'Next':  self.next,
			'GoToResourceId':  self.goto,
			'AccessLog':  self.showLogs,
			'Reload': self.reload,
			'Switch': self.switchView,
			'Attach': self.showAttachments,
			'Duplicate': self.duplicate,
			'BatchInsert': self.batchInsert,
			'BatchUpdate': self.batchUpdate,
			'BatchButton': self.batchButton,
			'BatchUpdateField': self.batchUpdateField,
			'StoreViewSettings': self.storeViewSettings,
		}

		if res_id:
			if isinstance(res_id, int):
				res_id = [res_id]
			self.screen.load(res_id)
		else:
			if len(view_type) and view_type[0]=='form':
				self.screen.new()

		self.updateSwitchView()

		self.reloadTimer = QTimer(self)
		self.connect( self.reloadTimer, SIGNAL('timeout()'), self.autoReload )
		self.pendingReload = False

		# We always use the Subscriber as the class itself will handle
		# whether the module exists on the server or not
		self.subscriber = Rpc.Subscriber(Rpc.session, self)
		if Settings.value('koo.auto_reload'):
			self.subscriber.subscribe( 'updated_model:%s' % model, self.autoReload )

	def notifyRecordModified(self):
		self.updateStatus( _('<font color="blue">Document modified</font>') )

	## @brief Establishes that every value seconds a reload should be scheduled.
	# If value is < 0 only Subscription based reloads are executed. Note that if
	# value is != 0 Subscription based reloads are always used if available.
	def setAutoReload(self, value):
		if value:
			# We use both, timer and subscriber as in some cases information may change
			# only virtually: Say change the color of a row depending on current time.
			# If the value is negative we don't start the timer but keep subscription,
			# so this allows setting -1 in autorefresh when you don't want timed updates
			# but only when data is changed in the server.
			if value > 0:
				self.reloadTimer.start( int(value) * 1000 )
			if not Settings.value('koo.auto_reload'):
				# Do not subscribe again if that was already done in the constructor
				self.subscriber.subscribe( 'updated_model:%s' % self.model, self.autoReload )
		else:
			self.reloadTimer.stop()

	def setAllowOpenInNewWindow( self, value ):
		self._allowOpenInNewWindow = value

	def goto(self):
		if not self.modifiedSave():
			return
		dialog = GoToIdDialog( self )
		if dialog.exec_() == QDialog.Rejected:
			return
		if not dialog.result in self.group.ids():
			QMessageBox.information(self, _('Go To Id'), _("Resouce with ID '%s' not found.") % dialog.result )
			return
		self.screen.load( [dialog.result] )
		
	def setStatusBarVisible(self, value):
		self.uiStatusLabel.setVisible( value )
		self.uiStatus.setVisible( value )
		self.uiRecordStatus.setVisible( value )
		
	def showAttachments(self):
		id = self.screen.currentId()
		if id:
			if Settings.value('koo.attachments_dialog'):
				QApplication.setOverrideCursor( Qt.WaitCursor )
				try:
					window = AttachmentDialog(self.model, id, self)
					self.connect( window, SIGNAL('destroyed()'), self.attachmentsClosed )
				except Rpc.RpcException, e:
					QApplication.restoreOverrideCursor()
					return
				QApplication.restoreOverrideCursor()
				window.show()
			else:
				context = self.context.copy()
				context.update(Rpc.session.context)
				action = Rpc.session.execute('/object', 'execute', 'ir.attachment', 'action_get', context)
				action['domain'] = [('res_model', '=', self.model), ('res_id', '=', id)]
				context['default_res_model'] = self.model
				context['default_res_id'] = id
				Api.instance.executeAction( action, {}, context )
		else: