-
Notifications
You must be signed in to change notification settings - Fork 5
/
qt_plugin_dialog.py
1549 lines (1341 loc) · 55.7 KB
/
qt_plugin_dialog.py
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import contextlib
import importlib.metadata
import os
import sys
import webbrowser
from functools import partial
from pathlib import Path
from typing import Dict, List, Literal, NamedTuple, Optional, Sequence, Tuple
import napari.plugins
import napari.resources
import npe2
from napari._qt.qt_resources import QColoredSVGIcon, get_current_stylesheet
from napari._qt.qthreading import create_worker
from napari._qt.widgets.qt_message_popup import WarnPopup
from napari._qt.widgets.qt_tooltip import QtToolTipLabel
from napari.plugins.utils import normalized_name
from napari.settings import get_settings
from napari.utils.misc import (
parse_version,
running_as_constructor_app,
)
from napari.utils.notifications import show_info, show_warning
from napari.utils.translations import trans
from qtpy.QtCore import QPoint, QSize, Qt, QTimer, Signal, Slot
from qtpy.QtGui import (
QAction,
QActionGroup,
QFont,
QKeySequence,
QMovie,
QShortcut,
)
from qtpy.QtWidgets import (
QCheckBox,
QComboBox,
QDialog,
QFrame,
QGridLayout,
QHBoxLayout,
QLabel,
QLineEdit,
QListWidget,
QListWidgetItem,
QMenu,
QPushButton,
QSizePolicy,
QSplitter,
QTextEdit,
QToolButton,
QVBoxLayout,
QWidget,
)
from superqt import QCollapsible, QElidingLabel
from napari_plugin_manager.npe2api import (
cache_clear,
iter_napari_plugin_info,
)
from napari_plugin_manager.qt_package_installer import (
InstallerActions,
InstallerQueue,
InstallerTools,
ProcessFinishedData,
)
from napari_plugin_manager.qt_widgets import ClickableLabel
from napari_plugin_manager.utils import is_conda_package
# Scaling factor for each list widget item when expanding.
CONDA = 'Conda'
PYPI = 'PyPI'
ON_BUNDLE = running_as_constructor_app()
IS_NAPARI_CONDA_INSTALLED = is_conda_package('napari')
STYLES_PATH = Path(__file__).parent / 'styles.qss'
def _show_message(widget):
message = trans._(
'When installing/uninstalling npe2 plugins, '
'you must restart napari for UI changes to take effect.'
)
if widget.isVisible():
button = widget.action_button
warn_dialog = WarnPopup(text=message)
global_point = widget.action_button.mapToGlobal(
button.rect().topRight()
)
global_point = QPoint(
global_point.x() - button.width(), global_point.y()
)
warn_dialog.move(global_point)
warn_dialog.exec_()
class ProjectInfoVersions(NamedTuple):
metadata: npe2.PackageMetadata
display_name: str
pypi_versions: List[str]
conda_versions: List[str]
class PluginListItem(QFrame):
"""An entry in the plugin dialog. This will include the package name, summary,
author, source, version, and buttons to update, install/uninstall, etc."""
# item, package_name, action_name, version, installer_choice
actionRequested = Signal(QListWidgetItem, str, object, str, object)
def __init__(
self,
item: QListWidgetItem,
package_name: str,
display_name: str,
version: str = '',
url: str = '',
summary: str = '',
author: str = '',
license: str = "UNKNOWN", # noqa: A002
*,
plugin_name: Optional[str] = None,
parent: QWidget = None,
enabled: bool = True,
installed: bool = False,
npe_version=1,
versions_conda: Optional[List[str]] = None,
versions_pypi: Optional[List[str]] = None,
prefix=None,
) -> None:
super().__init__(parent)
self.prefix = prefix
self.item = item
self.url = url
self.name = package_name
self.npe_version = npe_version
self._version = version
self._versions_conda = versions_conda
self._versions_pypi = versions_pypi
self.setup_ui(enabled)
if package_name == display_name:
name = package_name
else:
name = f"{display_name} <small>({package_name})</small>"
self.plugin_name.setText(name)
if len(versions_pypi) > 0:
self._populate_version_dropdown(PYPI)
else:
self._populate_version_dropdown(CONDA)
mod_version = version.replace('.', '․') # noqa: RUF001
self.version.setWordWrap(True)
self.version.setText(mod_version)
self.version.setToolTip(version)
if summary:
self.summary.setText(summary)
if author:
self.package_author.setText(author)
self.package_author.setWordWrap(True)
self.cancel_btn.setVisible(False)
self._handle_npe2_plugin(npe_version)
self._set_installed(installed, package_name)
self._populate_version_dropdown(self.get_installer_source())
def _set_installed(self, installed: bool, package_name):
if installed:
if is_conda_package(package_name):
self.source.setText(CONDA)
self.enabled_checkbox.show()
self.action_button.setText(trans._("Uninstall"))
self.action_button.setObjectName("remove_button")
self.info_choice_wdg.hide()
self.install_info_button.addWidget(self.info_widget)
self.info_widget.show()
else:
self.enabled_checkbox.hide()
self.action_button.setText(trans._("Install"))
self.action_button.setObjectName("install_button")
self.info_widget.hide()
self.install_info_button.addWidget(self.info_choice_wdg)
self.info_choice_wdg.show()
def _handle_npe2_plugin(self, npe_version):
if npe_version in (None, 1):
return
opacity = 0.4 if npe_version == 'shim' else 1
text = trans._('npe1 (adapted)') if npe_version == 'shim' else 'npe2'
icon = QColoredSVGIcon.from_resources('logo_silhouette')
self.set_status(
icon.colored(color='#33F0FF', opacity=opacity).pixmap(20, 20), text
)
def set_status(self, icon=None, text=''):
"""Set the status icon and text. next to the package name."""
if icon:
self.status_icon.setPixmap(icon)
if text:
self.status_label.setText(text)
self.status_icon.setVisible(bool(icon))
self.status_label.setVisible(bool(text))
def set_busy(
self,
text: str,
action_name: Optional[
Literal['install', 'uninstall', 'cancel', 'upgrade']
] = None,
):
"""Updates status text and what buttons are visible when any button is pushed.
Parameters
----------
text: str
The new string to be displayed as the status.
action_name: str
The action of the button pressed.
"""
self.item_status.setText(text)
if action_name == 'upgrade':
self.cancel_btn.setVisible(True)
self.action_button.setVisible(False)
elif action_name in {'uninstall', 'install'}:
self.action_button.setVisible(False)
self.cancel_btn.setVisible(True)
elif action_name == 'cancel':
self.action_button.setVisible(True)
self.action_button.setDisabled(False)
self.cancel_btn.setVisible(False)
else: # pragma: no cover
raise ValueError(f"Not supported {action_name}")
def setup_ui(self, enabled=True):
"""Define the layout of the PluginListItem"""
# Enabled checkbox
self.enabled_checkbox = QCheckBox(self)
self.enabled_checkbox.setChecked(enabled)
self.enabled_checkbox.setToolTip(trans._("enable/disable"))
self.enabled_checkbox.setText("")
self.enabled_checkbox.stateChanged.connect(self._on_enabled_checkbox)
sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.enabled_checkbox.sizePolicy().hasHeightForWidth()
)
self.enabled_checkbox.setSizePolicy(sizePolicy)
self.enabled_checkbox.setMinimumSize(QSize(20, 0))
# Plugin name
self.plugin_name = ClickableLabel(self) # To style content
font_plugin_name = QFont()
font_plugin_name.setPointSize(15)
font_plugin_name.setUnderline(True)
self.plugin_name.setFont(font_plugin_name)
# Status
self.status_icon = QLabel(self)
self.status_icon.setVisible(False)
self.status_label = QLabel(self)
self.status_label.setVisible(False)
if self.url and self.url != 'UNKNOWN':
# Do not want to highlight on hover unless there is a website.
self.plugin_name.setObjectName('plugin_name_web')
else:
self.plugin_name.setObjectName('plugin_name')
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(
self.plugin_name.sizePolicy().hasHeightForWidth()
)
self.plugin_name.setSizePolicy(sizePolicy)
# Warning icon
icon = QColoredSVGIcon.from_resources("warning")
self.warning_tooltip = QtToolTipLabel(self)
# TODO: This color should come from the theme but the theme needs
# to provide the right color. Default warning should be orange, not
# red. Code example:
# theme_name = get_settings().appearance.theme
# napari.utils.theme.get_theme(theme_name, as_dict=False).warning.as_hex()
self.warning_tooltip.setPixmap(
icon.colored(color="#E3B617").pixmap(15, 15)
)
self.warning_tooltip.setVisible(False)
# Item status
self.item_status = QLabel(self)
self.item_status.setObjectName("small_italic_text")
self.item_status.setSizePolicy(sizePolicy)
# Summary
self.summary = QElidingLabel(parent=self)
self.summary.setObjectName('summary_text')
self.summary.setWordWrap(True)
font_summary = QFont()
font_summary.setPointSize(10)
self.summary.setFont(font_summary)
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(1)
sizePolicy.setVerticalStretch(0)
self.summary.setSizePolicy(sizePolicy)
self.summary.setContentsMargins(0, -2, 0, -2)
# Package author
self.package_author = QElidingLabel(self)
self.package_author.setObjectName('author_text')
self.package_author.setWordWrap(True)
self.package_author.setSizePolicy(sizePolicy)
# Update button
self.update_btn = QPushButton('Update', self)
self.update_btn.setObjectName("install_button")
self.update_btn.setVisible(False)
self.update_btn.clicked.connect(self._update_requested)
sizePolicy.setRetainSizeWhenHidden(True)
sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
self.update_btn.setSizePolicy(sizePolicy)
self.update_btn.clicked.connect(self._update_requested)
# Action Button
self.action_button = QPushButton(self)
self.action_button.setFixedWidth(70)
sizePolicy1 = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
self.action_button.setSizePolicy(sizePolicy1)
self.action_button.clicked.connect(self._action_requested)
# Cancel
self.cancel_btn = QPushButton("Cancel", self)
self.cancel_btn.setObjectName("remove_button")
self.cancel_btn.setSizePolicy(sizePolicy)
self.cancel_btn.setFixedWidth(70)
self.cancel_btn.clicked.connect(self._cancel_requested)
# Collapsible button
coll_icon = QColoredSVGIcon.from_resources('right_arrow').colored(
color='white',
)
exp_icon = QColoredSVGIcon.from_resources('down_arrow').colored(
color='white',
)
self.install_info_button = QCollapsible(
"Installation Info", collapsedIcon=coll_icon, expandedIcon=exp_icon
)
self.install_info_button.setLayoutDirection(
Qt.RightToLeft
) # Make icon appear on the right
self.install_info_button.setObjectName("install_info_button")
self.install_info_button.setFixedWidth(180)
self.install_info_button.content().layout().setContentsMargins(
0, 0, 0, 0
)
self.install_info_button.content().setContentsMargins(0, 0, 0, 0)
self.install_info_button.content().layout().setSpacing(0)
self.install_info_button.layout().setContentsMargins(0, 0, 0, 0)
self.install_info_button.layout().setSpacing(2)
self.install_info_button.setSizePolicy(sizePolicy)
# Information widget for available packages
self.info_choice_wdg = QWidget(self)
self.info_choice_wdg.setObjectName('install_choice')
self.source_choice_text = QLabel('Source:')
self.version_choice_text = QLabel('Version:')
self.source_choice_dropdown = QComboBox()
self.version_choice_dropdown = QComboBox()
if IS_NAPARI_CONDA_INSTALLED and self._versions_conda:
self.source_choice_dropdown.addItem(CONDA)
if self._versions_pypi:
self.source_choice_dropdown.addItem(PYPI)
source = self.get_installer_source()
self.source_choice_dropdown.setCurrentText(source)
self._populate_version_dropdown(source)
self.source_choice_dropdown.currentTextChanged.connect(
self._populate_version_dropdown
)
# Information widget for installed packages
self.info_widget = QWidget(self)
self.info_widget.setLayoutDirection(Qt.LeftToRight)
self.info_widget.setObjectName("info_widget")
self.info_widget.setFixedWidth(180)
self.source_text = QLabel('Source:')
self.source = QLabel(PYPI)
self.version_text = QLabel('Version:')
self.version = QElidingLabel()
self.version.setWordWrap(True)
info_layout = QGridLayout()
info_layout.setContentsMargins(0, 0, 0, 0)
info_layout.setVerticalSpacing(0)
info_layout.addWidget(self.source_text, 0, 0)
info_layout.addWidget(self.source, 1, 0)
info_layout.addWidget(self.version_text, 0, 1)
info_layout.addWidget(self.version, 1, 1)
self.info_widget.setLayout(info_layout)
# Error indicator
self.error_indicator = QPushButton()
self.error_indicator.setObjectName("warning_icon")
self.error_indicator.setCursor(Qt.CursorShape.PointingHandCursor)
self.error_indicator.hide()
# region - Layout
# -----------------------------------------------------------------
layout = QHBoxLayout()
layout.setSpacing(2)
layout_left = QVBoxLayout()
layout_right = QVBoxLayout()
layout_top = QHBoxLayout()
layout_bottom = QHBoxLayout()
layout_bottom.setSpacing(4)
layout_left.addWidget(
self.enabled_checkbox, alignment=Qt.AlignmentFlag.AlignTop
)
layout_right.addLayout(layout_top, 1)
layout_right.addLayout(layout_bottom, 100)
layout.addLayout(layout_left)
layout.addLayout(layout_right)
self.setLayout(layout)
layout_top.addWidget(self.plugin_name)
layout_top.addWidget(self.status_icon)
layout_top.addWidget(self.status_label)
layout_top.addWidget(self.item_status)
layout_top.addStretch()
layout_bottom.addWidget(
self.summary, alignment=Qt.AlignmentFlag.AlignTop, stretch=3
)
layout_bottom.addWidget(
self.package_author, alignment=Qt.AlignmentFlag.AlignTop, stretch=1
)
layout_bottom.addWidget(
self.update_btn, alignment=Qt.AlignmentFlag.AlignTop
)
layout_bottom.addWidget(
self.install_info_button, alignment=Qt.AlignmentFlag.AlignTop
)
layout_bottom.addWidget(
self.action_button, alignment=Qt.AlignmentFlag.AlignTop
)
layout_bottom.addWidget(
self.cancel_btn, alignment=Qt.AlignmentFlag.AlignTop
)
info_layout = QGridLayout()
info_layout.setContentsMargins(0, 0, 0, 0)
info_layout.setVerticalSpacing(0)
info_layout.addWidget(self.source_choice_text, 0, 0, 1, 1)
info_layout.addWidget(self.source_choice_dropdown, 1, 0, 1, 1)
info_layout.addWidget(self.version_choice_text, 0, 1, 1, 1)
info_layout.addWidget(self.version_choice_dropdown, 1, 1, 1, 1)
# endregion - Layout
self.info_choice_wdg.setLayout(info_layout)
self.info_choice_wdg.setLayoutDirection(Qt.LeftToRight)
self.info_choice_wdg.setObjectName("install_choice_widget")
self.info_choice_wdg.hide()
def _populate_version_dropdown(self, source: Literal["PyPI", "Conda"]):
"""Display the versions available after selecting a source: pypi or conda."""
if source == PYPI:
versions = self._versions_pypi
else:
versions = self._versions_conda
self.version_choice_dropdown.clear()
for version in versions:
self.version_choice_dropdown.addItem(version)
def _on_enabled_checkbox(self, state: int):
"""Called with `state` when checkbox is clicked."""
enabled = bool(state)
plugin_name = self.plugin_name.text()
pm2 = npe2.PluginManager.instance()
if plugin_name in pm2:
pm2.enable(plugin_name) if state else pm2.disable(plugin_name)
return
for (
npe1_name,
_,
distname,
) in napari.plugins.plugin_manager.iter_available():
if distname and (normalized_name(distname) == plugin_name):
napari.plugins.plugin_manager.set_blocked(
npe1_name, not enabled
)
return
def _cancel_requested(self):
version = self.version_choice_dropdown.currentText()
tool = self.get_installer_tool()
self.actionRequested.emit(
self.item, self.name, InstallerActions.CANCEL, version, tool
)
def _action_requested(self):
version = self.version_choice_dropdown.currentText()
tool = self.get_installer_tool()
action = (
InstallerActions.INSTALL
if self.action_button.objectName() == 'install_button'
else InstallerActions.UNINSTALL
)
self.actionRequested.emit(self.item, self.name, action, version, tool)
def _update_requested(self):
version = self.version_choice_dropdown.currentText()
tool = self.get_installer_tool()
self.actionRequested.emit(
self.item, self.name, InstallerActions.UPGRADE, version, tool
)
def show_warning(self, message: str = ""):
"""Show warning icon and tooltip."""
self.warning_tooltip.setVisible(bool(message))
self.warning_tooltip.setToolTip(message)
def get_installer_source(self):
return (
CONDA
if self.source_choice_dropdown.currentText() == CONDA
or is_conda_package(self.name)
else PYPI
)
def get_installer_tool(self):
return (
InstallerTools.CONDA
if self.source_choice_dropdown.currentText() == CONDA
or is_conda_package(self.name, prefix=self.prefix)
else InstallerTools.PIP
)
class QPluginList(QListWidget):
_SORT_ORDER_PREFIX = '0-'
def __init__(self, parent: QWidget, installer: InstallerQueue) -> None:
super().__init__(parent)
self.installer = installer
self._remove_list = []
self._data = []
self._initial_height = None
self.setSortingEnabled(True)
def count_visible(self) -> int:
"""Return the number of visible items.
Visible items are the result of the normal `count` method minus
any hidden items.
"""
hidden = 0
count = self.count()
for i in range(count):
item = self.item(i)
hidden += item.isHidden()
return count - hidden
@Slot(tuple)
def addItem(
self,
project_info: ProjectInfoVersions,
installed=False,
plugin_name=None,
enabled=True,
npe_version=None,
):
pkg_name = project_info.metadata.name
# don't add duplicates
if (
self.findItems(pkg_name, Qt.MatchFlag.MatchFixedString)
and not plugin_name
):
return
# including summary here for sake of filtering below.
searchable_text = f"{pkg_name} {project_info.display_name} {project_info.metadata.summary}"
item = QListWidgetItem(searchable_text, self)
item.version = project_info.metadata.version
super().addItem(item)
widg = PluginListItem(
item=item,
package_name=pkg_name,
display_name=project_info.display_name,
version=project_info.metadata.version,
url=project_info.metadata.home_page,
summary=project_info.metadata.summary,
author=project_info.metadata.author,
license=project_info.metadata.license,
parent=self,
plugin_name=plugin_name,
enabled=enabled,
installed=installed,
npe_version=npe_version,
versions_conda=project_info.conda_versions,
versions_pypi=project_info.pypi_versions,
)
item.widget = widg
item.npe_version = npe_version
item.setSizeHint(widg.sizeHint())
self.setItemWidget(item, widg)
if project_info.metadata.home_page:
widg.plugin_name.clicked.connect(
partial(webbrowser.open, project_info.metadata.home_page)
)
widg.actionRequested.connect(self.handle_action)
item.setSizeHint(item.widget.size())
if self._initial_height is None:
self._initial_height = item.widget.size().height()
widg.install_info_button.setDuration(0)
widg.install_info_button.toggled.connect(
lambda: self._resize_pluginlistitem(item)
)
def removeItem(self, name):
count = self.count()
for i in range(count):
item = self.item(i)
if item.widget.name == name:
self.takeItem(i)
break
def refreshItem(self, name, version=None):
count = self.count()
for i in range(count):
item = self.item(i)
if item.widget.name == name:
if version is not None:
item.version = version
mod_version = version.replace('.', '․') # noqa: RUF001
item.widget.version.setText(mod_version)
item.widget.version.setToolTip(version)
item.widget.set_busy('', InstallerActions.CANCEL)
if item.text().startswith(self._SORT_ORDER_PREFIX):
item.setText(item.text()[len(self._SORT_ORDER_PREFIX) :])
break
def _resize_pluginlistitem(self, item):
"""Resize the plugin list item, especially after toggling QCollapsible."""
if item.widget.install_info_button.isExpanded():
item.widget.setFixedHeight(self._initial_height + 35)
else:
item.widget.setFixedHeight(self._initial_height)
item.setSizeHint(QSize(0, item.widget.height()))
def handle_action(
self,
item: QListWidgetItem,
pkg_name: str,
action_name: InstallerActions,
version: Optional[str] = None,
installer_choice: Optional[str] = None,
):
"""Determine which action is called (install, uninstall, update, cancel).
Update buttons appropriately and run the action."""
widget = item.widget
tool = installer_choice or widget.get_installer_tool()
self._remove_list.append((pkg_name, item))
self._warn_dialog = None
if not item.text().startswith(self._SORT_ORDER_PREFIX):
item.setText(f"{self._SORT_ORDER_PREFIX}{item.text()}")
# TODO: NPE version unknown before installing
if (
widget.npe_version != 1
and action_name == InstallerActions.UNINSTALL
):
_show_message(widget)
if action_name == InstallerActions.INSTALL:
if version:
pkg_name += (
f"=={item.widget.version_choice_dropdown.currentText()}"
)
widget.set_busy(trans._("installing..."), action_name)
job_id = self.installer.install(
tool=tool,
pkgs=[pkg_name],
# origins="TODO",
)
widget.setProperty("current_job_id", job_id)
if self._warn_dialog:
self._warn_dialog.exec_()
self.scrollToTop()
if action_name == InstallerActions.UPGRADE:
if hasattr(item, 'latest_version'):
pkg_name += f"=={item.latest_version}"
widget.set_busy(trans._("updating..."), action_name)
widget.update_btn.setDisabled(True)
widget.action_button.setDisabled(True)
job_id = self.installer.upgrade(
tool=tool,
pkgs=[pkg_name],
# origins="TODO",
)
widget.setProperty("current_job_id", job_id)
if self._warn_dialog:
self._warn_dialog.exec_()
self.scrollToTop()
elif action_name == InstallerActions.UNINSTALL:
widget.set_busy(trans._("uninstalling..."), action_name)
widget.update_btn.setDisabled(True)
job_id = self.installer.uninstall(
tool=tool,
pkgs=[pkg_name],
# origins="TODO",
# upgrade=False,
)
widget.setProperty("current_job_id", job_id)
if self._warn_dialog:
self._warn_dialog.exec_()
self.scrollToTop()
elif action_name == InstallerActions.CANCEL:
widget.set_busy(trans._("cancelling..."), action_name)
try:
job_id = widget.property("current_job_id")
self.installer.cancel(job_id)
finally:
widget.setProperty("current_job_id", None)
def set_data(self, data):
self._data = data
def is_running(self):
return self.count() != len(self._data)
def packages(self):
return [self.item(idx).widget.name for idx in range(self.count())]
@Slot(npe2.PackageMetadata, bool)
def tag_outdated(self, metadata: npe2.PackageMetadata, is_available: bool):
"""Determines if an installed plugin is up to date with the latest version.
If it is not, the latest version will be displayed on the update button.
"""
if not is_available:
return
for item in self.findItems(
metadata.name, Qt.MatchFlag.MatchStartsWith
):
current = item.version
latest = metadata.version
is_marked_outdated = getattr(item, 'outdated', False)
if parse_version(current) >= parse_version(latest):
# currently is up to date
if is_marked_outdated:
# previously marked as outdated, need to update item
# `outdated` state and hide item widget `update_btn`
item.outdated = False
widg = self.itemWidget(item)
widg.update_btn.setVisible(False)
continue
if is_marked_outdated:
# already tagged it
continue
item.outdated = True
item.latest_version = latest
widg = self.itemWidget(item)
widg.update_btn.setVisible(True)
widg.update_btn.setText(
trans._("update (v{latest})", latest=latest)
)
def tag_unavailable(self, metadata: npe2.PackageMetadata):
"""
Tag list items as unavailable for install with conda-forge.
This will disable the item and the install button and add a warning
icon with a hover tooltip.
"""
for item in self.findItems(
metadata.name, Qt.MatchFlag.MatchStartsWith
):
widget = self.itemWidget(item)
widget.show_warning(
trans._(
"Plugin not yet available for installation within the bundle application"
)
)
widget.setObjectName("unavailable")
widget.style().unpolish(widget)
widget.style().polish(widget)
widget.action_button.setEnabled(False)
widget.warning_tooltip.setVisible(True)
def filter(self, text: str, starts_with_chars: int = 1):
"""Filter items to those containing `text`."""
if text:
# PySide has some issues, so we compare using id
# See: https://bugreports.qt.io/browse/PYSIDE-74
flag = (
Qt.MatchFlag.MatchStartsWith
if len(text) <= starts_with_chars
else Qt.MatchFlag.MatchContains
)
if len(text) <= starts_with_chars:
flag = Qt.MatchFlag.MatchStartsWith
queries = (text, f'napari-{text}')
else:
flag = Qt.MatchFlag.MatchContains
queries = (text,)
shown = {
id(it)
for query in queries
for it in self.findItems(query, flag)
}
for i in range(self.count()):
item = self.item(i)
item.setHidden(id(item) not in shown)
else:
for i in range(self.count()):
item = self.item(i)
item.setHidden(False)
class QtPluginDialog(QDialog):
def __init__(self, parent=None, prefix=None) -> None:
super().__init__(parent)
self._parent = parent
if (
parent is not None
and getattr(parent, '_plugin_dialog', None) is None
):
self._parent._plugin_dialog = self
self.already_installed = set()
self.available_set = set()
self._prefix = prefix
self._first_open = True
self._plugin_queue = [] # Store plugin data to be added
self._plugin_data = [] # Store all plugin data
self._filter_texts = []
self._filter_idxs_cache = set()
self._filter_timer = QTimer(self)
self.worker = None
# timer to avoid triggering a filter for every keystroke
self._filter_timer.setInterval(140) # ms
self._filter_timer.timeout.connect(self.filter)
self._filter_timer.setSingleShot(True)
self._plugin_data_map = {}
self._add_items_timer = QTimer(self)
# Timer to avoid race conditions and incorrect count of plugins when
# refreshing multiple times in a row. After click we disable the
# `Refresh` button and re-enable it after 3 seconds.
self._refresh_timer = QTimer(self)
self._refresh_timer.setInterval(3000) # ms
self._refresh_timer.setSingleShot(True)
self._refresh_timer.timeout.connect(self._enable_refresh_button)
# Add items in batches with a pause to avoid blocking the UI
self._add_items_timer.setInterval(61) # ms
self._add_items_timer.timeout.connect(self._add_items)
self.installer = InstallerQueue(parent=self, prefix=prefix)
self.setWindowTitle(trans._('Plugin Manager'))
self._setup_ui()
self.installer.set_output_widget(self.stdout_text)
self.installer.started.connect(self._on_installer_start)
self.installer.processFinished.connect(self._on_process_finished)
self.installer.allFinished.connect(self._on_installer_all_finished)
self.setAcceptDrops(True)
if (
parent is not None and parent._plugin_dialog is self
) or parent is None:
self.refresh()
self._setup_shortcuts()
# region - Private methods
# ------------------------------------------------------------------------
def _enable_refresh_button(self):
self.refresh_button.setEnabled(True)
def _quit(self):
self.close()
with contextlib.suppress(AttributeError):
self._parent.close(quit_app=True, confirm_need=True)
def _setup_shortcuts(self):
self._refresh_styles_action = QAction(trans._('Refresh Styles'), self)
self._refresh_styles_action.setShortcut('Ctrl+R')
self._refresh_styles_action.triggered.connect(self._update_theme)
self.addAction(self._refresh_styles_action)
self._quit_action = QAction(trans._('Exit'), self)
self._quit_action.setShortcut('Ctrl+Q')
self._quit_action.setMenuRole(QAction.QuitRole)
self._quit_action.triggered.connect(self._quit)
self.addAction(self._quit_action)
self._close_shortcut = QShortcut(
QKeySequence(Qt.CTRL | Qt.Key_W), self
)
self._close_shortcut.activated.connect(self.close)
get_settings().appearance.events.theme.connect(self._update_theme)
def _update_theme(self, event):
stylesheet = get_current_stylesheet([STYLES_PATH])
self.setStyleSheet(stylesheet)
def _on_installer_start(self):
"""Updates dialog buttons and status when installing a plugin."""
self.cancel_all_btn.setVisible(True)
self.working_indicator.show()
self.process_success_indicator.hide()
self.process_error_indicator.hide()
self.refresh_button.setDisabled(True)
def _on_process_finished(self, process_finished_data: ProcessFinishedData):
action = process_finished_data['action']
exit_code = process_finished_data['exit_code']
pkg_names = [
pkg.split('==')[0] for pkg in process_finished_data['pkgs']
]
if action == InstallerActions.INSTALL:
if exit_code == 0:
for pkg_name in pkg_names:
if pkg_name in self.available_set:
self.available_set.remove(pkg_name)
self.available_list.removeItem(pkg_name)
self._add_installed(pkg_name)
self._tag_outdated_plugins()
else:
for pkg_name in pkg_names:
self.available_list.refreshItem(pkg_name)
elif action == InstallerActions.UNINSTALL:
if exit_code == 0:
for pkg_name in pkg_names:
if pkg_name in self.already_installed:
self.already_installed.remove(pkg_name)
self.installed_list.removeItem(pkg_name)
self._add_to_available(pkg_name)
else:
for pkg_name in pkg_names:
self.installed_list.refreshItem(pkg_name)
elif action == InstallerActions.UPGRADE:
pkg_info = [
(pkg.split('==')[0], pkg.split('==')[1])
for pkg in process_finished_data['pkgs']
]
for pkg_name, pkg_version in pkg_info:
self.installed_list.refreshItem(pkg_name, version=pkg_version)
self._tag_outdated_plugins()
elif action in [InstallerActions.CANCEL, InstallerActions.CANCEL_ALL]:
for pkg_name in pkg_names:
self.installed_list.refreshItem(pkg_name)
self.available_list.refreshItem(pkg_name)
self._tag_outdated_plugins()
self.working_indicator.hide()
if exit_code:
self.process_error_indicator.show()
else:
self.process_success_indicator.show()