GUIElements.py 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File Modified (major mod): Marius Adrian Stanciu #
  10. # Date: 3/10/2019 #
  11. # ##########################################################
  12. from PyQt5 import QtGui, QtCore, QtWidgets
  13. from PyQt5.QtCore import Qt, pyqtSlot, QSettings
  14. from PyQt5.QtWidgets import QTextEdit, QCompleter, QAction
  15. from PyQt5.QtGui import QKeySequence, QTextCursor
  16. from copy import copy
  17. import re
  18. import logging
  19. import html
  20. import gettext
  21. import FlatCAMTranslation as fcTranslate
  22. import builtins
  23. log = logging.getLogger('base')
  24. fcTranslate.apply_language('strings')
  25. if '_' not in builtins.__dict__:
  26. _ = gettext.gettext
  27. EDIT_SIZE_HINT = 70
  28. class RadioSet(QtWidgets.QWidget):
  29. activated_custom = QtCore.pyqtSignal(str)
  30. def __init__(self, choices, orientation='horizontal', parent=None, stretch=None):
  31. """
  32. The choices are specified as a list of dictionaries containing:
  33. * 'label': Shown in the UI
  34. * 'value': The value returned is selected
  35. :param choices: List of choices. See description.
  36. :param orientation: 'horizontal' (default) of 'vertical'.
  37. :param parent: Qt parent widget.
  38. :type choices: list
  39. """
  40. super(RadioSet, self).__init__(parent)
  41. self.choices = copy(choices)
  42. if orientation == 'horizontal':
  43. layout = QtWidgets.QHBoxLayout()
  44. else:
  45. layout = QtWidgets.QVBoxLayout()
  46. group = QtWidgets.QButtonGroup(self)
  47. for choice in self.choices:
  48. choice['radio'] = QtWidgets.QRadioButton(choice['label'])
  49. group.addButton(choice['radio'])
  50. layout.addWidget(choice['radio'], stretch=0)
  51. choice['radio'].toggled.connect(self.on_toggle)
  52. layout.setContentsMargins(0, 0, 0, 0)
  53. if stretch is False:
  54. pass
  55. else:
  56. layout.addStretch()
  57. self.setLayout(layout)
  58. self.group_toggle_fn = lambda: None
  59. def on_toggle(self):
  60. # log.debug("Radio toggled")
  61. radio = self.sender()
  62. if radio.isChecked():
  63. self.group_toggle_fn()
  64. ret_val = str(self.get_value())
  65. self.activated_custom.emit(ret_val)
  66. return
  67. def get_value(self):
  68. for choice in self.choices:
  69. if choice['radio'].isChecked():
  70. return choice['value']
  71. log.error("No button was toggled in RadioSet.")
  72. return None
  73. def set_value(self, val):
  74. for choice in self.choices:
  75. if choice['value'] == val:
  76. choice['radio'].setChecked(True)
  77. return
  78. log.error("Value given is not part of this RadioSet: %s" % str(val))
  79. # class RadioGroupChoice(QtWidgets.QWidget):
  80. # def __init__(self, label_1, label_2, to_check, hide_list, show_list, parent=None):
  81. # """
  82. # The choices are specified as a list of dictionaries containing:
  83. #
  84. # * 'label': Shown in the UI
  85. # * 'value': The value returned is selected
  86. #
  87. # :param choices: List of choices. See description.
  88. # :param orientation: 'horizontal' (default) of 'vertical'.
  89. # :param parent: Qt parent widget.
  90. # :type choices: list
  91. # """
  92. # super().__init__(parent)
  93. #
  94. # group = QtGui.QButtonGroup(self)
  95. #
  96. # self.lbl1 = label_1
  97. # self.lbl2 = label_2
  98. # self.hide_list = hide_list
  99. # self.show_list = show_list
  100. #
  101. # self.btn1 = QtGui.QRadioButton(str(label_1))
  102. # self.btn2 = QtGui.QRadioButton(str(label_2))
  103. # group.addButton(self.btn1)
  104. # group.addButton(self.btn2)
  105. #
  106. # if to_check == 1:
  107. # self.btn1.setChecked(True)
  108. # else:
  109. # self.btn2.setChecked(True)
  110. #
  111. # self.btn1.toggled.connect(lambda: self.btn_state(self.btn1))
  112. # self.btn2.toggled.connect(lambda: self.btn_state(self.btn2))
  113. #
  114. # def btn_state(self, btn):
  115. # if btn.text() == self.lbl1:
  116. # if btn.isChecked() is True:
  117. # self.show_widgets(self.show_list)
  118. # self.hide_widgets(self.hide_list)
  119. # else:
  120. # self.show_widgets(self.hide_list)
  121. # self.hide_widgets(self.show_list)
  122. #
  123. # def hide_widgets(self, lst):
  124. # for wgt in lst:
  125. # wgt.hide()
  126. #
  127. # def show_widgets(self, lst):
  128. # for wgt in lst:
  129. # wgt.show()
  130. class FCTree(QtWidgets.QTreeWidget):
  131. resize_sig = QtCore.pyqtSignal()
  132. def __init__(self, parent=None, columns=2, header_hidden=True, extended_sel=False, protected_column=None):
  133. super(FCTree, self).__init__(parent)
  134. self.setColumnCount(columns)
  135. self.setHeaderHidden(header_hidden)
  136. self.header().setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  137. self.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Expanding)
  138. palette = QtGui.QPalette()
  139. palette.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.Highlight,
  140. palette.color(QtGui.QPalette.Active, QtGui.QPalette.Highlight))
  141. # make inactive rows text some color as active; may be useful in the future
  142. # palette.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.HighlightedText,
  143. # palette.color(QtGui.QPalette.Active, QtGui.QPalette.HighlightedText))
  144. self.setPalette(palette)
  145. if extended_sel:
  146. self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  147. self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  148. self.protected_column = protected_column
  149. self.itemDoubleClicked.connect(self.on_double_click)
  150. self.header().sectionDoubleClicked.connect(self.on_header_double_click)
  151. self.resize_sig.connect(self.on_resize)
  152. def on_double_click(self, item, column):
  153. # from here: https://stackoverflow.com/questions/2801959/making-only-one-column-of-a-qtreewidgetitem-editable
  154. tmp_flags = item.flags()
  155. if self.is_editable(column):
  156. item.setFlags(tmp_flags | QtCore.Qt.ItemIsEditable)
  157. elif tmp_flags & QtCore.Qt.ItemIsEditable:
  158. item.setFlags(tmp_flags ^ QtCore.Qt.ItemIsEditable)
  159. def on_header_double_click(self, column):
  160. header = self.header()
  161. header.setSectionResizeMode(column, QtWidgets.QHeaderView.ResizeToContents)
  162. width = header.sectionSize(column)
  163. header.setSectionResizeMode(column, QtWidgets.QHeaderView.Interactive)
  164. header.resizeSection(column, width)
  165. def is_editable(self, tested_col):
  166. try:
  167. ret_val = False if tested_col in self.protected_column else True
  168. except TypeError:
  169. ret_val = False
  170. return ret_val
  171. def addParent(self, parent, title, expanded=False, color=None, font=None):
  172. item = QtWidgets.QTreeWidgetItem(parent, [title])
  173. item.setChildIndicatorPolicy(QtWidgets.QTreeWidgetItem.ShowIndicator)
  174. item.setExpanded(expanded)
  175. if color is not None:
  176. # item.setTextColor(0, color) # PyQt4
  177. item.setForeground(0, QtGui.QBrush(color))
  178. if font is not None:
  179. item.setFont(0, font)
  180. return item
  181. def addParentEditable(self, parent, title, color=None, font=None, font_items=None, editable=False):
  182. item = QtWidgets.QTreeWidgetItem(parent)
  183. item.setChildIndicatorPolicy(QtWidgets.QTreeWidgetItem.DontShowIndicator)
  184. if editable:
  185. item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
  186. item.setFlags(item.flags() | QtCore.Qt.ItemIsSelectable)
  187. for t in range(len(title)):
  188. item.setText(t, title[t])
  189. if color is not None:
  190. # item.setTextColor(0, color) # PyQt4
  191. item.setForeground(0, QtGui.QBrush(color))
  192. if font and font_items:
  193. try:
  194. for fi in font_items:
  195. item.setFont(fi, font)
  196. except TypeError:
  197. item.setFont(font_items, font)
  198. elif font:
  199. item.setFont(0, font)
  200. return item
  201. def addChild(self, parent, title, column1=None, font=None, font_items=None, editable=False):
  202. item = QtWidgets.QTreeWidgetItem(parent)
  203. if editable:
  204. item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
  205. item.setText(0, str(title[0]))
  206. if column1 is not None:
  207. item.setText(1, str(title[1]))
  208. if font and font_items:
  209. try:
  210. for fi in font_items:
  211. item.setFont(fi, font)
  212. except TypeError:
  213. item.setFont(font_items, font)
  214. def resizeEvent(self, event):
  215. """ Resize all sections to content and user interactive """
  216. super(FCTree, self).resizeEvent(event)
  217. self.on_resize()
  218. def on_resize(self):
  219. header = self.header()
  220. for column in range(header.count()):
  221. header.setSectionResizeMode(column, QtWidgets.QHeaderView.ResizeToContents)
  222. width = header.sectionSize(column)
  223. header.setSectionResizeMode(column, QtWidgets.QHeaderView.Interactive)
  224. header.resizeSection(column, width)
  225. class LengthEntry(QtWidgets.QLineEdit):
  226. def __init__(self, output_units='IN', decimals=None, parent=None):
  227. super(LengthEntry, self).__init__(parent)
  228. self.output_units = output_units
  229. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  230. # Unit conversion table OUTPUT-INPUT
  231. self.scales = {
  232. 'IN': {'IN': 1.0,
  233. 'MM': 1/25.4},
  234. 'MM': {'IN': 25.4,
  235. 'MM': 1.0}
  236. }
  237. self.readyToEdit = True
  238. self.editingFinished.connect(self.on_edit_finished)
  239. self.decimals = decimals if decimals is not None else 4
  240. def on_edit_finished(self):
  241. self.clearFocus()
  242. def mousePressEvent(self, e, Parent=None):
  243. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  244. if self.readyToEdit:
  245. self.selectAll()
  246. self.readyToEdit = False
  247. def focusOutEvent(self, e):
  248. # don't focus out if the user requests an popup menu
  249. if e.reason() != QtCore.Qt.PopupFocusReason:
  250. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  251. self.deselect()
  252. self.readyToEdit = True
  253. def returnPressed(self, *args, **kwargs):
  254. val = self.get_value()
  255. if val is not None:
  256. self.set_text(str(val))
  257. else:
  258. log.warning("Could not interpret entry: %s" % self.get_text())
  259. def get_value(self):
  260. raw = str(self.text()).strip(' ')
  261. # match = self.format_re.search(raw)
  262. try:
  263. units = raw[-2:]
  264. units = self.scales[self.output_units][units.upper()]
  265. value = raw[:-2]
  266. return float(eval(value)) * units
  267. except IndexError:
  268. value = raw
  269. return float(eval(value))
  270. except KeyError:
  271. value = raw
  272. return float(eval(value))
  273. except Exception:
  274. log.warning("Could not parse value in entry: %s" % str(raw))
  275. return None
  276. def set_value(self, val, decimals=None):
  277. dec_digits = decimals if decimals is not None else self.decimals
  278. self.setText(str('%.*f' % (dec_digits, val)))
  279. def sizeHint(self):
  280. default_hint_size = super(LengthEntry, self).sizeHint()
  281. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  282. class FloatEntry(QtWidgets.QLineEdit):
  283. def __init__(self, decimals=None, parent=None):
  284. super(FloatEntry, self).__init__(parent)
  285. self.readyToEdit = True
  286. self.editingFinished.connect(self.on_edit_finished)
  287. self.decimals = decimals if decimals is not None else 4
  288. def on_edit_finished(self):
  289. self.clearFocus()
  290. def mousePressEvent(self, e, Parent=None):
  291. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  292. if self.readyToEdit is True:
  293. self.selectAll()
  294. self.readyToEdit = False
  295. def focusOutEvent(self, e):
  296. # don't focus out if the user requests an popup menu
  297. if e.reason() != QtCore.Qt.PopupFocusReason:
  298. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  299. self.deselect()
  300. self.readyToEdit = True
  301. def returnPressed(self, *args, **kwargs):
  302. val = self.get_value()
  303. if val is not None:
  304. self.set_text(str(val))
  305. else:
  306. log.warning("Could not interpret entry: %s" % self.text())
  307. def get_value(self):
  308. raw = str(self.text()).strip(' ')
  309. try:
  310. evaled = eval(raw)
  311. return float(evaled)
  312. except Exception as e:
  313. if raw != '':
  314. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  315. return None
  316. def set_value(self, val, decimals=None):
  317. dig_digits = decimals if decimals is not None else self.decimals
  318. if val is not None:
  319. self.setText("%.*f" % (dig_digits, float(val)))
  320. else:
  321. self.setText("")
  322. def sizeHint(self):
  323. default_hint_size = super(FloatEntry, self).sizeHint()
  324. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  325. class FloatEntry2(QtWidgets.QLineEdit):
  326. def __init__(self, decimals=None, parent=None):
  327. super(FloatEntry2, self).__init__(parent)
  328. self.readyToEdit = True
  329. self.editingFinished.connect(self.on_edit_finished)
  330. self.decimals = decimals if decimals is not None else 4
  331. def on_edit_finished(self):
  332. self.clearFocus()
  333. def mousePressEvent(self, e, Parent=None):
  334. super(FloatEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  335. if self.readyToEdit:
  336. self.selectAll()
  337. self.readyToEdit = False
  338. def focusOutEvent(self, e):
  339. # don't focus out if the user requests an popup menu
  340. if e.reason() != QtCore.Qt.PopupFocusReason:
  341. super(FloatEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  342. self.deselect()
  343. self.readyToEdit = True
  344. def get_value(self):
  345. raw = str(self.text()).strip(' ')
  346. try:
  347. evaled = eval(raw)
  348. return float(evaled)
  349. except Exception as e:
  350. if raw != '':
  351. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  352. return None
  353. def set_value(self, val, decimals=None):
  354. dig_digits = decimals if decimals is not None else self.decimals
  355. self.setText("%.*f" % (dig_digits, val))
  356. def sizeHint(self):
  357. default_hint_size = super(FloatEntry2, self).sizeHint()
  358. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  359. class IntEntry(QtWidgets.QLineEdit):
  360. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  361. super(IntEntry, self).__init__(parent)
  362. self.allow_empty = allow_empty
  363. self.empty_val = empty_val
  364. self.readyToEdit = True
  365. self.editingFinished.connect(self.on_edit_finished)
  366. def on_edit_finished(self):
  367. self.clearFocus()
  368. def mousePressEvent(self, e, Parent=None):
  369. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  370. if self.readyToEdit:
  371. self.selectAll()
  372. self.readyToEdit = False
  373. def focusOutEvent(self, e):
  374. # don't focus out if the user requests an popup menu
  375. if e.reason() != QtCore.Qt.PopupFocusReason:
  376. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  377. self.deselect()
  378. self.readyToEdit = True
  379. def get_value(self):
  380. if self.allow_empty:
  381. if str(self.text()) == "":
  382. return self.empty_val
  383. # make the text() first a float and then int because if text is a float type,
  384. # the int() can't convert directly a "text float" into a int type.
  385. ret_val = float(self.text())
  386. ret_val = int(ret_val)
  387. return ret_val
  388. def set_value(self, val):
  389. if val == self.empty_val and self.allow_empty:
  390. self.setText("")
  391. return
  392. self.setText(str(val))
  393. def sizeHint(self):
  394. default_hint_size = super(IntEntry, self).sizeHint()
  395. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  396. class FCEntry(QtWidgets.QLineEdit):
  397. def __init__(self, decimals=None, alignment=None, border_color=None, parent=None):
  398. super(FCEntry, self).__init__(parent)
  399. self.readyToEdit = True
  400. self.editingFinished.connect(self.on_edit_finished)
  401. self.decimals = decimals if decimals is not None else 4
  402. if border_color:
  403. self.setStyleSheet("QLineEdit {border: 1px solid %s;}" % border_color)
  404. if alignment:
  405. if alignment == 'center':
  406. align_val = QtCore.Qt.AlignHCenter
  407. elif alignment == 'right':
  408. align_val = QtCore.Qt.AlignRight
  409. else:
  410. align_val = QtCore.Qt.AlignLeft
  411. self.setAlignment(align_val)
  412. def on_edit_finished(self):
  413. self.clearFocus()
  414. def mousePressEvent(self, e, parent=None):
  415. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  416. if self.readyToEdit:
  417. self.selectAll()
  418. self.readyToEdit = False
  419. def focusOutEvent(self, e):
  420. if e.reason() != QtCore.Qt.PopupFocusReason:
  421. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  422. self.deselect()
  423. self.readyToEdit = True
  424. def get_value(self):
  425. return str(self.text())
  426. def set_value(self, val, decimals=None):
  427. decimal_digits = decimals if decimals is not None else self.decimals
  428. if type(val) is float:
  429. self.setText('%.*f' % (decimal_digits, val))
  430. elif val is None:
  431. self.setText('')
  432. else:
  433. self.setText(str(val))
  434. def sizeHint(self):
  435. default_hint_size = super(FCEntry, self).sizeHint()
  436. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  437. class FCEntry2(FCEntry):
  438. def __init__(self, parent=None):
  439. super(FCEntry2, self).__init__(parent)
  440. def set_value(self, val, decimals=4):
  441. try:
  442. fval = float(val)
  443. except ValueError:
  444. return
  445. self.setText('%.*f' % (decimals, fval))
  446. class FCEntry3(FCEntry):
  447. def __init__(self, parent=None):
  448. super(FCEntry3, self).__init__(parent)
  449. def set_value(self, val, decimals=4):
  450. try:
  451. fval = float(val)
  452. except ValueError:
  453. return
  454. self.setText('%.*f' % (decimals, fval))
  455. def get_value(self):
  456. value = str(self.text()).strip(' ')
  457. try:
  458. return float(eval(value))
  459. except Exception as e:
  460. log.warning("Could not parse value in entry: %s" % str(e))
  461. return None
  462. class EvalEntry(QtWidgets.QLineEdit):
  463. def __init__(self, parent=None):
  464. super(EvalEntry, self).__init__(parent)
  465. self.readyToEdit = True
  466. self.editingFinished.connect(self.on_edit_finished)
  467. def on_edit_finished(self):
  468. self.clearFocus()
  469. def mousePressEvent(self, e, parent=None):
  470. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  471. if self.readyToEdit:
  472. self.selectAll()
  473. self.readyToEdit = False
  474. def focusOutEvent(self, e):
  475. if e.reason() != QtCore.Qt.PopupFocusReason:
  476. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  477. self.deselect()
  478. self.readyToEdit = True
  479. def returnPressed(self, *args, **kwargs):
  480. val = self.get_value()
  481. if val is not None:
  482. self.setText(str(val))
  483. else:
  484. log.warning("Could not interpret entry: %s" % self.get_text())
  485. def get_value(self):
  486. raw = str(self.text()).strip(' ')
  487. evaled = 0.0
  488. try:
  489. evaled = eval(raw)
  490. except Exception as e:
  491. if raw != '':
  492. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  493. return None
  494. return evaled
  495. def set_value(self, val):
  496. self.setText(str(val))
  497. def sizeHint(self):
  498. default_hint_size = super(EvalEntry, self).sizeHint()
  499. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  500. class EvalEntry2(QtWidgets.QLineEdit):
  501. def __init__(self, parent=None):
  502. super(EvalEntry2, self).__init__(parent)
  503. self.readyToEdit = True
  504. self.editingFinished.connect(self.on_edit_finished)
  505. def on_edit_finished(self):
  506. self.clearFocus()
  507. def mousePressEvent(self, e, parent=None):
  508. super(EvalEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  509. if self.readyToEdit:
  510. self.selectAll()
  511. self.readyToEdit = False
  512. def focusOutEvent(self, e):
  513. if e.reason() != QtCore.Qt.PopupFocusReason:
  514. super(EvalEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  515. self.deselect()
  516. self.readyToEdit = True
  517. def get_value(self):
  518. raw = str(self.text()).strip(' ')
  519. evaled = 0.0
  520. try:
  521. evaled = eval(raw)
  522. except Exception as e:
  523. if raw != '':
  524. log.error("Could not evaluate val: %s, error: %s" % (str(raw), str(e)))
  525. return None
  526. return evaled
  527. def set_value(self, val):
  528. self.setText(str(val))
  529. def sizeHint(self):
  530. default_hint_size = super(EvalEntry2, self).sizeHint()
  531. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  532. class FCColorEntry(QtWidgets.QFrame):
  533. def __init__(self, **kwargs):
  534. super().__init__(**kwargs)
  535. self.entry = FCEntry()
  536. self.button = QtWidgets.QPushButton()
  537. self.button.setFixedSize(15, 15)
  538. self.button.setStyleSheet("border-color: dimgray;")
  539. self.layout = QtWidgets.QHBoxLayout()
  540. self.layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  541. self.layout.setContentsMargins(0, 0, 0, 0)
  542. self.layout.addWidget(self.entry)
  543. self.layout.addWidget(self.button)
  544. self.setLayout(self.layout)
  545. self.entry.editingFinished.connect(self._sync_button_color)
  546. self.button.clicked.connect(self._on_button_clicked)
  547. def get_value(self) -> str:
  548. return self.entry.get_value()
  549. def set_value(self, value: str):
  550. self.entry.set_value(value)
  551. self._sync_button_color()
  552. def _sync_button_color(self):
  553. value = self.get_value()
  554. self.button.setStyleSheet("background-color:%s;" % self._extract_color(value))
  555. def _on_button_clicked(self):
  556. value = self.entry.get_value()
  557. current_color = QtGui.QColor(self._extract_color(value))
  558. color_dialog = QtWidgets.QColorDialog()
  559. selected_color = color_dialog.getColor(initial=current_color, options=QtWidgets.QColorDialog.ShowAlphaChannel)
  560. if selected_color.isValid() is False:
  561. return
  562. new_value = str(selected_color.name()) + self._extract_alpha(value)
  563. self.set_value(new_value)
  564. def _extract_color(self, value: str) -> str:
  565. return value[:7]
  566. def _extract_alpha(self, value: str) -> str:
  567. return value[7:9]
  568. class FCSliderWithSpinner(QtWidgets.QFrame):
  569. def __init__(self, min=0, max=100, step=1, **kwargs):
  570. super().__init__(**kwargs)
  571. self.slider = QtWidgets.QSlider(QtCore.Qt.Horizontal)
  572. self.slider.setMinimum(min)
  573. self.slider.setMaximum(max)
  574. self.slider.setSingleStep(step)
  575. self.spinner = FCSpinner()
  576. self.spinner.set_range(min, max)
  577. self.spinner.set_step(step)
  578. self.spinner.setMinimumWidth(70)
  579. self.layout = QtWidgets.QHBoxLayout()
  580. self.layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  581. self.layout.setContentsMargins(0, 0, 0, 0)
  582. self.layout.addWidget(self.slider)
  583. self.layout.addWidget(self.spinner)
  584. self.setLayout(self.layout)
  585. self.slider.valueChanged.connect(self._on_slider)
  586. self.spinner.valueChanged.connect(self._on_spinner)
  587. def get_value(self) -> int:
  588. return self.spinner.get_value()
  589. def set_value(self, value: int):
  590. self.spinner.set_value(value)
  591. def _on_spinner(self):
  592. spinner_value = self.spinner.value()
  593. self.slider.setValue(spinner_value)
  594. def _on_slider(self):
  595. slider_value = self.slider.value()
  596. self.spinner.set_value(slider_value)
  597. class FCSpinner(QtWidgets.QSpinBox):
  598. returnPressed = QtCore.pyqtSignal()
  599. confirmation_signal = QtCore.pyqtSignal(bool, float, float)
  600. def __init__(self, suffix=None, alignment=None, parent=None, callback=None):
  601. super(FCSpinner, self).__init__(parent)
  602. self.readyToEdit = True
  603. self.editingFinished.connect(self.on_edit_finished)
  604. if callback:
  605. self.confirmation_signal.connect(callback)
  606. self.lineEdit().installEventFilter(self)
  607. if suffix:
  608. self.setSuffix(' %s' % str(suffix))
  609. if alignment:
  610. if alignment == 'center':
  611. align_val = QtCore.Qt.AlignHCenter
  612. elif alignment == 'right':
  613. align_val = QtCore.Qt.AlignRight
  614. else:
  615. align_val = QtCore.Qt.AlignLeft
  616. self.setAlignment(align_val)
  617. self.prev_readyToEdit = True
  618. def eventFilter(self, object, event):
  619. if event.type() == QtCore.QEvent.MouseButtonPress and self.prev_readyToEdit is True:
  620. self.prev_readyToEdit = False
  621. if self.isEnabled():
  622. if self.readyToEdit:
  623. self.lineEdit().selectAll()
  624. self.readyToEdit = False
  625. else:
  626. self.lineEdit().deselect()
  627. return True
  628. return False
  629. def keyPressEvent(self, event):
  630. if event.key() == Qt.Key_Enter:
  631. self.returnPressed.emit()
  632. self.clearFocus()
  633. else:
  634. super().keyPressEvent(event)
  635. def wheelEvent(self, *args, **kwargs):
  636. # should work only there is a focus in the lineedit of the SpinBox
  637. if self.readyToEdit is False:
  638. super().wheelEvent(*args, **kwargs)
  639. def on_edit_finished(self):
  640. self.clearFocus()
  641. self.returnPressed.emit()
  642. # def mousePressEvent(self, e, parent=None):
  643. # super(FCSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  644. # if self.readyToEdit:
  645. # self.lineEdit().selectAll()
  646. # self.readyToEdit = False
  647. def focusOutEvent(self, e):
  648. # don't focus out if the user requests an popup menu
  649. if e.reason() != QtCore.Qt.PopupFocusReason:
  650. super(FCSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  651. self.lineEdit().deselect()
  652. self.readyToEdit = True
  653. self.prev_readyToEdit = True
  654. def valueFromText(self, text):
  655. txt = text.strip('%%')
  656. try:
  657. ret_val = int(txt)
  658. except ValueError:
  659. ret_val = 0
  660. return ret_val
  661. def get_value(self):
  662. return int(self.value())
  663. def set_value(self, val):
  664. try:
  665. k = int(val)
  666. except Exception as e:
  667. log.debug(str(e))
  668. return
  669. self.setValue(k)
  670. def validate(self, p_str, p_int):
  671. text = p_str
  672. min_val = self.minimum()
  673. max_val = self.maximum()
  674. try:
  675. if int(text) < min_val or int(text) > max_val:
  676. self.confirmation_signal.emit(False, min_val, max_val)
  677. return QtGui.QValidator.Intermediate, text, p_int
  678. except ValueError:
  679. pass
  680. self.confirmation_signal.emit(True, min_val, max_val)
  681. return QtGui.QValidator.Acceptable, p_str, p_int
  682. def set_range(self, min_val, max_val):
  683. self.blockSignals(True)
  684. self.setRange(min_val, max_val)
  685. self.blockSignals(False)
  686. def set_step(self, p_int):
  687. self.blockSignals(True)
  688. self.setSingleStep(p_int)
  689. self.blockSignals(False)
  690. # def sizeHint(self):
  691. # default_hint_size = super(FCSpinner, self).sizeHint()
  692. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  693. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  694. returnPressed = QtCore.pyqtSignal()
  695. confirmation_signal = QtCore.pyqtSignal(bool, float, float)
  696. def __init__(self, suffix=None, alignment=None, parent=None, callback=None):
  697. """
  698. :param suffix: a char added to the end of the value in the LineEdit; like a '%' or '$' etc
  699. :param alignment: the value is aligned to left or right
  700. :param parent:
  701. :param callback: called when the entered value is outside limits; the min and max value will be passed to it
  702. """
  703. super(FCDoubleSpinner, self).__init__(parent)
  704. self.readyToEdit = True
  705. self.editingFinished.connect(self.on_edit_finished)
  706. if callback:
  707. self.confirmation_signal.connect(callback)
  708. self.lineEdit().installEventFilter(self)
  709. # by default don't allow the minus sign to be entered as the default for QDoubleSpinBox is the positive range
  710. # between 0.00 and 99.00 (2 decimals)
  711. self.lineEdit().setValidator(
  712. QtGui.QRegExpValidator(QtCore.QRegExp("\+?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  713. if suffix:
  714. self.setSuffix(' %s' % str(suffix))
  715. if alignment:
  716. if alignment == 'center':
  717. align_val = QtCore.Qt.AlignHCenter
  718. elif alignment == 'right':
  719. align_val = QtCore.Qt.AlignRight
  720. else:
  721. align_val = QtCore.Qt.AlignLeft
  722. self.setAlignment(align_val)
  723. self.prev_readyToEdit = True
  724. def on_edit_finished(self):
  725. self.clearFocus()
  726. self.returnPressed.emit()
  727. def eventFilter(self, object, event):
  728. if event.type() == QtCore.QEvent.MouseButtonPress and self.prev_readyToEdit is True:
  729. self.prev_readyToEdit = False
  730. if self.isEnabled():
  731. if self.readyToEdit:
  732. self.cursor_pos = self.lineEdit().cursorPosition()
  733. self.lineEdit().selectAll()
  734. self.readyToEdit = False
  735. else:
  736. self.lineEdit().deselect()
  737. return True
  738. return False
  739. def keyPressEvent(self, event):
  740. if event.key() == Qt.Key_Enter:
  741. self.returnPressed.emit()
  742. self.clearFocus()
  743. else:
  744. super().keyPressEvent(event)
  745. def wheelEvent(self, *args, **kwargs):
  746. # should work only there is a focus in the lineedit of the SpinBox
  747. if self.readyToEdit is False:
  748. super().wheelEvent(*args, **kwargs)
  749. def focusOutEvent(self, e):
  750. # don't focus out if the user requests an popup menu
  751. if e.reason() != QtCore.Qt.PopupFocusReason:
  752. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  753. self.lineEdit().deselect()
  754. self.readyToEdit = True
  755. self.prev_readyToEdit = True
  756. def valueFromText(self, p_str):
  757. text = p_str.replace(',', '.')
  758. text = text.strip('%%')
  759. try:
  760. ret_val = float(text)
  761. except ValueError:
  762. ret_val = 0.0
  763. return ret_val
  764. def validate(self, p_str, p_int):
  765. text = p_str.replace(',', '.')
  766. min_val = self.minimum()
  767. max_val = self.maximum()
  768. try:
  769. if float(text) < min_val or float(text) > max_val:
  770. self.confirmation_signal.emit(False, min_val, max_val)
  771. return QtGui.QValidator.Intermediate, text, p_int
  772. except ValueError:
  773. pass
  774. self.confirmation_signal.emit(True, min_val, max_val)
  775. return QtGui.QValidator.Acceptable, p_str, p_int
  776. def get_value(self):
  777. return float(self.value())
  778. def set_value(self, val):
  779. try:
  780. k = float(val)
  781. except Exception as e:
  782. log.debug(str(e))
  783. return
  784. self.setValue(k)
  785. def set_precision(self, val):
  786. self.setDecimals(val)
  787. # make sure that the user can't type more decimals than the set precision
  788. if self.minimum() < 0 or self.maximum() <= 0:
  789. self.lineEdit().setValidator(
  790. QtGui.QRegExpValidator(QtCore.QRegExp("-?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  791. else:
  792. self.lineEdit().setValidator(
  793. QtGui.QRegExpValidator(QtCore.QRegExp("\+?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  794. def set_range(self, min_val, max_val):
  795. if min_val < 0 or max_val <= 0:
  796. self.lineEdit().setValidator(
  797. QtGui.QRegExpValidator(QtCore.QRegExp("-?[0-9]*[.,]?[0-9]{%d}" % self.decimals()), self))
  798. self.setRange(min_val, max_val)
  799. # def sizeHint(self):
  800. # default_hint_size = super(FCDoubleSpinner, self).sizeHint()
  801. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  802. class FCCheckBox(QtWidgets.QCheckBox):
  803. def __init__(self, label='', parent=None):
  804. super(FCCheckBox, self).__init__(str(label), parent)
  805. def get_value(self):
  806. return self.isChecked()
  807. def set_value(self, val):
  808. self.setChecked(val)
  809. def toggle(self):
  810. self.set_value(not self.get_value())
  811. class FCTextArea(QtWidgets.QPlainTextEdit):
  812. def __init__(self, parent=None):
  813. super(FCTextArea, self).__init__(parent)
  814. def set_value(self, val):
  815. self.setPlainText(val)
  816. def get_value(self):
  817. return str(self.toPlainText())
  818. def sizeHint(self, custom_sizehint=None):
  819. default_hint_size = super(FCTextArea, self).sizeHint()
  820. if custom_sizehint is None:
  821. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  822. else:
  823. return QtCore.QSize(custom_sizehint, default_hint_size.height())
  824. class FCTextAreaRich(QtWidgets.QTextEdit):
  825. def __init__(self, parent=None):
  826. super(FCTextAreaRich, self).__init__(parent)
  827. def set_value(self, val):
  828. self.setText(val)
  829. def get_value(self):
  830. return str(self.toPlainText())
  831. def sizeHint(self):
  832. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  833. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  834. class FCTextAreaExtended(QtWidgets.QTextEdit):
  835. def __init__(self, parent=None):
  836. super().__init__(parent)
  837. self.completer = MyCompleter()
  838. self.model = QtCore.QStringListModel()
  839. self.completer.setModel(self.model)
  840. self.set_model_data(keyword_list=[])
  841. self.completer.insertText.connect(self.insertCompletion)
  842. self.completer.popup().clicked.connect(self.insert_completion_click)
  843. self.completer_enable = False
  844. def set_model_data(self, keyword_list):
  845. self.model.setStringList(keyword_list)
  846. def insert_completion_click(self):
  847. self.completer.insertText.emit(self.completer.getSelected())
  848. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  849. def insertCompletion(self, completion):
  850. tc = self.textCursor()
  851. extra = (len(completion) - len(self.completer.completionPrefix()))
  852. # don't insert if the word is finished but add a space instead
  853. if extra == 0:
  854. tc.insertText(' ')
  855. self.completer.popup().hide()
  856. return
  857. tc.movePosition(QTextCursor.Left)
  858. tc.movePosition(QTextCursor.EndOfWord)
  859. tc.insertText(completion[-extra:])
  860. # add a space after inserting the word
  861. tc.insertText(' ')
  862. self.setTextCursor(tc)
  863. self.completer.popup().hide()
  864. def focusInEvent(self, event):
  865. if self.completer:
  866. self.completer.setWidget(self)
  867. QTextEdit.focusInEvent(self, event)
  868. def set_value(self, val):
  869. self.setText(val)
  870. def get_value(self):
  871. self.toPlainText()
  872. def insertFromMimeData(self, data):
  873. """
  874. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  875. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  876. :param data:
  877. :return:
  878. """
  879. modifier = QtWidgets.QApplication.keyboardModifiers()
  880. if modifier == Qt.ShiftModifier:
  881. text = data.text()
  882. text = text.replace('\\', '/')
  883. self.insertPlainText(text)
  884. else:
  885. self.insertPlainText(data.text())
  886. def keyPressEvent(self, event):
  887. """
  888. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  889. :param event:
  890. :return:
  891. """
  892. key = event.key()
  893. modifier = QtWidgets.QApplication.keyboardModifiers()
  894. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  895. if key == QtCore.Qt.Key_V:
  896. clipboard = QtWidgets.QApplication.clipboard()
  897. clip_text = clipboard.text()
  898. clip_text = clip_text.replace('\\', '/')
  899. self.insertPlainText(clip_text)
  900. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  901. self.comment()
  902. tc = self.textCursor()
  903. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  904. self.completer.insertText.emit(self.completer.getSelected())
  905. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  906. return
  907. elif key == Qt.Key_BraceLeft:
  908. tc.insertText('{}')
  909. self.moveCursor(QtGui.QTextCursor.Left)
  910. elif key == Qt.Key_BracketLeft:
  911. tc.insertText('[]')
  912. self.moveCursor(QtGui.QTextCursor.Left)
  913. elif key == Qt.Key_ParenLeft:
  914. tc.insertText('()')
  915. self.moveCursor(QtGui.QTextCursor.Left)
  916. elif key == Qt.Key_BraceRight:
  917. tc.select(QtGui.QTextCursor.WordUnderCursor)
  918. if tc.selectedText() == '}':
  919. tc.movePosition(QTextCursor.Right)
  920. self.setTextCursor(tc)
  921. else:
  922. tc.clearSelection()
  923. self.textCursor().insertText('}')
  924. elif key == Qt.Key_BracketRight:
  925. tc.select(QtGui.QTextCursor.WordUnderCursor)
  926. if tc.selectedText() == ']':
  927. tc.movePosition(QTextCursor.Right)
  928. self.setTextCursor(tc)
  929. else:
  930. tc.clearSelection()
  931. self.textCursor().insertText(']')
  932. elif key == Qt.Key_ParenRight:
  933. tc.select(QtGui.QTextCursor.WordUnderCursor)
  934. if tc.selectedText() == ')':
  935. tc.movePosition(QTextCursor.Right)
  936. self.setTextCursor(tc)
  937. else:
  938. tc.clearSelection()
  939. self.textCursor().insertText(')')
  940. else:
  941. super(FCTextAreaExtended, self).keyPressEvent(event)
  942. if self.completer_enable:
  943. tc.select(QTextCursor.WordUnderCursor)
  944. cr = self.cursorRect()
  945. if len(tc.selectedText()) > 0:
  946. self.completer.setCompletionPrefix(tc.selectedText())
  947. popup = self.completer.popup()
  948. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  949. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  950. + self.completer.popup().verticalScrollBar().sizeHint().width())
  951. self.completer.complete(cr)
  952. else:
  953. self.completer.popup().hide()
  954. def comment(self):
  955. """
  956. Got it from here:
  957. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  958. :return:
  959. """
  960. pos = self.textCursor().position()
  961. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  962. line_text = self.textCursor().block().text()
  963. if self.textCursor().block().text().startswith(" "):
  964. # skip the white space
  965. self.moveCursor(QtGui.QTextCursor.NextWord)
  966. self.moveCursor(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
  967. character = self.textCursor().selectedText()
  968. if character == "#":
  969. # delete #
  970. self.textCursor().deletePreviousChar()
  971. # delete white space
  972. self.moveCursor(QtGui.QTextCursor.NextWord, QtGui.QTextCursor.KeepAnchor)
  973. self.textCursor().removeSelectedText()
  974. else:
  975. self.moveCursor(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
  976. self.textCursor().insertText("# ")
  977. cursor = QtGui.QTextCursor(self.textCursor())
  978. cursor.setPosition(pos)
  979. self.setTextCursor(cursor)
  980. class FCPlainTextAreaExtended(QtWidgets.QPlainTextEdit):
  981. def __init__(self, parent=None):
  982. super().__init__(parent)
  983. self.completer = MyCompleter()
  984. self.model = QtCore.QStringListModel()
  985. self.completer.setModel(self.model)
  986. self.set_model_data(keyword_list=[])
  987. self.completer.insertText.connect(self.insertCompletion)
  988. self.completer.popup().clicked.connect(self.insert_completion_click)
  989. self.completer_enable = False
  990. def append(self, text):
  991. """
  992. Added this to make this subclass compatible with FCTextAreaExtended
  993. :param text: string
  994. :return:
  995. """
  996. self.appendPlainText(text)
  997. def set_model_data(self, keyword_list):
  998. self.model.setStringList(keyword_list)
  999. def insert_completion_click(self):
  1000. self.completer.insertText.emit(self.completer.getSelected())
  1001. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1002. def insertCompletion(self, completion):
  1003. tc = self.textCursor()
  1004. extra = (len(completion) - len(self.completer.completionPrefix()))
  1005. # don't insert if the word is finished but add a space instead
  1006. if extra == 0:
  1007. tc.insertText(' ')
  1008. self.completer.popup().hide()
  1009. return
  1010. tc.movePosition(QTextCursor.Left)
  1011. tc.movePosition(QTextCursor.EndOfWord)
  1012. tc.insertText(completion[-extra:])
  1013. # add a space after inserting the word
  1014. tc.insertText(' ')
  1015. self.setTextCursor(tc)
  1016. self.completer.popup().hide()
  1017. def focusInEvent(self, event):
  1018. if self.completer:
  1019. self.completer.setWidget(self)
  1020. QtWidgets.QPlainTextEdit.focusInEvent(self, event)
  1021. def set_value(self, val):
  1022. self.setPlainText(val)
  1023. def get_value(self):
  1024. self.toPlainText()
  1025. def insertFromMimeData(self, data):
  1026. """
  1027. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  1028. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  1029. :param data:
  1030. :return:
  1031. """
  1032. modifier = QtWidgets.QApplication.keyboardModifiers()
  1033. if modifier == Qt.ShiftModifier:
  1034. text = data.text()
  1035. text = text.replace('\\', '/')
  1036. self.insertPlainText(text)
  1037. else:
  1038. self.insertPlainText(data.text())
  1039. def keyPressEvent(self, event):
  1040. """
  1041. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  1042. :param event:
  1043. :return:
  1044. """
  1045. key = event.key()
  1046. modifier = QtWidgets.QApplication.keyboardModifiers()
  1047. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  1048. if key == QtCore.Qt.Key_V:
  1049. clipboard = QtWidgets.QApplication.clipboard()
  1050. clip_text = clipboard.text()
  1051. clip_text = clip_text.replace('\\', '/')
  1052. self.insertPlainText(clip_text)
  1053. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  1054. self.comment()
  1055. tc = self.textCursor()
  1056. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  1057. self.completer.insertText.emit(self.completer.getSelected())
  1058. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1059. return
  1060. elif key == Qt.Key_BraceLeft:
  1061. tc.insertText('{}')
  1062. self.moveCursor(QtGui.QTextCursor.Left)
  1063. elif key == Qt.Key_BracketLeft:
  1064. tc.insertText('[]')
  1065. self.moveCursor(QtGui.QTextCursor.Left)
  1066. elif key == Qt.Key_ParenLeft:
  1067. tc.insertText('()')
  1068. self.moveCursor(QtGui.QTextCursor.Left)
  1069. elif key == Qt.Key_BraceRight:
  1070. tc.select(QtGui.QTextCursor.WordUnderCursor)
  1071. if tc.selectedText() == '}':
  1072. tc.movePosition(QTextCursor.Right)
  1073. self.setTextCursor(tc)
  1074. else:
  1075. tc.clearSelection()
  1076. self.textCursor().insertText('}')
  1077. elif key == Qt.Key_BracketRight:
  1078. tc.select(QtGui.QTextCursor.WordUnderCursor)
  1079. if tc.selectedText() == ']':
  1080. tc.movePosition(QTextCursor.Right)
  1081. self.setTextCursor(tc)
  1082. else:
  1083. tc.clearSelection()
  1084. self.textCursor().insertText(']')
  1085. elif key == Qt.Key_ParenRight:
  1086. tc.select(QtGui.QTextCursor.WordUnderCursor)
  1087. if tc.selectedText() == ')':
  1088. tc.movePosition(QTextCursor.Right)
  1089. self.setTextCursor(tc)
  1090. else:
  1091. tc.clearSelection()
  1092. self.textCursor().insertText(')')
  1093. else:
  1094. super(FCPlainTextAreaExtended, self).keyPressEvent(event)
  1095. if self.completer_enable:
  1096. tc.select(QTextCursor.WordUnderCursor)
  1097. cr = self.cursorRect()
  1098. if len(tc.selectedText()) > 0:
  1099. self.completer.setCompletionPrefix(tc.selectedText())
  1100. popup = self.completer.popup()
  1101. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  1102. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  1103. + self.completer.popup().verticalScrollBar().sizeHint().width())
  1104. self.completer.complete(cr)
  1105. else:
  1106. self.completer.popup().hide()
  1107. def comment(self):
  1108. """
  1109. Got it from here:
  1110. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  1111. :return:
  1112. """
  1113. pos = self.textCursor().position()
  1114. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  1115. line_text = self.textCursor().block().text()
  1116. if self.textCursor().block().text().startswith(" "):
  1117. # skip the white space
  1118. self.moveCursor(QtGui.QTextCursor.NextWord)
  1119. self.moveCursor(QtGui.QTextCursor.NextCharacter, QtGui.QTextCursor.KeepAnchor)
  1120. character = self.textCursor().selectedText()
  1121. if character == "#":
  1122. # delete #
  1123. self.textCursor().deletePreviousChar()
  1124. # delete white space
  1125. self.moveCursor(QtGui.QTextCursor.NextWord, QtGui.QTextCursor.KeepAnchor)
  1126. self.textCursor().removeSelectedText()
  1127. else:
  1128. self.moveCursor(QtGui.QTextCursor.PreviousCharacter, QtGui.QTextCursor.KeepAnchor)
  1129. self.textCursor().insertText("# ")
  1130. cursor = QtGui.QTextCursor(self.textCursor())
  1131. cursor.setPosition(pos)
  1132. self.setTextCursor(cursor)
  1133. class FCComboBox(QtWidgets.QComboBox):
  1134. def __init__(self, parent=None, callback=None):
  1135. super(FCComboBox, self).__init__(parent)
  1136. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  1137. self.view = self.view()
  1138. self.view.viewport().installEventFilter(self)
  1139. self.view.setContextMenuPolicy(Qt.CustomContextMenu)
  1140. self._set_last = False
  1141. self._obj_type = None
  1142. # the callback() will be called on customcontextmenu event and will be be passed 2 parameters:
  1143. # pos = mouse right click click position
  1144. # self = is the combobox object itself
  1145. if callback:
  1146. self.view.customContextMenuRequested.connect(lambda pos: callback(pos, self))
  1147. def eventFilter(self, obj, event):
  1148. if event.type() == QtCore.QEvent.MouseButtonRelease:
  1149. if event.button() == Qt.RightButton:
  1150. return True
  1151. return False
  1152. def wheelEvent(self, *args, **kwargs):
  1153. pass
  1154. def get_value(self):
  1155. return str(self.currentText())
  1156. def set_value(self, val):
  1157. self.setCurrentIndex(self.findText(str(val)))
  1158. @property
  1159. def is_last(self):
  1160. return self._set_last
  1161. @is_last.setter
  1162. def is_last(self, val):
  1163. self._set_last = val
  1164. if self._set_last is True:
  1165. self.model().rowsInserted.connect(self.on_model_changed)
  1166. self.setCurrentIndex(1)
  1167. @property
  1168. def obj_type(self):
  1169. return self._obj_type
  1170. @obj_type.setter
  1171. def obj_type(self, val):
  1172. self._obj_type = val
  1173. def on_model_changed(self, parent, first, last):
  1174. if self.model().data(parent, QtCore.Qt.DisplayRole) == self.obj_type:
  1175. self.setCurrentIndex(first)
  1176. class FCInputDialog(QtWidgets.QInputDialog):
  1177. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None,
  1178. init_val=None):
  1179. super(FCInputDialog, self).__init__(parent)
  1180. self.allow_empty = ok
  1181. self.empty_val = val
  1182. self.val = 0.0
  1183. self.ok = ''
  1184. self.init_value = init_val if init_val else 0.0
  1185. if title is None:
  1186. self.title = 'title'
  1187. else:
  1188. self.title = title
  1189. if text is None:
  1190. self.text = 'text'
  1191. else:
  1192. self.text = text
  1193. if min is None:
  1194. self.min = 0
  1195. else:
  1196. self.min = min
  1197. if max is None:
  1198. self.max = 0
  1199. else:
  1200. self.max = max
  1201. if decimals is None:
  1202. self.decimals = 6
  1203. else:
  1204. self.decimals = decimals
  1205. def get_value(self):
  1206. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  1207. max=self.max, decimals=self.decimals, value=self.init_value)
  1208. return [self.val, self.ok]
  1209. # "Transform", "Enter the Angle value:"
  1210. def set_value(self, val):
  1211. pass
  1212. class FCButton(QtWidgets.QPushButton):
  1213. def __init__(self, parent=None):
  1214. super(FCButton, self).__init__(parent)
  1215. def get_value(self):
  1216. return self.isChecked()
  1217. def set_value(self, val):
  1218. self.setText(str(val))
  1219. class FCLabel(QtWidgets.QLabel):
  1220. clicked = QtCore.pyqtSignal(bool)
  1221. def __init__(self, parent=None):
  1222. super(FCLabel, self).__init__(parent)
  1223. # for the usage of this label as a clickable label, to know that current state
  1224. self.clicked_state = False
  1225. def mousePressEvent(self, event):
  1226. self.clicked_state = not self.clicked_state
  1227. self.clicked.emit(self.clicked_state)
  1228. def get_value(self):
  1229. return self.text()
  1230. def set_value(self, val):
  1231. self.setText(str(val))
  1232. class FCMenu(QtWidgets.QMenu):
  1233. def __init__(self):
  1234. super().__init__()
  1235. self.mouse_is_panning = False
  1236. self.popup_active = False
  1237. def popup(self, pos, action=None):
  1238. super().popup(pos)
  1239. self.mouse_is_panning = False
  1240. self.popup_active = True
  1241. class FCTab(QtWidgets.QTabWidget):
  1242. def __init__(self, parent=None):
  1243. super(FCTab, self).__init__(parent)
  1244. self.setTabsClosable(True)
  1245. self.tabCloseRequested.connect(self.closeTab)
  1246. def deleteTab(self, currentIndex):
  1247. widget = self.widget(currentIndex)
  1248. if widget is not None:
  1249. widget.deleteLater()
  1250. self.removeTab(currentIndex)
  1251. def closeTab(self, currentIndex):
  1252. self.removeTab(currentIndex)
  1253. def protectTab(self, currentIndex):
  1254. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1255. # class FCTabBar(QtWidgets.QTabBar):
  1256. # def tabSizeHint(self, index):
  1257. # size =QtWidgets.QTabBar.tabSizeHint(self, index)
  1258. # w = int(self.width()/self.count())
  1259. # return QtCore.QSize(w, size.height())
  1260. class FCDetachableTab(QtWidgets.QTabWidget):
  1261. """
  1262. From here:
  1263. https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  1264. """
  1265. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1266. super().__init__()
  1267. self.tabBar = self.FCTabBar(self)
  1268. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  1269. self.tabBar.onCloseTabSignal.connect(self.on_closetab_middle_button)
  1270. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  1271. self.set_detachable(val=True)
  1272. self.setTabBar(self.tabBar)
  1273. # Used to keep a reference to detached tabs since their QMainWindow
  1274. # does not have a parent
  1275. self.detachedTabs = {}
  1276. # a way to make sure that tabs can't be closed after they attach to the parent tab
  1277. self.protect_tab = True if protect is not None and protect is True else False
  1278. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  1279. # Close all detached tabs if the application is closed explicitly
  1280. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  1281. # used by the property self.useOldIndex(param)
  1282. self.use_old_index = None
  1283. self.old_index = None
  1284. self.setTabsClosable(True)
  1285. self.tabCloseRequested.connect(self.closeTab)
  1286. def set_rmb_callback(self, callback):
  1287. """
  1288. :param callback: Function to call on right mouse click on tab
  1289. :type callback: func
  1290. :return: None
  1291. """
  1292. self.tabBar.right_click.connect(callback)
  1293. def set_detachable(self, val=True):
  1294. try:
  1295. self.tabBar.onDetachTabSignal.disconnect()
  1296. except TypeError:
  1297. pass
  1298. if val is True:
  1299. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  1300. # the tab can be moved around
  1301. self.tabBar.can_be_dragged = True
  1302. else:
  1303. # the detached tab can't be moved
  1304. self.tabBar.can_be_dragged = False
  1305. return val
  1306. def setupContextMenu(self):
  1307. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1308. def addContextMenu(self, entry, call_function, icon=None, initial_checked=False):
  1309. action_name = str(entry)
  1310. action = QtWidgets.QAction(self)
  1311. action.setCheckable(True)
  1312. action.setText(action_name)
  1313. if icon:
  1314. assert isinstance(icon, QtGui.QIcon), \
  1315. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1316. action.setIcon(icon)
  1317. action.setChecked(initial_checked)
  1318. self.addAction(action)
  1319. action.triggered.connect(call_function)
  1320. def useOldIndex(self, param):
  1321. if param:
  1322. self.use_old_index = True
  1323. else:
  1324. self.use_old_index = False
  1325. def deleteTab(self, currentIndex):
  1326. widget = self.widget(currentIndex)
  1327. if widget is not None:
  1328. widget.deleteLater()
  1329. self.removeTab(currentIndex)
  1330. def closeTab(self, currentIndex):
  1331. """
  1332. Slot connected to the tabCloseRequested signal
  1333. :param currentIndex:
  1334. :return:
  1335. """
  1336. self.removeTab(currentIndex)
  1337. def on_closetab_middle_button(self, current_index):
  1338. """
  1339. :param current_index:
  1340. :return:
  1341. """
  1342. # if tab is protected don't delete it
  1343. if self.tabBar.tabButton(current_index, QtWidgets.QTabBar.RightSide) is not None:
  1344. self.removeTab(current_index)
  1345. def protectTab(self, currentIndex):
  1346. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1347. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1348. def setMovable(self, movable):
  1349. """
  1350. The default movable functionality of QTabWidget must remain disabled
  1351. so as not to conflict with the added features
  1352. :param movable:
  1353. :return:
  1354. """
  1355. pass
  1356. @pyqtSlot(int, int)
  1357. def moveTab(self, fromIndex, toIndex):
  1358. """
  1359. Move a tab from one position (index) to another
  1360. :param fromIndex: the original index location of the tab
  1361. :param toIndex: the new index location of the tab
  1362. :return:
  1363. """
  1364. widget = self.widget(fromIndex)
  1365. icon = self.tabIcon(fromIndex)
  1366. text = self.tabText(fromIndex)
  1367. self.removeTab(fromIndex)
  1368. self.insertTab(toIndex, widget, icon, text)
  1369. self.setCurrentIndex(toIndex)
  1370. @pyqtSlot(int, QtCore.QPoint)
  1371. def detachTab(self, index, point):
  1372. """
  1373. Detach the tab by removing it's contents and placing them in
  1374. a DetachedTab window
  1375. :param index: the index location of the tab to be detached
  1376. :param point: the screen position for creating the new DetachedTab window
  1377. :return:
  1378. """
  1379. self.old_index = index
  1380. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  1381. name = "FlatCAM " + self.tabText(index)
  1382. icon = self.tabIcon(index)
  1383. if icon.isNull():
  1384. icon = self.window().windowIcon()
  1385. contentWidget = self.widget(index)
  1386. try:
  1387. contentWidgetRect = contentWidget.frameGeometry()
  1388. except AttributeError:
  1389. return
  1390. # Create a new detached tab window
  1391. detachedTab = self.FCDetachedTab(name, contentWidget)
  1392. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  1393. detachedTab.setWindowIcon(icon)
  1394. detachedTab.setGeometry(contentWidgetRect)
  1395. detachedTab.onCloseSignal.connect(self.attachTab)
  1396. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  1397. detachedTab.move(point)
  1398. detachedTab.show()
  1399. # Create a reference to maintain access to the detached tab
  1400. self.detachedTabs[name] = detachedTab
  1401. def attachTab(self, contentWidget, name, icon, insertAt=None):
  1402. """
  1403. Re-attach the tab by removing the content from the DetachedTab window,
  1404. closing it, and placing the content back into the DetachableTabWidget
  1405. :param contentWidget: the content widget from the DetachedTab window
  1406. :param name: the name of the detached tab
  1407. :param icon: the window icon for the detached tab
  1408. :param insertAt: insert the re-attached tab at the given index
  1409. :return:
  1410. """
  1411. # Make the content widget a child of this widget
  1412. contentWidget.setParent(self)
  1413. # Remove the reference
  1414. del self.detachedTabs[name]
  1415. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  1416. name = name.partition(' ')[2]
  1417. # helps in restoring the tab to the same index that it was before was detached
  1418. insert_index = self.old_index if self.use_old_index is True else insertAt
  1419. # Create an image from the given icon (for comparison)
  1420. if not icon.isNull():
  1421. try:
  1422. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  1423. tabIconImage = tabIconPixmap.toImage()
  1424. except IndexError:
  1425. tabIconImage = None
  1426. else:
  1427. tabIconImage = None
  1428. # Create an image of the main window icon (for comparison)
  1429. if not icon.isNull():
  1430. try:
  1431. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  1432. windowIconImage = windowIconPixmap.toImage()
  1433. except IndexError:
  1434. windowIconImage = None
  1435. else:
  1436. windowIconImage = None
  1437. # Determine if the given image and the main window icon are the same.
  1438. # If they are, then do not add the icon to the tab
  1439. if tabIconImage == windowIconImage:
  1440. if insert_index is None:
  1441. index = self.addTab(contentWidget, name)
  1442. else:
  1443. index = self.insertTab(insert_index, contentWidget, name)
  1444. else:
  1445. if insert_index is None:
  1446. index = self.addTab(contentWidget, icon, name)
  1447. else:
  1448. index = self.insertTab(insert_index, contentWidget, icon, name)
  1449. # on reattaching the tab if protect is true then the closure button is not added
  1450. if self.protect_tab is True:
  1451. self.protectTab(index)
  1452. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  1453. if self.protect_by_name is not None:
  1454. for tab_name in self.protect_by_name:
  1455. for index in range(self.count()):
  1456. if str(tab_name) == str(self.tabText(index)):
  1457. self.protectTab(index)
  1458. # Make this tab the current tab
  1459. if index > -1:
  1460. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  1461. def removeTabByName(self, name):
  1462. """
  1463. Remove the tab with the given name, even if it is detached
  1464. :param name: the name of the tab to be removed
  1465. :return:
  1466. """
  1467. # Remove the tab if it is attached
  1468. attached = False
  1469. for index in range(self.count()):
  1470. if str(name) == str(self.tabText(index)):
  1471. self.removeTab(index)
  1472. attached = True
  1473. break
  1474. # If the tab is not attached, close it's window and
  1475. # remove the reference to it
  1476. if not attached:
  1477. for key in self.detachedTabs:
  1478. if str(name) == str(key):
  1479. self.detachedTabs[key].onCloseSignal.disconnect()
  1480. self.detachedTabs[key].close()
  1481. del self.detachedTabs[key]
  1482. break
  1483. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  1484. def detachedTabDrop(self, name, index, dropPos):
  1485. """
  1486. Handle dropping of a detached tab inside the DetachableTabWidget
  1487. :param name: the name of the detached tab
  1488. :param index: the index of an existing tab (if the tab bar
  1489. # determined that the drop occurred on an
  1490. # existing tab)
  1491. :param dropPos: the mouse cursor position when the drop occurred
  1492. :return:
  1493. """
  1494. # If the drop occurred on an existing tab, insert the detached
  1495. # tab at the existing tab's location
  1496. if index > -1:
  1497. # Create references to the detached tab's content and icon
  1498. contentWidget = self.detachedTabs[name].contentWidget
  1499. icon = self.detachedTabs[name].windowIcon()
  1500. # Disconnect the detached tab's onCloseSignal so that it
  1501. # does not try to re-attach automatically
  1502. self.detachedTabs[name].onCloseSignal.disconnect()
  1503. # Close the detached
  1504. self.detachedTabs[name].close()
  1505. # Re-attach the tab at the given index
  1506. self.attachTab(contentWidget, name, icon, index)
  1507. # If the drop did not occur on an existing tab, determine if the drop
  1508. # occurred in the tab bar area (the area to the side of the QTabBar)
  1509. else:
  1510. # Find the drop position relative to the DetachableTabWidget
  1511. tabDropPos = self.mapFromGlobal(dropPos)
  1512. # If the drop position is inside the DetachableTabWidget...
  1513. if self.rect().contains(tabDropPos):
  1514. # If the drop position is inside the tab bar area (the
  1515. # area to the side of the QTabBar) or there are not tabs
  1516. # currently attached...
  1517. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  1518. # Close the detached tab and allow it to re-attach
  1519. # automatically
  1520. self.detachedTabs[name].close()
  1521. def closeDetachedTabs(self):
  1522. """
  1523. Close all tabs that are currently detached.
  1524. :return:
  1525. """
  1526. listOfDetachedTabs = []
  1527. for key in self.detachedTabs:
  1528. listOfDetachedTabs.append(self.detachedTabs[key])
  1529. for detachedTab in listOfDetachedTabs:
  1530. detachedTab.close()
  1531. class FCDetachedTab(QtWidgets.QMainWindow):
  1532. """
  1533. When a tab is detached, the contents are placed into this QMainWindow. The tab
  1534. can be re-attached by closing the dialog or by dragging the window into the tab bar
  1535. """
  1536. onCloseSignal = QtCore.pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  1537. onDropSignal = QtCore.pyqtSignal(str, QtCore.QPoint)
  1538. def __init__(self, name, contentWidget):
  1539. QtWidgets.QMainWindow.__init__(self, None)
  1540. self.setObjectName(name)
  1541. self.setWindowTitle(name)
  1542. self.contentWidget = contentWidget
  1543. self.setCentralWidget(self.contentWidget)
  1544. self.contentWidget.show()
  1545. self.windowDropFilter = self.WindowDropFilter()
  1546. self.installEventFilter(self.windowDropFilter)
  1547. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  1548. @QtCore.pyqtSlot(QtCore.QPoint)
  1549. def windowDropSlot(self, dropPos):
  1550. """
  1551. Handle a window drop event
  1552. :param dropPos: the mouse cursor position of the drop
  1553. :return:
  1554. """
  1555. self.onDropSignal.emit(self.objectName(), dropPos)
  1556. def closeEvent(self, event):
  1557. """
  1558. If the window is closed, emit the onCloseSignal and give the
  1559. content widget back to the DetachableTabWidget
  1560. :param event: a close event
  1561. :return:
  1562. """
  1563. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  1564. class WindowDropFilter(QtCore.QObject):
  1565. """
  1566. An event filter class to detect a QMainWindow drop event
  1567. """
  1568. onDropSignal = QtCore.pyqtSignal(QtCore.QPoint)
  1569. def __init__(self):
  1570. QtCore.QObject.__init__(self)
  1571. self.lastEvent = None
  1572. def eventFilter(self, obj, event):
  1573. """
  1574. Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  1575. event that immediately follows a Move event
  1576. :param obj: the object that generated the event
  1577. :param event: the current event
  1578. :return:
  1579. """
  1580. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  1581. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  1582. # Determine the position of the mouse cursor and emit it with the
  1583. # onDropSignal
  1584. mouseCursor = QtGui.QCursor()
  1585. dropPos = mouseCursor.pos()
  1586. self.onDropSignal.emit(dropPos)
  1587. self.lastEvent = event.type()
  1588. return True
  1589. else:
  1590. self.lastEvent = event.type()
  1591. return False
  1592. class FCTabBar(QtWidgets.QTabBar):
  1593. onDetachTabSignal = QtCore.pyqtSignal(int, QtCore.QPoint)
  1594. onMoveTabSignal = QtCore.pyqtSignal(int, int)
  1595. detachedTabDropSignal = QtCore.pyqtSignal(str, int, QtCore.QPoint)
  1596. onCloseTabSignal = QtCore.pyqtSignal(int)
  1597. right_click = QtCore.pyqtSignal(int)
  1598. def __init__(self, parent=None):
  1599. QtWidgets.QTabBar.__init__(self, parent)
  1600. self.setAcceptDrops(True)
  1601. self.setElideMode(QtCore.Qt.ElideRight)
  1602. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  1603. self.prev_index = -1
  1604. self.dragStartPos = QtCore.QPoint()
  1605. self.dragDropedPos = QtCore.QPoint()
  1606. self.mouseCursor = QtGui.QCursor()
  1607. self.dragInitiated = False
  1608. # set this to False and the tab will no longer be displayed as detached
  1609. self.can_be_dragged = True
  1610. def mouseDoubleClickEvent(self, event):
  1611. """
  1612. Send the onDetachTabSignal when a tab is double clicked
  1613. :param event: a mouse double click event
  1614. :return:
  1615. """
  1616. event.accept()
  1617. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  1618. def mousePressEvent(self, event):
  1619. """
  1620. Set the starting position for a drag event when the left mouse button is pressed.
  1621. Start detection of a right mouse click.
  1622. :param event: a mouse press event
  1623. :return:
  1624. """
  1625. if event.button() == QtCore.Qt.LeftButton:
  1626. self.dragStartPos = event.pos()
  1627. elif event.button() == QtCore.Qt.RightButton:
  1628. self.prev_index = self.tabAt(event.pos())
  1629. self.dragDropedPos.setX(0)
  1630. self.dragDropedPos.setY(0)
  1631. self.dragInitiated = False
  1632. QtWidgets.QTabBar.mousePressEvent(self, event)
  1633. def mouseReleaseEvent(self, event):
  1634. """
  1635. Finish the detection of the right mouse click on the tab
  1636. :param event: a mouse press event
  1637. :return:
  1638. """
  1639. if event.button() == QtCore.Qt.RightButton and self.prev_index == self.tabAt(event.pos()):
  1640. self.right_click.emit(self.prev_index)
  1641. if event.button() == QtCore.Qt.MiddleButton:
  1642. self.onCloseTabSignal.emit(int(self.tabAt(event.pos())))
  1643. self.prev_index = -1
  1644. QtWidgets.QTabBar.mouseReleaseEvent(self, event)
  1645. def mouseMoveEvent(self, event):
  1646. """
  1647. Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  1648. drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  1649. bar, emit an onDetachTabSignal.
  1650. :param event: a mouse move event
  1651. :return:
  1652. """
  1653. # Determine if the current movement is detected as a drag
  1654. if not self.dragStartPos.isNull() and \
  1655. ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  1656. self.dragInitiated = True
  1657. # If the current movement is a drag initiated by the left button
  1658. if (event.buttons() & QtCore.Qt.LeftButton) and self.dragInitiated and self.can_be_dragged:
  1659. # Stop the move event
  1660. finishMoveEvent = QtGui.QMouseEvent(
  1661. QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier
  1662. )
  1663. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  1664. # Convert the move event into a drag
  1665. drag = QtGui.QDrag(self)
  1666. mimeData = QtCore.QMimeData()
  1667. # mimeData.setData('action', 'application/tab-detach')
  1668. drag.setMimeData(mimeData)
  1669. # screen = QScreen(self.parentWidget().currentWidget().winId())
  1670. # Create the appearance of dragging the tab content
  1671. try:
  1672. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  1673. except Exception as e:
  1674. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  1675. return
  1676. targetPixmap = QtGui.QPixmap(pixmap.size())
  1677. targetPixmap.fill(QtCore.Qt.transparent)
  1678. painter = QtGui.QPainter(targetPixmap)
  1679. painter.setOpacity(0.85)
  1680. painter.drawPixmap(0, 0, pixmap)
  1681. painter.end()
  1682. drag.setPixmap(targetPixmap)
  1683. # Initiate the drag
  1684. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  1685. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  1686. # must be set manually
  1687. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  1688. dropAction = QtCore.Qt.MoveAction
  1689. # If the drag completed outside of the tab bar, detach the tab and move
  1690. # the content to the current cursor position
  1691. if dropAction == QtCore.Qt.IgnoreAction:
  1692. event.accept()
  1693. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  1694. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  1695. elif dropAction == QtCore.Qt.MoveAction:
  1696. if not self.dragDropedPos.isNull():
  1697. event.accept()
  1698. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  1699. else:
  1700. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  1701. def dragEnterEvent(self, event):
  1702. """
  1703. Determine if the drag has entered a tab position from another tab position
  1704. :param event: a drag enter event
  1705. :return:
  1706. """
  1707. mimeData = event.mimeData()
  1708. # formats = mcd imeData.formats()
  1709. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  1710. # event.acceptProposedAction()
  1711. QtWidgets.QTabBar.dragMoveEvent(self, event)
  1712. def dropEvent(self, event):
  1713. """
  1714. Get the position of the end of the drag
  1715. :param event: a drop event
  1716. :return:
  1717. """
  1718. self.dragDropedPos = event.pos()
  1719. QtWidgets.QTabBar.dropEvent(self, event)
  1720. def detachedTabDrop(self, name, dropPos):
  1721. """
  1722. Determine if the detached tab drop event occurred on an existing tab,
  1723. then send the event to the DetachableTabWidget
  1724. :param name:
  1725. :param dropPos:
  1726. :return:
  1727. """
  1728. tabDropPos = self.mapFromGlobal(dropPos)
  1729. index = self.tabAt(tabDropPos)
  1730. self.detachedTabDropSignal.emit(name, index, dropPos)
  1731. class FCDetachableTab2(FCDetachableTab):
  1732. tab_closed_signal = QtCore.pyqtSignal(object, int)
  1733. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1734. super(FCDetachableTab2, self).__init__(protect=protect, protect_by_name=protect_by_name, parent=parent)
  1735. def closeTab(self, currentIndex):
  1736. """
  1737. Slot connected to the tabCloseRequested signal
  1738. :param currentIndex:
  1739. :return:
  1740. """
  1741. # idx = self.currentIndex()
  1742. tab_name = self.widget(currentIndex).objectName()
  1743. self.tab_closed_signal.emit(tab_name, currentIndex)
  1744. self.removeTab(currentIndex)
  1745. class VerticalScrollArea(QtWidgets.QScrollArea):
  1746. """
  1747. This widget extends QtGui.QScrollArea to make a vertical-only
  1748. scroll area that also expands horizontally to accommodate
  1749. its contents.
  1750. """
  1751. def __init__(self, parent=None):
  1752. QtWidgets.QScrollArea.__init__(self, parent=parent)
  1753. self.setWidgetResizable(True)
  1754. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1755. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  1756. def eventFilter(self, source, event):
  1757. """
  1758. The event filter gets automatically installed when setWidget()
  1759. is called.
  1760. :param source:
  1761. :param event:
  1762. :return:
  1763. """
  1764. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  1765. # log.debug("VerticalScrollArea: Widget resized:")
  1766. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  1767. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  1768. self.setMinimumWidth(self.widget().sizeHint().width() +
  1769. self.verticalScrollBar().sizeHint().width())
  1770. # if self.verticalScrollBar().isVisible():
  1771. # log.debug(" Scroll bar visible")
  1772. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  1773. # self.verticalScrollBar().width())
  1774. # else:
  1775. # log.debug(" Scroll bar hidden")
  1776. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  1777. return QtWidgets.QWidget.eventFilter(self, source, event)
  1778. class OptionalInputSection:
  1779. def __init__(self, cb, optinputs, logic=True):
  1780. """
  1781. Associates the a checkbox with a set of inputs.
  1782. :param cb: Checkbox that enables the optional inputs.
  1783. :param optinputs: List of widgets that are optional.
  1784. :param logic: When True the logic is normal, when False the logic is in reverse
  1785. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1786. for logic=False, when the checkbox is checked the widgets are Disabled
  1787. :return:
  1788. """
  1789. assert isinstance(cb, FCCheckBox), \
  1790. "Expected an FCCheckBox, got %s" % type(cb)
  1791. self.cb = cb
  1792. self.optinputs = optinputs
  1793. self.logic = logic
  1794. self.on_cb_change()
  1795. self.cb.stateChanged.connect(self.on_cb_change)
  1796. def on_cb_change(self):
  1797. if self.cb.checkState():
  1798. for widget in self.optinputs:
  1799. if self.logic is True:
  1800. widget.setEnabled(True)
  1801. else:
  1802. widget.setEnabled(False)
  1803. else:
  1804. for widget in self.optinputs:
  1805. if self.logic is True:
  1806. widget.setEnabled(False)
  1807. else:
  1808. widget.setEnabled(True)
  1809. class OptionalHideInputSection:
  1810. def __init__(self, cb, optinputs, logic=True):
  1811. """
  1812. Associates the a checkbox with a set of inputs.
  1813. :param cb: Checkbox that enables the optional inputs.
  1814. :param optinputs: List of widgets that are optional.
  1815. :param logic: When True the logic is normal, when False the logic is in reverse
  1816. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1817. for logic=False, when the checkbox is checked the widgets are Disabled
  1818. :return:
  1819. """
  1820. assert isinstance(cb, FCCheckBox), \
  1821. "Expected an FCCheckBox, got %s" % type(cb)
  1822. self.cb = cb
  1823. self.optinputs = optinputs
  1824. self.logic = logic
  1825. self.on_cb_change()
  1826. self.cb.stateChanged.connect(self.on_cb_change)
  1827. def on_cb_change(self):
  1828. if self.cb.checkState():
  1829. for widget in self.optinputs:
  1830. if self.logic is True:
  1831. widget.show()
  1832. else:
  1833. widget.hide()
  1834. else:
  1835. for widget in self.optinputs:
  1836. if self.logic is True:
  1837. widget.hide()
  1838. else:
  1839. widget.show()
  1840. class FCTable(QtWidgets.QTableWidget):
  1841. drag_drop_sig = QtCore.pyqtSignal()
  1842. def __init__(self, drag_drop=False, protected_rows=None, parent=None):
  1843. super(FCTable, self).__init__(parent)
  1844. palette = QtGui.QPalette()
  1845. palette.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.Highlight,
  1846. palette.color(QtGui.QPalette.Active, QtGui.QPalette.Highlight))
  1847. # make inactive rows text some color as active; may be useful in the future
  1848. # palette.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.HighlightedText,
  1849. # palette.color(QtGui.QPalette.Active, QtGui.QPalette.HighlightedText))
  1850. self.setPalette(palette)
  1851. if drag_drop:
  1852. self.setDragEnabled(True)
  1853. self.setAcceptDrops(True)
  1854. self.viewport().setAcceptDrops(True)
  1855. self.setDragDropOverwriteMode(False)
  1856. self.setDropIndicatorShown(True)
  1857. self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1858. self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1859. self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
  1860. self.rows_not_for_drag_and_drop = []
  1861. if protected_rows:
  1862. try:
  1863. for r in protected_rows:
  1864. self.rows_not_for_drag_and_drop.append(r)
  1865. except TypeError:
  1866. self.rows_not_for_drag_and_drop = [protected_rows]
  1867. self.rows_to_move = []
  1868. def sizeHint(self):
  1869. default_hint_size = super(FCTable, self).sizeHint()
  1870. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1871. def getHeight(self):
  1872. height = self.horizontalHeader().height()
  1873. for i in range(self.rowCount()):
  1874. height += self.rowHeight(i)
  1875. return height
  1876. def getWidth(self):
  1877. width = self.verticalHeader().width()
  1878. for i in range(self.columnCount()):
  1879. width += self.columnWidth(i)
  1880. return width
  1881. # color is in format QtGui.Qcolor(r, g, b, alpha) with or without alpha
  1882. def setColortoRow(self, rowIndex, color):
  1883. for j in range(self.columnCount()):
  1884. self.item(rowIndex, j).setBackground(color)
  1885. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  1886. def mousePressEvent(self, event):
  1887. if not self.itemAt(event.pos()):
  1888. self.clearSelection()
  1889. self.clearFocus()
  1890. else:
  1891. QtWidgets.QTableWidget.mousePressEvent(self, event)
  1892. def setupContextMenu(self):
  1893. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1894. def addContextMenu(self, entry, call_function, icon=None):
  1895. action_name = str(entry)
  1896. action = QtWidgets.QAction(self)
  1897. action.setText(action_name)
  1898. if icon:
  1899. assert isinstance(icon, QtGui.QIcon), \
  1900. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1901. action.setIcon(icon)
  1902. self.addAction(action)
  1903. action.triggered.connect(call_function)
  1904. # def dropEvent(self, event: QtGui.QDropEvent):
  1905. # if not event.isAccepted() and event.source() == self:
  1906. # drop_row = self.drop_on(event)
  1907. #
  1908. # rows = sorted(set(item.row() for item in self.selectedItems()))
  1909. # # rows_to_move = [
  1910. # # [QtWidgets.QTableWidgetItem(self.item(row_index, column_index))
  1911. # # for column_index in range(self.columnCount())] for row_index in rows
  1912. # # ]
  1913. # self.rows_to_move[:] = []
  1914. # for row_index in rows:
  1915. # row_items = []
  1916. # for column_index in range(self.columnCount()):
  1917. # r_item = self.item(row_index, column_index)
  1918. # w_item = self.cellWidget(row_index, column_index)
  1919. #
  1920. # if r_item is not None:
  1921. # row_items.append(QtWidgets.QTableWidgetItem(r_item))
  1922. # elif w_item is not None:
  1923. # row_items.append(w_item)
  1924. #
  1925. # self.rows_to_move.append(row_items)
  1926. #
  1927. # for row_index in reversed(rows):
  1928. # self.removeRow(row_index)
  1929. # if row_index < drop_row:
  1930. # drop_row -= 1
  1931. #
  1932. # for row_index, data in enumerate(self.rows_to_move):
  1933. # row_index += drop_row
  1934. # self.insertRow(row_index)
  1935. #
  1936. # for column_index, column_data in enumerate(data):
  1937. # if isinstance(column_data, QtWidgets.QTableWidgetItem):
  1938. # self.setItem(row_index, column_index, column_data)
  1939. # else:
  1940. # self.setCellWidget(row_index, column_index, column_data)
  1941. #
  1942. # event.accept()
  1943. # for row_index in range(len(self.rows_to_move)):
  1944. # self.item(drop_row + row_index, 0).setSelected(True)
  1945. # self.item(drop_row + row_index, 1).setSelected(True)
  1946. #
  1947. # super().dropEvent(event)
  1948. #
  1949. # def drop_on(self, event):
  1950. # ret_val = False
  1951. # index = self.indexAt(event.pos())
  1952. # if not index.isValid():
  1953. # return self.rowCount()
  1954. #
  1955. # ret_val = index.row() + 1 if self.is_below(event.pos(), index) else index.row()
  1956. #
  1957. # return ret_val
  1958. #
  1959. # def is_below(self, pos, index):
  1960. # rect = self.visualRect(index)
  1961. # margin = 2
  1962. # if pos.y() - rect.top() < margin:
  1963. # return False
  1964. # elif rect.bottom() - pos.y() < margin:
  1965. # return True
  1966. # # noinspection PyTypeChecker
  1967. # return rect.contains(pos, True) and not (
  1968. # int(self.model().flags(index)) & Qt.ItemIsDropEnabled) and pos.y() >= rect.center().y()
  1969. def dropEvent(self, event):
  1970. """
  1971. From here: https://stackoverflow.com/questions/26227885/drag-and-drop-rows-within-qtablewidget
  1972. :param event:
  1973. :return:
  1974. """
  1975. if event.source() == self:
  1976. rows = set([mi.row() for mi in self.selectedIndexes()])
  1977. # if one of the selected rows for drag and drop is within the protected list, return
  1978. for r in rows:
  1979. if r in self.rows_not_for_drag_and_drop:
  1980. return
  1981. targetRow = self.indexAt(event.pos()).row()
  1982. rows.discard(targetRow)
  1983. rows = sorted(rows)
  1984. if not rows:
  1985. return
  1986. if targetRow == -1:
  1987. targetRow = self.rowCount()
  1988. for _ in range(len(rows)):
  1989. self.insertRow(targetRow)
  1990. rowMapping = {} # Src row to target row.
  1991. for idx, row in enumerate(rows):
  1992. if row < targetRow:
  1993. rowMapping[row] = targetRow + idx
  1994. else:
  1995. rowMapping[row + len(rows)] = targetRow + idx
  1996. colCount = self.columnCount()
  1997. for srcRow, tgtRow in sorted(rowMapping.items()):
  1998. for col in range(0, colCount):
  1999. new_item = self.item(srcRow, col)
  2000. if new_item is None:
  2001. new_item = self.cellWidget(srcRow, col)
  2002. if isinstance(new_item, QtWidgets.QTableWidgetItem):
  2003. new_item = self.takeItem(srcRow, col)
  2004. self.setItem(tgtRow, col, new_item)
  2005. else:
  2006. self.setCellWidget(tgtRow, col, new_item)
  2007. for row in reversed(sorted(rowMapping.keys())):
  2008. self.removeRow(row)
  2009. event.accept()
  2010. self.drag_drop_sig.emit()
  2011. return
  2012. class SpinBoxDelegate(QtWidgets.QItemDelegate):
  2013. def __init__(self, units):
  2014. super(SpinBoxDelegate, self).__init__()
  2015. self.units = units
  2016. self.current_value = None
  2017. def createEditor(self, parent, option, index):
  2018. editor = QtWidgets.QDoubleSpinBox(parent)
  2019. editor.setMinimum(-999.9999)
  2020. editor.setMaximum(999.9999)
  2021. if self.units == 'MM':
  2022. editor.setDecimals(2)
  2023. else:
  2024. editor.setDecimals(3)
  2025. return editor
  2026. def setEditorData(self, spinBox, index):
  2027. try:
  2028. value = float(index.model().data(index, Qt.EditRole))
  2029. except ValueError:
  2030. value = self.current_value
  2031. # return
  2032. spinBox.setValue(value)
  2033. def setModelData(self, spinBox, model, index):
  2034. spinBox.interpretText()
  2035. value = spinBox.value()
  2036. self.current_value = value
  2037. model.setData(index, value, Qt.EditRole)
  2038. def updateEditorGeometry(self, editor, option, index):
  2039. editor.setGeometry(option.rect)
  2040. def setDecimals(self, spinbox, digits):
  2041. spinbox.setDecimals(digits)
  2042. class Dialog_box(QtWidgets.QWidget):
  2043. def __init__(self, title=None, label=None, icon=None, initial_text=None):
  2044. """
  2045. :param title: string with the window title
  2046. :param label: string with the message inside the dialog box
  2047. """
  2048. super(Dialog_box, self).__init__()
  2049. if initial_text is None:
  2050. self.location = str((0, 0))
  2051. else:
  2052. self.location = initial_text
  2053. self.ok = False
  2054. self.dialog_box = QtWidgets.QInputDialog()
  2055. self.dialog_box.setMinimumWidth(290)
  2056. self.setWindowIcon(icon)
  2057. self.location, self.ok = self.dialog_box.getText(self, title, label,
  2058. text=str(self.location).replace('(', '').replace(')', ''))
  2059. self.readyToEdit = True
  2060. def mousePressEvent(self, e, parent=None):
  2061. super(Dialog_box, self).mousePressEvent(e) # required to deselect on 2e click
  2062. if self.readyToEdit:
  2063. self.lineEdit().selectAll()
  2064. self.readyToEdit = False
  2065. def focusOutEvent(self, e):
  2066. # don't focus out if the user requests an popup menu
  2067. if e.reason() != QtCore.Qt.PopupFocusReason:
  2068. super(Dialog_box, self).focusOutEvent(e) # required to remove cursor on focusOut
  2069. self.lineEdit().deselect()
  2070. self.readyToEdit = True
  2071. class DialogBoxRadio(QtWidgets.QDialog):
  2072. def __init__(self, title=None, label=None, icon=None, initial_text=None, reference='abs', parent=None):
  2073. """
  2074. :param title: string with the window title
  2075. :param label: string with the message inside the dialog box
  2076. """
  2077. super(DialogBoxRadio, self).__init__()
  2078. if initial_text is None:
  2079. self.location = str((0, 0))
  2080. else:
  2081. self.location = initial_text
  2082. self.ok = False
  2083. self.setWindowIcon(icon)
  2084. self.setWindowTitle(str(title))
  2085. self.form = QtWidgets.QFormLayout(self)
  2086. self.ref_label = QtWidgets.QLabel('%s:' % _("Reference"))
  2087. self.ref_label.setToolTip(
  2088. _("The reference can be:\n"
  2089. "- Absolute -> the reference point is point (0,0)\n"
  2090. "- Relative -> the reference point is the mouse position before Jump")
  2091. )
  2092. self.ref_radio = RadioSet([
  2093. {"label": _("Abs"), "value": "abs"},
  2094. {"label": _("Relative"), "value": "rel"}
  2095. ], orientation='horizontal', stretch=False)
  2096. self.ref_radio.set_value(reference)
  2097. self.form.addRow(self.ref_label, self.ref_radio)
  2098. self.form.addRow(QtWidgets.QLabel(''))
  2099. self.wdg_label = QtWidgets.QLabel('<b>%s</b>' % str(label))
  2100. self.form.addRow(self.wdg_label)
  2101. self.loc_label = QtWidgets.QLabel('%s:' % _("Location"))
  2102. self.loc_label.setToolTip(
  2103. _("The Location value is a tuple (x,y).\n"
  2104. "If the reference is Absolute then the Jump will be at the position (x,y).\n"
  2105. "If the reference is Relative then the Jump will be at the (x,y) distance\n"
  2106. "from the current mouse location point.")
  2107. )
  2108. self.lineEdit = EvalEntry(self)
  2109. self.lineEdit.setText(str(self.location).replace('(', '').replace(')', ''))
  2110. self.lineEdit.selectAll()
  2111. self.lineEdit.setFocus()
  2112. self.form.addRow(self.loc_label, self.lineEdit)
  2113. self.button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  2114. Qt.Horizontal, parent=self)
  2115. self.form.addRow(self.button_box)
  2116. self.button_box.accepted.connect(self.accept)
  2117. self.button_box.rejected.connect(self.reject)
  2118. self.readyToEdit = True
  2119. if self.exec_() == QtWidgets.QDialog.Accepted:
  2120. self.ok = True
  2121. self.location = self.lineEdit.text()
  2122. self.reference = self.ref_radio.get_value()
  2123. else:
  2124. self.ok = False
  2125. class _BrowserTextEdit(QTextEdit):
  2126. def __init__(self, version, app=None):
  2127. QTextEdit.__init__(self)
  2128. self.menu = None
  2129. self.version = version
  2130. self.app = app
  2131. def contextMenuEvent(self, event):
  2132. self.menu = self.createStandardContextMenu(event.pos())
  2133. if self.app:
  2134. save_action = QAction(_("Save Log"), self)
  2135. self.menu.addAction(save_action)
  2136. save_action.triggered.connect(lambda: self.save_log(app=self.app))
  2137. clear_action = QAction(_("Clear"), self)
  2138. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  2139. self.menu.addAction(clear_action)
  2140. clear_action.triggered.connect(self.clear)
  2141. if self.app:
  2142. close_action = QAction(_("Close"), self)
  2143. self.menu.addAction(close_action)
  2144. close_action.triggered.connect(lambda: self.app.ui.shell_dock.hide())
  2145. self.menu.exec_(event.globalPos())
  2146. def clear(self):
  2147. QTextEdit.clear(self)
  2148. text = "!FlatCAM %s? - %s" % (self.version, _("Type >help< to get started"))
  2149. text = html.escape(text)
  2150. # hack so I can make text bold because the escape method will replace the '<' and '>' signs with html code
  2151. text = text.replace('!', '<b>')
  2152. text = text.replace('?', '</b>')
  2153. text += '<br><br>'
  2154. self.moveCursor(QTextCursor.End)
  2155. self.insertHtml(text)
  2156. def save_log(self, app):
  2157. html_content = self.toHtml()
  2158. txt_content = self.toPlainText()
  2159. app.save_to_file(content_to_save=html_content, txt_content=txt_content)
  2160. class _ExpandableTextEdit(QTextEdit):
  2161. """
  2162. Class implements edit line, which expands themselves automatically
  2163. """
  2164. historyNext = QtCore.pyqtSignal()
  2165. historyPrev = QtCore.pyqtSignal()
  2166. def __init__(self, termwidget, *args):
  2167. QTextEdit.__init__(self, *args)
  2168. self.setStyleSheet("font: 9pt \"Courier\";")
  2169. self._fittedHeight = 1
  2170. self.textChanged.connect(self._fit_to_document)
  2171. self._fit_to_document()
  2172. self._termWidget = termwidget
  2173. self.completer = MyCompleter()
  2174. self.model = QtCore.QStringListModel()
  2175. self.completer.setModel(self.model)
  2176. self.set_model_data(keyword_list=[])
  2177. self.completer.insertText.connect(self.insertCompletion)
  2178. self.completer.popup().clicked.connect(self.insert_completion_click)
  2179. def set_model_data(self, keyword_list):
  2180. self.model.setStringList(keyword_list)
  2181. def insert_completion_click(self):
  2182. self.completer.insertText.emit(self.completer.getSelected())
  2183. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  2184. def insertCompletion(self, completion):
  2185. tc = self.textCursor()
  2186. extra = (len(completion) - len(self.completer.completionPrefix()))
  2187. # don't insert if the word is finished but add a space instead
  2188. if extra == 0:
  2189. tc.insertText(' ')
  2190. self.completer.popup().hide()
  2191. return
  2192. tc.movePosition(QTextCursor.Left)
  2193. tc.movePosition(QTextCursor.EndOfWord)
  2194. tc.insertText(completion[-extra:])
  2195. # add a space after inserting the word
  2196. tc.insertText(' ')
  2197. self.setTextCursor(tc)
  2198. self.completer.popup().hide()
  2199. def focusInEvent(self, event):
  2200. if self.completer:
  2201. self.completer.setWidget(self)
  2202. QTextEdit.focusInEvent(self, event)
  2203. def keyPressEvent(self, event):
  2204. """
  2205. Catch keyboard events. Process Enter, Up, Down
  2206. """
  2207. key = event.key()
  2208. if (key == Qt.Key_Tab or key == Qt.Key_Return or key == Qt.Key_Enter) and self.completer.popup().isVisible():
  2209. self.completer.insertText.emit(self.completer.getSelected())
  2210. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  2211. return
  2212. if event.matches(QKeySequence.InsertParagraphSeparator):
  2213. text = self.toPlainText()
  2214. if self._termWidget.is_command_complete(text):
  2215. self._termWidget.exec_current_command()
  2216. return
  2217. elif event.matches(QKeySequence.MoveToNextLine):
  2218. text = self.toPlainText()
  2219. cursor_pos = self.textCursor().position()
  2220. textBeforeEnd = text[cursor_pos:]
  2221. if len(textBeforeEnd.split('\n')) <= 1:
  2222. self.historyNext.emit()
  2223. return
  2224. elif event.matches(QKeySequence.MoveToPreviousLine):
  2225. text = self.toPlainText()
  2226. cursor_pos = self.textCursor().position()
  2227. text_before_start = text[:cursor_pos]
  2228. # lineCount = len(textBeforeStart.splitlines())
  2229. line_count = len(text_before_start.split('\n'))
  2230. if len(text_before_start) > 0 and \
  2231. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  2232. line_count += 1
  2233. if line_count <= 1:
  2234. self.historyPrev.emit()
  2235. return
  2236. elif event.matches(QKeySequence.MoveToNextPage) or event.matches(QKeySequence.MoveToPreviousPage):
  2237. return self._termWidget.browser().keyPressEvent(event)
  2238. tc = self.textCursor()
  2239. QTextEdit.keyPressEvent(self, event)
  2240. tc.select(QTextCursor.WordUnderCursor)
  2241. cr = self.cursorRect()
  2242. if len(tc.selectedText()) > 0:
  2243. self.completer.setCompletionPrefix(tc.selectedText())
  2244. popup = self.completer.popup()
  2245. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  2246. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  2247. + self.completer.popup().verticalScrollBar().sizeHint().width())
  2248. self.completer.complete(cr)
  2249. else:
  2250. self.completer.popup().hide()
  2251. def sizeHint(self):
  2252. """
  2253. QWidget sizeHint impelemtation
  2254. """
  2255. hint = QTextEdit.sizeHint(self)
  2256. hint.setHeight(self._fittedHeight)
  2257. return hint
  2258. def _fit_to_document(self):
  2259. """
  2260. Update widget height to fit all text
  2261. """
  2262. documentsize = self.document().size().toSize()
  2263. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  2264. self.setMaximumHeight(self._fittedHeight)
  2265. self.updateGeometry()
  2266. def insertFromMimeData(self, mime_data):
  2267. # Paste only plain text.
  2268. self.insertPlainText(mime_data.text())
  2269. class MyCompleter(QCompleter):
  2270. insertText = QtCore.pyqtSignal(str)
  2271. def __init__(self, parent=None):
  2272. QCompleter.__init__(self)
  2273. self.setCompletionMode(QCompleter.PopupCompletion)
  2274. self.highlighted.connect(self.setHighlighted)
  2275. # self.popup().installEventFilter(self)
  2276. # def eventFilter(self, obj, event):
  2277. # if event.type() == QtCore.QEvent.Wheel and obj is self.popup():
  2278. # pass
  2279. # return False
  2280. def setHighlighted(self, text):
  2281. self.lastSelected = text
  2282. def getSelected(self):
  2283. return self.lastSelected
  2284. class FCTextAreaLineNumber(QtWidgets.QFrame):
  2285. textChanged = QtCore.pyqtSignal()
  2286. class NumberBar(QtWidgets.QWidget):
  2287. def __init__(self, edit):
  2288. QtWidgets.QWidget.__init__(self, edit)
  2289. self.edit = edit
  2290. self.adjustWidth(1)
  2291. def paintEvent(self, event):
  2292. self.edit.numberbarPaint(self, event)
  2293. QtWidgets.QWidget.paintEvent(self, event)
  2294. def adjustWidth(self, count):
  2295. # three spaces added to the width to make up for the space added in the line number
  2296. width = self.fontMetrics().width(str(count) + ' ')
  2297. if self.width() != width:
  2298. self.setFixedWidth(width)
  2299. def updateContents(self, rect, scroll):
  2300. if scroll:
  2301. self.scroll(0, scroll)
  2302. else:
  2303. # It would be nice to do
  2304. # self.update(0, rect.y(), self.width(), rect.height())
  2305. # But we can't because it will not remove the bold on the
  2306. # current line if word wrap is enabled and a new block is
  2307. # selected.
  2308. self.update()
  2309. class PlainTextEdit(FCPlainTextAreaExtended):
  2310. """
  2311. TextEdit with line numbers and highlight
  2312. From here: https://nachtimwald.com/2009/08/19/better-qplaintextedit-with-line-numbers/
  2313. and from here: https://doc.qt.io/qt-5/qtwidgets-widgets-codeeditor-example.html
  2314. """
  2315. def __init__(self, *args):
  2316. FCPlainTextAreaExtended.__init__(self, *args)
  2317. # self.setFrameStyle(QFrame.NoFrame)
  2318. self.setFrameStyle(QtWidgets.QFrame.NoFrame)
  2319. self.highlight()
  2320. # self.setLineWrapMode(QPlainTextEdit.NoWrap)
  2321. self.cursorPositionChanged.connect(self.highlight)
  2322. def highlight(self):
  2323. hi_selection = QTextEdit.ExtraSelection()
  2324. hi_selection.format.setBackground(self.palette().alternateBase())
  2325. hi_selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True)
  2326. hi_selection.cursor = self.textCursor()
  2327. hi_selection.cursor.clearSelection()
  2328. self.setExtraSelections([hi_selection])
  2329. def numberbarPaint(self, number_bar, event):
  2330. font_metrics = self.fontMetrics()
  2331. current_line = self.document().findBlock(self.textCursor().position()).blockNumber() + 1
  2332. painter = QtGui.QPainter(number_bar)
  2333. painter.fillRect(event.rect(), QtCore.Qt.lightGray)
  2334. block = self.firstVisibleBlock()
  2335. line_count = int(block.blockNumber())
  2336. block_top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
  2337. block_bottom = block_top + int(self.blockBoundingRect(block).height())
  2338. # Iterate over all visible text blocks in the document.
  2339. while block.isValid() and block_top <= event.rect().bottom():
  2340. line_count += 1
  2341. # Check if the position of the block is out side of the visible
  2342. # area.
  2343. if block.isVisible() and block_bottom >= event.rect().top():
  2344. # We want the line number for the selected line to be bold.
  2345. if line_count == current_line:
  2346. font = painter.font()
  2347. font.setBold(True)
  2348. painter.setPen(QtCore.Qt.blue)
  2349. painter.setFont(font)
  2350. else:
  2351. font = painter.font()
  2352. font.setBold(False)
  2353. painter.setPen(self.palette().base().color())
  2354. painter.setFont(font)
  2355. # Draw the line number right justified at the position of the line.
  2356. paint_rect = QtCore.QRect(0, block_top, number_bar.width(), font_metrics.height())
  2357. # I add some spaces to the line_count to prettify; make sure to remember adjust the width in the
  2358. # NumberBar() class above
  2359. painter.drawText(paint_rect, Qt.AlignRight, ' ' + str(line_count) + ' ')
  2360. block = block.next()
  2361. block_top = block_bottom
  2362. block_bottom = block_top + self.blockBoundingRect(block).height()
  2363. painter.end()
  2364. def __init__(self, *args):
  2365. QtWidgets.QFrame.__init__(self, *args)
  2366. self.setFrameStyle(QtWidgets.QFrame.StyledPanel | QtWidgets.QFrame.Sunken)
  2367. self.edit = self.PlainTextEdit()
  2368. self.number_bar = self.NumberBar(self.edit)
  2369. hbox = QtWidgets.QHBoxLayout(self)
  2370. hbox.setSpacing(0)
  2371. hbox.setContentsMargins(0, 0, 0, 0)
  2372. hbox.addWidget(self.number_bar)
  2373. hbox.addWidget(self.edit)
  2374. self.edit.blockCountChanged.connect(self.number_bar.adjustWidth)
  2375. self.edit.updateRequest.connect(self.number_bar.updateContents)
  2376. def getText(self):
  2377. return str(self.edit.toPlainText())
  2378. def setText(self, text):
  2379. self.edit.setPlainText(text)
  2380. def isModified(self):
  2381. return self.edit.document().isModified()
  2382. def setModified(self, modified):
  2383. self.edit.document().setModified(modified)
  2384. def setLineWrapMode(self, mode):
  2385. self.edit.setLineWrapMode(mode)
  2386. class FCFileSaveDialog(QtWidgets.QFileDialog):
  2387. def __init__(self, *args):
  2388. super(FCFileSaveDialog, self).__init__(*args)
  2389. @staticmethod
  2390. def get_saved_filename(parent=None, caption='', directory='', filter='', initialFilter=''):
  2391. filename, _filter = QtWidgets.QFileDialog.getSaveFileName(parent=parent, caption=caption,
  2392. directory=directory, filter=filter,
  2393. initialFilter=initialFilter)
  2394. filename = str(filename)
  2395. if filename == '':
  2396. return filename, _filter
  2397. extension = '.' + _filter.strip(')').rpartition('.')[2]
  2398. if filename.endswith(extension) or extension == '.*':
  2399. return filename, _filter
  2400. else:
  2401. filename += extension
  2402. return filename, _filter
  2403. def rreplace(s, old, new, occurrence):
  2404. """
  2405. Credits go here:
  2406. https://stackoverflow.com/questions/2556108/rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string
  2407. :param s: string to be processed
  2408. :param old: old char to be replaced
  2409. :param new: new char to replace the old one
  2410. :param occurrence: how many places from end to replace the old char
  2411. :return: modified string
  2412. """
  2413. li = s.rsplit(old, occurrence)
  2414. return new.join(li)