design.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. var offsetLeft = target.offsetLeft;
  86. document.documentElement.querySelector('body').scrollTop = offsetTop;
  87. document.documentElement.querySelector('body').scrollLeft = offsetLeft;
  88. """
  89. self.evaluateJS(command)
  90. def evaluateJS(self, command):
  91. self.page().mainFrame().evaluateJavaScript(command)
  92. # ____ __
  93. # / _/___ _________ ___ _____/ /_____ _____
  94. # / // __ \/ ___/ __ \/ _ \/ ___/ __/ __ \/ ___/
  95. # _/ // / / (__ ) /_/ / __/ /__/ /_/ /_/ / /
  96. # /___/_/ /_/____/ .___/\___/\___/\__/\____/_/
  97. # /_/
  98. class WebkitInspector(QWebInspector):
  99. def __init__(self, parent, webkitview):
  100. super(WebkitInspector, self).__init__(parent)
  101. self.webkitview = webkitview
  102. self.setPage(self.webkitview.page())
  103. self.showMaximized()
  104. # TODO: webkitinspector is disappearing when chaging tabs
  105. # ______ ______
  106. # /_ __/___ ____ / / __ )____ ______
  107. # / / / __ \/ __ \/ / __ / __ `/ ___/
  108. # / / / /_/ / /_/ / / /_/ / /_/ / /
  109. # /_/ \____/\____/_/_____/\__,_/_/
  110. class WebViewToolBar(QWidget):
  111. def __init__(self, parent):
  112. super(WebViewToolBar, self).__init__(parent)
  113. self.parent = parent
  114. font = QFont()
  115. # font.setFamily("Droid Sans Mono")
  116. # font.setFixedPitch(True)
  117. font.setPointSize(8)
  118. self.setFont(font)
  119. self.hbox = QHBoxLayout()
  120. self.hbox.setContentsMargins(0,0,0,0)
  121. self.preview = QCheckBox('Prev&iew', self)
  122. self.preview.stateChanged.connect(self.onPreview)
  123. self.hbox.addWidget(self.preview)
  124. self.debug = QCheckBox('Deb&ug', self)
  125. self.debug.stateChanged.connect(self.onDebug)
  126. self.hbox.addWidget(self.debug)
  127. self.grid = QCheckBox('&Grid', self)
  128. self.grid.stateChanged.connect(self.onGrid)
  129. self.hbox.addWidget(self.grid)
  130. self.spread = QCheckBox('&Spread', self)
  131. self.spread.stateChanged.connect(self.onSpread)
  132. self.hbox.addWidget(self.spread)
  133. self.facing = QCheckBox('Fa&cing', self)
  134. self.facing.stateChanged.connect(self.onFacing)
  135. self.hbox.addWidget(self.facing)
  136. #
  137. self.hbox.addStretch()
  138. #
  139. # zoom
  140. self.hbox.addWidget(QLabel("Zoom:"))
  141. self.zoom = QSpinBox(self)
  142. # TODO: action
  143. self.hbox.addWidget(self.zoom)
  144. # page
  145. self.gotopage = QLabel("Go to Page: /"+self.parent.core.docsettings['np'])
  146. self.hbox.addWidget(self.gotopage)
  147. self.page = QSpinBox()
  148. self.page.setMinimum(0)
  149. self.page.setMaximum(int(self.parent.core.docsettings['np']))
  150. self.page.valueChanged.connect(self.onChangePage)
  151. self.hbox.addWidget(self.page)
  152. self.addpage = QPushButton("&Add Page", self)
  153. self.addpage.clicked.connect(self.onAddPage)
  154. self.hbox.addWidget(self.addpage)
  155. self.rmpage = QPushButton("Re&move Page", self)
  156. self.rmpage.clicked.connect(self.onRmPage)
  157. self.hbox.addWidget(self.rmpage)
  158. #
  159. self.hbox.addStretch()
  160. #
  161. self.reload = QPushButton("&Reload", self)
  162. # self.reload.setShortcut('Ctrl+Shift+r')
  163. # TODO: how to define same shortcut in different places
  164. # self.reload.setIcon(Icon(ico)))
  165. self.reload.clicked.connect(self.onReload)
  166. self.hbox.addWidget(self.reload)
  167. self.genpdf = QPushButton("&PDF", self)
  168. # self.genpdf.setShortcut('Ctrl+Shift+r')
  169. # TODO: how to define same shortcut in different places
  170. # self.genpdf.setIcon(Icon(ico)))
  171. self.genpdf.clicked.connect(self.onGenPDF)
  172. self.hbox.addWidget(self.genpdf)
  173. self.setLayout(self.hbox)
  174. # def onCheckboxAction(self, box):
  175. # self.parent.webkitview.toggleDocClass(box, self[box].isChecked())
  176. # self.recToolbarState(box, self[box].isChecked())
  177. def onPreview(self):
  178. print('Toolbar : onPreview', self.preview.isChecked())
  179. self.parent.webkitview.toggleDocClass('preview', self.preview.isChecked())
  180. self.recToolbarState('preview', self.preview.isChecked())
  181. def onDebug(self):
  182. self.parent.webkitview.toggleDocClass('debug', self.debug.isChecked())
  183. self.recToolbarState('debug', self.debug.isChecked())
  184. def onGrid(self):
  185. self.parent.webkitview.toggleDocClass('grid', self.grid.isChecked())
  186. self.recToolbarState('grid', self.grid.isChecked())
  187. def onSpread(self):
  188. self.parent.webkitview.toggleDocClass('spread', self.spread.isChecked())
  189. self.recToolbarState('spread', self.spread.isChecked())
  190. def onFacing(self):
  191. self.parent.webkitview.toggleDocClass('facing', self.facing.isChecked())
  192. self.recToolbarState('facing', self.facing.isChecked())
  193. def onChangePage(self, i):
  194. print("onChangePage : "+str(i))
  195. self.parent.webkitview.changePage(i)
  196. def onAddPage(self):
  197. # print("onAddPage")
  198. self.parent.core.addPage()
  199. def onRmPage(self):
  200. # print("onAddPage")
  201. self.parent.core.rmPage()
  202. # def refreshNumberPage(self):
  203. def onReload(self):
  204. # print("onReload")
  205. self.parent.webkitview.reload()
  206. def onGenPDF(self):
  207. print("onGenPDF")
  208. self.parent.webkitview.ongenPDF()
  209. def recToolbarState(self, prop, val):
  210. # print('recToolbarState : '+prop, val)
  211. settings = QSettings('FiguresLibres', 'Cascade')
  212. settings.setValue('design/toolbar/'+prop, val)
  213. # print('recToolbarState after : '+prop, settings.value('design/toolbar/'+prop))
  214. def onRefresh(self):
  215. # apply precedent toolbar state
  216. settings = QSettings('FiguresLibres', 'Cascade')
  217. self.preview.setChecked(bool(settings.value('design/toolbar/preview', False, type=bool)))
  218. self.debug.setChecked(bool(settings.value('design/toolbar/debug', False, type=bool)))
  219. self.grid.setChecked(bool(settings.value('design/toolbar/grid', False, type=bool)))
  220. self.spread.setChecked(bool(settings.value('design/toolbar/spread', False, type=bool)))
  221. self.facing.setChecked(bool(settings.value('design/toolbar/facing', False, type=bool)))
  222. # trigger webview changes
  223. self.parent.webkitview.toggleDocClass('preview', self.preview.isChecked())
  224. self.parent.webkitview.toggleDocClass('debug', self.debug.isChecked())
  225. self.parent.webkitview.toggleDocClass('grid', self.grid.isChecked())
  226. self.parent.webkitview.toggleDocClass('spread', self.spread.isChecked())
  227. self.gotopage.setText("Go to Page: /"+str(self.parent.core.docsettings['np']))
  228. self.parent.webkitview.changePage(self.page.value())
  229. # ______ ___ __
  230. # / ____/___/ (_) /_____ _____
  231. # / __/ / __ / / __/ __ \/ ___/
  232. # / /___/ /_/ / / /_/ /_/ / /
  233. # /_____/\__,_/_/\__/\____/_/
  234. class CodeEditor(QPlainTextEdit):
  235. def __init__(self, parent, core, tabs, file, mode):
  236. super(CodeEditor, self).__init__()
  237. self.parent = parent
  238. self.core = core
  239. self.tabs = tabs
  240. self.file = file
  241. self.hl= highlighter.Highlighter(self.document(),mode)
  242. self.setText()
  243. self.setTabStopWidth(15)
  244. self.textChanged.connect(self.onTextChanged)
  245. self.shortcut = QShortcut(QKeySequence("Ctrl+s"), self)
  246. self.shortcut.activated.connect(self.save)
  247. def setText(self):
  248. # try:
  249. # self.textChanged.disconnect(self.onTextChanged)
  250. # except Exception as e:
  251. # print(e)
  252. self.filepath = os.path.join(self.core.cwd,self.file)
  253. self.clear()
  254. self.insertPlainText(open(self.filepath, 'r').read())
  255. self.changed = False
  256. font = QFont()
  257. font.setFamily("Droid Sans Mono")
  258. font.setFixedPitch(True)
  259. font.setPointSize(12)
  260. self.setFont(font)
  261. def onTextChanged(self):
  262. print('textChanged')
  263. # print(self.toPlainText())
  264. # open(self.filepath, 'w').write(self.toPlainText())
  265. if not self.changed:
  266. self.changed = True
  267. i = self.tabs.currentIndex()
  268. # self.tabs.setTabText(i, re.sub(r'^\**\s', '', self.tabs.tabText(i)))
  269. self.tabs.setTabText(i, "* "+self.tabs.tabText(i))
  270. # TODO: indicate that webview needs to be reloaded
  271. def save(self):
  272. if self.changed:
  273. open(self.filepath, 'w').write(self.toPlainText())
  274. i = self.tabs.currentIndex()
  275. self.tabs.setTabText(i, re.sub(r'^\**\s', '', self.tabs.tabText(i)))
  276. self.parent.reloadView()
  277. self.changed = False
  278. # TODO: how to combine file save and project save
  279. class Editor(QWidget):
  280. def __init__(self, parent):
  281. super(Editor, self).__init__()
  282. self.parent = parent
  283. self.layout = QVBoxLayout(self)
  284. self.layout.setContentsMargins(0,0,0,0)
  285. # Initialize tab screen
  286. self.tabs = QTabWidget()
  287. self.scsstab = CodeEditor(self, self.parent.core, self.tabs, 'assets/css/styles.scss', "sass")
  288. self.jstab = CodeEditor(self, self.parent.core, self.tabs, 'assets/js/script.js', 'js')
  289. # Add tabs
  290. self.tabs.addTab(self.scsstab,"scss")
  291. self.tabs.addTab(self.jstab,"js")
  292. # Add tabs to widget
  293. self.layout.addWidget(self.tabs)
  294. self.setLayout(self.layout)
  295. def refresh(self):
  296. self.scsstab.setText()
  297. self.jstab.setText()
  298. def reloadView(self):
  299. self.parent.webkitview.reload()
  300. # _____ __ __
  301. # / ___// /_____ ______/ /__
  302. # \__ \/ __/ __ `/ ___/ //_/
  303. # ___/ / /_/ /_/ / /__/ ,<
  304. # /____/\__/\__,_/\___/_/|_|
  305. class DesignStack(QWidget):
  306. def __init__(self, core):
  307. super(DesignStack, self).__init__()
  308. self.core = core
  309. # self.grid = QGridLayout()
  310. self.hbox = QHBoxLayout()
  311. self.hbox.setContentsMargins(0,0,0,0)
  312. self.setLayout(self.hbox)
  313. self.webview = QWidget()
  314. self.webview.vbox = QVBoxLayout()
  315. self.webview.setLayout(self.webview.vbox)
  316. self.webview.vbox.setContentsMargins(0,0,0,0)
  317. # toolbar
  318. self.webviewtoolbar = WebViewToolBar(self)
  319. self.webview.vbox.addWidget(self.webviewtoolbar)
  320. # webkitview
  321. self.webkitview = WebkitView(self, core)
  322. # webkitinspector
  323. self.webkitinspector = WebkitInspector(self, self.webkitview)
  324. shortcut = QShortcut(self)
  325. shortcut.setKey("F12")
  326. shortcut.activated.connect(self.toggleInspector)
  327. self.webkitinspector.setVisible(False)
  328. # V layout
  329. self.vsplitter = QSplitter(QtCore.Qt.Vertical)
  330. self.vsplitter.addWidget(self.webkitview)
  331. self.vsplitter.addWidget(self.webkitinspector)
  332. self.vsplitter.splitterMoved.connect(self.movedSplitter)
  333. self.webview.vbox.addWidget(self.vsplitter)
  334. # H layout
  335. self.hsplitter = QSplitter(QtCore.Qt.Horizontal)
  336. self.hsplitter.addWidget(self.webview)
  337. # editor
  338. self.editor = Editor(self)
  339. self.hsplitter.addWidget(self.editor)
  340. self.hsplitter.splitterMoved.connect(self.movedSplitter)
  341. self.hbox.addWidget(self.hsplitter)
  342. self.restorePrefs()
  343. def toggleInspector(self):
  344. self.webkitinspector.setVisible(not self.webkitinspector.isVisible())
  345. def restorePrefs(self):
  346. settings = QSettings('FiguresLibres', 'Cascade')
  347. print(settings.value('design/vsplitter/sizes', self.vsplitter.sizes()))
  348. vals = settings.value('design/vsplitter/sizes', None)
  349. if vals:
  350. sizes = []
  351. for size in vals: sizes.append(int(size))
  352. self.vsplitter.setSizes(sizes)
  353. vals = settings.value('design/hsplitter/sizes', None)
  354. if vals:
  355. sizes = []
  356. for size in vals: sizes.append(int(size))
  357. self.hsplitter.setSizes(sizes)
  358. def movedSplitter(self):
  359. settings = QSettings('FiguresLibres', 'Cascade')
  360. # print(self.vsplitter.sizes())
  361. settings.setValue('design/vsplitter/sizes', self.vsplitter.sizes())
  362. settings.setValue('design/hsplitter/sizes', self.hsplitter.sizes())
  363. def refresh(self):
  364. self.editor.refresh()
  365. self.webkitview.refresh()