GUIElements.py 117 KB

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