GUIElements.py 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459
  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(EvalEntry):
  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. right_clicked = QtCore.pyqtSignal(bool)
  1263. middle_clicked = QtCore.pyqtSignal(bool)
  1264. def __init__(self, parent=None):
  1265. super(FCLabel, self).__init__(parent)
  1266. # for the usage of this label as a clickable label, to know that current state
  1267. self.clicked_state = False
  1268. self.middle_clicked_state = False
  1269. self.right_clicked_state = False
  1270. def mousePressEvent(self, event):
  1271. if event.button() == Qt.LeftButton:
  1272. self.clicked_state = not self.clicked_state
  1273. self.clicked.emit(self.clicked_state)
  1274. elif event.button() == Qt.RightButton:
  1275. self.right_clicked_state = not self.right_clicked_state
  1276. self.right_clicked.emit(True)
  1277. elif event.button() == Qt.MiddleButton:
  1278. self.middle_clicked_state = not self.middle_clicked_state
  1279. self.middle_clicked.emit(True)
  1280. def get_value(self):
  1281. return self.text()
  1282. def set_value(self, val):
  1283. self.setText(str(val))
  1284. class FCMenu(QtWidgets.QMenu):
  1285. def __init__(self):
  1286. super().__init__()
  1287. self.mouse_is_panning = False
  1288. self.popup_active = False
  1289. def popup(self, pos, action=None):
  1290. super().popup(pos)
  1291. self.mouse_is_panning = False
  1292. self.popup_active = True
  1293. class FCTab(QtWidgets.QTabWidget):
  1294. def __init__(self, parent=None):
  1295. super(FCTab, self).__init__(parent)
  1296. self.setTabsClosable(True)
  1297. self.tabCloseRequested.connect(self.closeTab)
  1298. def deleteTab(self, currentIndex):
  1299. widget = self.widget(currentIndex)
  1300. if widget is not None:
  1301. widget.deleteLater()
  1302. self.removeTab(currentIndex)
  1303. def closeTab(self, currentIndex):
  1304. self.removeTab(currentIndex)
  1305. def protectTab(self, currentIndex):
  1306. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1307. # class FCTabBar(QtWidgets.QTabBar):
  1308. # def tabSizeHint(self, index):
  1309. # size =QtWidgets.QTabBar.tabSizeHint(self, index)
  1310. # w = int(self.width()/self.count())
  1311. # return QtCore.QSize(w, size.height())
  1312. class FCDetachableTab(QtWidgets.QTabWidget):
  1313. """
  1314. From here:
  1315. https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  1316. """
  1317. tab_detached = QtCore.pyqtSignal(str)
  1318. tab_attached = QtCore.pyqtSignal(str)
  1319. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1320. super().__init__(parent=parent)
  1321. self.tabBar = self.FCTabBar(self)
  1322. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  1323. self.tabBar.onCloseTabSignal.connect(self.on_closetab_middle_button)
  1324. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  1325. self.set_detachable(val=True)
  1326. self.setTabBar(self.tabBar)
  1327. # Used to keep a reference to detached tabs since their QMainWindow
  1328. # does not have a parent
  1329. self.detachedTabs = {}
  1330. # a way to make sure that tabs can't be closed after they attach to the parent tab
  1331. self.protect_tab = True if protect is not None and protect is True else False
  1332. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  1333. # Close all detached tabs if the application is closed explicitly
  1334. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  1335. # used by the property self.useOldIndex(param)
  1336. self.use_old_index = None
  1337. self.old_index = None
  1338. self.setTabsClosable(True)
  1339. self.tabCloseRequested.connect(self.closeTab)
  1340. def set_rmb_callback(self, callback):
  1341. """
  1342. :param callback: Function to call on right mouse click on tab
  1343. :type callback: func
  1344. :return: None
  1345. """
  1346. self.tabBar.right_click.connect(callback)
  1347. def set_detachable(self, val=True):
  1348. try:
  1349. self.tabBar.onDetachTabSignal.disconnect()
  1350. except TypeError:
  1351. pass
  1352. if val is True:
  1353. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  1354. # the tab can be moved around
  1355. self.tabBar.can_be_dragged = True
  1356. else:
  1357. # the detached tab can't be moved
  1358. self.tabBar.can_be_dragged = False
  1359. return val
  1360. def setupContextMenu(self):
  1361. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1362. def addContextMenu(self, entry, call_function, icon=None, initial_checked=False):
  1363. action_name = str(entry)
  1364. action = QtWidgets.QAction(self)
  1365. action.setCheckable(True)
  1366. action.setText(action_name)
  1367. if icon:
  1368. assert isinstance(icon, QtGui.QIcon), \
  1369. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1370. action.setIcon(icon)
  1371. action.setChecked(initial_checked)
  1372. self.addAction(action)
  1373. action.triggered.connect(call_function)
  1374. def useOldIndex(self, param):
  1375. if param:
  1376. self.use_old_index = True
  1377. else:
  1378. self.use_old_index = False
  1379. def deleteTab(self, currentIndex):
  1380. widget = self.widget(currentIndex)
  1381. if widget is not None:
  1382. widget.deleteLater()
  1383. self.removeTab(currentIndex)
  1384. def closeTab(self, currentIndex):
  1385. """
  1386. Slot connected to the tabCloseRequested signal
  1387. :param currentIndex:
  1388. :return:
  1389. """
  1390. self.removeTab(currentIndex)
  1391. def on_closetab_middle_button(self, current_index):
  1392. """
  1393. :param current_index:
  1394. :return:
  1395. """
  1396. # if tab is protected don't delete it
  1397. if self.tabBar.tabButton(current_index, QtWidgets.QTabBar.RightSide) is not None:
  1398. self.removeTab(current_index)
  1399. def protectTab(self, currentIndex):
  1400. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1401. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  1402. def setMovable(self, movable):
  1403. """
  1404. The default movable functionality of QTabWidget must remain disabled
  1405. so as not to conflict with the added features
  1406. :param movable:
  1407. :return:
  1408. """
  1409. pass
  1410. @pyqtSlot(int, int)
  1411. def moveTab(self, fromIndex, toIndex):
  1412. """
  1413. Move a tab from one position (index) to another
  1414. :param fromIndex: the original index location of the tab
  1415. :param toIndex: the new index location of the tab
  1416. :return:
  1417. """
  1418. widget = self.widget(fromIndex)
  1419. icon = self.tabIcon(fromIndex)
  1420. text = self.tabText(fromIndex)
  1421. self.removeTab(fromIndex)
  1422. self.insertTab(toIndex, widget, icon, text)
  1423. self.setCurrentIndex(toIndex)
  1424. # @pyqtSlot(int, QtCore.QPoint)
  1425. def detachTab(self, index, point):
  1426. """
  1427. Detach the tab by removing it's contents and placing them in
  1428. a DetachedTab window
  1429. :param index: the index location of the tab to be detached
  1430. :param point: the screen position for creating the new DetachedTab window
  1431. :return:
  1432. """
  1433. self.old_index = index
  1434. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  1435. name = "FlatCAM " + self.tabText(index)
  1436. icon = self.tabIcon(index)
  1437. if icon.isNull():
  1438. icon = self.window().windowIcon()
  1439. contentWidget = self.widget(index)
  1440. try:
  1441. contentWidgetRect = contentWidget.frameGeometry()
  1442. except AttributeError:
  1443. return
  1444. # Create a new detached tab window
  1445. detachedTab = self.FCDetachedTab(name, contentWidget)
  1446. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  1447. detachedTab.setWindowIcon(icon)
  1448. detachedTab.setGeometry(contentWidgetRect)
  1449. detachedTab.onCloseSignal.connect(self.attachTab)
  1450. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  1451. detachedTab.move(point)
  1452. detachedTab.show()
  1453. # Create a reference to maintain access to the detached tab
  1454. self.detachedTabs[name] = detachedTab
  1455. self.tab_detached.emit(name)
  1456. def attachTab(self, contentWidget, name, icon, insertAt=None):
  1457. """
  1458. Re-attach the tab by removing the content from the DetachedTab window,
  1459. closing it, and placing the content back into the DetachableTabWidget
  1460. :param contentWidget: the content widget from the DetachedTab window
  1461. :param name: the name of the detached tab
  1462. :param icon: the window icon for the detached tab
  1463. :param insertAt: insert the re-attached tab at the given index
  1464. :return:
  1465. """
  1466. old_name = name
  1467. # Make the content widget a child of this widget
  1468. contentWidget.setParent(self)
  1469. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  1470. name = name.partition(' ')[2]
  1471. # helps in restoring the tab to the same index that it was before was detached
  1472. insert_index = self.old_index if self.use_old_index is True else insertAt
  1473. # Create an image from the given icon (for comparison)
  1474. if not icon.isNull():
  1475. try:
  1476. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  1477. tabIconImage = tabIconPixmap.toImage()
  1478. except IndexError:
  1479. tabIconImage = None
  1480. else:
  1481. tabIconImage = None
  1482. # Create an image of the main window icon (for comparison)
  1483. if not icon.isNull():
  1484. try:
  1485. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  1486. windowIconImage = windowIconPixmap.toImage()
  1487. except IndexError:
  1488. windowIconImage = None
  1489. else:
  1490. windowIconImage = None
  1491. # Determine if the given image and the main window icon are the same.
  1492. # If they are, then do not add the icon to the tab
  1493. if tabIconImage == windowIconImage:
  1494. if insert_index is None:
  1495. index = self.addTab(contentWidget, name)
  1496. else:
  1497. index = self.insertTab(insert_index, contentWidget, name)
  1498. else:
  1499. if insert_index is None:
  1500. index = self.addTab(contentWidget, icon, name)
  1501. else:
  1502. index = self.insertTab(insert_index, contentWidget, icon, name)
  1503. obj_name = contentWidget.objectName()
  1504. self.tab_attached.emit(obj_name)
  1505. # on reattaching the tab if protect is true then the closure button is not added
  1506. if self.protect_tab is True:
  1507. self.protectTab(index)
  1508. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  1509. if self.protect_by_name is not None:
  1510. for tab_name in self.protect_by_name:
  1511. for index in range(self.count()):
  1512. if str(tab_name) == str(self.tabText(index)):
  1513. self.protectTab(index)
  1514. # Make this tab the current tab
  1515. if index > -1:
  1516. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  1517. # Remove the reference
  1518. # Unix-like OS's crash with segmentation fault after this. FOr whatever reason, they loose reference
  1519. if sys.platform == 'win32':
  1520. try:
  1521. del self.detachedTabs[old_name]
  1522. except KeyError:
  1523. pass
  1524. def removeTabByName(self, name):
  1525. """
  1526. Remove the tab with the given name, even if it is detached
  1527. :param name: the name of the tab to be removed
  1528. :return:
  1529. """
  1530. # Remove the tab if it is attached
  1531. attached = False
  1532. for index in range(self.count()):
  1533. if str(name) == str(self.tabText(index)):
  1534. self.removeTab(index)
  1535. attached = True
  1536. break
  1537. # If the tab is not attached, close it's window and
  1538. # remove the reference to it
  1539. if not attached:
  1540. for key in self.detachedTabs:
  1541. if str(name) == str(key):
  1542. self.detachedTabs[key].onCloseSignal.disconnect()
  1543. self.detachedTabs[key].close()
  1544. del self.detachedTabs[key]
  1545. break
  1546. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  1547. def detachedTabDrop(self, name, index, dropPos):
  1548. """
  1549. Handle dropping of a detached tab inside the DetachableTabWidget
  1550. :param name: the name of the detached tab
  1551. :param index: the index of an existing tab (if the tab bar
  1552. # determined that the drop occurred on an
  1553. # existing tab)
  1554. :param dropPos: the mouse cursor position when the drop occurred
  1555. :return:
  1556. """
  1557. # If the drop occurred on an existing tab, insert the detached
  1558. # tab at the existing tab's location
  1559. if index > -1:
  1560. # Create references to the detached tab's content and icon
  1561. contentWidget = self.detachedTabs[name].contentWidget
  1562. icon = self.detachedTabs[name].windowIcon()
  1563. # Disconnect the detached tab's onCloseSignal so that it
  1564. # does not try to re-attach automatically
  1565. self.detachedTabs[name].onCloseSignal.disconnect()
  1566. # Close the detached
  1567. self.detachedTabs[name].close()
  1568. # Re-attach the tab at the given index
  1569. self.attachTab(contentWidget, name, icon, index)
  1570. # If the drop did not occur on an existing tab, determine if the drop
  1571. # occurred in the tab bar area (the area to the side of the QTabBar)
  1572. else:
  1573. # Find the drop position relative to the DetachableTabWidget
  1574. tabDropPos = self.mapFromGlobal(dropPos)
  1575. # If the drop position is inside the DetachableTabWidget...
  1576. if self.rect().contains(tabDropPos):
  1577. # If the drop position is inside the tab bar area (the
  1578. # area to the side of the QTabBar) or there are not tabs
  1579. # currently attached...
  1580. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  1581. # Close the detached tab and allow it to re-attach
  1582. # automatically
  1583. self.detachedTabs[name].close()
  1584. def closeDetachedTabs(self):
  1585. """
  1586. Close all tabs that are currently detached.
  1587. :return:
  1588. """
  1589. listOfDetachedTabs = []
  1590. for key in self.detachedTabs:
  1591. listOfDetachedTabs.append(self.detachedTabs[key])
  1592. for detachedTab in listOfDetachedTabs:
  1593. detachedTab.close()
  1594. class FCDetachedTab(QtWidgets.QMainWindow):
  1595. """
  1596. When a tab is detached, the contents are placed into this QMainWindow. The tab
  1597. can be re-attached by closing the dialog or by dragging the window into the tab bar
  1598. """
  1599. onCloseSignal = QtCore.pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  1600. onDropSignal = QtCore.pyqtSignal(str, QtCore.QPoint)
  1601. def __init__(self, name, contentWidget):
  1602. QtWidgets.QMainWindow.__init__(self, None)
  1603. self.setObjectName(name)
  1604. self.setWindowTitle(name)
  1605. self.contentWidget = contentWidget
  1606. self.setCentralWidget(self.contentWidget)
  1607. self.contentWidget.show()
  1608. self.windowDropFilter = self.WindowDropFilter()
  1609. self.installEventFilter(self.windowDropFilter)
  1610. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  1611. @QtCore.pyqtSlot(QtCore.QPoint)
  1612. def windowDropSlot(self, dropPos):
  1613. """
  1614. Handle a window drop event
  1615. :param dropPos: the mouse cursor position of the drop
  1616. :return:
  1617. """
  1618. self.onDropSignal.emit(self.objectName(), dropPos)
  1619. def closeEvent(self, event):
  1620. """
  1621. If the window is closed, emit the onCloseSignal and give the
  1622. content widget back to the DetachableTabWidget
  1623. :param event: a close event
  1624. :return:
  1625. """
  1626. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  1627. class WindowDropFilter(QtCore.QObject):
  1628. """
  1629. An event filter class to detect a QMainWindow drop event
  1630. """
  1631. onDropSignal = QtCore.pyqtSignal(QtCore.QPoint)
  1632. def __init__(self):
  1633. QtCore.QObject.__init__(self)
  1634. self.lastEvent = None
  1635. def eventFilter(self, obj, event):
  1636. """
  1637. Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  1638. event that immediately follows a Move event
  1639. :param obj: the object that generated the event
  1640. :param event: the current event
  1641. :return:
  1642. """
  1643. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  1644. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  1645. # Determine the position of the mouse cursor and emit it with the
  1646. # onDropSignal
  1647. mouseCursor = QtGui.QCursor()
  1648. dropPos = mouseCursor.pos()
  1649. self.onDropSignal.emit(dropPos)
  1650. self.lastEvent = event.type()
  1651. return True
  1652. else:
  1653. self.lastEvent = event.type()
  1654. return False
  1655. class FCTabBar(QtWidgets.QTabBar):
  1656. onDetachTabSignal = QtCore.pyqtSignal(int, QtCore.QPoint)
  1657. onMoveTabSignal = QtCore.pyqtSignal(int, int)
  1658. detachedTabDropSignal = QtCore.pyqtSignal(str, int, QtCore.QPoint)
  1659. onCloseTabSignal = QtCore.pyqtSignal(int)
  1660. right_click = QtCore.pyqtSignal(int)
  1661. def __init__(self, parent=None):
  1662. QtWidgets.QTabBar.__init__(self, parent)
  1663. self.setAcceptDrops(True)
  1664. self.setElideMode(QtCore.Qt.ElideRight)
  1665. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  1666. self.prev_index = -1
  1667. self.dragStartPos = QtCore.QPoint()
  1668. self.dragDropedPos = QtCore.QPoint()
  1669. self.mouseCursor = QtGui.QCursor()
  1670. self.dragInitiated = False
  1671. # set this to False and the tab will no longer be displayed as detached
  1672. self.can_be_dragged = True
  1673. def mouseDoubleClickEvent(self, event):
  1674. """
  1675. Send the onDetachTabSignal when a tab is double clicked
  1676. :param event: a mouse double click event
  1677. :return:
  1678. """
  1679. event.accept()
  1680. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  1681. def mousePressEvent(self, event):
  1682. """
  1683. Set the starting position for a drag event when the left mouse button is pressed.
  1684. Start detection of a right mouse click.
  1685. :param event: a mouse press event
  1686. :return:
  1687. """
  1688. if event.button() == QtCore.Qt.LeftButton:
  1689. self.dragStartPos = event.pos()
  1690. elif event.button() == QtCore.Qt.RightButton:
  1691. self.prev_index = self.tabAt(event.pos())
  1692. self.dragDropedPos.setX(0)
  1693. self.dragDropedPos.setY(0)
  1694. self.dragInitiated = False
  1695. QtWidgets.QTabBar.mousePressEvent(self, event)
  1696. def mouseReleaseEvent(self, event):
  1697. """
  1698. Finish the detection of the right mouse click on the tab
  1699. :param event: a mouse press event
  1700. :return:
  1701. """
  1702. if event.button() == QtCore.Qt.RightButton and self.prev_index == self.tabAt(event.pos()):
  1703. self.right_click.emit(self.prev_index)
  1704. if event.button() == QtCore.Qt.MiddleButton:
  1705. self.onCloseTabSignal.emit(int(self.tabAt(event.pos())))
  1706. self.prev_index = -1
  1707. QtWidgets.QTabBar.mouseReleaseEvent(self, event)
  1708. def mouseMoveEvent(self, event):
  1709. """
  1710. Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  1711. drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  1712. bar, emit an onDetachTabSignal.
  1713. :param event: a mouse move event
  1714. :return:
  1715. """
  1716. # Determine if the current movement is detected as a drag
  1717. if not self.dragStartPos.isNull() and \
  1718. ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  1719. self.dragInitiated = True
  1720. # If the current movement is a drag initiated by the left button
  1721. if (event.buttons() & QtCore.Qt.LeftButton) and self.dragInitiated and self.can_be_dragged:
  1722. # Stop the move event
  1723. finishMoveEvent = QtGui.QMouseEvent(
  1724. QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier
  1725. )
  1726. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  1727. # Convert the move event into a drag
  1728. drag = QtGui.QDrag(self)
  1729. mimeData = QtCore.QMimeData()
  1730. # mimeData.setData('action', 'application/tab-detach')
  1731. drag.setMimeData(mimeData)
  1732. # screen = QScreen(self.parentWidget().currentWidget().winId())
  1733. # Create the appearance of dragging the tab content
  1734. try:
  1735. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  1736. except Exception as e:
  1737. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  1738. return
  1739. targetPixmap = QtGui.QPixmap(pixmap.size())
  1740. targetPixmap.fill(QtCore.Qt.transparent)
  1741. painter = QtGui.QPainter(targetPixmap)
  1742. painter.setOpacity(0.85)
  1743. painter.drawPixmap(0, 0, pixmap)
  1744. painter.end()
  1745. drag.setPixmap(targetPixmap)
  1746. # Initiate the drag
  1747. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  1748. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  1749. # must be set manually
  1750. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  1751. dropAction = QtCore.Qt.MoveAction
  1752. # If the drag completed outside of the tab bar, detach the tab and move
  1753. # the content to the current cursor position
  1754. if dropAction == QtCore.Qt.IgnoreAction:
  1755. event.accept()
  1756. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  1757. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  1758. elif dropAction == QtCore.Qt.MoveAction:
  1759. if not self.dragDropedPos.isNull():
  1760. event.accept()
  1761. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  1762. else:
  1763. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  1764. def dragEnterEvent(self, event):
  1765. """
  1766. Determine if the drag has entered a tab position from another tab position
  1767. :param event: a drag enter event
  1768. :return:
  1769. """
  1770. mimeData = event.mimeData()
  1771. # formats = mcd imeData.formats()
  1772. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  1773. # event.acceptProposedAction()
  1774. QtWidgets.QTabBar.dragMoveEvent(self, event)
  1775. def dropEvent(self, event):
  1776. """
  1777. Get the position of the end of the drag
  1778. :param event: a drop event
  1779. :return:
  1780. """
  1781. self.dragDropedPos = event.pos()
  1782. QtWidgets.QTabBar.dropEvent(self, event)
  1783. def detachedTabDrop(self, name, dropPos):
  1784. """
  1785. Determine if the detached tab drop event occurred on an existing tab,
  1786. then send the event to the DetachableTabWidget
  1787. :param name:
  1788. :param dropPos:
  1789. :return:
  1790. """
  1791. tabDropPos = self.mapFromGlobal(dropPos)
  1792. index = self.tabAt(tabDropPos)
  1793. self.detachedTabDropSignal.emit(name, index, dropPos)
  1794. class FCDetachableTab2(FCDetachableTab):
  1795. tab_closed_signal = QtCore.pyqtSignal(object, int)
  1796. def __init__(self, protect=None, protect_by_name=None, parent=None):
  1797. super(FCDetachableTab2, self).__init__(protect=protect, protect_by_name=protect_by_name, parent=parent)
  1798. try:
  1799. self.tabBar.onCloseTabSignal.disconnect()
  1800. except TypeError:
  1801. pass
  1802. self.tabBar.onCloseTabSignal.connect(self.on_closetab_middle_button)
  1803. def on_closetab_middle_button(self, current_index):
  1804. """
  1805. :param current_index:
  1806. :return:
  1807. """
  1808. # if tab is protected don't delete it
  1809. if self.tabBar.tabButton(current_index, QtWidgets.QTabBar.RightSide) is not None:
  1810. self.closeTab(current_index)
  1811. def closeTab(self, currentIndex):
  1812. """
  1813. Slot connected to the tabCloseRequested signal
  1814. :param currentIndex:
  1815. :return:
  1816. """
  1817. # idx = self.currentIndex()
  1818. tab_name = self.widget(currentIndex).objectName()
  1819. self.tab_closed_signal.emit(tab_name, currentIndex)
  1820. self.removeTab(currentIndex)
  1821. class VerticalScrollArea(QtWidgets.QScrollArea):
  1822. """
  1823. This widget extends QtGui.QScrollArea to make a vertical-only
  1824. scroll area that also expands horizontally to accommodate
  1825. its contents.
  1826. """
  1827. def __init__(self, parent=None):
  1828. QtWidgets.QScrollArea.__init__(self, parent=parent)
  1829. self.setWidgetResizable(True)
  1830. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1831. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  1832. def eventFilter(self, source, event):
  1833. """
  1834. The event filter gets automatically installed when setWidget()
  1835. is called.
  1836. :param source:
  1837. :param event:
  1838. :return:
  1839. """
  1840. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  1841. # log.debug("VerticalScrollArea: Widget resized:")
  1842. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  1843. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  1844. self.setMinimumWidth(self.widget().sizeHint().width() +
  1845. self.verticalScrollBar().sizeHint().width())
  1846. # if self.verticalScrollBar().isVisible():
  1847. # log.debug(" Scroll bar visible")
  1848. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  1849. # self.verticalScrollBar().width())
  1850. # else:
  1851. # log.debug(" Scroll bar hidden")
  1852. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  1853. return QtWidgets.QWidget.eventFilter(self, source, event)
  1854. class OptionalInputSection:
  1855. def __init__(self, cb, optinputs, logic=True):
  1856. """
  1857. Associates the a checkbox with a set of inputs.
  1858. :param cb: Checkbox that enables the optional inputs.
  1859. :param optinputs: List of widgets that are optional.
  1860. :param logic: When True the logic is normal, when False the logic is in reverse
  1861. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1862. for logic=False, when the checkbox is checked the widgets are Disabled
  1863. :return:
  1864. """
  1865. assert isinstance(cb, FCCheckBox), \
  1866. "Expected an FCCheckBox, got %s" % type(cb)
  1867. self.cb = cb
  1868. self.optinputs = optinputs
  1869. self.logic = logic
  1870. self.on_cb_change()
  1871. self.cb.stateChanged.connect(self.on_cb_change)
  1872. def on_cb_change(self):
  1873. if self.cb.checkState():
  1874. for widget in self.optinputs:
  1875. if self.logic is True:
  1876. widget.setEnabled(True)
  1877. else:
  1878. widget.setEnabled(False)
  1879. else:
  1880. for widget in self.optinputs:
  1881. if self.logic is True:
  1882. widget.setEnabled(False)
  1883. else:
  1884. widget.setEnabled(True)
  1885. class OptionalHideInputSection:
  1886. def __init__(self, cb, optinputs, logic=True):
  1887. """
  1888. Associates the a checkbox with a set of inputs.
  1889. :param cb: Checkbox that enables the optional inputs.
  1890. :type cb: QtWidgets.QCheckBox
  1891. :param optinputs: List of widgets that are optional.
  1892. :type optinputs: list
  1893. :param logic: When True the logic is normal, when False the logic is in reverse
  1894. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1895. for logic=False, when the checkbox is checked the widgets are Disabled
  1896. :type logic: bool
  1897. :return:
  1898. """
  1899. assert isinstance(cb, FCCheckBox), \
  1900. "Expected an FCCheckBox, got %s" % type(cb)
  1901. self.cb = cb
  1902. self.optinputs = optinputs
  1903. self.logic = logic
  1904. self.on_cb_change()
  1905. self.cb.stateChanged.connect(self.on_cb_change)
  1906. def on_cb_change(self):
  1907. if self.cb.checkState():
  1908. for widget in self.optinputs:
  1909. if self.logic is True:
  1910. widget.show()
  1911. else:
  1912. widget.hide()
  1913. else:
  1914. for widget in self.optinputs:
  1915. if self.logic is True:
  1916. widget.hide()
  1917. else:
  1918. widget.show()
  1919. class FCTable(QtWidgets.QTableWidget):
  1920. drag_drop_sig = QtCore.pyqtSignal(object, int)
  1921. lost_focus = QtCore.pyqtSignal()
  1922. def __init__(self, drag_drop=False, protected_rows=None, parent=None):
  1923. super(FCTable, self).__init__(parent)
  1924. palette = QtGui.QPalette()
  1925. palette.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.Highlight,
  1926. palette.color(QtGui.QPalette.Active, QtGui.QPalette.Highlight))
  1927. # make inactive rows text some color as active; may be useful in the future
  1928. # palette.setColor(QtGui.QPalette.Inactive, QtGui.QPalette.HighlightedText,
  1929. # palette.color(QtGui.QPalette.Active, QtGui.QPalette.HighlightedText))
  1930. self.setPalette(palette)
  1931. if drag_drop:
  1932. self.setDragEnabled(True)
  1933. self.setAcceptDrops(True)
  1934. self.viewport().setAcceptDrops(True)
  1935. self.setDragDropOverwriteMode(False)
  1936. self.setDropIndicatorShown(True)
  1937. self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1938. self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  1939. self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
  1940. self.rows_not_for_drag_and_drop = []
  1941. if protected_rows:
  1942. try:
  1943. for r in protected_rows:
  1944. self.rows_not_for_drag_and_drop.append(r)
  1945. except TypeError:
  1946. self.rows_not_for_drag_and_drop = [protected_rows]
  1947. self.rows_to_move = []
  1948. self.rows_dragged = None
  1949. def sizeHint(self):
  1950. default_hint_size = super(FCTable, self).sizeHint()
  1951. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1952. def getHeight(self):
  1953. height = self.horizontalHeader().height()
  1954. for i in range(self.rowCount()):
  1955. height += self.rowHeight(i)
  1956. return height
  1957. def getWidth(self):
  1958. width = self.verticalHeader().width()
  1959. for i in range(self.columnCount()):
  1960. width += self.columnWidth(i)
  1961. return width
  1962. # color is in format QtGui.Qcolor(r, g, b, alpha) with or without alpha
  1963. def setColortoRow(self, rowIndex, color):
  1964. for j in range(self.columnCount()):
  1965. self.item(rowIndex, j).setBackground(color)
  1966. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  1967. def mousePressEvent(self, event):
  1968. clicked_item = self.itemAt(event.pos())
  1969. if not clicked_item:
  1970. self.clearSelection()
  1971. self.clearFocus()
  1972. else:
  1973. self.rows_dragged = [it.row() for it in self.selectedItems()]
  1974. QtWidgets.QTableWidget.mousePressEvent(self, event)
  1975. def focusOutEvent(self, event):
  1976. self.lost_focus.emit()
  1977. super().focusOutEvent(event)
  1978. def setupContextMenu(self):
  1979. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1980. def addContextMenu(self, entry, call_function, icon=None):
  1981. action_name = str(entry)
  1982. action = QtWidgets.QAction(self)
  1983. action.setText(action_name)
  1984. if icon:
  1985. assert isinstance(icon, QtGui.QIcon), \
  1986. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1987. action.setIcon(icon)
  1988. self.addAction(action)
  1989. action.triggered.connect(call_function)
  1990. # def dropEvent(self, event: QtGui.QDropEvent):
  1991. # if not event.isAccepted() and event.source() == self:
  1992. # drop_row = self.drop_on(event)
  1993. #
  1994. # rows = sorted(set(item.row() for item in self.selectedItems()))
  1995. # # rows_to_move = [
  1996. # # [QtWidgets.QTableWidgetItem(self.item(row_index, column_index))
  1997. # # for column_index in range(self.columnCount())] for row_index in rows
  1998. # # ]
  1999. # self.rows_to_move[:] = []
  2000. # for row_index in rows:
  2001. # row_items = []
  2002. # for column_index in range(self.columnCount()):
  2003. # r_item = self.item(row_index, column_index)
  2004. # w_item = self.cellWidget(row_index, column_index)
  2005. #
  2006. # if r_item is not None:
  2007. # row_items.append(QtWidgets.QTableWidgetItem(r_item))
  2008. # elif w_item is not None:
  2009. # row_items.append(w_item)
  2010. #
  2011. # self.rows_to_move.append(row_items)
  2012. #
  2013. # for row_index in reversed(rows):
  2014. # self.removeRow(row_index)
  2015. # if row_index < drop_row:
  2016. # drop_row -= 1
  2017. #
  2018. # for row_index, data in enumerate(self.rows_to_move):
  2019. # row_index += drop_row
  2020. # self.insertRow(row_index)
  2021. #
  2022. # for column_index, column_data in enumerate(data):
  2023. # if isinstance(column_data, QtWidgets.QTableWidgetItem):
  2024. # self.setItem(row_index, column_index, column_data)
  2025. # else:
  2026. # self.setCellWidget(row_index, column_index, column_data)
  2027. #
  2028. # event.accept()
  2029. # for row_index in range(len(self.rows_to_move)):
  2030. # self.item(drop_row + row_index, 0).setSelected(True)
  2031. # self.item(drop_row + row_index, 1).setSelected(True)
  2032. #
  2033. # super().dropEvent(event)
  2034. #
  2035. # def drop_on(self, event):
  2036. # ret_val = False
  2037. # index = self.indexAt(event.pos())
  2038. # if not index.isValid():
  2039. # return self.rowCount()
  2040. #
  2041. # ret_val = index.row() + 1 if self.is_below(event.pos(), index) else index.row()
  2042. #
  2043. # return ret_val
  2044. #
  2045. # def is_below(self, pos, index):
  2046. # rect = self.visualRect(index)
  2047. # margin = 2
  2048. # if pos.y() - rect.top() < margin:
  2049. # return False
  2050. # elif rect.bottom() - pos.y() < margin:
  2051. # return True
  2052. # # noinspection PyTypeChecker
  2053. # return rect.contains(pos, True) and not (
  2054. # int(self.model().flags(index)) & Qt.ItemIsDropEnabled) and pos.y() >= rect.center().y()
  2055. def dragEnterEvent(self, e: QtGui.QDragEnterEvent) -> None:
  2056. if e.source() == self:
  2057. self.blockSignals(True)
  2058. e.accept()
  2059. else:
  2060. e.ignore()
  2061. # def dropEvent(self, event):
  2062. # """
  2063. # From here: https://stackoverflow.com/questions/26227885/drag-and-drop-rows-within-qtablewidget
  2064. # :param event:
  2065. # :return:
  2066. # """
  2067. # if event.source() == self:
  2068. # event.acceptProposedAction()
  2069. #
  2070. # # create a set of the selected rows that are dragged to another position
  2071. # rows = set([mi.row() for mi in self.selectedIndexes()])
  2072. # # if one of the selected rows for drag and drop is within the protected list, return
  2073. # for r in rows:
  2074. # if r in self.rows_not_for_drag_and_drop:
  2075. # return
  2076. #
  2077. # drop_index = self.indexAt(event.pos())
  2078. # # row where we drop the selected rows
  2079. # targetRow = drop_index.row()
  2080. #
  2081. # # drop_indicator = self.dropIndicatorPosition()
  2082. # # if targetRow != -1:
  2083. # # if drop_indicator == QtWidgets.QAbstractItemView.AboveItem:
  2084. # # print("above")
  2085. # # elif drop_indicator == QtWidgets.QAbstractItemView.BelowItem:
  2086. # # print("below")
  2087. # # elif drop_indicator == QtWidgets.QAbstractItemView.OnItem:
  2088. # # print("on")
  2089. # # elif drop_indicator == QtWidgets.QAbstractItemView.OnViewport:
  2090. # # print("on viewport")
  2091. #
  2092. # # if we drop on one row from the already dragged rows
  2093. # rows.discard(targetRow)
  2094. # rows = sorted(rows)
  2095. # if not rows:
  2096. # return
  2097. # if targetRow == -1:
  2098. # targetRow = self.rowCount()
  2099. #
  2100. # # insert empty rows at the index of the targetRow
  2101. # for _ in range(len(rows)):
  2102. # self.insertRow(targetRow)
  2103. #
  2104. # rowMapping = {} # Src row to target row.
  2105. # for idx, row in enumerate(rows):
  2106. # if row < targetRow:
  2107. # rowMapping[row] = targetRow + idx
  2108. # else:
  2109. # rowMapping[row + len(rows)] = targetRow + idx
  2110. #
  2111. # colCount = self.columnCount()
  2112. # for srcRow, tgtRow in sorted(rowMapping.items()):
  2113. # for col in range(0, colCount):
  2114. # new_item = self.item(srcRow, col)
  2115. # if new_item is None:
  2116. # new_item = self.cellWidget(srcRow, col)
  2117. #
  2118. # if isinstance(new_item, QtWidgets.QTableWidgetItem):
  2119. # new_item = self.takeItem(srcRow, col)
  2120. # self.setItem(tgtRow, col, new_item)
  2121. # else:
  2122. # self.setCellWidget(tgtRow, col, new_item)
  2123. #
  2124. # for row in reversed(sorted(rowMapping.keys())):
  2125. # self.removeRow(row)
  2126. #
  2127. # self.blockSignals(False)
  2128. # self.drag_drop_sig.emit(int(self.row_dragged), int(targetRow))
  2129. # else:
  2130. # event.ignore()
  2131. def dropEvent(self, event: QtGui.QDropEvent):
  2132. if not event.isAccepted() and event.source() == self:
  2133. drop_row = self.drop_on(event)
  2134. rows = sorted(set(item.row() for item in self.selectedItems()))
  2135. rows_to_move = []
  2136. for row_index in rows:
  2137. temp_lst = []
  2138. for column_index in range(self.columnCount()):
  2139. col_data = self.item(row_index, column_index)
  2140. if isinstance(col_data, QtWidgets.QTableWidgetItem):
  2141. table_item = QtWidgets.QTableWidgetItem(col_data)
  2142. else:
  2143. old_item = self.cellWidget(row_index, column_index)
  2144. if isinstance(old_item, QtWidgets.QComboBox):
  2145. table_item = FCComboBox()
  2146. items = [old_item.itemText(i) for i in range(old_item.count())]
  2147. table_item.addItems(items)
  2148. table_item.setCurrentIndex(old_item.currentIndex())
  2149. elif isinstance(old_item, QtWidgets.QCheckBox):
  2150. table_item = FCCheckBox()
  2151. table_item.setChecked(old_item.isChecked())
  2152. table_item.setText(old_item.text())
  2153. else:
  2154. table_item = None
  2155. temp_lst.append(table_item)
  2156. rows_to_move.append(temp_lst)
  2157. for row_index in reversed(rows):
  2158. self.removeRow(row_index)
  2159. if row_index < drop_row:
  2160. drop_row -= 1
  2161. for row_index, data in enumerate(rows_to_move):
  2162. row_index += drop_row
  2163. self.insertRow(row_index)
  2164. for column_index, column_data in enumerate(data):
  2165. if column_data is None:
  2166. continue
  2167. if isinstance(column_data, QtWidgets.QTableWidgetItem):
  2168. self.setItem(row_index, column_index, column_data)
  2169. else:
  2170. self.setCellWidget(row_index, column_index, column_data)
  2171. event.accept()
  2172. for row_index in range(len(rows_to_move)):
  2173. self.item(drop_row + row_index, 0).setSelected(True)
  2174. self.item(drop_row + row_index, 1).setSelected(True)
  2175. self.blockSignals(False)
  2176. self.drag_drop_sig.emit(self.rows_dragged, int(drop_row))
  2177. self.blockSignals(False)
  2178. self.resizeRowsToContents()
  2179. super().dropEvent(event)
  2180. def drop_on(self, event):
  2181. index = self.indexAt(event.pos())
  2182. if not index.isValid():
  2183. return self.rowCount()
  2184. return index.row() + 1 if self.is_below(event.pos(), index) else index.row()
  2185. def is_below(self, pos, index):
  2186. rect = self.visualRect(index)
  2187. margin = 2
  2188. if pos.y() - rect.top() < margin:
  2189. return False
  2190. elif rect.bottom() - pos.y() < margin:
  2191. return True
  2192. # noinspection PyTypeChecker
  2193. return rect.contains(pos, True) and not (int(self.model().flags(index)) & Qt.ItemIsDropEnabled) and \
  2194. pos.y() >= rect.center().y()
  2195. class SpinBoxDelegate(QtWidgets.QItemDelegate):
  2196. def __init__(self, units):
  2197. super(SpinBoxDelegate, self).__init__()
  2198. self.units = units
  2199. self.current_value = None
  2200. def createEditor(self, parent, option, index):
  2201. editor = QtWidgets.QDoubleSpinBox(parent)
  2202. editor.setMinimum(-999.9999)
  2203. editor.setMaximum(999.9999)
  2204. if self.units == 'MM':
  2205. editor.setDecimals(2)
  2206. else:
  2207. editor.setDecimals(3)
  2208. return editor
  2209. def setEditorData(self, spinBox, index):
  2210. try:
  2211. value = float(index.model().data(index, Qt.EditRole))
  2212. except ValueError:
  2213. value = self.current_value
  2214. # return
  2215. spinBox.setValue(value)
  2216. def setModelData(self, spinBox, model, index):
  2217. spinBox.interpretText()
  2218. value = spinBox.value()
  2219. self.current_value = value
  2220. model.setData(index, value, Qt.EditRole)
  2221. def updateEditorGeometry(self, editor, option, index):
  2222. editor.setGeometry(option.rect)
  2223. @staticmethod
  2224. def setDecimals(spinbox, digits):
  2225. spinbox.setDecimals(digits)
  2226. class Dialog_box(QtWidgets.QWidget):
  2227. def __init__(self, title=None, label=None, icon=None, initial_text=None):
  2228. """
  2229. :param title: string with the window title
  2230. :param label: string with the message inside the dialog box
  2231. """
  2232. super(Dialog_box, self).__init__()
  2233. if initial_text is None:
  2234. self.location = str((0, 0))
  2235. else:
  2236. self.location = initial_text
  2237. self.ok = False
  2238. self.dialog_box = QtWidgets.QInputDialog()
  2239. self.dialog_box.setMinimumWidth(290)
  2240. self.setWindowIcon(icon)
  2241. self.location, self.ok = self.dialog_box.getText(self, title, label,
  2242. text=str(self.location).replace('(', '').replace(')', ''))
  2243. self.readyToEdit = True
  2244. def mousePressEvent(self, e, parent=None):
  2245. super(Dialog_box, self).mousePressEvent(e) # required to deselect on 2e click
  2246. if self.readyToEdit:
  2247. self.lineEdit().selectAll()
  2248. self.readyToEdit = False
  2249. def focusOutEvent(self, e):
  2250. # don't focus out if the user requests an popup menu
  2251. if e.reason() != QtCore.Qt.PopupFocusReason:
  2252. super(Dialog_box, self).focusOutEvent(e) # required to remove cursor on focusOut
  2253. self.lineEdit().deselect()
  2254. self.readyToEdit = True
  2255. class DialogBoxRadio(QtWidgets.QDialog):
  2256. def __init__(self, title=None, label=None, icon=None, initial_text=None, reference='abs', parent=None):
  2257. """
  2258. :param title: string with the window title
  2259. :param label: string with the message inside the dialog box
  2260. """
  2261. super(DialogBoxRadio, self).__init__(parent=parent)
  2262. if initial_text is None:
  2263. self.location = str((0, 0))
  2264. else:
  2265. self.location = initial_text
  2266. self.ok = False
  2267. self.setWindowIcon(icon)
  2268. self.setWindowTitle(str(title))
  2269. self.form = QtWidgets.QFormLayout(self)
  2270. self.ref_label = QtWidgets.QLabel('%s:' % _("Reference"))
  2271. self.ref_label.setToolTip(
  2272. _("The reference can be:\n"
  2273. "- Absolute -> the reference point is point (0,0)\n"
  2274. "- Relative -> the reference point is the mouse position before Jump")
  2275. )
  2276. self.ref_radio = RadioSet([
  2277. {"label": _("Abs"), "value": "abs"},
  2278. {"label": _("Relative"), "value": "rel"}
  2279. ], orientation='horizontal', stretch=False)
  2280. self.ref_radio.set_value(reference)
  2281. self.form.addRow(self.ref_label, self.ref_radio)
  2282. self.form.addRow(QtWidgets.QLabel(''))
  2283. self.wdg_label = QtWidgets.QLabel('<b>%s</b>' % str(label))
  2284. self.form.addRow(self.wdg_label)
  2285. self.loc_label = QtWidgets.QLabel('%s:' % _("Location"))
  2286. self.loc_label.setToolTip(
  2287. _("The Location value is a tuple (x,y).\n"
  2288. "If the reference is Absolute then the Jump will be at the position (x,y).\n"
  2289. "If the reference is Relative then the Jump will be at the (x,y) distance\n"
  2290. "from the current mouse location point.")
  2291. )
  2292. self.lineEdit = EvalEntry(parent=self)
  2293. self.lineEdit.setText(str(self.location).replace('(', '').replace(')', ''))
  2294. self.lineEdit.selectAll()
  2295. self.lineEdit.setFocus()
  2296. self.form.addRow(self.loc_label, self.lineEdit)
  2297. self.button_box = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  2298. orientation=Qt.Horizontal, parent=self)
  2299. self.form.addRow(self.button_box)
  2300. self.button_box.accepted.connect(self.accept)
  2301. self.button_box.rejected.connect(self.reject)
  2302. self.readyToEdit = True
  2303. if self.exec_() == QtWidgets.QDialog.Accepted:
  2304. self.ok = True
  2305. self.location = self.lineEdit.text()
  2306. self.reference = self.ref_radio.get_value()
  2307. else:
  2308. self.ok = False
  2309. class _BrowserTextEdit(QTextEdit):
  2310. def __init__(self, version, app=None):
  2311. QTextEdit.__init__(self)
  2312. self.menu = None
  2313. self.version = version
  2314. self.app = app
  2315. def contextMenuEvent(self, event):
  2316. self.menu = self.createStandardContextMenu(event.pos())
  2317. if self.app:
  2318. save_action = QAction(_("Save Log"), self)
  2319. self.menu.addAction(save_action)
  2320. save_action.triggered.connect(lambda: self.save_log(app=self.app))
  2321. clear_action = QAction(_("Clear"), self)
  2322. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  2323. self.menu.addAction(clear_action)
  2324. clear_action.triggered.connect(self.clear)
  2325. if self.app:
  2326. close_action = QAction(_("Close"), self)
  2327. self.menu.addAction(close_action)
  2328. close_action.triggered.connect(lambda: self.app.ui.shell_dock.hide())
  2329. self.menu.exec_(event.globalPos())
  2330. def clear(self):
  2331. QTextEdit.clear(self)
  2332. text = "!FlatCAM %s? - %s" % (self.version, _("Type >help< to get started"))
  2333. text = html.escape(text)
  2334. # hack so I can make text bold because the escape method will replace the '<' and '>' signs with html code
  2335. text = text.replace('!', '<b>')
  2336. text = text.replace('?', '</b>')
  2337. text += '<br><br>'
  2338. self.moveCursor(QTextCursor.End)
  2339. self.insertHtml(text)
  2340. def save_log(self, app):
  2341. html_content = self.toHtml()
  2342. txt_content = self.toPlainText()
  2343. app.save_to_file(content_to_save=html_content, txt_content=txt_content)
  2344. class _ExpandableTextEdit(QTextEdit):
  2345. """
  2346. Class implements edit line, which expands themselves automatically
  2347. """
  2348. historyNext = QtCore.pyqtSignal()
  2349. historyPrev = QtCore.pyqtSignal()
  2350. def __init__(self, termwidget, *args):
  2351. QTextEdit.__init__(self, *args)
  2352. self.setStyleSheet("font: 9pt \"Courier\";")
  2353. self._fittedHeight = 1
  2354. self.textChanged.connect(self._fit_to_document)
  2355. self._fit_to_document()
  2356. self._termWidget = termwidget
  2357. self.completer = MyCompleter()
  2358. self.model = QtCore.QStringListModel()
  2359. self.completer.setModel(self.model)
  2360. self.set_model_data(keyword_list=[])
  2361. self.completer.insertText.connect(self.insertCompletion)
  2362. self.completer.popup().clicked.connect(self.insert_completion_click)
  2363. def set_model_data(self, keyword_list):
  2364. self.model.setStringList(keyword_list)
  2365. def insert_completion_click(self):
  2366. self.completer.insertText.emit(self.completer.getSelected())
  2367. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  2368. def insertCompletion(self, completion):
  2369. tc = self.textCursor()
  2370. extra = (len(completion) - len(self.completer.completionPrefix()))
  2371. # don't insert if the word is finished but add a space instead
  2372. if extra == 0:
  2373. tc.insertText(' ')
  2374. self.completer.popup().hide()
  2375. return
  2376. tc.movePosition(QTextCursor.Left)
  2377. tc.movePosition(QTextCursor.EndOfWord)
  2378. tc.insertText(completion[-extra:])
  2379. # add a space after inserting the word
  2380. tc.insertText(' ')
  2381. self.setTextCursor(tc)
  2382. self.completer.popup().hide()
  2383. def focusInEvent(self, event):
  2384. if self.completer:
  2385. self.completer.setWidget(self)
  2386. QTextEdit.focusInEvent(self, event)
  2387. def keyPressEvent(self, event):
  2388. """
  2389. Catch keyboard events. Process Enter, Up, Down
  2390. """
  2391. key = event.key()
  2392. if (key == Qt.Key_Tab or key == Qt.Key_Return or key == Qt.Key_Enter) and self.completer.popup().isVisible():
  2393. self.completer.insertText.emit(self.completer.getSelected())
  2394. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  2395. return
  2396. if event.matches(QKeySequence.InsertParagraphSeparator):
  2397. text = self.toPlainText()
  2398. if self._termWidget.is_command_complete(text):
  2399. self._termWidget.exec_current_command()
  2400. return
  2401. elif event.matches(QKeySequence.MoveToNextLine):
  2402. text = self.toPlainText()
  2403. cursor_pos = self.textCursor().position()
  2404. textBeforeEnd = text[cursor_pos:]
  2405. if len(textBeforeEnd.split('\n')) <= 1:
  2406. self.historyNext.emit()
  2407. return
  2408. elif event.matches(QKeySequence.MoveToPreviousLine):
  2409. text = self.toPlainText()
  2410. cursor_pos = self.textCursor().position()
  2411. text_before_start = text[:cursor_pos]
  2412. # lineCount = len(textBeforeStart.splitlines())
  2413. line_count = len(text_before_start.split('\n'))
  2414. if len(text_before_start) > 0 and \
  2415. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  2416. line_count += 1
  2417. if line_count <= 1:
  2418. self.historyPrev.emit()
  2419. return
  2420. elif event.matches(QKeySequence.MoveToNextPage) or event.matches(QKeySequence.MoveToPreviousPage):
  2421. return self._termWidget.browser().keyPressEvent(event)
  2422. tc = self.textCursor()
  2423. QTextEdit.keyPressEvent(self, event)
  2424. tc.select(QTextCursor.WordUnderCursor)
  2425. cr = self.cursorRect()
  2426. if len(tc.selectedText()) > 0:
  2427. self.completer.setCompletionPrefix(tc.selectedText())
  2428. popup = self.completer.popup()
  2429. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  2430. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  2431. + self.completer.popup().verticalScrollBar().sizeHint().width())
  2432. self.completer.complete(cr)
  2433. else:
  2434. self.completer.popup().hide()
  2435. def sizeHint(self):
  2436. """
  2437. QWidget sizeHint impelemtation
  2438. """
  2439. hint = QTextEdit.sizeHint(self)
  2440. hint.setHeight(self._fittedHeight)
  2441. return hint
  2442. def _fit_to_document(self):
  2443. """
  2444. Update widget height to fit all text
  2445. """
  2446. documentsize = self.document().size().toSize()
  2447. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  2448. self.setMaximumHeight(self._fittedHeight)
  2449. self.updateGeometry()
  2450. def insertFromMimeData(self, mime_data):
  2451. # Paste only plain text.
  2452. self.insertPlainText(mime_data.text())
  2453. class MyCompleter(QCompleter):
  2454. insertText = QtCore.pyqtSignal(str)
  2455. def __init__(self, parent=None):
  2456. QCompleter.__init__(self, parent=parent)
  2457. self.setCompletionMode(QCompleter.PopupCompletion)
  2458. self.highlighted.connect(self.setHighlighted)
  2459. self.lastSelected = ''
  2460. # self.popup().installEventFilter(self)
  2461. # def eventFilter(self, obj, event):
  2462. # if event.type() == QtCore.QEvent.Wheel and obj is self.popup():
  2463. # pass
  2464. # return False
  2465. def setHighlighted(self, text):
  2466. self.lastSelected = text
  2467. def getSelected(self):
  2468. return self.lastSelected
  2469. class FCTextAreaLineNumber(QtWidgets.QFrame):
  2470. textChanged = QtCore.pyqtSignal()
  2471. class NumberBar(QtWidgets.QWidget):
  2472. def __init__(self, edit):
  2473. QtWidgets.QWidget.__init__(self, edit)
  2474. self.edit = edit
  2475. self.adjustWidth(1)
  2476. def paintEvent(self, event):
  2477. self.edit.numberbarPaint(self, event)
  2478. QtWidgets.QWidget.paintEvent(self, event)
  2479. def adjustWidth(self, count):
  2480. # three spaces added to the width to make up for the space added in the line number
  2481. width = self.fontMetrics().width(str(count) + ' ')
  2482. if self.width() != width:
  2483. self.setFixedWidth(width)
  2484. def updateContents(self, rect, scroll):
  2485. if scroll:
  2486. self.scroll(0, scroll)
  2487. else:
  2488. # It would be nice to do
  2489. # self.update(0, rect.y(), self.width(), rect.height())
  2490. # But we can't because it will not remove the bold on the
  2491. # current line if word wrap is enabled and a new block is
  2492. # selected.
  2493. self.update()
  2494. class PlainTextEdit(FCPlainTextAreaExtended):
  2495. """
  2496. TextEdit with line numbers and highlight
  2497. From here: https://nachtimwald.com/2009/08/19/better-qplaintextedit-with-line-numbers/
  2498. and from here: https://doc.qt.io/qt-5/qtwidgets-widgets-codeeditor-example.html
  2499. """
  2500. def __init__(self, *args):
  2501. FCPlainTextAreaExtended.__init__(self, *args)
  2502. # self.setFrameStyle(QFrame.NoFrame)
  2503. self.setFrameStyle(QtWidgets.QFrame.NoFrame)
  2504. self.highlight()
  2505. # self.setLineWrapMode(QPlainTextEdit.NoWrap)
  2506. self.cursorPositionChanged.connect(self.highlight)
  2507. def highlight(self):
  2508. hi_selection = QTextEdit.ExtraSelection()
  2509. hi_selection.format.setBackground(self.palette().alternateBase())
  2510. hi_selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True)
  2511. hi_selection.cursor = self.textCursor()
  2512. hi_selection.cursor.clearSelection()
  2513. self.setExtraSelections([hi_selection])
  2514. def numberbarPaint(self, number_bar, event):
  2515. font_metrics = self.fontMetrics()
  2516. current_line = self.document().findBlock(self.textCursor().position()).blockNumber() + 1
  2517. painter = QtGui.QPainter(number_bar)
  2518. painter.fillRect(event.rect(), QtCore.Qt.lightGray)
  2519. block = self.firstVisibleBlock()
  2520. line_count = int(block.blockNumber())
  2521. block_top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
  2522. block_bottom = block_top + int(self.blockBoundingRect(block).height())
  2523. # Iterate over all visible text blocks in the document.
  2524. while block.isValid() and block_top <= event.rect().bottom():
  2525. line_count += 1
  2526. # Check if the position of the block is out side of the visible
  2527. # area.
  2528. if block.isVisible() and block_bottom >= event.rect().top():
  2529. # We want the line number for the selected line to be bold.
  2530. if line_count == current_line:
  2531. font = painter.font()
  2532. font.setBold(True)
  2533. painter.setPen(QtCore.Qt.blue)
  2534. painter.setFont(font)
  2535. else:
  2536. font = painter.font()
  2537. font.setBold(False)
  2538. painter.setPen(self.palette().base().color())
  2539. painter.setFont(font)
  2540. # Draw the line number right justified at the position of the line.
  2541. paint_rect = QtCore.QRect(0, block_top, number_bar.width(), font_metrics.height())
  2542. # I add some spaces to the line_count to prettify; make sure to remember adjust the width in the
  2543. # NumberBar() class above
  2544. painter.drawText(paint_rect, Qt.AlignRight, ' ' + str(line_count) + ' ')
  2545. block = block.next()
  2546. block_top = block_bottom
  2547. block_bottom = block_top + self.blockBoundingRect(block).height()
  2548. painter.end()
  2549. def __init__(self, *args):
  2550. QtWidgets.QFrame.__init__(self, *args)
  2551. self.setFrameStyle(QtWidgets.QFrame.StyledPanel | QtWidgets.QFrame.Sunken)
  2552. self.edit = self.PlainTextEdit()
  2553. self.number_bar = self.NumberBar(self.edit)
  2554. hbox = QtWidgets.QHBoxLayout(self)
  2555. hbox.setSpacing(0)
  2556. hbox.setContentsMargins(0, 0, 0, 0)
  2557. hbox.addWidget(self.number_bar)
  2558. hbox.addWidget(self.edit)
  2559. self.edit.blockCountChanged.connect(self.number_bar.adjustWidth)
  2560. self.edit.updateRequest.connect(self.number_bar.updateContents)
  2561. def getText(self):
  2562. return str(self.edit.toPlainText())
  2563. def setText(self, text):
  2564. self.edit.setPlainText(text)
  2565. def isModified(self):
  2566. return self.edit.document().isModified()
  2567. def setModified(self, modified):
  2568. self.edit.document().setModified(modified)
  2569. def setLineWrapMode(self, mode):
  2570. self.edit.setLineWrapMode(mode)
  2571. class FCFileSaveDialog(QtWidgets.QFileDialog):
  2572. def __init__(self, *args):
  2573. super(FCFileSaveDialog, self).__init__(*args)
  2574. @staticmethod
  2575. def get_saved_filename(parent=None, caption='', directory='', ext_filter='', initialFilter=''):
  2576. filename, _filter = QtWidgets.QFileDialog.getSaveFileName(parent=parent, caption=caption,
  2577. directory=directory, filter=ext_filter,
  2578. initialFilter=initialFilter)
  2579. filename = str(filename)
  2580. if filename == '':
  2581. return filename, _filter
  2582. extension = '.' + _filter.strip(')').rpartition('.')[2]
  2583. if filename.endswith(extension) or extension == '.*':
  2584. return filename, _filter
  2585. else:
  2586. filename += extension
  2587. return filename, _filter
  2588. class FCDock(QtWidgets.QDockWidget):
  2589. def __init__(self, *args, **kwargs):
  2590. super(FCDock, self).__init__(*args)
  2591. self.close_callback = kwargs["close_callback"] if "close_callback" in kwargs else None
  2592. def closeEvent(self, event: QtGui.QCloseEvent) -> None:
  2593. self.close_callback()
  2594. super().closeEvent(event)
  2595. def show(self) -> None:
  2596. if self.isFloating():
  2597. self.setFloating(False)
  2598. super().show()
  2599. class FlatCAMActivityView(QtWidgets.QWidget):
  2600. """
  2601. This class create and control the activity icon displayed in the App status bar
  2602. """
  2603. def __init__(self, app, parent=None):
  2604. super().__init__(parent=parent)
  2605. self.app = app
  2606. if self.app.defaults["global_activity_icon"] == "Ball green":
  2607. icon = self.app.resource_location + '/active_2_static.png'
  2608. movie = self.app.resource_location + "/active_2.gif"
  2609. elif self.app.defaults["global_activity_icon"] == "Ball black":
  2610. icon = self.app.resource_location + '/active_static.png'
  2611. movie = self.app.resource_location + "/active.gif"
  2612. elif self.app.defaults["global_activity_icon"] == "Arrow green":
  2613. icon = self.app.resource_location + '/active_3_static.png'
  2614. movie = self.app.resource_location + "/active_3.gif"
  2615. elif self.app.defaults["global_activity_icon"] == "Eclipse green":
  2616. icon = self.app.resource_location + '/active_4_static.png'
  2617. movie = self.app.resource_location + "/active_4.gif"
  2618. else:
  2619. icon = self.app.resource_location + '/active_static.png'
  2620. movie = self.app.resource_location + "/active.gif"
  2621. self.setMinimumWidth(200)
  2622. self.movie_path = movie
  2623. self.icon_path = icon
  2624. self.icon = FCLabel(self)
  2625. self.icon.setGeometry(0, 0, 16, 12)
  2626. self.movie = QtGui.QMovie(self.movie_path)
  2627. self.icon.setMovie(self.movie)
  2628. # self.movie.start()
  2629. layout = QtWidgets.QHBoxLayout()
  2630. layout.setContentsMargins(5, 0, 5, 0)
  2631. layout.setAlignment(QtCore.Qt.AlignLeft)
  2632. self.setLayout(layout)
  2633. layout.addWidget(self.icon)
  2634. self.text = QtWidgets.QLabel(self)
  2635. self.text.setText(_("Idle."))
  2636. self.icon.setPixmap(QtGui.QPixmap(self.icon_path))
  2637. layout.addWidget(self.text)
  2638. self.icon.clicked.connect(self.app.on_toolbar_replot)
  2639. def set_idle(self):
  2640. self.movie.stop()
  2641. self.text.setText(_("Idle."))
  2642. def set_busy(self, msg, no_movie=None):
  2643. if no_movie is not True:
  2644. self.icon.setMovie(self.movie)
  2645. self.movie.start()
  2646. self.text.setText(msg)
  2647. class FlatCAMInfoBar(QtWidgets.QWidget):
  2648. """
  2649. This class create a place to display the App messages in the Status Bar
  2650. """
  2651. def __init__(self, parent=None, app=None):
  2652. super(FlatCAMInfoBar, self).__init__(parent=parent)
  2653. self.app = app
  2654. self.icon = QtWidgets.QLabel(self)
  2655. self.icon.setGeometry(0, 0, 12, 12)
  2656. self.pmap = QtGui.QPixmap(self.app.resource_location + '/graylight12.png')
  2657. self.icon.setPixmap(self.pmap)
  2658. self.lock_pmaps = False
  2659. layout = QtWidgets.QHBoxLayout()
  2660. layout.setContentsMargins(5, 0, 5, 0)
  2661. self.setLayout(layout)
  2662. layout.addWidget(self.icon)
  2663. self.text = QtWidgets.QLabel(self)
  2664. self.text.setText(_("Application started ..."))
  2665. self.text.setToolTip(_("Hello!"))
  2666. layout.addWidget(self.text)
  2667. layout.addStretch()
  2668. def set_text_(self, text, color=None):
  2669. self.text.setText(text)
  2670. self.text.setToolTip(text)
  2671. if color:
  2672. self.text.setStyleSheet('color: %s' % str(color))
  2673. def set_status(self, text, level="info"):
  2674. level = str(level)
  2675. if self.lock_pmaps is not True:
  2676. self.pmap.fill()
  2677. if level == "ERROR" or level == "ERROR_NOTCL":
  2678. self.pmap = QtGui.QPixmap(self.app.resource_location + '/redlight12.png')
  2679. elif level.lower() == "success":
  2680. self.pmap = QtGui.QPixmap(self.app.resource_location + '/greenlight12.png')
  2681. elif level == "WARNING" or level == "WARNING_NOTCL":
  2682. self.pmap = QtGui.QPixmap(self.app.resource_location + '/yellowlight12.png')
  2683. elif level.lower() == "selected":
  2684. self.pmap = QtGui.QPixmap(self.app.resource_location + '/bluelight12.png')
  2685. else:
  2686. self.pmap = QtGui.QPixmap(self.app.resource_location + '/graylight12.png')
  2687. try:
  2688. self.set_text_(text)
  2689. self.icon.setPixmap(self.pmap)
  2690. except Exception as e:
  2691. log.debug("FlatCAMInfoBar.set_status() --> %s" % str(e))
  2692. class FlatCAMSystemTray(QtWidgets.QSystemTrayIcon):
  2693. """
  2694. This class create the Sys Tray icon for the app
  2695. """
  2696. def __init__(self, app, icon, headless=None, parent=None):
  2697. # QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
  2698. super().__init__(icon, parent=parent)
  2699. self.app = app
  2700. menu = QtWidgets.QMenu(parent)
  2701. menu_runscript = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/script14.png'),
  2702. '%s' % _('Run Script ...'), self)
  2703. menu_runscript.setToolTip(
  2704. _("Will run the opened Tcl Script thus\n"
  2705. "enabling the automation of certain\n"
  2706. "functions of FlatCAM.")
  2707. )
  2708. menu.addAction(menu_runscript)
  2709. menu.addSeparator()
  2710. if headless is None:
  2711. self.menu_open = menu.addMenu(QtGui.QIcon(self.app.resource_location + '/folder32_bis.png'), _('Open'))
  2712. # Open Project ...
  2713. menu_openproject = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/folder16.png'),
  2714. _('Open Project ...'), self)
  2715. self.menu_open.addAction(menu_openproject)
  2716. self.menu_open.addSeparator()
  2717. # Open Gerber ...
  2718. menu_opengerber = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/flatcam_icon24.png'),
  2719. _('Open &Gerber ...\tCtrl+G'), self)
  2720. self.menu_open.addAction(menu_opengerber)
  2721. # Open Excellon ...
  2722. menu_openexcellon = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/open_excellon32.png'),
  2723. _('Open &Excellon ...\tCtrl+E'), self)
  2724. self.menu_open.addAction(menu_openexcellon)
  2725. # Open G-Code ...
  2726. menu_opengcode = QtWidgets.QAction(QtGui.QIcon(self.app.resource_location + '/code.png'),
  2727. _('Open G-&Code ...'), self)
  2728. self.menu_open.addAction(menu_opengcode)
  2729. self.menu_open.addSeparator()
  2730. menu_openproject.triggered.connect(self.app.on_file_openproject)
  2731. menu_opengerber.triggered.connect(self.app.on_fileopengerber)
  2732. menu_openexcellon.triggered.connect(self.app.on_fileopenexcellon)
  2733. menu_opengcode.triggered.connect(self.app.on_fileopengcode)
  2734. exitAction = menu.addAction(_("Exit"))
  2735. exitAction.setIcon(QtGui.QIcon(self.app.resource_location + '/power16.png'))
  2736. self.setContextMenu(menu)
  2737. menu_runscript.triggered.connect(lambda: self.app.on_filerunscript(
  2738. silent=True if self.app.cmd_line_headless == 1 else False))
  2739. exitAction.triggered.connect(self.app.final_save)
  2740. def message_dialog(title, message, kind="info", parent=None):
  2741. """
  2742. Builds and show a custom QMessageBox to be used in FlatCAM.
  2743. :param title: title of the QMessageBox
  2744. :param message: message to be displayed
  2745. :param kind: type of QMessageBox; will display a specific icon.
  2746. :param parent: parent
  2747. :return: None
  2748. """
  2749. icon = {"info": QtWidgets.QMessageBox.Information,
  2750. "warning": QtWidgets.QMessageBox.Warning,
  2751. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2752. dlg = QtWidgets.QMessageBox(icon, title, message, parent=parent)
  2753. dlg.setText(message)
  2754. dlg.exec_()
  2755. def rreplace(s, old, new, occurrence):
  2756. """
  2757. Credits go here:
  2758. https://stackoverflow.com/questions/2556108/rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string
  2759. :param s: string to be processed
  2760. :param old: old char to be replaced
  2761. :param new: new char to replace the old one
  2762. :param occurrence: how many places from end to replace the old char
  2763. :return: modified string
  2764. """
  2765. li = s.rsplit(old, occurrence)
  2766. return new.join(li)