File: searchmodel.py

package info (click to toggle)
pypibrowser 1.5-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, wheezy
  • size: 504 kB
  • ctags: 222
  • sloc: python: 3,385; makefile: 8; sh: 1
file content (469 lines) | stat: -rw-r--r-- 18,076 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
#!/usr/bin/env python

"""
searchmodel.py

Copyright (C) 2006 David Boddie

This file is part of PyPI Browser, a GUI browser for the Python Package Index.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
"""

import pypi
from PyQt4.QtCore import *
from PyQt4.QtGui import QFont, QSortFilterProxyModel
from packagemodel import PackageModel, ProxyModelMixIn


class SearchModel(QSortFilterProxyModel, ProxyModelMixIn):

    """SearchModel(QSortFilterProxyModel, ProxyModelMixIn)
    
    A model for providing search results from a package index based on
    searches for packages using standard fields and user-specified text.
    
    This model is a filtering proxy model, meaning that it filters
    communication between a source model and any other components, such
    as views and delegates. It performs two functions, providing filtering
    of items based on the results of package index searches and optional
    filtering of items based on whether they are checked or not.
    
    Internal Implementation:
    
    When the search() method is called, a dictionary is compiled that
    relates package names to dictionaries containing information about
    each matching package release. When the filterAcceptsRow() method
    is called to filter rows out of the information supplied by the
    package model, the data in the first column of the relevant row (the
    package name) is checked against the results dictionary, and the
    row is discarded if the package name is not in the dictionary.
    
    Similarly, when the setData() method is called with an index
    corresponding to a release and a value for the CheckStateRole, the
    state of the markedReleases dictionary is updated to include the
    relevant package and releases so that the filterAcceptsRow() method
    can discard packages that have no marked releases if the filter is
    enabled.
    
    Note that the filterAcceptsRow() method checks for marked packages
    before examining the results dictionary and checks for a special
    None value for the results to ensure that no filtering is performed
    if no valid search has been made.
    """
    
    fields = \
    (
        "name", "version", "author", "summary", "description",
        "stable_version", "author_email", "maintainer",
        "maintainer_email", "license", "platform", "download_url",
        "home_page", "keywords", "classifiers"
    )
    
    def __init__(self, server, parent = None):
    
        QSortFilterProxyModel.__init__(self, parent)
        
        self.package_server = server
        self.field = "name"
        self.terms = ""
        self.results = None
        self.markedPackages = {}
        self.markedFilter = False
        self.newFilter = False
        
        self.displayFields = \
        {
            "name": self.tr("Name"), "version": self.tr("Version"),
            "author": self.tr("Author"), "summary": self.tr("Summary"),
            "description": self.tr("Description"), 
            "stable_version": self.tr("Stable version"),
            "author_email": self.tr("Author e-mail"),
            "maintainer": self.tr("Maintainer"),
            "maintainer_email": self.tr("Maintainer e-mail"),
            "license": self.tr("License"), "platform": self.tr("Platform"),
            "download_url": self.tr("Download URL"),
            "home_page": self.tr("Home page"), 
            "keywords": self.tr("Keywords"),
            "classifiers": self.tr("Classifiers")
        }
        
        font = QFont()
        font.setBold(True)
        self.newPackageFont = QVariant(font)
    
    def clear(self):
    
        """clear(self)
        
        Clears any internal mappings defined by the model and additionally
        resets the results and marked packages dictionaries.
        """
        
        self.results = None
        self.markedPackages = {}
        QSortFilterProxyModel.clear(self)
    
    def columnCount(self, index):
    
        return 3
    
    def data(self, index, role):
    
        """data(self, index, role)
        
        Returns the data described by the given role for the item
        corresponding to the specified index.
        
        The method only provides information for indexes where the
        CheckStateRole is relevant. All other requests are passed to the
        base class which ensures that data from the source model is passed
        through correctly to views and delegates.
        """
        
        sourceIndex = self.mapToSource(index)
        parent = sourceIndex.parent()
        
        if role == Qt.CheckStateRole:
            if parent.isValid() and sourceIndex.column() == 0:
            
                # Quick test: If the package name is not in the marked
                # packages dictionary then return an unchecked state.
                # We need to check for invalid download roles here because
                # it's not enough to return the correct flags in the flags()
                # method.
                
                try:
                    packageName = unicode(parent.data().toString())
                    package, markedReleases = self.markedPackages[packageName]
                except KeyError:
                    if index.data(PackageModel.DownloadRole).isValid():
                        return QVariant(Qt.Unchecked)
                    else:
                        return QVariant()
                
                # If the release name is in the list of marked releases for
                # the package then return a checked state; otherwise return
                # an unchecked state. We need to check for invalid download
                # roles here because it's not enough to return the correct
                # flags in the flags() method.
                
                releaseName = unicode(sourceIndex.data().toString())
                if releaseName in markedReleases:
                    return QVariant(Qt.Checked)
                elif index.data(PackageModel.DownloadRole).isValid():
                    return QVariant(Qt.Unchecked)
                else:
                    return QVariant()
        
        elif role == Qt.FontRole and not parent.isValid() and \
            sourceIndex.data(PackageModel.NewPackageRole).toBool():
        
            return self.newPackageFont
        
        return QSortFilterProxyModel.data(self, index, role)
    
    def filterAcceptsRow(self, source_row, source_parent):
    
        """filterAcceptsRow(self, source_row, source_parent)
        
        Returns true if the model exposes the given source_row containing
        child items corresponding to child indexes of the source_parent
        model index; otherwise returns false.
        
        If the marked package filter is enabled, this method first filters
        out rows corresponding to packages if there are no marked releases
        for those packages.
        
        If a search has been performed, the first column of each unfiltered
        row (corresponding to a package name for a top-level item and
        a release version for a first-level item) is checked against the
        results dictionary. Those releases that are not in the dictionary
        and packages with no marked releases are discarded.
        """
        
        # If the marked or new package filters are being applied then filter
        # out top-level items that aren't in either the marked packages or
        # the new packages dictionaries.
        
        if not source_parent.isValid():
            index = self.sourceModel().index(source_row, 0, source_parent)
            if self.markedFilter:
                if unicode(index.data().toString()) not in self.markedPackages:
                    return False
            if self.newFilter:
                if not index.data(PackageModel.NewPackageRole).toBool():
                    return False
        
        if self.results is None:
            return True
        elif source_parent.isValid():
            return True
        
        index = self.sourceModel().index(source_row, 0, source_parent)
        name = unicode(index.data().toString())
        
        if name in self.results:
        
            # Add the information returned from the search to the item from
            # the source model.
            details = self.results[name]
            package = index.internalPointer()
            if package.releases is not None:
            
                for release in package.releases:
                    if release.version == details["version"]:
                        break
                else:
                    release = pypi.Release(package, details["version"])
                    package.releases.append(release)
                
                if not release.description:
                    release.description = pypi.Description(release, details)
            
            return True
        
        else:
            return False
    
    def flags(self, index):
    
        """flags(self, index)
        
        Returns the flags for the item corresponding to the specified index.
        
        All items are enabled, and the first column of rows containing
        release information are also checkable.
        """
        
        if not index.isValid():
            return QSortFilterProxyModel.flags(self, index)
        
        parent = index.parent()
        
        if not parent.isValid():
            # Top-level packages are enabled only.
            return Qt.ItemIsEnabled
        
        else:
            # The first column of release items are enabled and checkable.
            if index.column() == 0:
                if index.data(PackageModel.DownloadRole).isValid():
                    return Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
                else:
                    return Qt.ItemIsEnabled
            else:
                return Qt.ItemIsEnabled
    
    def hasChildren(self, index):
    
        """hasChildren(self, index)
        
        Returns true if the item in the source model corresponding to the
        given index has child items; otherwise returns false.
        
        This reimplemented method is necessary to ensure that views do not
        call rowCount() for each top-level index and cause the source model
        to query the server for each package.
        """
        
        return self.sourceModel().hasChildren(self.mapToSource(index))
    
    def listPackages(self):
    
        """listPackages(self)
        
        Convenience method that resets the model and requests a new list of
        packages via the source model.
        """
        
        QSortFilterProxyModel.reset(self)
        self.sourceModel().listPackages()
    
    def search(self):
    
        """search(self)
        
        Searches the package index using the search field and terms, then
        resets the model to ensure that attached components are updated to
        take account of the new search results.
        
        The results are processed to make a dictionary mapping package names
        to the match for each package.
        """
        
        if self.terms.strip() == u"":
            self.results = None
            self.reset()
            self.sendMessage()
            return
        
        self.emit(SIGNAL("operationStarted()"))
        self.results = {}
        
        for result in self.package_server.search(
            {self.field: self.terms}):
            self.results[result["name"]] = result
        
        self.reset()
        self.sendMessage()
        self.emit(SIGNAL("operationFinished()"))
    
    def sendMessage(self):
    
        """sendMessage(self)
        
        Inform attached components about the results of a search or filtering
        operation.
        """
        
        if self.results is None:
            if self.markedFilter and self.newFilter:
                self.emit(SIGNAL("resultsFound(const QString &)"),
                          self.tr("Showing all new marked packages."))
            elif self.markedFilter:
                self.emit(SIGNAL("resultsFound(const QString &)"),
                          self.tr("Showing all marked packages."))
            elif self.newFilter:
                self.emit(SIGNAL("resultsFound(const QString &)"),
                          self.tr("Showing all new packages."))
            else:
                self.emit(SIGNAL("resultsFound(const QString &)"),
                          self.tr("Showing all packages."))
        else:
            if self.markedFilter and self.newFilter:
                self.emit(SIGNAL("resultsFound(const QString &)"),
                          self.tr("Showing new marked packages from a set of %1 with '%2' matching '%3'.").arg(
                          str(len(self.results)), self.displayFields[self.field],
                          self.terms))
            elif self.markedFilter:
                self.emit(SIGNAL("resultsFound(const QString &)"),
                          self.tr("Showing marked packages from a set of %1 with '%2' matching '%3'.").arg(
                          str(len(self.results)), self.displayFields[self.field],
                          self.terms))
            elif self.newFilter:
                self.emit(SIGNAL("resultsFound(const QString &)"),
                          self.tr("Showing new packages from a set of %1 with '%2' matching '%3'.").arg(
                          str(len(self.results)), self.displayFields[self.field],
                          self.terms))
            else:
                if QT_VERSION & 0xffff00 < 0x40200:
                    text = self.tr("Showing %1 package(s) with '%2' matching '%3'.", "Number of packages")
                else:
                    text = self.tr("Showing %1 package(s) with '%2' matching '%3'.", "Number of packages", len(self.results))
                
                self.emit(SIGNAL("resultsFound(const QString &)"),
                          text.arg(str(len(self.results)), self.displayFields[self.field],
                                   self.terms))
    
    def setData(self, index, value, role):
    
        """setData(self, index, value, role)
        
        Sets the data for the item corresponding to the given index and role
        to the specified value.
        
        This model only intercepts the CheckStateRole to ensure that, when
        releases are marked, the internal dictionary of marked packages
        is updated.
        
        For all other roles, the data is passed through to the source model.
        """
        
        if not index.isValid():
            return QSortFilterProxyModel.setData(self, index, value, role)
        elif role != Qt.CheckStateRole:
            return QSortFilterProxyModel.setData(self, index, value, role)
        
        # The dictionary contains rows of top-level items in the model,
        # so don't try and store rows of child items as it will only
        # lead to confusion.
        
        sourceIndex = self.mapToSource(index)
        parent = sourceIndex.parent()
        
        if parent.isValid():
        
            packageName = unicode(parent.data().toString())
            package, markedReleases = self.markedPackages.get(packageName,
                                      (parent.internalPointer(), {}))
            
            releaseName = unicode(sourceIndex.data().toString())
            if value.toBool():
                markedReleases[releaseName] = True
            elif releaseName in markedReleases:
                del markedReleases[releaseName]
            
            if markedReleases != {}:
                self.markedPackages[packageName] = package, markedReleases
            elif self.markedPackages.has_key(packageName):
                del self.markedPackages[packageName]
            
            self.emit(SIGNAL("markedChanged(bool)"), self.markedPackages != {})
            self.emit(SIGNAL("dataChanged(const QModelIndex &, const QModelIndex &)"),
                      index, index)
            return True
        
        return False
    
    def setMarkedFilter(self, enable):
    
        """setMarkedFilter(self, enable)
        
        Enables or disables the marked package filter.
        """
        
        self.markedFilter = enable
        self.reset()
        self.sendMessage()
    
    def setNewFilter(self, enable):
    
        """setNewFilter(self, enable)
        
        Enables or disables the new package filter.
        """
        
        self.newFilter = enable
        self.reset()
        self.sendMessage()
    
    def setSearchField(self, row):
    
        """setSearchField(self, row)
        
        Sets the search field to the text in the field list specified by the
        row and updates the model with the results of a new search.
        """
        
        self.field = self.fields[row]
        self.search()
    
    def setSearchTerms(self, text):
    
        """setSearchTerms(self, text)
        
        Sets the search terms to the text specified.
        
        No search is performed since the text supplied may be incomplete.
        When the text is complete, it is expected that another component
        will call the search() method when a suitable user action occurs.
        """
        
        self.terms = unicode(text)
    
    def setServer(self, server):
    
        self.package_server = server