GUIElements.py 99 KB

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