GUIElements.py 111 KB

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