GUIElements.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  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, pyqtSignal, pyqtSlot
  14. from PyQt5.QtWidgets import QTextEdit, QCompleter, QAction
  15. from PyQt5.QtGui import QColor, QKeySequence, QPalette, QTextCursor
  16. from copy import copy
  17. import re
  18. import logging
  19. import html
  20. log = logging.getLogger('base')
  21. EDIT_SIZE_HINT = 70
  22. class RadioSet(QtWidgets.QWidget):
  23. activated_custom = QtCore.pyqtSignal(str)
  24. def __init__(self, choices, orientation='horizontal', parent=None, stretch=None):
  25. """
  26. The choices are specified as a list of dictionaries containing:
  27. * 'label': Shown in the UI
  28. * 'value': The value returned is selected
  29. :param choices: List of choices. See description.
  30. :param orientation: 'horizontal' (default) of 'vertical'.
  31. :param parent: Qt parent widget.
  32. :type choices: list
  33. """
  34. super(RadioSet, self).__init__(parent)
  35. self.choices = copy(choices)
  36. if orientation == 'horizontal':
  37. layout = QtWidgets.QHBoxLayout()
  38. else:
  39. layout = QtWidgets.QVBoxLayout()
  40. group = QtWidgets.QButtonGroup(self)
  41. for choice in self.choices:
  42. choice['radio'] = QtWidgets.QRadioButton(choice['label'])
  43. group.addButton(choice['radio'])
  44. layout.addWidget(choice['radio'], stretch=0)
  45. choice['radio'].toggled.connect(self.on_toggle)
  46. layout.setContentsMargins(0, 0, 0, 0)
  47. if stretch is False:
  48. pass
  49. else:
  50. layout.addStretch()
  51. self.setLayout(layout)
  52. self.group_toggle_fn = lambda: None
  53. def on_toggle(self):
  54. # log.debug("Radio toggled")
  55. radio = self.sender()
  56. if radio.isChecked():
  57. self.group_toggle_fn()
  58. ret_val = str(self.get_value())
  59. self.activated_custom.emit(ret_val)
  60. return
  61. def get_value(self):
  62. for choice in self.choices:
  63. if choice['radio'].isChecked():
  64. return choice['value']
  65. log.error("No button was toggled in RadioSet.")
  66. return None
  67. def set_value(self, val):
  68. for choice in self.choices:
  69. if choice['value'] == val:
  70. choice['radio'].setChecked(True)
  71. return
  72. log.error("Value given is not part of this RadioSet: %s" % str(val))
  73. # class RadioGroupChoice(QtWidgets.QWidget):
  74. # def __init__(self, label_1, label_2, to_check, hide_list, show_list, parent=None):
  75. # """
  76. # The choices are specified as a list of dictionaries containing:
  77. #
  78. # * 'label': Shown in the UI
  79. # * 'value': The value returned is selected
  80. #
  81. # :param choices: List of choices. See description.
  82. # :param orientation: 'horizontal' (default) of 'vertical'.
  83. # :param parent: Qt parent widget.
  84. # :type choices: list
  85. # """
  86. # super().__init__(parent)
  87. #
  88. # group = QtGui.QButtonGroup(self)
  89. #
  90. # self.lbl1 = label_1
  91. # self.lbl2 = label_2
  92. # self.hide_list = hide_list
  93. # self.show_list = show_list
  94. #
  95. # self.btn1 = QtGui.QRadioButton(str(label_1))
  96. # self.btn2 = QtGui.QRadioButton(str(label_2))
  97. # group.addButton(self.btn1)
  98. # group.addButton(self.btn2)
  99. #
  100. # if to_check == 1:
  101. # self.btn1.setChecked(True)
  102. # else:
  103. # self.btn2.setChecked(True)
  104. #
  105. # self.btn1.toggled.connect(lambda: self.btn_state(self.btn1))
  106. # self.btn2.toggled.connect(lambda: self.btn_state(self.btn2))
  107. #
  108. # def btn_state(self, btn):
  109. # if btn.text() == self.lbl1:
  110. # if btn.isChecked() is True:
  111. # self.show_widgets(self.show_list)
  112. # self.hide_widgets(self.hide_list)
  113. # else:
  114. # self.show_widgets(self.hide_list)
  115. # self.hide_widgets(self.show_list)
  116. #
  117. # def hide_widgets(self, lst):
  118. # for wgt in lst:
  119. # wgt.hide()
  120. #
  121. # def show_widgets(self, lst):
  122. # for wgt in lst:
  123. # wgt.show()
  124. class LengthEntry(QtWidgets.QLineEdit):
  125. def __init__(self, output_units='IN', parent=None):
  126. super(LengthEntry, self).__init__(parent)
  127. self.output_units = output_units
  128. self.format_re = re.compile(r"^([^\s]+)(?:\s([a-zA-Z]+))?$")
  129. # Unit conversion table OUTPUT-INPUT
  130. self.scales = {
  131. 'IN': {'IN': 1.0,
  132. 'MM': 1/25.4},
  133. 'MM': {'IN': 25.4,
  134. 'MM': 1.0}
  135. }
  136. self.readyToEdit = True
  137. self.editingFinished.connect(self.on_edit_finished)
  138. def on_edit_finished(self):
  139. self.clearFocus()
  140. def mousePressEvent(self, e, Parent=None):
  141. super(LengthEntry, self).mousePressEvent(e) # required to deselect on 2e click
  142. if self.readyToEdit:
  143. self.selectAll()
  144. self.readyToEdit = False
  145. def focusOutEvent(self, e):
  146. super(LengthEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  147. self.deselect()
  148. self.readyToEdit = True
  149. def returnPressed(self, *args, **kwargs):
  150. val = self.get_value()
  151. if val is not None:
  152. self.set_text(str(val))
  153. else:
  154. log.warning("Could not interpret entry: %s" % self.get_text())
  155. def get_value(self):
  156. raw = str(self.text()).strip(' ')
  157. # match = self.format_re.search(raw)
  158. try:
  159. units = raw[-2:]
  160. units = self.scales[self.output_units][units.upper()]
  161. value = raw[:-2]
  162. return float(eval(value))* units
  163. except IndexError:
  164. value = raw
  165. return float(eval(value))
  166. except KeyError:
  167. value = raw
  168. return float(eval(value))
  169. except:
  170. log.warning("Could not parse value in entry: %s" % str(raw))
  171. return None
  172. def set_value(self, val):
  173. self.setText(str('%.4f' % val))
  174. def sizeHint(self):
  175. default_hint_size = super(LengthEntry, self).sizeHint()
  176. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  177. class FloatEntry(QtWidgets.QLineEdit):
  178. def __init__(self, parent=None):
  179. super(FloatEntry, self).__init__(parent)
  180. self.readyToEdit = True
  181. self.editingFinished.connect(self.on_edit_finished)
  182. def on_edit_finished(self):
  183. self.clearFocus()
  184. def mousePressEvent(self, e, Parent=None):
  185. super(FloatEntry, self).mousePressEvent(e) # required to deselect on 2e click
  186. if self.readyToEdit:
  187. self.selectAll()
  188. self.readyToEdit = False
  189. def focusOutEvent(self, e):
  190. super(FloatEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  191. self.deselect()
  192. self.readyToEdit = True
  193. def returnPressed(self, *args, **kwargs):
  194. val = self.get_value()
  195. if val is not None:
  196. self.set_text(str(val))
  197. else:
  198. log.warning("Could not interpret entry: %s" % self.text())
  199. def get_value(self):
  200. raw = str(self.text()).strip(' ')
  201. evaled = 0.0
  202. try:
  203. evaled = eval(raw)
  204. except:
  205. if evaled is not None:
  206. log.error("Could not evaluate: %s" % str(raw))
  207. return None
  208. return float(evaled)
  209. def set_value(self, val):
  210. if val is not None:
  211. self.setText("%.4f" % val)
  212. else:
  213. self.setText("")
  214. def sizeHint(self):
  215. default_hint_size = super(FloatEntry, self).sizeHint()
  216. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  217. class FloatEntry2(QtWidgets.QLineEdit):
  218. def __init__(self, parent=None):
  219. super(FloatEntry2, self).__init__(parent)
  220. self.readyToEdit = True
  221. self.editingFinished.connect(self.on_edit_finished)
  222. def on_edit_finished(self):
  223. self.clearFocus()
  224. def mousePressEvent(self, e, Parent=None):
  225. super(FloatEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  226. if self.readyToEdit:
  227. self.selectAll()
  228. self.readyToEdit = False
  229. def focusOutEvent(self, e):
  230. super(FloatEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  231. self.deselect()
  232. self.readyToEdit = True
  233. def get_value(self):
  234. raw = str(self.text()).strip(' ')
  235. evaled = 0.0
  236. try:
  237. evaled = eval(raw)
  238. except:
  239. if evaled is not None:
  240. log.error("Could not evaluate: %s" % str(raw))
  241. return None
  242. return float(evaled)
  243. def set_value(self, val):
  244. self.setText("%.4f" % val)
  245. def sizeHint(self):
  246. default_hint_size = super(FloatEntry2, self).sizeHint()
  247. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  248. class IntEntry(QtWidgets.QLineEdit):
  249. def __init__(self, parent=None, allow_empty=False, empty_val=None):
  250. super(IntEntry, self).__init__(parent)
  251. self.allow_empty = allow_empty
  252. self.empty_val = empty_val
  253. self.readyToEdit = True
  254. self.editingFinished.connect(self.on_edit_finished)
  255. def on_edit_finished(self):
  256. self.clearFocus()
  257. def mousePressEvent(self, e, Parent=None):
  258. super(IntEntry, self).mousePressEvent(e) # required to deselect on 2e click
  259. if self.readyToEdit:
  260. self.selectAll()
  261. self.readyToEdit = False
  262. def focusOutEvent(self, e):
  263. super(IntEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  264. self.deselect()
  265. self.readyToEdit = True
  266. def get_value(self):
  267. if self.allow_empty:
  268. if str(self.text()) == "":
  269. return self.empty_val
  270. # make the text() first a float and then int because if text is a float type,
  271. # the int() can't convert directly a "text float" into a int type.
  272. ret_val = float(self.text())
  273. ret_val = int(ret_val)
  274. return ret_val
  275. def set_value(self, val):
  276. if val == self.empty_val and self.allow_empty:
  277. self.setText("")
  278. return
  279. self.setText(str(val))
  280. def sizeHint(self):
  281. default_hint_size = super(IntEntry, self).sizeHint()
  282. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  283. class FCEntry(QtWidgets.QLineEdit):
  284. def __init__(self, parent=None):
  285. super(FCEntry, self).__init__(parent)
  286. self.readyToEdit = True
  287. self.editingFinished.connect(self.on_edit_finished)
  288. def on_edit_finished(self):
  289. self.clearFocus()
  290. def mousePressEvent(self, e, Parent=None):
  291. super(FCEntry, self).mousePressEvent(e) # required to deselect on 2e click
  292. if self.readyToEdit:
  293. self.selectAll()
  294. self.readyToEdit = False
  295. def focusOutEvent(self, e):
  296. super(FCEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  297. self.deselect()
  298. self.readyToEdit = True
  299. def get_value(self):
  300. return str(self.text())
  301. def set_value(self, val):
  302. if type(val) is float:
  303. self.setText('%.4f' % val)
  304. else:
  305. self.setText(str(val))
  306. def sizeHint(self):
  307. default_hint_size = super(FCEntry, self).sizeHint()
  308. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  309. class FCEntry2(FCEntry):
  310. def __init__(self, parent=None):
  311. super(FCEntry2, self).__init__(parent)
  312. self.readyToEdit = True
  313. self.editingFinished.connect(self.on_edit_finished)
  314. def on_edit_finished(self):
  315. self.clearFocus()
  316. def set_value(self, val, decimals=4):
  317. try:
  318. fval = float(val)
  319. except ValueError:
  320. return
  321. self.setText('%.*f' % (decimals, fval))
  322. class FCEntry3(FCEntry):
  323. def __init__(self, parent=None):
  324. super(FCEntry3, self).__init__(parent)
  325. self.readyToEdit = True
  326. self.editingFinished.connect(self.on_edit_finished)
  327. def on_edit_finished(self):
  328. self.clearFocus()
  329. def set_value(self, val, decimals=4):
  330. try:
  331. fval = float(val)
  332. except ValueError:
  333. return
  334. self.setText('%.*f' % (decimals, fval))
  335. def get_value(self):
  336. value = str(self.text()).strip(' ')
  337. try:
  338. return float(eval(value))
  339. except Exception as e:
  340. log.warning("Could not parse value in entry: %s" % str(e))
  341. return None
  342. class EvalEntry(QtWidgets.QLineEdit):
  343. def __init__(self, parent=None):
  344. super(EvalEntry, self).__init__(parent)
  345. self.readyToEdit = True
  346. self.editingFinished.connect(self.on_edit_finished)
  347. def on_edit_finished(self):
  348. self.clearFocus()
  349. def mousePressEvent(self, e, Parent=None):
  350. super(EvalEntry, self).mousePressEvent(e) # required to deselect on 2e click
  351. if self.readyToEdit:
  352. self.selectAll()
  353. self.readyToEdit = False
  354. def focusOutEvent(self, e):
  355. super(EvalEntry, self).focusOutEvent(e) # required to remove cursor on focusOut
  356. self.deselect()
  357. self.readyToEdit = True
  358. def returnPressed(self, *args, **kwargs):
  359. val = self.get_value()
  360. if val is not None:
  361. self.setText(str(val))
  362. else:
  363. log.warning("Could not interpret entry: %s" % self.get_text())
  364. def get_value(self):
  365. raw = str(self.text()).strip(' ')
  366. evaled = 0.0
  367. try:
  368. evaled = eval(raw)
  369. except:
  370. if evaled is not None:
  371. log.error("Could not evaluate: %s" % str(raw))
  372. return None
  373. return evaled
  374. def set_value(self, val):
  375. self.setText(str(val))
  376. def sizeHint(self):
  377. default_hint_size = super(EvalEntry, self).sizeHint()
  378. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  379. class EvalEntry2(QtWidgets.QLineEdit):
  380. def __init__(self, parent=None):
  381. super(EvalEntry2, self).__init__(parent)
  382. self.readyToEdit = True
  383. self.editingFinished.connect(self.on_edit_finished)
  384. def on_edit_finished(self):
  385. self.clearFocus()
  386. def mousePressEvent(self, e, Parent=None):
  387. super(EvalEntry2, self).mousePressEvent(e) # required to deselect on 2e click
  388. if self.readyToEdit:
  389. self.selectAll()
  390. self.readyToEdit = False
  391. def focusOutEvent(self, e):
  392. super(EvalEntry2, self).focusOutEvent(e) # required to remove cursor on focusOut
  393. self.deselect()
  394. self.readyToEdit = True
  395. def get_value(self):
  396. raw = str(self.text()).strip(' ')
  397. evaled = 0.0
  398. try:
  399. evaled = eval(raw)
  400. except:
  401. if evaled is not None:
  402. log.error("Could not evaluate: %s" % str(raw))
  403. return None
  404. return evaled
  405. def set_value(self, val):
  406. self.setText(str(val))
  407. def sizeHint(self):
  408. default_hint_size = super(EvalEntry2, self).sizeHint()
  409. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  410. class FCCheckBox(QtWidgets.QCheckBox):
  411. def __init__(self, label='', parent=None):
  412. super(FCCheckBox, self).__init__(str(label), parent)
  413. def get_value(self):
  414. return self.isChecked()
  415. def set_value(self, val):
  416. self.setChecked(val)
  417. def toggle(self):
  418. self.set_value(not self.get_value())
  419. class FCTextArea(QtWidgets.QPlainTextEdit):
  420. def __init__(self, parent=None):
  421. super(FCTextArea, self).__init__(parent)
  422. def set_value(self, val):
  423. self.setPlainText(val)
  424. def get_value(self):
  425. return str(self.toPlainText())
  426. def sizeHint(self):
  427. default_hint_size = super(FCTextArea, self).sizeHint()
  428. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  429. class FCTextAreaRich(QtWidgets.QTextEdit):
  430. def __init__(self, parent=None):
  431. super(FCTextAreaRich, self).__init__(parent)
  432. def set_value(self, val):
  433. self.setText(val)
  434. def get_value(self):
  435. return str(self.toPlainText())
  436. def sizeHint(self):
  437. default_hint_size = super(FCTextAreaRich, self).sizeHint()
  438. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  439. class FCTextAreaExtended(QtWidgets.QTextEdit):
  440. def __init__(self, parent=None):
  441. super(FCTextAreaExtended, self).__init__(parent)
  442. self.completer = MyCompleter()
  443. self.model = QtCore.QStringListModel()
  444. self.completer.setModel(self.model)
  445. self.set_model_data(keyword_list=[])
  446. self.completer.insertText.connect(self.insertCompletion)
  447. self.completer_enable = False
  448. def set_model_data(self, keyword_list):
  449. self.model.setStringList(keyword_list)
  450. def insertCompletion(self, completion):
  451. tc = self.textCursor()
  452. extra = (len(completion) - len(self.completer.completionPrefix()))
  453. # don't insert if the word is finished but add a space instead
  454. if extra == 0:
  455. tc.insertText(' ')
  456. self.completer.popup().hide()
  457. return
  458. tc.movePosition(QTextCursor.Left)
  459. tc.movePosition(QTextCursor.EndOfWord)
  460. tc.insertText(completion[-extra:])
  461. # add a space after inserting the word
  462. tc.insertText(' ')
  463. self.setTextCursor(tc)
  464. self.completer.popup().hide()
  465. def focusInEvent(self, event):
  466. if self.completer:
  467. self.completer.setWidget(self)
  468. QTextEdit.focusInEvent(self, event)
  469. def set_value(self, val):
  470. self.setText(val)
  471. def get_value(self):
  472. self.toPlainText()
  473. def insertFromMimeData(self, data):
  474. """
  475. Reimplemented such that when SHIFT is pressed and doing click Paste in the contextual menu, the '\' symbol
  476. is replaced with the '/' symbol. That's because of the difference in path separators in Windows and TCL
  477. :param data:
  478. :return:
  479. """
  480. modifier = QtWidgets.QApplication.keyboardModifiers()
  481. if modifier == Qt.ShiftModifier:
  482. text = data.text()
  483. text = text.replace('\\', '/')
  484. self.insertPlainText(text)
  485. else:
  486. self.insertPlainText(data.text())
  487. def keyPressEvent(self, event):
  488. """
  489. Reimplemented so the CTRL + SHIFT + V shortcut key combo will paste the text but replacing '\' with '/'
  490. :param event:
  491. :return:
  492. """
  493. key = event.key()
  494. modifier = QtWidgets.QApplication.keyboardModifiers()
  495. if modifier & Qt.ControlModifier and modifier & Qt.ShiftModifier:
  496. if key == QtCore.Qt.Key_V:
  497. clipboard = QtWidgets.QApplication.clipboard()
  498. clip_text = clipboard.text()
  499. clip_text = clip_text.replace('\\', '/')
  500. self.insertPlainText(clip_text)
  501. if modifier & Qt.ControlModifier and key == Qt.Key_Slash:
  502. self.comment()
  503. tc = self.textCursor()
  504. if (key == Qt.Key_Tab or key == Qt.Key_Enter or key == Qt.Key_Return) and self.completer.popup().isVisible():
  505. self.completer.insertText.emit(self.completer.getSelected())
  506. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  507. return
  508. elif key == Qt.Key_BraceLeft:
  509. tc.insertText('{}')
  510. self.moveCursor(QtGui.QTextCursor.Left)
  511. elif key == Qt.Key_BracketLeft:
  512. tc.insertText('[]')
  513. self.moveCursor(QtGui.QTextCursor.Left)
  514. elif key == Qt.Key_ParenLeft:
  515. tc.insertText('()')
  516. self.moveCursor(QtGui.QTextCursor.Left)
  517. elif key == Qt.Key_BraceRight:
  518. tc.select(QtGui.QTextCursor.WordUnderCursor)
  519. if tc.selectedText() == '}':
  520. tc.movePosition(QTextCursor.Right)
  521. self.setTextCursor(tc)
  522. else:
  523. tc.clearSelection()
  524. self.textCursor().insertText('}')
  525. elif key == Qt.Key_BracketRight:
  526. tc.select(QtGui.QTextCursor.WordUnderCursor)
  527. if tc.selectedText() == ']':
  528. tc.movePosition(QTextCursor.Right)
  529. self.setTextCursor(tc)
  530. else:
  531. tc.clearSelection()
  532. self.textCursor().insertText(']')
  533. elif key == Qt.Key_ParenRight:
  534. tc.select(QtGui.QTextCursor.WordUnderCursor)
  535. if tc.selectedText() == ')':
  536. tc.movePosition(QTextCursor.Right)
  537. self.setTextCursor(tc)
  538. else:
  539. tc.clearSelection()
  540. self.textCursor().insertText(')')
  541. else:
  542. super(FCTextAreaExtended, self).keyPressEvent(event)
  543. if self.completer_enable:
  544. tc.select(QTextCursor.WordUnderCursor)
  545. cr = self.cursorRect()
  546. if len(tc.selectedText()) > 0:
  547. self.completer.setCompletionPrefix(tc.selectedText())
  548. popup = self.completer.popup()
  549. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  550. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  551. + self.completer.popup().verticalScrollBar().sizeHint().width())
  552. self.completer.complete(cr)
  553. else:
  554. self.completer.popup().hide()
  555. def comment(self):
  556. """
  557. Got it from here:
  558. https://stackoverflow.com/questions/49898820/how-to-get-text-next-to-cursor-in-qtextedit-in-pyqt4
  559. :return:
  560. """
  561. pos = self.textCursor().position()
  562. self.moveCursor(QtGui.QTextCursor.StartOfLine)
  563. line_text = self.textCursor().block().text()
  564. if self.textCursor().block().text().startswith(" "):
  565. # skip the white space
  566. self.moveCursor(QtGui.QTextCursor.NextWord)
  567. self.moveCursor(QtGui.QTextCursor.NextCharacter,QtGui.QTextCursor.KeepAnchor)
  568. character = self.textCursor().selectedText()
  569. if character == "#":
  570. # delete #
  571. self.textCursor().deletePreviousChar()
  572. # delete white space
  573. self.moveCursor(QtGui.QTextCursor.NextWord,QtGui.QTextCursor.KeepAnchor)
  574. self.textCursor().removeSelectedText()
  575. else:
  576. self.moveCursor(QtGui.QTextCursor.PreviousCharacter,QtGui.QTextCursor.KeepAnchor)
  577. self.textCursor().insertText("# ")
  578. cursor = QtGui.QTextCursor(self.textCursor())
  579. cursor.setPosition(pos)
  580. self.setTextCursor(cursor)
  581. class FCComboBox(QtWidgets.QComboBox):
  582. def __init__(self, parent=None, callback=None):
  583. super(FCComboBox, self).__init__(parent)
  584. self.setFocusPolicy(QtCore.Qt.StrongFocus)
  585. self.view = self.view()
  586. self.view.viewport().installEventFilter(self)
  587. self.view.setContextMenuPolicy(Qt.CustomContextMenu)
  588. # the callback() will be called on customcontextmenu event and will be be passed 2 parameters:
  589. # pos = mouse right click click position
  590. # self = is the combobox object itself
  591. if callback:
  592. self.view.customContextMenuRequested.connect(lambda pos: callback(pos, self))
  593. def eventFilter(self, obj, event):
  594. if event.type() == QtCore.QEvent.MouseButtonRelease:
  595. if event.button() == Qt.RightButton:
  596. return True
  597. return False
  598. def wheelEvent(self, *args, **kwargs):
  599. pass
  600. def get_value(self):
  601. return str(self.currentText())
  602. def set_value(self, val):
  603. self.setCurrentIndex(self.findText(str(val)))
  604. class FCInputDialog(QtWidgets.QInputDialog):
  605. def __init__(self, parent=None, ok=False, val=None, title=None, text=None, min=None, max=None, decimals=None,
  606. init_val=None):
  607. super(FCInputDialog, self).__init__(parent)
  608. self.allow_empty = ok
  609. self.empty_val = val
  610. self.val = 0.0
  611. self.ok = ''
  612. self.init_value = init_val if init_val else 0.0
  613. if title is None:
  614. self.title = 'title'
  615. else:
  616. self.title = title
  617. if text is None:
  618. self.text = 'text'
  619. else:
  620. self.text = text
  621. if min is None:
  622. self.min = 0
  623. else:
  624. self.min = min
  625. if max is None:
  626. self.max = 0
  627. else:
  628. self.max = max
  629. if decimals is None:
  630. self.decimals = 6
  631. else:
  632. self.decimals = decimals
  633. def get_value(self):
  634. self.val, self.ok = self.getDouble(self, self.title, self.text, min=self.min,
  635. max=self.max, decimals=self.decimals, value=self.init_value)
  636. return [self.val, self.ok]
  637. # "Transform", "Enter the Angle value:"
  638. def set_value(self, val):
  639. pass
  640. class FCButton(QtWidgets.QPushButton):
  641. def __init__(self, parent=None):
  642. super(FCButton, self).__init__(parent)
  643. def get_value(self):
  644. return self.isChecked()
  645. def set_value(self, val):
  646. self.setText(str(val))
  647. class FCMenu(QtWidgets.QMenu):
  648. def __init__(self):
  649. super().__init__()
  650. self.mouse_is_panning = False
  651. def popup(self, pos, action=None):
  652. self.mouse_is_panning = False
  653. super().popup(pos)
  654. class FCTab(QtWidgets.QTabWidget):
  655. def __init__(self, parent=None):
  656. super(FCTab, self).__init__(parent)
  657. self.setTabsClosable(True)
  658. self.tabCloseRequested.connect(self.closeTab)
  659. def deleteTab(self, currentIndex):
  660. widget = self.widget(currentIndex)
  661. if widget is not None:
  662. widget.deleteLater()
  663. self.removeTab(currentIndex)
  664. def closeTab(self, currentIndex):
  665. self.removeTab(currentIndex)
  666. def protectTab(self, currentIndex):
  667. self.tabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  668. class FCDetachableTab(QtWidgets.QTabWidget):
  669. """
  670. From here:
  671. https://stackoverflow.com/questions/47267195/in-pyqt4-is-it-possible-to-detach-tabs-from-a-qtabwidget
  672. """
  673. def __init__(self, protect=None, protect_by_name=None, parent=None):
  674. super().__init__()
  675. self.tabBar = self.FCTabBar(self)
  676. self.tabBar.onDetachTabSignal.connect(self.detachTab)
  677. self.tabBar.onMoveTabSignal.connect(self.moveTab)
  678. self.tabBar.detachedTabDropSignal.connect(self.detachedTabDrop)
  679. self.setTabBar(self.tabBar)
  680. # Used to keep a reference to detached tabs since their QMainWindow
  681. # does not have a parent
  682. self.detachedTabs = {}
  683. # a way to make sure that tabs can't be closed after they attach to the parent tab
  684. self.protect_tab = True if protect is not None and protect is True else False
  685. self.protect_by_name = protect_by_name if isinstance(protect_by_name, list) else None
  686. # Close all detached tabs if the application is closed explicitly
  687. QtWidgets.qApp.aboutToQuit.connect(self.closeDetachedTabs) # @UndefinedVariable
  688. # used by the property self.useOldIndex(param)
  689. self.use_old_index = None
  690. self.old_index = None
  691. self.setTabsClosable(True)
  692. self.tabCloseRequested.connect(self.closeTab)
  693. def useOldIndex(self, param):
  694. if param:
  695. self.use_old_index = True
  696. else:
  697. self.use_old_index = False
  698. def deleteTab(self, currentIndex):
  699. widget = self.widget(currentIndex)
  700. if widget is not None:
  701. widget.deleteLater()
  702. self.removeTab(currentIndex)
  703. def closeTab(self, currentIndex):
  704. """
  705. Slot connected to the tabCloseRequested signal
  706. :param currentIndex:
  707. :return:
  708. """
  709. self.removeTab(currentIndex)
  710. def protectTab(self, currentIndex):
  711. # self.FCTabBar().setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  712. self.tabBar.setTabButton(currentIndex, QtWidgets.QTabBar.RightSide, None)
  713. def setMovable(self, movable):
  714. """
  715. The default movable functionality of QTabWidget must remain disabled
  716. so as not to conflict with the added features
  717. :param movable:
  718. :return:
  719. """
  720. pass
  721. @pyqtSlot(int, int)
  722. def moveTab(self, fromIndex, toIndex):
  723. """
  724. Move a tab from one position (index) to another
  725. :param fromIndex: the original index location of the tab
  726. :param toIndex: the new index location of the tab
  727. :return:
  728. """
  729. widget = self.widget(fromIndex)
  730. icon = self.tabIcon(fromIndex)
  731. text = self.tabText(fromIndex)
  732. self.removeTab(fromIndex)
  733. self.insertTab(toIndex, widget, icon, text)
  734. self.setCurrentIndex(toIndex)
  735. @pyqtSlot(int, QtCore.QPoint)
  736. def detachTab(self, index, point):
  737. """
  738. Detach the tab by removing it's contents and placing them in
  739. a DetachedTab window
  740. :param index: the index location of the tab to be detached
  741. :param point: the screen position for creating the new DetachedTab window
  742. :return:
  743. """
  744. self.old_index = index
  745. # Get the tab content and add name FlatCAM to the tab so we know on which app is this tab linked
  746. name = "FlatCAM " + self.tabText(index)
  747. icon = self.tabIcon(index)
  748. if icon.isNull():
  749. icon = self.window().windowIcon()
  750. contentWidget = self.widget(index)
  751. try:
  752. contentWidgetRect = contentWidget.frameGeometry()
  753. except AttributeError:
  754. return
  755. # Create a new detached tab window
  756. detachedTab = self.FCDetachedTab(name, contentWidget)
  757. detachedTab.setWindowModality(QtCore.Qt.NonModal)
  758. detachedTab.setWindowIcon(icon)
  759. detachedTab.setGeometry(contentWidgetRect)
  760. detachedTab.onCloseSignal.connect(self.attachTab)
  761. detachedTab.onDropSignal.connect(self.tabBar.detachedTabDrop)
  762. detachedTab.move(point)
  763. detachedTab.show()
  764. # Create a reference to maintain access to the detached tab
  765. self.detachedTabs[name] = detachedTab
  766. def attachTab(self, contentWidget, name, icon, insertAt=None):
  767. """
  768. Re-attach the tab by removing the content from the DetachedTab window,
  769. closing it, and placing the content back into the DetachableTabWidget
  770. :param contentWidget: the content widget from the DetachedTab window
  771. :param name: the name of the detached tab
  772. :param icon: the window icon for the detached tab
  773. :param insertAt: insert the re-attached tab at the given index
  774. :return:
  775. """
  776. # Make the content widget a child of this widget
  777. contentWidget.setParent(self)
  778. # Remove the reference
  779. del self.detachedTabs[name]
  780. # make sure that we strip the 'FlatCAM' part of the detached name otherwise the tab name will be too long
  781. name = name.partition(' ')[2]
  782. # helps in restoring the tab to the same index that it was before was detached
  783. insert_index = self.old_index if self.use_old_index is True else insertAt
  784. # Create an image from the given icon (for comparison)
  785. if not icon.isNull():
  786. try:
  787. tabIconPixmap = icon.pixmap(icon.availableSizes()[0])
  788. tabIconImage = tabIconPixmap.toImage()
  789. except IndexError:
  790. tabIconImage = None
  791. else:
  792. tabIconImage = None
  793. # Create an image of the main window icon (for comparison)
  794. if not icon.isNull():
  795. try:
  796. windowIconPixmap = self.window().windowIcon().pixmap(icon.availableSizes()[0])
  797. windowIconImage = windowIconPixmap.toImage()
  798. except IndexError:
  799. windowIconImage = None
  800. else:
  801. windowIconImage = None
  802. # Determine if the given image and the main window icon are the same.
  803. # If they are, then do not add the icon to the tab
  804. if tabIconImage == windowIconImage:
  805. if insert_index is None:
  806. index = self.addTab(contentWidget, name)
  807. else:
  808. index = self.insertTab(insert_index, contentWidget, name)
  809. else:
  810. if insert_index is None:
  811. index = self.addTab(contentWidget, icon, name)
  812. else:
  813. index = self.insertTab(insert_index, contentWidget, icon, name)
  814. # on reattaching the tab if protect is true then the closure button is not added
  815. if self.protect_tab is True:
  816. self.protectTab(index)
  817. # on reattaching the tab disable the closure button for the tabs with the name in the self.protect_by_name list
  818. if self.protect_by_name is not None:
  819. for tab_name in self.protect_by_name:
  820. for index in range(self.count()):
  821. if str(tab_name) == str(self.tabText(index)):
  822. self.protectTab(index)
  823. # Make this tab the current tab
  824. if index > -1:
  825. self.setCurrentIndex(insert_index) if self.use_old_index else self.setCurrentIndex(index)
  826. def removeTabByName(self, name):
  827. """
  828. Remove the tab with the given name, even if it is detached
  829. :param name: the name of the tab to be removed
  830. :return:
  831. """
  832. # Remove the tab if it is attached
  833. attached = False
  834. for index in range(self.count()):
  835. if str(name) == str(self.tabText(index)):
  836. self.removeTab(index)
  837. attached = True
  838. break
  839. # If the tab is not attached, close it's window and
  840. # remove the reference to it
  841. if not attached:
  842. for key in self.detachedTabs:
  843. if str(name) == str(key):
  844. self.detachedTabs[key].onCloseSignal.disconnect()
  845. self.detachedTabs[key].close()
  846. del self.detachedTabs[key]
  847. break
  848. @QtCore.pyqtSlot(str, int, QtCore.QPoint)
  849. def detachedTabDrop(self, name, index, dropPos):
  850. """
  851. Handle dropping of a detached tab inside the DetachableTabWidget
  852. :param name: the name of the detached tab
  853. :param index: the index of an existing tab (if the tab bar
  854. # determined that the drop occurred on an
  855. # existing tab)
  856. :param dropPos: the mouse cursor position when the drop occurred
  857. :return:
  858. """
  859. # If the drop occurred on an existing tab, insert the detached
  860. # tab at the existing tab's location
  861. if index > -1:
  862. # Create references to the detached tab's content and icon
  863. contentWidget = self.detachedTabs[name].contentWidget
  864. icon = self.detachedTabs[name].windowIcon()
  865. # Disconnect the detached tab's onCloseSignal so that it
  866. # does not try to re-attach automatically
  867. self.detachedTabs[name].onCloseSignal.disconnect()
  868. # Close the detached
  869. self.detachedTabs[name].close()
  870. # Re-attach the tab at the given index
  871. self.attachTab(contentWidget, name, icon, index)
  872. # If the drop did not occur on an existing tab, determine if the drop
  873. # occurred in the tab bar area (the area to the side of the QTabBar)
  874. else:
  875. # Find the drop position relative to the DetachableTabWidget
  876. tabDropPos = self.mapFromGlobal(dropPos)
  877. # If the drop position is inside the DetachableTabWidget...
  878. if self.rect().contains(tabDropPos):
  879. # If the drop position is inside the tab bar area (the
  880. # area to the side of the QTabBar) or there are not tabs
  881. # currently attached...
  882. if tabDropPos.y() < self.tabBar.height() or self.count() == 0:
  883. # Close the detached tab and allow it to re-attach
  884. # automatically
  885. self.detachedTabs[name].close()
  886. def closeDetachedTabs(self):
  887. """
  888. Close all tabs that are currently detached.
  889. :return:
  890. """
  891. listOfDetachedTabs = []
  892. for key in self.detachedTabs:
  893. listOfDetachedTabs.append(self.detachedTabs[key])
  894. for detachedTab in listOfDetachedTabs:
  895. detachedTab.close()
  896. class FCDetachedTab(QtWidgets.QMainWindow):
  897. """
  898. When a tab is detached, the contents are placed into this QMainWindow. The tab
  899. can be re-attached by closing the dialog or by dragging the window into the tab bar
  900. """
  901. onCloseSignal = pyqtSignal(QtWidgets.QWidget, str, QtGui.QIcon)
  902. onDropSignal = pyqtSignal(str, QtCore.QPoint)
  903. def __init__(self, name, contentWidget):
  904. QtWidgets.QMainWindow.__init__(self, None)
  905. self.setObjectName(name)
  906. self.setWindowTitle(name)
  907. self.contentWidget = contentWidget
  908. self.setCentralWidget(self.contentWidget)
  909. self.contentWidget.show()
  910. self.windowDropFilter = self.WindowDropFilter()
  911. self.installEventFilter(self.windowDropFilter)
  912. self.windowDropFilter.onDropSignal.connect(self.windowDropSlot)
  913. @QtCore.pyqtSlot(QtCore.QPoint)
  914. def windowDropSlot(self, dropPos):
  915. """
  916. Handle a window drop event
  917. :param dropPos: the mouse cursor position of the drop
  918. :return:
  919. """
  920. self.onDropSignal.emit(self.objectName(), dropPos)
  921. def closeEvent(self, event):
  922. """
  923. If the window is closed, emit the onCloseSignal and give the
  924. content widget back to the DetachableTabWidget
  925. :param event: a close event
  926. :return:
  927. """
  928. self.onCloseSignal.emit(self.contentWidget, self.objectName(), self.windowIcon())
  929. class WindowDropFilter(QtCore.QObject):
  930. """
  931. An event filter class to detect a QMainWindow drop event
  932. """
  933. onDropSignal = pyqtSignal(QtCore.QPoint)
  934. def __init__(self):
  935. QtCore.QObject.__init__(self)
  936. self.lastEvent = None
  937. def eventFilter(self, obj, event):
  938. """
  939. Detect a QMainWindow drop event by looking for a NonClientAreaMouseMove (173)
  940. event that immediately follows a Move event
  941. :param obj: the object that generated the event
  942. :param event: the current event
  943. :return:
  944. """
  945. # If a NonClientAreaMouseMove (173) event immediately follows a Move event...
  946. if self.lastEvent == QtCore.QEvent.Move and event.type() == 173:
  947. # Determine the position of the mouse cursor and emit it with the
  948. # onDropSignal
  949. mouseCursor = QtGui.QCursor()
  950. dropPos = mouseCursor.pos()
  951. self.onDropSignal.emit(dropPos)
  952. self.lastEvent = event.type()
  953. return True
  954. else:
  955. self.lastEvent = event.type()
  956. return False
  957. class FCTabBar(QtWidgets.QTabBar):
  958. onDetachTabSignal = pyqtSignal(int, QtCore.QPoint)
  959. onMoveTabSignal = pyqtSignal(int, int)
  960. detachedTabDropSignal = pyqtSignal(str, int, QtCore.QPoint)
  961. def __init__(self, parent=None):
  962. QtWidgets.QTabBar.__init__(self, parent)
  963. self.setAcceptDrops(True)
  964. self.setElideMode(QtCore.Qt.ElideRight)
  965. self.setSelectionBehaviorOnRemove(QtWidgets.QTabBar.SelectLeftTab)
  966. self.dragStartPos = QtCore.QPoint()
  967. self.dragDropedPos = QtCore.QPoint()
  968. self.mouseCursor = QtGui.QCursor()
  969. self.dragInitiated = False
  970. def mouseDoubleClickEvent(self, event):
  971. """
  972. Send the onDetachTabSignal when a tab is double clicked
  973. :param event: a mouse double click event
  974. :return:
  975. """
  976. event.accept()
  977. self.onDetachTabSignal.emit(self.tabAt(event.pos()), self.mouseCursor.pos())
  978. def mousePressEvent(self, event):
  979. """
  980. Set the starting position for a drag event when the mouse button is pressed
  981. :param event: a mouse press event
  982. :return:
  983. """
  984. if event.button() == QtCore.Qt.LeftButton:
  985. self.dragStartPos = event.pos()
  986. self.dragDropedPos.setX(0)
  987. self.dragDropedPos.setY(0)
  988. self.dragInitiated = False
  989. QtWidgets.QTabBar.mousePressEvent(self, event)
  990. def mouseMoveEvent(self, event):
  991. """
  992. Determine if the current movement is a drag. If it is, convert it into a QDrag. If the
  993. drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab
  994. bar, emit an onDetachTabSignal.
  995. :param event: a mouse move event
  996. :return:
  997. """
  998. # Determine if the current movement is detected as a drag
  999. if not self.dragStartPos.isNull() and \
  1000. ((event.pos() - self.dragStartPos).manhattanLength() < QtWidgets.QApplication.startDragDistance()):
  1001. self.dragInitiated = True
  1002. # If the current movement is a drag initiated by the left button
  1003. if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated):
  1004. # Stop the move event
  1005. finishMoveEvent = QtGui.QMouseEvent(
  1006. QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier
  1007. )
  1008. QtWidgets.QTabBar.mouseMoveEvent(self, finishMoveEvent)
  1009. # Convert the move event into a drag
  1010. drag = QtGui.QDrag(self)
  1011. mimeData = QtCore.QMimeData()
  1012. # mimeData.setData('action', 'application/tab-detach')
  1013. drag.setMimeData(mimeData)
  1014. # screen = QScreen(self.parentWidget().currentWidget().winId())
  1015. # Create the appearance of dragging the tab content
  1016. try:
  1017. pixmap = self.parent().widget(self.tabAt(self.dragStartPos)).grab()
  1018. except Exception as e:
  1019. log.debug("GUIElements.FCDetachable. FCTabBar.mouseMoveEvent() --> %s" % str(e))
  1020. return
  1021. targetPixmap = QtGui.QPixmap(pixmap.size())
  1022. targetPixmap.fill(QtCore.Qt.transparent)
  1023. painter = QtGui.QPainter(targetPixmap)
  1024. painter.setOpacity(0.85)
  1025. painter.drawPixmap(0, 0, pixmap)
  1026. painter.end()
  1027. drag.setPixmap(targetPixmap)
  1028. # Initiate the drag
  1029. dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction)
  1030. # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it
  1031. # must be set manually
  1032. if self.dragDropedPos.x() != 0 and self.dragDropedPos.y() != 0:
  1033. dropAction = QtCore.Qt.MoveAction
  1034. # If the drag completed outside of the tab bar, detach the tab and move
  1035. # the content to the current cursor position
  1036. if dropAction == QtCore.Qt.IgnoreAction:
  1037. event.accept()
  1038. self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos())
  1039. # Else if the drag completed inside the tab bar, move the selected tab to the new position
  1040. elif dropAction == QtCore.Qt.MoveAction:
  1041. if not self.dragDropedPos.isNull():
  1042. event.accept()
  1043. self.onMoveTabSignal.emit(self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos))
  1044. else:
  1045. QtWidgets.QTabBar.mouseMoveEvent(self, event)
  1046. def dragEnterEvent(self, event):
  1047. """
  1048. Determine if the drag has entered a tab position from another tab position
  1049. :param event: a drag enter event
  1050. :return:
  1051. """
  1052. mimeData = event.mimeData()
  1053. # formats = mcd imeData.formats()
  1054. # if formats.contains('action') and mimeData.data('action') == 'application/tab-detach':
  1055. # event.acceptProposedAction()
  1056. QtWidgets.QTabBar.dragMoveEvent(self, event)
  1057. def dropEvent(self, event):
  1058. """
  1059. Get the position of the end of the drag
  1060. :param event: a drop event
  1061. :return:
  1062. """
  1063. self.dragDropedPos = event.pos()
  1064. QtWidgets.QTabBar.dropEvent(self, event)
  1065. def detachedTabDrop(self, name, dropPos):
  1066. """
  1067. Determine if the detached tab drop event occurred on an existing tab,
  1068. then send the event to the DetachableTabWidget
  1069. :param name:
  1070. :param dropPos:
  1071. :return:
  1072. """
  1073. tabDropPos = self.mapFromGlobal(dropPos)
  1074. index = self.tabAt(tabDropPos)
  1075. self.detachedTabDropSignal.emit(name, index, dropPos)
  1076. class VerticalScrollArea(QtWidgets.QScrollArea):
  1077. """
  1078. This widget extends QtGui.QScrollArea to make a vertical-only
  1079. scroll area that also expands horizontally to accomodate
  1080. its contents.
  1081. """
  1082. def __init__(self, parent=None):
  1083. QtWidgets.QScrollArea.__init__(self, parent=parent)
  1084. self.setWidgetResizable(True)
  1085. self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  1086. self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
  1087. def eventFilter(self, source, event):
  1088. """
  1089. The event filter gets automatically installed when setWidget()
  1090. is called.
  1091. :param source:
  1092. :param event:
  1093. :return:
  1094. """
  1095. if event.type() == QtCore.QEvent.Resize and source == self.widget():
  1096. # log.debug("VerticalScrollArea: Widget resized:")
  1097. # log.debug(" minimumSizeHint().width() = %d" % self.widget().minimumSizeHint().width())
  1098. # log.debug(" verticalScrollBar().width() = %d" % self.verticalScrollBar().width())
  1099. self.setMinimumWidth(self.widget().sizeHint().width() +
  1100. self.verticalScrollBar().sizeHint().width())
  1101. # if self.verticalScrollBar().isVisible():
  1102. # log.debug(" Scroll bar visible")
  1103. # self.setMinimumWidth(self.widget().minimumSizeHint().width() +
  1104. # self.verticalScrollBar().width())
  1105. # else:
  1106. # log.debug(" Scroll bar hidden")
  1107. # self.setMinimumWidth(self.widget().minimumSizeHint().width())
  1108. return QtWidgets.QWidget.eventFilter(self, source, event)
  1109. class OptionalInputSection:
  1110. def __init__(self, cb, optinputs, logic=True):
  1111. """
  1112. Associates the a checkbox with a set of inputs.
  1113. :param cb: Checkbox that enables the optional inputs.
  1114. :param optinputs: List of widgets that are optional.
  1115. :param logic: When True the logic is normal, when False the logic is in reverse
  1116. It means that for logic=True, when the checkbox is checked the widgets are Enabled, and
  1117. for logic=False, when the checkbox is checked the widgets are Disabled
  1118. :return:
  1119. """
  1120. assert isinstance(cb, FCCheckBox), \
  1121. "Expected an FCCheckBox, got %s" % type(cb)
  1122. self.cb = cb
  1123. self.optinputs = optinputs
  1124. self.logic = logic
  1125. self.on_cb_change()
  1126. self.cb.stateChanged.connect(self.on_cb_change)
  1127. def on_cb_change(self):
  1128. if self.cb.checkState():
  1129. for widget in self.optinputs:
  1130. if self.logic is True:
  1131. widget.setEnabled(True)
  1132. else:
  1133. widget.setEnabled(False)
  1134. else:
  1135. for widget in self.optinputs:
  1136. if self.logic is True:
  1137. widget.setEnabled(False)
  1138. else:
  1139. widget.setEnabled(True)
  1140. class FCTable(QtWidgets.QTableWidget):
  1141. def __init__(self, parent=None):
  1142. super(FCTable, self).__init__(parent)
  1143. def sizeHint(self):
  1144. default_hint_size = super(FCTable, self).sizeHint()
  1145. return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1146. def getHeight(self):
  1147. height = self.horizontalHeader().height()
  1148. for i in range(self.rowCount()):
  1149. height += self.rowHeight(i)
  1150. return height
  1151. def getWidth(self):
  1152. width = self.verticalHeader().width()
  1153. for i in range(self.columnCount()):
  1154. width += self.columnWidth(i)
  1155. return width
  1156. # color is in format QtGui.Qcolor(r, g, b, alfa) with or without alfa
  1157. def setColortoRow(self, rowIndex, color):
  1158. for j in range(self.columnCount()):
  1159. self.item(rowIndex, j).setBackground(color)
  1160. # if user is clicking an blank area inside the QTableWidget it will deselect currently selected rows
  1161. def mousePressEvent(self, event):
  1162. if self.itemAt(event.pos()) is None:
  1163. self.clearSelection()
  1164. else:
  1165. QtWidgets.QTableWidget.mousePressEvent(self, event)
  1166. def setupContextMenu(self):
  1167. self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1168. def addContextMenu(self, entry, call_function, icon=None):
  1169. action_name = str(entry)
  1170. action = QtWidgets.QAction(self)
  1171. action.setText(action_name)
  1172. if icon:
  1173. assert isinstance(icon, QtGui.QIcon), \
  1174. "Expected the argument to be QtGui.QIcon. Instead it is %s" % type(icon)
  1175. action.setIcon(icon)
  1176. self.addAction(action)
  1177. action.triggered.connect(call_function)
  1178. class SpinBoxDelegate(QtWidgets.QItemDelegate):
  1179. def __init__(self, units):
  1180. super(SpinBoxDelegate, self).__init__()
  1181. self.units = units
  1182. self.current_value = None
  1183. def createEditor(self, parent, option, index):
  1184. editor = QtWidgets.QDoubleSpinBox(parent)
  1185. editor.setMinimum(-999.9999)
  1186. editor.setMaximum(999.9999)
  1187. if self.units == 'MM':
  1188. editor.setDecimals(2)
  1189. else:
  1190. editor.setDecimals(3)
  1191. return editor
  1192. def setEditorData(self, spinBox, index):
  1193. try:
  1194. value = float(index.model().data(index, Qt.EditRole))
  1195. except ValueError:
  1196. value = self.current_value
  1197. # return
  1198. spinBox.setValue(value)
  1199. def setModelData(self, spinBox, model, index):
  1200. spinBox.interpretText()
  1201. value = spinBox.value()
  1202. self.current_value = value
  1203. model.setData(index, value, Qt.EditRole)
  1204. def updateEditorGeometry(self, editor, option, index):
  1205. editor.setGeometry(option.rect)
  1206. def setDecimals(self, spinbox, digits):
  1207. spinbox.setDecimals(digits)
  1208. class FCSpinner(QtWidgets.QSpinBox):
  1209. def __init__(self, parent=None):
  1210. super(FCSpinner, self).__init__(parent)
  1211. self.readyToEdit = True
  1212. self.editingFinished.connect(self.on_edit_finished)
  1213. def on_edit_finished(self):
  1214. self.clearFocus()
  1215. def mousePressEvent(self, e, parent=None):
  1216. super(FCSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  1217. if self.readyToEdit:
  1218. self.lineEdit().selectAll()
  1219. self.readyToEdit = False
  1220. def focusOutEvent(self, e):
  1221. super(FCSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  1222. self.lineEdit().deselect()
  1223. self.readyToEdit = True
  1224. def get_value(self):
  1225. return str(self.value())
  1226. def set_value(self, val):
  1227. try:
  1228. k = int(val)
  1229. except Exception as e:
  1230. log.debug(str(e))
  1231. return
  1232. self.setValue(k)
  1233. def set_range(self, min_val, max_val):
  1234. self.setRange(min_val, max_val)
  1235. # def sizeHint(self):
  1236. # default_hint_size = super(FCSpinner, self).sizeHint()
  1237. # return QtCore.QSize(EDIT_SIZE_HINT, default_hint_size.height())
  1238. class FCDoubleSpinner(QtWidgets.QDoubleSpinBox):
  1239. def __init__(self, parent=None):
  1240. super(FCDoubleSpinner, self).__init__(parent)
  1241. self.readyToEdit = True
  1242. self.editingFinished.connect(self.on_edit_finished)
  1243. def on_edit_finished(self):
  1244. self.clearFocus()
  1245. def mousePressEvent(self, e, parent=None):
  1246. super(FCDoubleSpinner, self).mousePressEvent(e) # required to deselect on 2e click
  1247. if self.readyToEdit:
  1248. self.lineEdit().selectAll()
  1249. self.readyToEdit = False
  1250. def focusOutEvent(self, e):
  1251. super(FCDoubleSpinner, self).focusOutEvent(e) # required to remove cursor on focusOut
  1252. self.lineEdit().deselect()
  1253. self.readyToEdit = True
  1254. def get_value(self):
  1255. return str(self.value())
  1256. def set_value(self, val):
  1257. try:
  1258. k = int(val)
  1259. except Exception as e:
  1260. log.debug(str(e))
  1261. return
  1262. self.setValue(k)
  1263. def set_precision(self, val):
  1264. self.setDecimals(val)
  1265. def set_range(self, min_val, max_val):
  1266. self.setRange(min_val, max_val)
  1267. class Dialog_box(QtWidgets.QWidget):
  1268. def __init__(self, title=None, label=None, icon=None):
  1269. """
  1270. :param title: string with the window title
  1271. :param label: string with the message inside the dialog box
  1272. """
  1273. super(Dialog_box, self).__init__()
  1274. self.location = (0, 0)
  1275. self.ok = False
  1276. dialog_box = QtWidgets.QInputDialog()
  1277. dialog_box.setFixedWidth(290)
  1278. self.setWindowIcon(icon)
  1279. self.location, self.ok = dialog_box.getText(self, title, label, text="0, 0")
  1280. self.readyToEdit = True
  1281. def mousePressEvent(self, e, parent=None):
  1282. super(Dialog_box, self).mousePressEvent(e) # required to deselect on 2e click
  1283. if self.readyToEdit:
  1284. self.lineEdit().selectAll()
  1285. self.readyToEdit = False
  1286. def focusOutEvent(self, e):
  1287. super(Dialog_box, self).focusOutEvent(e) # required to remove cursor on focusOut
  1288. self.lineEdit().deselect()
  1289. self.readyToEdit = True
  1290. class _BrowserTextEdit(QTextEdit):
  1291. def __init__(self, version):
  1292. QTextEdit.__init__(self)
  1293. self.menu = None
  1294. self.version = version
  1295. def contextMenuEvent(self, event):
  1296. self.menu = self.createStandardContextMenu(event.pos())
  1297. clear_action = QAction("Clear", self)
  1298. clear_action.setShortcut(QKeySequence(Qt.Key_Delete)) # it's not working, the shortcut
  1299. self.menu.addAction(clear_action)
  1300. clear_action.triggered.connect(self.clear)
  1301. self.menu.exec_(event.globalPos())
  1302. def clear(self):
  1303. QTextEdit.clear(self)
  1304. text = "FlatCAM %s (c)2014-2019 Juan Pablo Caram (Type help to get started)\n\n" % self.version
  1305. text = html.escape(text)
  1306. text = text.replace('\n', '<br/>')
  1307. self.moveCursor(QTextCursor.End)
  1308. self.insertHtml(text)
  1309. class _ExpandableTextEdit(QTextEdit):
  1310. """
  1311. Class implements edit line, which expands themselves automatically
  1312. """
  1313. historyNext = pyqtSignal()
  1314. historyPrev = pyqtSignal()
  1315. def __init__(self, termwidget, *args):
  1316. QTextEdit.__init__(self, *args)
  1317. self.setStyleSheet("font: 9pt \"Courier\";")
  1318. self._fittedHeight = 1
  1319. self.textChanged.connect(self._fit_to_document)
  1320. self._fit_to_document()
  1321. self._termWidget = termwidget
  1322. self.completer = MyCompleter()
  1323. self.model = QtCore.QStringListModel()
  1324. self.completer.setModel(self.model)
  1325. self.set_model_data(keyword_list=[])
  1326. self.completer.insertText.connect(self.insertCompletion)
  1327. def set_model_data(self, keyword_list):
  1328. self.model.setStringList(keyword_list)
  1329. def insertCompletion(self, completion):
  1330. tc = self.textCursor()
  1331. extra = (len(completion) - len(self.completer.completionPrefix()))
  1332. # don't insert if the word is finished but add a space instead
  1333. if extra == 0:
  1334. tc.insertText(' ')
  1335. self.completer.popup().hide()
  1336. return
  1337. tc.movePosition(QTextCursor.Left)
  1338. tc.movePosition(QTextCursor.EndOfWord)
  1339. tc.insertText(completion[-extra:])
  1340. # add a space after inserting the word
  1341. tc.insertText(' ')
  1342. self.setTextCursor(tc)
  1343. self.completer.popup().hide()
  1344. def focusInEvent(self, event):
  1345. if self.completer:
  1346. self.completer.setWidget(self)
  1347. QTextEdit.focusInEvent(self, event)
  1348. def keyPressEvent(self, event):
  1349. """
  1350. Catch keyboard events. Process Enter, Up, Down
  1351. """
  1352. key = event.key()
  1353. if (key == Qt.Key_Tab or key == Qt.Key_Return or key == Qt.Key_Enter) and self.completer.popup().isVisible():
  1354. self.completer.insertText.emit(self.completer.getSelected())
  1355. self.completer.setCompletionMode(QCompleter.PopupCompletion)
  1356. return
  1357. if event.matches(QKeySequence.InsertParagraphSeparator):
  1358. text = self.toPlainText()
  1359. if self._termWidget.is_command_complete(text):
  1360. self._termWidget.exec_current_command()
  1361. return
  1362. elif event.matches(QKeySequence.MoveToNextLine):
  1363. text = self.toPlainText()
  1364. cursor_pos = self.textCursor().position()
  1365. textBeforeEnd = text[cursor_pos:]
  1366. if len(textBeforeEnd.split('\n')) <= 1:
  1367. self.historyNext.emit()
  1368. return
  1369. elif event.matches(QKeySequence.MoveToPreviousLine):
  1370. text = self.toPlainText()
  1371. cursor_pos = self.textCursor().position()
  1372. text_before_start = text[:cursor_pos]
  1373. # lineCount = len(textBeforeStart.splitlines())
  1374. line_count = len(text_before_start.split('\n'))
  1375. if len(text_before_start) > 0 and \
  1376. (text_before_start[-1] == '\n' or text_before_start[-1] == '\r'):
  1377. line_count += 1
  1378. if line_count <= 1:
  1379. self.historyPrev.emit()
  1380. return
  1381. elif event.matches(QKeySequence.MoveToNextPage) or \
  1382. event.matches(QKeySequence.MoveToPreviousPage):
  1383. return self._termWidget.browser().keyPressEvent(event)
  1384. tc = self.textCursor()
  1385. QTextEdit.keyPressEvent(self, event)
  1386. tc.select(QTextCursor.WordUnderCursor)
  1387. cr = self.cursorRect()
  1388. if len(tc.selectedText()) > 0:
  1389. self.completer.setCompletionPrefix(tc.selectedText())
  1390. popup = self.completer.popup()
  1391. popup.setCurrentIndex(self.completer.completionModel().index(0, 0))
  1392. cr.setWidth(self.completer.popup().sizeHintForColumn(0)
  1393. + self.completer.popup().verticalScrollBar().sizeHint().width())
  1394. self.completer.complete(cr)
  1395. else:
  1396. self.completer.popup().hide()
  1397. def sizeHint(self):
  1398. """
  1399. QWidget sizeHint impelemtation
  1400. """
  1401. hint = QTextEdit.sizeHint(self)
  1402. hint.setHeight(self._fittedHeight)
  1403. return hint
  1404. def _fit_to_document(self):
  1405. """
  1406. Update widget height to fit all text
  1407. """
  1408. documentsize = self.document().size().toSize()
  1409. self._fittedHeight = documentsize.height() + (self.height() - self.viewport().height())
  1410. self.setMaximumHeight(self._fittedHeight)
  1411. self.updateGeometry()
  1412. def insertFromMimeData(self, mime_data):
  1413. # Paste only plain text.
  1414. self.insertPlainText(mime_data.text())
  1415. class MyCompleter(QCompleter):
  1416. insertText = pyqtSignal(str)
  1417. def __init__(self, parent=None):
  1418. QCompleter.__init__(self)
  1419. self.setCompletionMode(QCompleter.PopupCompletion)
  1420. self.highlighted.connect(self.setHighlighted)
  1421. def setHighlighted(self, text):
  1422. self.lastSelected = text
  1423. def getSelected(self):
  1424. return self.lastSelected