design.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # @Author: Bachir Soussi Chiadmi <bach>
  4. # @Date: 23-05-2017
  5. # @Email: bachir@figureslibres.io
  6. # @Filename: design.py
  7. # @Last modified by: bach
  8. # @Last modified time: 03-06-2017
  9. # @License: GPL-V3
  10. import os, re
  11. # sys,
  12. from PyQt5 import QtCore
  13. from PyQt5.QtCore import QUrl, QSettings, QSizeF
  14. from PyQt5.QtGui import QKeySequence, QFont
  15. from PyQt5.QtWidgets import QWidget, QTabWidget, QVBoxLayout, QHBoxLayout, QSplitter, QPlainTextEdit, QShortcut, QPushButton, QCheckBox, QSpinBox, QLabel
  16. from PyQt5.QtWebKit import QWebSettings
  17. from PyQt5.QtWebKitWidgets import QWebView, QWebInspector
  18. from PyQt5.QtPrintSupport import QPrintPreviewDialog, QPrinter
  19. from classes import highlighter
  20. # _ __ __ _ ___
  21. # | | / /__ / /_| | / (_)__ _ __
  22. # | | /| / / _ \/ __ \ | / / / _ \ | /| / /
  23. # | |/ |/ / __/ /_/ / |/ / / __/ |/ |/ /
  24. # |__/|__/\___/_.___/|___/_/\___/|__/|__/
  25. class WebkitView(QWebView):
  26. def __init__(self, parent, core):
  27. self.parent = parent
  28. self.core = core
  29. self.port = core.server.port
  30. self.view = QWebView.__init__(self, parent)
  31. self.setZoomFactor(1)
  32. self.loadFinished.connect(self.onLoaded)
  33. self.load(QUrl('http://localhost:'+str(self.port)))
  34. self.settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)
  35. # self.settings().setAttribute(QWebSettings.PluginsEnabled, True)
  36. self.initPDF()
  37. # self.mainframe = self.page.mainFrame()
  38. # print(self.mainframe)
  39. def onLoaded(self):
  40. print("WebView : onLoaded")
  41. self.parent.webviewtoolbar.onRefresh()
  42. def initPDF(self):
  43. self.printer = QPrinter(QPrinter.HighResolution)
  44. self.printer.setFullPage(True)
  45. # self.printer.setPageMargins(0,0,0,0,QPrinter.Millimeter)
  46. self.printer.setFontEmbeddingEnabled(True)
  47. self.printer.setColorMode(QPrinter.Color)
  48. # TODO: set the page size and orientation from doc settings
  49. # (need to do doc settings before that)
  50. # self.printer.setPageSize(QPrinter.A4)
  51. self.printer.setPaperSize(QSizeF(210, 300), QPrinter.Millimeter)
  52. # self.printer.setOrientation(QPrinter.Portrait)
  53. self.printer.setOutputFormat(QPrinter.PdfFormat)
  54. self.printer.setCreator('Cascade')
  55. self.printer.setDocName(self.core.projectname)
  56. self.printer.setOutputFileName(self.core.projectname+".pdf")
  57. # self.setFixedWidth(1000)
  58. def ongenPDF(self):
  59. # QPrinter::Custom
  60. # dialog = QPrintPreviewDialog(self.printer)
  61. # dialog.setWindowState(Qt.WindowMaximized)
  62. # dialog.paintRequested.connect(self.print_)
  63. # dialog.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowMinMaxButtonsHint | Qt.WindowCloseButtonHint | Qt.WindowContextHelpButtonHint)
  64. # dialog.exec()
  65. # TODO: open a dialogue to ask where to save the pdf
  66. # TODO: reload webview and wait for it before printing
  67. # TODO: addd a progress bar
  68. # self.webview.
  69. self.print_(self.printer)
  70. def refresh(self):
  71. self.initPDF()
  72. self.reload()
  73. def toggleDocClass(self, c="",a=True):
  74. if a :
  75. togg = "add"
  76. else :
  77. togg = "remove"
  78. command = """document.documentElement.classList."""+togg+"""('"""+c+"""')"""
  79. self.evaluateJS(command)
  80. def changePage(self,p=0):
  81. command = """
  82. var pageNumber = """+str(p)+""";
  83. var target = document.documentElement.querySelectorAll('.paper')[pageNumber];
  84. var offsetTop = target.offsetTop;
  85. document.documentElement.querySelector('body').scrollTop = offsetTop;
  86. """
  87. self.evaluateJS(command)
  88. def evaluateJS(self, command):
  89. self.page().mainFrame().evaluateJavaScript(command)
  90. # ____ __
  91. # / _/___ _________ ___ _____/ /_____ _____
  92. # / // __ \/ ___/ __ \/ _ \/ ___/ __/ __ \/ ___/
  93. # _/ // / / (__ ) /_/ / __/ /__/ /_/ /_/ / /
  94. # /___/_/ /_/____/ .___/\___/\___/\__/\____/_/
  95. # /_/
  96. class WebkitInspector(QWebInspector):
  97. def __init__(self, parent, webkitview):
  98. super(WebkitInspector, self).__init__(parent)
  99. self.webkitview = webkitview
  100. self.setPage(self.webkitview.page())
  101. self.showMaximized()
  102. # TODO: webkitinspector is disappearing when chaging tabs
  103. # ______ ______
  104. # /_ __/___ ____ / / __ )____ ______
  105. # / / / __ \/ __ \/ / __ / __ `/ ___/
  106. # / / / /_/ / /_/ / / /_/ / /_/ / /
  107. # /_/ \____/\____/_/_____/\__,_/_/
  108. class WebViewToolBar(QWidget):
  109. def __init__(self, parent):
  110. super(WebViewToolBar, self).__init__(parent)
  111. self.parent = parent
  112. font = QFont()
  113. # font.setFamily("Droid Sans Mono")
  114. # font.setFixedPitch(True)
  115. font.setPointSize(8)
  116. self.setFont(font)
  117. self.hbox = QHBoxLayout()
  118. self.hbox.setContentsMargins(0,0,0,0)
  119. self.preview = QCheckBox('Prev&iew', self)
  120. self.preview.stateChanged.connect(self.onPreview)
  121. self.hbox.addWidget(self.preview)
  122. self.debug = QCheckBox('Deb&ug', self)
  123. self.debug.stateChanged.connect(self.onDebug)
  124. self.hbox.addWidget(self.debug)
  125. self.grid = QCheckBox('&Grid', self)
  126. self.grid.stateChanged.connect(self.onGrid)
  127. self.hbox.addWidget(self.grid)
  128. self.spread = QCheckBox('&Spread', self)
  129. self.spread.stateChanged.connect(self.onSpread)
  130. self.hbox.addWidget(self.spread)
  131. self.facing = QCheckBox('Fa&cing', self)
  132. self.facing.stateChanged.connect(self.onFacing)
  133. self.hbox.addWidget(self.facing)
  134. #
  135. self.hbox.addStretch()
  136. #
  137. # zoom
  138. self.hbox.addWidget(QLabel("Zoom:"))
  139. self.zoom = QSpinBox(self)
  140. # TODO: action
  141. self.hbox.addWidget(self.zoom)
  142. # page
  143. self.gotopage = QLabel("Go to Page: /"+self.parent.core.docsettings['np'])
  144. self.hbox.addWidget(self.gotopage)
  145. self.page = QSpinBox()
  146. self.page.setMinimum(0)
  147. self.page.setMaximum(int(self.parent.core.docsettings['np']))
  148. self.page.valueChanged.connect(self.onChangePage)
  149. self.hbox.addWidget(self.page)
  150. self.addpage = QPushButton("&Add Page", self)
  151. self.addpage.clicked.connect(self.onAddPage)
  152. self.hbox.addWidget(self.addpage)
  153. self.rmpage = QPushButton("Re&move Page", self)
  154. self.rmpage.clicked.connect(self.onRmPage)
  155. self.hbox.addWidget(self.rmpage)
  156. #
  157. self.hbox.addStretch()
  158. #
  159. self.reload = QPushButton("&Reload", self)
  160. # self.reload.setShortcut('Ctrl+Shift+r')
  161. # TODO: how to define same shortcut in different places
  162. # self.reload.setIcon(Icon(ico)))
  163. self.reload.clicked.connect(self.onReload)
  164. self.hbox.addWidget(self.reload)
  165. self.genpdf = QPushButton("&PDF", self)
  166. # self.genpdf.setShortcut('Ctrl+Shift+r')
  167. # TODO: how to define same shortcut in different places
  168. # self.genpdf.setIcon(Icon(ico)))
  169. self.genpdf.clicked.connect(self.onGenPDF)
  170. self.hbox.addWidget(self.genpdf)
  171. self.setLayout(self.hbox)
  172. # def onCheckboxAction(self, box):
  173. # self.parent.webkitview.toggleDocClass(box, self[box].isChecked())
  174. # self.recToolbarState(box, self[box].isChecked())
  175. def onPreview(self):
  176. print('Toolbar : onPreview', self.preview.isChecked())
  177. self.parent.webkitview.toggleDocClass('preview', self.preview.isChecked())
  178. self.recToolbarState('preview', self.preview.isChecked())
  179. def onDebug(self):
  180. self.parent.webkitview.toggleDocClass('debug', self.debug.isChecked())
  181. self.recToolbarState('debug', self.debug.isChecked())
  182. def onGrid(self):
  183. self.parent.webkitview.toggleDocClass('grid', self.grid.isChecked())
  184. self.recToolbarState('grid', self.grid.isChecked())
  185. def onSpread(self):
  186. self.parent.webkitview.toggleDocClass('spread', self.spread.isChecked())
  187. self.recToolbarState('spread', self.spread.isChecked())
  188. def onFacing(self):
  189. self.parent.webkitview.toggleDocClass('facing', self.facing.isChecked())
  190. self.recToolbarState('facing', self.facing.isChecked())
  191. def onChangePage(self, i):
  192. print("onChangePage : "+str(i))
  193. self.parent.webkitview.changePage(i)
  194. def onAddPage(self):
  195. # print("onAddPage")
  196. self.parent.core.addPage()
  197. def onRmPage(self):
  198. # print("onAddPage")
  199. self.parent.core.rmPage()
  200. # def refreshNumberPage(self):
  201. def onReload(self):
  202. # print("onReload")
  203. self.parent.webkitview.reload()
  204. def onGenPDF(self):
  205. print("onGenPDF")
  206. self.parent.webkitview.ongenPDF()
  207. def recToolbarState(self, prop, val):
  208. # print('recToolbarState : '+prop, val)
  209. settings = QSettings('FiguresLibres', 'Cascade')
  210. settings.setValue('design/toolbar/'+prop, val)
  211. # print('recToolbarState after : '+prop, settings.value('design/toolbar/'+prop))
  212. def onRefresh(self):
  213. # apply precedent toolbar state
  214. settings = QSettings('FiguresLibres', 'Cascade')
  215. self.preview.setChecked(bool(settings.value('design/toolbar/preview', False, type=bool)))
  216. self.debug.setChecked(bool(settings.value('design/toolbar/debug', False, type=bool)))
  217. self.grid.setChecked(bool(settings.value('design/toolbar/grid', False, type=bool)))
  218. self.spread.setChecked(bool(settings.value('design/toolbar/spread', False, type=bool)))
  219. self.facing.setChecked(bool(settings.value('design/toolbar/facing', False, type=bool)))
  220. # trigger webview changes
  221. self.parent.webkitview.toggleDocClass('preview', self.preview.isChecked())
  222. self.parent.webkitview.toggleDocClass('debug', self.debug.isChecked())
  223. self.parent.webkitview.toggleDocClass('grid', self.grid.isChecked())
  224. self.parent.webkitview.toggleDocClass('spread', self.spread.isChecked())
  225. self.gotopage.setText("Go to Page: /"+str(self.parent.core.docsettings['np']))
  226. self.parent.webkitview.changePage(self.page.value())
  227. # ______ ___ __
  228. # / ____/___/ (_) /_____ _____
  229. # / __/ / __ / / __/ __ \/ ___/
  230. # / /___/ /_/ / / /_/ /_/ / /
  231. # /_____/\__,_/_/\__/\____/_/
  232. class CodeEditor(QPlainTextEdit):
  233. def __init__(self, parent, core, tabs, file, mode):
  234. super(CodeEditor, self).__init__()
  235. self.parent = parent
  236. self.core = core
  237. self.tabs = tabs
  238. self.file = file
  239. self.hl= highlighter.Highlighter(self.document(),mode)
  240. self.setText()
  241. self.setTabStopWidth(15)
  242. self.textChanged.connect(self.onTextChanged)
  243. self.shortcut = QShortcut(QKeySequence("Ctrl+s"), self)
  244. self.shortcut.activated.connect(self.save)
  245. def setText(self):
  246. # try:
  247. # self.textChanged.disconnect(self.onTextChanged)
  248. # except Exception as e:
  249. # print(e)
  250. self.filepath = os.path.join(self.core.cwd,self.file)
  251. self.clear()
  252. self.insertPlainText(open(self.filepath, 'r').read())
  253. self.changed = False
  254. font = QFont()
  255. font.setFamily("Droid Sans Mono")
  256. font.setFixedPitch(True)
  257. font.setPointSize(12)
  258. self.setFont(font)
  259. def onTextChanged(self):
  260. print('textChanged')
  261. # print(self.toPlainText())
  262. # open(self.filepath, 'w').write(self.toPlainText())
  263. if not self.changed:
  264. self.changed = True
  265. i = self.tabs.currentIndex()
  266. # self.tabs.setTabText(i, re.sub(r'^\**\s', '', self.tabs.tabText(i)))
  267. self.tabs.setTabText(i, "* "+self.tabs.tabText(i))
  268. # TODO: indicate that webview needs to be reloaded
  269. def save(self):
  270. if self.changed:
  271. open(self.filepath, 'w').write(self.toPlainText())
  272. i = self.tabs.currentIndex()
  273. self.tabs.setTabText(i, re.sub(r'^\**\s', '', self.tabs.tabText(i)))
  274. self.parent.reloadView()
  275. self.changed = False
  276. # TODO: how to combine file save and project save
  277. class Editor(QWidget):
  278. def __init__(self, parent):
  279. super(Editor, self).__init__()
  280. self.parent = parent
  281. self.layout = QVBoxLayout(self)
  282. self.layout.setContentsMargins(0,0,0,0)
  283. # Initialize tab screen
  284. self.tabs = QTabWidget()
  285. self.scsstab = CodeEditor(self, self.parent.core, self.tabs, 'assets/css/styles.scss', "sass")
  286. self.jstab = CodeEditor(self, self.parent.core, self.tabs, 'assets/js/script.js', 'js')
  287. # Add tabs
  288. self.tabs.addTab(self.scsstab,"scss")
  289. self.tabs.addTab(self.jstab,"js")
  290. # Add tabs to widget
  291. self.layout.addWidget(self.tabs)
  292. self.setLayout(self.layout)
  293. def refresh(self):
  294. self.scsstab.setText()
  295. self.jstab.setText()
  296. def reloadView(self):
  297. self.parent.webkitview.reload()
  298. # _____ __ __
  299. # / ___// /_____ ______/ /__
  300. # \__ \/ __/ __ `/ ___/ //_/
  301. # ___/ / /_/ /_/ / /__/ ,<
  302. # /____/\__/\__,_/\___/_/|_|
  303. class DesignStack(QWidget):
  304. def __init__(self, core):
  305. super(DesignStack, self).__init__()
  306. self.core = core
  307. # self.grid = QGridLayout()
  308. self.hbox = QHBoxLayout()
  309. self.hbox.setContentsMargins(0,0,0,0)
  310. self.setLayout(self.hbox)
  311. self.webview = QWidget()
  312. self.webview.vbox = QVBoxLayout()
  313. self.webview.setLayout(self.webview.vbox)
  314. self.webview.vbox.setContentsMargins(0,0,0,0)
  315. # toolbar
  316. self.webviewtoolbar = WebViewToolBar(self)
  317. self.webview.vbox.addWidget(self.webviewtoolbar)
  318. # webkitview
  319. self.webkitview = WebkitView(self, core)
  320. # webkitinspector
  321. self.webkitinspector = WebkitInspector(self, self.webkitview)
  322. shortcut = QShortcut(self)
  323. shortcut.setKey("F12")
  324. shortcut.activated.connect(self.toggleInspector)
  325. self.webkitinspector.setVisible(False)
  326. # V layout
  327. self.vsplitter = QSplitter(QtCore.Qt.Vertical)
  328. self.vsplitter.addWidget(self.webkitview)
  329. self.vsplitter.addWidget(self.webkitinspector)
  330. self.vsplitter.splitterMoved.connect(self.movedSplitter)
  331. self.webview.vbox.addWidget(self.vsplitter)
  332. # H layout
  333. self.hsplitter = QSplitter(QtCore.Qt.Horizontal)
  334. self.hsplitter.addWidget(self.webview)
  335. # editor
  336. self.editor = Editor(self)
  337. self.hsplitter.addWidget(self.editor)
  338. self.hsplitter.splitterMoved.connect(self.movedSplitter)
  339. self.hbox.addWidget(self.hsplitter)
  340. self.restorePrefs()
  341. def toggleInspector(self):
  342. self.webkitinspector.setVisible(not self.webkitinspector.isVisible())
  343. def restorePrefs(self):
  344. settings = QSettings('FiguresLibres', 'Cascade')
  345. print(settings.value('design/vsplitter/sizes', self.vsplitter.sizes()))
  346. vals = settings.value('design/vsplitter/sizes', None)
  347. if vals:
  348. sizes = []
  349. for size in vals: sizes.append(int(size))
  350. self.vsplitter.setSizes(sizes)
  351. vals = settings.value('design/hsplitter/sizes', None)
  352. if vals:
  353. sizes = []
  354. for size in vals: sizes.append(int(size))
  355. self.hsplitter.setSizes(sizes)
  356. def movedSplitter(self):
  357. settings = QSettings('FiguresLibres', 'Cascade')
  358. # print(self.vsplitter.sizes())
  359. settings.setValue('design/vsplitter/sizes', self.vsplitter.sizes())
  360. settings.setValue('design/hsplitter/sizes', self.hsplitter.sizes())
  361. def refresh(self):
  362. self.editor.refresh()
  363. self.webkitview.refresh()